Compare commits

..

30 Commits

Author SHA1 Message Date
overtrue 8398f17035 refactor(auth): return owned errors for upload size capabilities 2026-11-23 16:09:06 +08:00
overtrue 25df27a41b refactor(app): restrict the old stream and XML exports to tests 2026-11-23 16:09:06 +08:00
overtrue dec467da27 refactor(gateway): render metadata listings with native XML 2026-11-23 16:08:43 +08:00
overtrue 4b23847a75 refactor(object): retire the unused legacy length interface on PUT limits 2026-11-23 16:03:51 +08:00
overtrue 23405ff83a refactor(gateway): use native restore, version and object lock headers 2026-11-23 16:02:49 +08:00
overtrue 77107f62f3 refactor(http): classify control body digests with native host and path rules 2026-11-23 16:02:49 +08:00
overtrue 63e58d3c18 test(bucket): move request fields into the owner-state envelope 2026-11-23 16:02:49 +08:00
overtrue 6a7761cdb6 test(object): build the gateway post archive envelope directly
Replace the archive refusal fixture's from_s3s call with
RequestEnvelope::from_parts, keeping method, URI, headers, and
extensions. Credentials, region, and service stay absent. The
legacy-provenance, NotImplemented, and unpolled-body assertions are
unchanged.
2026-11-23 16:00:23 +08:00
overtrue 929582bc43 test(gateway): replace legacy configuration projections with frozen wire and cache fixtures 2026-11-23 15:53:00 +08:00
overtrue a1b4f29cc8 refactor(gateway): use native host validation and bucket deletion errors 2026-11-23 15:53:00 +08:00
overtrue 5e6f57c118 refactor(s3-types): render owned errors without the legacy HTTP serializer 2026-11-23 15:52:28 +08:00
overtrue 391e239711 refactor(auth): use gateway header coverage for protocol admission 2026-11-23 15:36:59 +08:00
overtrue db721d9bb1 refactor(gateway): return native lifecycle validation errors 2026-11-23 15:36:59 +08:00
overtrue 7125b37129 refactor(gateway): preserve native Veeam read errors across the cache 2026-11-23 15:36:58 +08:00
overtrue 6cb0e6971b test(bucket): build the owner-state envelope directly
Replace the create-bucket reqinfo fixture's from_s3s call with
RequestEnvelope::from_parts, keeping method, URI, headers, and
extensions. Credentials, region, and service stay absent. The
owner-state assertion is unchanged.
2026-11-23 15:33:18 +08:00
overtrue 41f11d030d refactor(gateway): use native errors for table listings and multipart headers 2026-11-23 15:00:00 +08:00
overtrue 69514b18de style(gateway): format native GET test seam exports 2026-11-23 14:58:03 +08:00
overtrue c66b0b4870 test(gateway): retire the legacy object response and stream adapter 2026-11-23 14:54:35 +08:00
overtrue c0795fa4e8 refactor(gateway): remove unused legacy GET fixture exports 2026-11-23 14:50:06 +08:00
overtrue 95ea979811 test(gateway): retire the remaining legacy GET request fixtures 2026-11-23 14:50:06 +08:00
overtrue 00a3abd6ef test(protocols): freeze the legacy COPY request head observations 2026-11-23 14:50:06 +08:00
overtrue 0ebd1f14ca refactor(gateway): share the native GET field projection 2026-11-23 14:50:06 +08:00
overtrue 18f5090671 fix(test): adapt the shared read benchmark to historical GET APIs 2026-11-23 14:50:06 +08:00
overtrue cd94ed59c5 test(gateway): exercise conditional reads through native GET requests 2026-11-23 14:50:06 +08:00
overtrue c58890f199 test(gateway): use native requests for conditional object copies 2026-11-23 14:50:06 +08:00
overtrue 526dd58f6d test(gateway): exercise copy authorization on the native upload path 2026-11-23 14:50:06 +08:00
overtrue 35a6de6eb5 refactor(gateway): retire legacy storage ETag projections 2026-11-23 14:50:06 +08:00
overtrue 0649e80b62 test(protocols): build the listing session envelope directly
Replace the listing session credential fixture's from_s3s call with
RequestEnvelope::from_parts, keeping method, URI, headers,
extensions, region, service, and credentials. The credential
projection assertions are unchanged.
2026-11-23 14:43:56 +08:00
overtrue f413a76f54 test(gateway): exercise PUT request boundaries with native inputs 2026-11-23 14:38:32 +08:00
overtrue 65d0a9118c refactor(gateway): use native ETags in metadata listings 2026-11-23 14:38:32 +08:00
133 changed files with 11897 additions and 22913 deletions
-1
View File
@@ -57,7 +57,6 @@ rustfs-scanner 1392 20
rustfs-scanner-metrics 90 0 rustfs-scanner-metrics 90 0
rustfs-security-governance 20 0 rustfs-security-governance 20 0
rustfs-signer 34 0 rustfs-signer 34 0
rustfs-sse 145 0
rustfs-storage-api 34 0 rustfs-storage-api 34 0
rustfs-targets 612 26 rustfs-targets 612 26
rustfs-test-utils 1 0 rustfs-test-utils 1 0
+1 -1
View File
@@ -231,7 +231,7 @@ jobs:
# --all-targets links the same test binaries as the reader lane. # --all-targets links the same test binaries as the reader lane.
CARGO_BUILD_JOBS: "2" CARGO_BUILD_JOBS: "2"
run: | run: |
cargo build -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2 cargo build -p rustfs -p rustfs-ecstore --all-targets --features rio-v2
cargo build -p rustfs --bins --features rio-v2,e2e-test-hooks cargo build -p rustfs --bins --features rio-v2,e2e-test-hooks
# Readers: the swift and sftp legs of test-and-lint-protocols. Built in # Readers: the swift and sftp legs of test-and-lint-protocols. Built in
+2 -2
View File
@@ -563,7 +563,7 @@ jobs:
run: chmod go-w "$(realpath "$HOME")" run: chmod go-w "$(realpath "$HOME")"
- name: Run rio-v2 clippy lints - name: Run rio-v2 clippy lints
run: cargo clippy -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2 -- -D warnings run: cargo clippy -p rustfs -p rustfs-ecstore --all-targets --features rio-v2 -- -D warnings
- name: Run rio-v2 feature tests - name: Run rio-v2 feature tests
shell: bash shell: bash
@@ -580,7 +580,7 @@ jobs:
rm -f target/nextest/ci/junit.xml rm -f target/nextest/ci/junit.xml
./scripts/ci/resource_sampler.sh start nextest-rio-v2 ./scripts/ci/resource_sampler.sh start nextest-rio-v2
trap './scripts/ci/resource_sampler.sh stop' EXIT trap './scripts/ci/resource_sampler.sh stop' EXIT
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore -p rustfs-sse --features rio-v2 \ cargo nextest run --profile ci -p rustfs -p rustfs-ecstore --features rio-v2 \
2>&1 | tee artifacts/workspace/nextest.log 2>&1 | tee artifacts/workspace/nextest.log
cargo test -p rustfs --doc --features rio-v2 cargo test -p rustfs --doc --features rio-v2
+1 -1
View File
@@ -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. | | 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. | | I/O and storage | `concurrency`, `ecstore`, `filemeta`, `heal`, `io-core`, `io-metrics`, `lifecycle`, `lock`, `object-capacity`, `object-data-cache`, `replication`, `rio`, `rio-v2`, `s3-client`, `scanner`, `storage-api` | Erasure-coded object storage, metadata, recovery, lifecycle, replication, locking, cache, I/O pipelines, and the engine-side S3 client for remote tier/transition targets. |
| Security and identity | `credentials`, `crypto`, `iam`, `keystone`, `kms`, `policy`, `security-governance`, `signer`, `sse`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, server-side encryption key resolution, TLS, and security contracts. | | Security and identity | `credentials`, `crypto`, `iam`, `keystone`, `kms`, `policy`, `security-governance`, `signer`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, TLS, and security contracts. |
| Protocols and contracts | `extension-schema`, `madmin`, `protos`, `protocols`, `s3-ops`, `s3-types`, `s3select-api`, `s3select-query` | Admin, inter-node, S3, S3 Select, and optional protocol contracts. | | 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. | | 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. | | Test support | `e2e_test`, `test-utils` | End-to-end validation and shared test bootstrap utilities. |
-1
View File
@@ -118,7 +118,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Four-layer regression-prevention tests guard against silent feature deletion: compile-time module assertion, module-presence unit test, cross-module `Protocol` enum assertion, end-to-end SSH banner test against the running binary - 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 ### 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. - **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): - **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. - **Persisted KMS configuration secrets** are sealed field-by-field with `RUSTFS_KMS_CONFIG_SECRET`. **When the variable is unset the secrets are persisted in cleartext and the server only warns** (`persisted KMS configuration carries cleartext secrets`); it never refuses the write. Set it, identically, on every node, and re-save the configuration to seal an existing one.
Generated
+10 -37
View File
@@ -10022,7 +10022,6 @@ dependencies = [
"rustfs-scanner-metrics", "rustfs-scanner-metrics",
"rustfs-security-governance", "rustfs-security-governance",
"rustfs-signer", "rustfs-signer",
"rustfs-sse",
"rustfs-storage-api", "rustfs-storage-api",
"rustfs-targets", "rustfs-targets",
"rustfs-test-utils", "rustfs-test-utils",
@@ -10397,7 +10396,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway" name = "rustfs-gateway"
version = "0.66.0" version = "0.66.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"bytes", "bytes",
@@ -10444,7 +10443,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-core" name = "rustfs-gateway-core"
version = "0.63.0" version = "0.63.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"bytes", "bytes",
"futures-core", "futures-core",
@@ -10465,7 +10464,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-dialect-rustfs-admin" name = "rustfs-gateway-dialect-rustfs-admin"
version = "0.13.0" version = "0.13.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"bytes", "bytes",
"form_urlencoded", "form_urlencoded",
@@ -10479,7 +10478,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-http" name = "rustfs-gateway-http"
version = "0.1.4" version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"hmac 0.13.0", "hmac 0.13.0",
"http 1.5.0", "http 1.5.0",
@@ -10497,7 +10496,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-macros" name = "rustfs-gateway-macros"
version = "0.1.4" version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -10507,7 +10506,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-sig" name = "rustfs-gateway-sig"
version = "0.15.0" version = "0.15.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"hmac 0.13.0", "hmac 0.13.0",
"http 1.5.0", "http 1.5.0",
@@ -10522,7 +10521,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-stream" name = "rustfs-gateway-stream"
version = "0.2.0" version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"bytes", "bytes",
@@ -10533,7 +10532,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-types" name = "rustfs-gateway-types"
version = "0.42.0+aws.2026-10-02" version = "0.42.0+aws.2026-10-02"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"bytes", "bytes",
"crc-fast", "crc-fast",
@@ -10556,7 +10555,7 @@ dependencies = [
[[package]] [[package]]
name = "rustfs-gateway-xml" name = "rustfs-gateway-xml"
version = "0.4.0" version = "0.4.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310" source = "git+https://github.com/rustfs/gateway.git?rev=1c7486f1113769f643144d635ede30520e735141#1c7486f1113769f643144d635ede30520e735141"
dependencies = [ dependencies = [
"quick-xml 0.41.0", "quick-xml 0.41.0",
] ]
@@ -11341,6 +11340,7 @@ dependencies = [
"hyper", "hyper",
"hyper-util", "hyper-util",
"pin-project-lite", "pin-project-lite",
"quick-xml 0.42.0",
"s3s", "s3s",
"serde", "serde",
"serde_json", "serde_json",
@@ -11505,33 +11505,6 @@ dependencies = [
"url", "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]] [[package]]
name = "rustfs-storage-api" name = "rustfs-storage-api"
version = "1.0.5" version = "1.0.5"
+6 -8
View File
@@ -61,7 +61,6 @@ members = [
"crates/security-governance", # Security governance contracts "crates/security-governance", # Security governance contracts
"crates/extension-schema", # Extension schema contracts "crates/extension-schema", # Extension schema contracts
"crates/signer", # client signer "crates/signer", # client signer
"crates/sse", # S3 server-side encryption key resolution and metadata
"crates/storage-api", # Storage API contracts "crates/storage-api", # Storage API contracts
"crates/test-utils", # Shared test bootstrap helpers (dev-dependency only) "crates/test-utils", # Shared test bootstrap helpers (dev-dependency only)
"crates/targets", # Target-specific configurations and utilities "crates/targets", # Target-specific configurations and utilities
@@ -143,7 +142,6 @@ rustfs-scanner = { path = "crates/scanner", version = "1.0.5" }
rustfs-security-governance = { path = "crates/security-governance", version = "1.0.5" } rustfs-security-governance = { path = "crates/security-governance", version = "1.0.5" }
rustfs-extension-schema = { path = "crates/extension-schema", 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-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-storage-api = { path = "crates/storage-api", version = "1.0.5" }
rustfs-trusted-proxies = { path = "crates/trusted-proxies", version = "1.0.5" } rustfs-trusted-proxies = { path = "crates/trusted-proxies", version = "1.0.5" }
rustfs-targets = { path = "crates/targets", version = "1.0.5" } rustfs-targets = { path = "crates/targets", version = "1.0.5" }
@@ -156,16 +154,16 @@ rustfs-zip = { path = "./crates/zip", version = "1.0.5" }
# engine crates move onto from s3s (rustfs/backlog#2745). The one pin of the # engine crates move onto from s3s (rustfs/backlog#2745). The one pin of the
# gateway in this workspace; no crate may enable a `compat-s3s*` feature except # gateway in this workspace; no crate may enable a `compat-s3s*` feature except
# the s3s-facing edge of the rustfs binary. # the s3s-facing edge of the rustfs binary.
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.42.0", default-features = false } rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.2.0", default-features = false } rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", version = "0.2.0", default-features = false }
# The gateway framework itself, consumed for its extension traits by the ring-2 # The gateway framework itself, consumed for its extension traits by the ring-2
# adapter. `default-features = false` keeps the `server` feature, and with it the # adapter. `default-features = false` keeps the `server` feature, and with it the
# server crate, out of the build. # server crate, out of the build.
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.66.0", default-features = false } rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", version = "0.66.0", default-features = false }
# Test-only: builds the `EffectiveHost` a host-resolution test queries with. # Test-only: builds the `EffectiveHost` a host-resolution test queries with.
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", default-features = false } rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.63.0", default-features = false } rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", version = "0.63.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.13.0", default-features = false } rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "1c7486f1113769f643144d635ede30520e735141", version = "0.13.0", default-features = false }
# Async Runtime and Networking # Async Runtime and Networking
async-channel = "2.5.0" async-channel = "2.5.0"
+1 -2
View File
@@ -6,8 +6,7 @@ Applies to `crates/kms/`.
When changing key-management behavior, verify compatibility with: When changing key-management behavior, verify compatibility with:
- `crates/sse/` (SSE key resolution; consumes this crate on the data path) - `rustfs/src/storage/sse.rs`
- `rustfs/src/storage/sse.rs` (binds `crates/sse/` to the running server)
- `rustfs/src/admin/handlers/kms.rs` - `rustfs/src/admin/handlers/kms.rs`
- `rustfs/src/admin/handlers/kms_dynamic.rs` - `rustfs/src/admin/handlers/kms_dynamic.rs`
- `rustfs/src/admin/handlers/kms_keys.rs` - `rustfs/src/admin/handlers/kms_keys.rs`
+3 -1
View File
@@ -36,7 +36,7 @@ default = []
# (rustfs/backlog#2734). Off by default; the runtime dependency tree of this # (rustfs/backlog#2734). Off by default; the runtime dependency tree of this
# crate carries no s3s unless a consumer asks. # crate carries no s3s unless a consumer asks.
# DELETE BY T4.2 (rustfs/backlog#2784) together with src/compat_s3s.rs. # DELETE BY T4.2 (rustfs/backlog#2784) together with src/compat_s3s.rs.
compat-s3s = ["dep:legacy-s3s"] compat-s3s = ["dep:legacy-s3s", "dep:quick-xml"]
hotpath = [] hotpath = []
hotpath-alloc = ["hotpath"] hotpath-alloc = ["hotpath"]
hotpath-cpu = ["hotpath"] hotpath-cpu = ["hotpath"]
@@ -48,6 +48,7 @@ http = { workspace = true }
http-body = { workspace = true } http-body = { workspace = true }
http-body-util = { workspace = true } http-body-util = { workspace = true }
pin-project-lite = { workspace = true } pin-project-lite = { workspace = true }
quick-xml = { workspace = true, optional = true }
# The s3s package under the name the legacy edge knows it by. Only # The s3s package under the name the legacy edge knows it by. Only
# src/compat_s3s.rs may use it; see that file's header for the footprint note. # src/compat_s3s.rs may use it; see that file's header for the footprint note.
legacy-s3s = { workspace = true, optional = true } legacy-s3s = { workspace = true, optional = true }
@@ -55,6 +56,7 @@ serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true, features = ["raw_value"] } serde_json = { workspace = true, features = ["raw_value"] }
[dev-dependencies] [dev-dependencies]
quick-xml = { workspace = true }
# Oracle for the parity tests in src/compat_s3s.rs; never a normal dependency. # Oracle for the parity tests in src/compat_s3s.rs; never a normal dependency.
legacy-s3s = { workspace = true } legacy-s3s = { workspace = true }
# The HTTP/1.1 server those parity tests compare bodies through, byte for byte. # The HTTP/1.1 server those parity tests compare bodies through, byte for byte.
+20 -6
View File
@@ -134,12 +134,26 @@ impl From<S3Error> for legacy_s3s::S3Error {
} }
impl S3Error { impl S3Error {
/// The pinned legacy serializer's XML response. Call sites stay on this type. /// An error wrapped with its original cause can retain response fields the caller did not override.
/// DELETE BY T4.2 with the rest of this file. pub(super) fn into_http_response_parts(self) -> crate::S3ErrorParts {
pub fn to_http_response(self) -> Result<http::Response<crate::Body>, Self> { let mut parts = self.into_parts();
let response = legacy_s3s::S3Error::from(self).to_http_response().map_err(Self::from)?; let original = parts
let (parts, body) = response.into_parts(); .source
Ok(http::Response::from_parts(parts, crate::Body::from(body))) .as_deref()
.and_then(|source| source.downcast_ref::<LegacyCause>())
.map(|cause| &cause.0)
.filter(|error| error.code() == &parts.code.clone().into());
if let Some(original) = original {
parts.message = parts
.message
.or_else(|| original.message().map(|text| Cow::Owned(text.to_owned())));
parts.request_id = parts.request_id.or_else(|| original.request_id().map(str::to_owned));
parts.status = parts.status.or_else(|| original.status_code());
parts.headers = parts.headers.or_else(|| original.headers().cloned());
} else if parts.message.is_none() {
parts.message = parts.code.default_message().map(Cow::Borrowed);
}
parts
} }
} }
@@ -0,0 +1,83 @@
// 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 legacy HTTP response contract for an owned S3 error.
use super::{S3Error, S3ErrorCode};
use crate::Body;
use http::header::{CONTENT_LENGTH, CONTENT_TYPE, TRANSFER_ENCODING};
use http::{HeaderValue, Response, StatusCode};
use quick_xml::escape::escape;
impl S3Error {
/// Renders this error as an HTTP response using the legacy S3 wire format.
///
/// # Errors
///
/// Returns `InternalError` if an XML field contains a disallowed control character.
pub fn to_http_response(self) -> Result<Response<Body>, Self> {
let parts = self.into_http_response_parts();
let status = parts
.status
.or_else(|| parts.code.status_code())
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
let bodyless = status.is_informational()
|| matches!(status, StatusCode::NO_CONTENT | StatusCode::RESET_CONTENT | StatusCode::NOT_MODIFIED);
let mut response = if bodyless {
Response::new(Body::empty())
} else {
let body = xml_body(parts.code.as_str(), parts.message.as_deref(), parts.request_id.as_deref())?;
let mut response = Response::new(body);
response
.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static("application/xml"));
response
};
*response.status_mut() = status;
if let Some(headers) = parts.headers {
*response.headers_mut() = headers;
}
if bodyless {
let headers = response.headers_mut();
headers.remove(CONTENT_LENGTH);
headers.remove(CONTENT_TYPE);
headers.remove(TRANSFER_ENCODING);
}
Ok(response)
}
}
fn xml_body(code: &str, message: Option<&str>, request_id: Option<&str>) -> Result<Body, S3Error> {
let mut xml = String::from(r#"<?xml version="1.0" encoding="UTF-8"?><Error><Code>"#);
xml.push_str(&escape(code));
xml.push_str("</Code>");
if let Some(message) = message {
xml.push_str("<Message>");
xml.push_str(&escape(message));
xml.push_str("</Message>");
}
if let Some(request_id) = request_id {
xml.push_str("<RequestId>");
xml.push_str(&escape(request_id));
xml.push_str("</RequestId>");
}
xml.push_str("</Error>");
if xml.bytes().any(|byte| byte < b' ' && !matches!(byte, b'\t' | b'\n' | b'\r')) {
return Err(S3Error::with_message(
S3ErrorCode::InternalError,
"XML response contains a control character",
));
}
Ok(Body::from(xml))
}
@@ -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.
//! Differential wire tests against the pinned legacy HTTP renderer.
use super::{S3Error, S3ErrorCode};
use http::header::{CONTENT_LENGTH, CONTENT_TYPE, TRANSFER_ENCODING};
use http::{HeaderMap, HeaderValue, StatusCode};
use http_body::Body as _;
use http_body_util::BodyExt;
use legacy_s3s::{S3Error as LegacyError, S3ErrorCode as LegacyCode};
fn errors(name: &str) -> (S3Error, LegacyError) {
let Ok(owned) = name.parse();
let Ok(legacy) = name.parse();
(S3Error::new(owned), LegacyError::new(legacy))
}
async fn assert_response(owned: S3Error, legacy: LegacyError) {
let name = legacy.code().as_str().to_owned();
let expected = legacy.to_http_response().expect("legacy response should render");
let actual = owned.to_http_response().expect("owned response should render");
assert_eq!(actual.status(), expected.status(), "{name}");
assert_eq!(actual.headers(), expected.headers(), "{name}");
assert_eq!(actual.body().is_end_stream(), expected.body().is_end_stream(), "{name}");
let length = expected
.body()
.size_hint()
.exact()
.expect("legacy error body has an exact size");
assert_eq!(actual.body().size_hint().exact(), Some(length), "{name}");
let expected = expected
.into_body()
.collect()
.await
.expect("read legacy error body")
.to_bytes();
let actual = actual.into_body().collect().await.expect("read owned error body").to_bytes();
assert_eq!(actual, expected, "{name}");
assert_eq!(u64::try_from(actual.len()).expect("body length fits in u64"), length, "{name}");
}
#[tokio::test]
async fn named_and_custom_code_defaults_match_legacy() {
for code in S3ErrorCode::NAMED {
let (owned, legacy) = errors(code.as_str());
assert_response(owned, legacy).await;
}
for name in ["", "TierNotFound", "Unknown&<Code>"] {
let (owned, legacy) = errors(name);
assert_response(owned, legacy).await;
}
}
#[tokio::test]
async fn explicit_xml_fields_and_headers_match_legacy() {
let mut headers = HeaderMap::new();
headers.append("x-amz-meta-repeated", HeaderValue::from_static("first"));
headers.append("x-amz-meta-repeated", HeaderValue::from_static("second"));
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/custom"));
headers.insert(CONTENT_LENGTH, HeaderValue::from_static("999"));
for (message, request_id, headers) in [
("", "", None),
("雪<&>\"'\t\n\r", "req<&>\"'雪", Some(HeaderMap::new())),
("message", "request", Some(headers)),
] {
let (mut owned, mut legacy) = errors("Custom&Code");
owned.set_message(message);
legacy.set_message(message);
owned.set_request_id(request_id);
legacy.set_request_id(request_id);
owned.set_status_code(StatusCode::CONFLICT);
legacy.set_status_code(StatusCode::CONFLICT);
if let Some(headers) = headers {
owned.set_headers(headers.clone());
legacy.set_headers(headers);
}
assert_response(owned, legacy).await;
}
}
#[tokio::test]
async fn bodyless_statuses_skip_xml_and_strip_framing_like_legacy() {
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/custom"));
headers.insert(CONTENT_LENGTH, HeaderValue::from_static("11"));
headers.insert(TRANSFER_ENCODING, HeaderValue::from_static("chunked"));
headers.append("warning", HeaderValue::from_static("first"));
headers.append("warning", HeaderValue::from_static("second"));
for status in [100, 101, 103, 199, 204, 205, 304] {
let status = StatusCode::from_u16(status).expect("valid status");
let (mut owned, mut legacy) = errors("InvalidRequest");
owned.set_status_code(status);
legacy.set_status_code(status);
owned.set_message("invalid XML \0");
legacy.set_message("invalid XML \0");
owned.set_headers(headers.clone());
legacy.set_headers(headers.clone());
assert_response(owned, legacy).await;
}
}
#[tokio::test]
async fn invalid_xml_in_each_field_returns_the_legacy_error() {
for (code, message, request_id) in [
("Bad\u{1f}Code", "message", "request"),
("InvalidRequest", "bad\u{b}message", "request"),
("InvalidRequest", "message", "bad\0request"),
] {
let (mut owned, mut legacy) = errors(code);
owned.set_message(message);
legacy.set_message(message);
owned.set_request_id(request_id);
legacy.set_request_id(request_id);
let expected = legacy.to_http_response().expect_err("legacy should reject invalid XML");
let actual = owned.to_http_response().expect_err("owned should reject invalid XML");
assert_eq!(actual.code().as_str(), expected.code().as_str());
assert_eq!(actual.message(), expected.message());
assert_response(actual, expected).await;
}
}
#[tokio::test]
async fn legacy_cause_retains_missing_message_until_the_owned_code_changes() {
// set_code on a legacy error retains its original, absent message.
let legacy_without_message = || {
let mut error =
LegacyError::with_source(LegacyCode::Custom("SourceOnly".into()), Box::new(std::io::Error::other("cause")));
error.set_code(LegacyCode::AccessDenied);
error
};
assert_response(S3Error::from(legacy_without_message()), legacy_without_message()).await;
let mut changed = S3Error::from(legacy_without_message());
changed.set_code(S3ErrorCode::NoSuchKey);
assert_response(changed, LegacyError::new(LegacyCode::NoSuchKey)).await;
}
+6 -2
View File
@@ -15,13 +15,17 @@
//! The S3 error carrier shared by every RustFS crate. //! The S3 error carrier shared by every RustFS crate.
//! //!
//! Responsible for: `S3Error` and its accessor contract, `S3Result`, `StdError`, //! Responsible for: `S3Error` and its accessor contract, `S3Result`, `StdError`,
//! `S3ErrorParts`, and the `s3_error` macro. //! `S3ErrorParts`, the `s3_error` macro, and the legacy-compatible HTTP response.
//! Not responsible for: the code set and its statuses (`code.rs`), s3s //! Not responsible for: the code set and its statuses (`code.rs`), s3s
//! conversions (`crate::compat_s3s`), or rendering an error onto the wire. //! conversions (`crate::compat_s3s`), or the gateway listener's rendering policy.
//! Upstream: `http`. Downstream: every crate that raises S3 errors; the legacy //! Upstream: `http`. Downstream: every crate that raises S3 errors; the legacy
//! edge converts through `compat_s3s`, the gateway edge through `into_parts`. //! edge converts through `compat_s3s`, the gateway edge through `into_parts`.
mod code; mod code;
#[cfg(any(test, feature = "compat-s3s"))]
mod http_response;
#[cfg(test)]
mod http_response_tests;
use http::{HeaderMap, StatusCode}; use http::{HeaderMap, StatusCode};
use std::borrow::Cow; use std::borrow::Cow;
+3 -3
View File
@@ -18,9 +18,9 @@
//! Responsible for: `EventName`, the error surface (`S3Error`, `S3ErrorCode`, //! Responsible for: `EventName`, the error surface (`S3Error`, `S3ErrorCode`,
//! `S3Result`, the `s3_error` macro) that every RustFS crate raises S3 errors with, //! `S3Result`, the `s3_error` macro) that every RustFS crate raises S3 errors with,
//! and `Body`, the type-erased body the outbound client crates send. //! and `Body`, the type-erased body the outbound client crates send.
//! Not responsible for: I/O, global state, wire rendering, S3 body semantics //! The `compat-s3s` feature also renders owned errors as HTTP responses and enables
//! (trailers, checksums, framing), or any s3s type; the legacy conversions live //! conversions to legacy types in `compat_s3s`. Transport I/O, shared state, trailers,
//! behind the `compat-s3s` feature in `compat_s3s` only. //! checksums, and body framing belong to the callers.
//! Upstream: `http`, `bytes`, `http-body`, `http-body-util`. Downstream: every //! Upstream: `http`, `bytes`, `http-body`, `http-body-util`. Downstream: every
//! crate that raises or inspects S3 errors, and the crates that build HTTP bodies. //! crate that raises or inspects S3 errors, and the crates that build HTTP bodies.
-57
View File
@@ -1,57 +0,0 @@
# SSE Crate Instructions
Applies to `crates/sse/`.
## Boundary
- This crate sits between the S3 layer and the storage engine and depends on neither. Its `rustfs-*` dependencies are pinned by `scripts/check_architecture_migration_rules.sh` to `rustfs-config`, `rustfs-kms`, `rustfs-policy`, `rustfs-s3-types`, and `rustfs-utils`; see [crate boundaries](../../docs/architecture/crate-boundaries.md).
- Anything the crate needs from the running server arrives through `SseHost` (`src/host.rs`), passed as the first argument of every entry point that consults the server. Do not add a global that stands in for the host: a caller must not be able to reach key selection without naming the server it speaks for.
- Translation to and from storage-engine types (`ObjectEncryptionResolver`, `WriteEncryption`, `MultipartCompletionAuthorization`) and request types belongs in `rustfs/src/storage/sse.rs`, not here.
- Report failures as `SseError`, classified with the S3 error code the caller answers with. A failure that did not originate from the request goes through `SseError::internal`, which keeps its detail out of the response.
## Layout
- `src/startup.rs` settles the state that is fixed for the lifetime of the process and reports it. Nothing that follows the KMS service state belongs there: the service follows configuration and can be started, restarted, or stopped from the admin API, so every choice that depends on it is made per request.
- `src/core/` holds the entry points (`write.rs`, `read.rs`, `rewrap.rs`) and the request principal (`request.rs`). An entry point only orders the steps; the decisions live in the two layers below it.
- `src/core/s3/` is what S3 defines: the SSE headers of a request and a response, the scheme a write or a stored object resolves to, the SSE-C checks, and the authorization of a KMS key.
- `src/core/keying/` is how RustFS forms, seals, and records an object's key. `direct.rs` and `object.rs` are the two modes, and each owns both directions of its stored record: the code that writes a key's metadata sits next to the code that reads it back. `mod.rs` is the only place that says which mode a build writes; `stored.rs` holds the order in which a read recognizes the modes and picks the provider that unwraps the data key; `metadata.rs` records the scheme and lists every stored key name.
- `src/kms/` holds the data-key providers: they wrap and unwrap a data key and decide nothing about schemes. The write and rewrap entry points, `core/keying/stored.rs`, and the startup check of the local master key call them; `core/s3/` never does.
Rules that keep the layers apart:
- `core/keying/` never imports from `core/s3/`. `core/s3/` reads stored metadata only through `core/keying/metadata.rs`. Anything else that needs both layers is joined in an entry point.
- `#[cfg(feature = "rio-v2")]` appears only under `core/keying/` and `kms/`. An entry point or `core/s3/` that needs a build-dependent answer asks `core/keying/` for it.
- A new stored format, including a MinIO-compatible one, is added under `core/keying/` (and `kms/` when it brings its own wrapping) without changes under `core/s3/`: a mode file with its record and read functions, one entry in the recognition order of `stored.rs`, and its key names in the lists of `metadata.rs`.
- A read decides from what the object recorded. The scheme a request advertises and whether a KMS is running now are write policy and runtime state; neither says how an existing object was keyed.
## Security
- Never log plaintext customer keys, decrypted key material, data-key envelopes, nonces, or SSE request payloads, including through error strings and `Debug` output.
- KMS audit tags may carry only the fields documented on `KmsRequestAuditState`.
- The `test-util` feature exposes authorization overrides and DEK-provider injection. It is a dev-dependency feature only; never enable it from a normal dependency.
## Change Coordination
When changing key resolution, metadata, or error classification, verify compatibility with:
- `rustfs/src/storage/sse.rs` (the host implementation and the engine-boundary adapters)
- `crates/kms/`
- `crates/utils/src/http/object_encryption_keys.rs` (the stored-metadata key vocabulary)
- `rustfs/src/kms_rekey.rs` and `rustfs/src/admin/handlers/kms*.rs`
## Testing
Run both builds; the `rio-v2` feature swaps the object-key scheme and compiles different code paths:
```bash
cargo nextest run -p rustfs-sse --no-tests fail
cargo nextest run -p rustfs-sse --features rio-v2 --no-tests fail
```
The adapter tests live with the adapter:
```bash
cargo nextest run -p rustfs --no-tests fail -E 'test(/^storage::sse::/)'
```
A change that should leave client-visible behavior or the stored form untouched (a refactor, a move between layers) is checked against a real server: run `scripts/test/sse_blackbox/` on the binary before and after the change, compare the two runs, and cross-read their data directories. Its README has the commands.
-70
View File
@@ -1,70 +0,0 @@
# Copyright 2024 RustFS Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
[package]
name = "rustfs-sse"
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
version.workspace = true
homepage.workspace = true
description = "S3 server-side encryption (SSE-S3, SSE-KMS, SSE-C) key resolution and metadata for RustFS."
keywords = ["sse", "encryption", "s3", "kms", "rustfs"]
categories = ["cryptography"]
[lints]
workspace = true
[features]
default = []
# MinIO-compatible sealed object keys (DARE). Mirrors the `rio-v2` feature of
# the server binary, which enables both together.
rio-v2 = ["dep:chacha20poly1305", "dep:hmac", "dep:sha2"]
# Test seams for dependents: per-principal authorization overrides, DEK
# provider injection and metadata fixtures. Never enable in a release build.
test-util = []
[dependencies]
# The only RustFS crates this one may reach. It sits between the S3 layer and
# the storage engine and must not depend on either: what it needs from the
# running server arrives through `SseHost`.
rustfs-config = { workspace = true }
rustfs-kms = { workspace = true }
rustfs-policy = { workspace = true }
rustfs-s3-types = { workspace = true }
rustfs-utils = { workspace = true, features = ["http", "path"] }
aes-gcm = { workspace = true, features = ["rand_core", "zeroize"] }
async-trait = { workspace = true }
base64-simd = { workspace = true }
chacha20poly1305 = { workspace = true, optional = true }
hmac = { workspace = true, optional = true }
http = { workspace = true }
md-5 = { workspace = true }
rand = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
sha2 = { workspace = true, optional = true }
tracing = { workspace = true }
[dev-dependencies]
# The fake AWS KMS endpoint the backend-selection tests talk to.
axum = { workspace = true }
temp-env = { workspace = true, features = ["async_closure"] }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "net", "rt-multi-thread", "sync", "time"] }
[lib]
doctest = false
-292
View File
@@ -1,292 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Per-request summary of data-plane KMS use, attached to the request's audit entry.
use crate::core::request::SseKmsPrincipal;
use crate::error::SseError;
use base64_simd::STANDARD as BASE64_STANDARD;
use rustfs_kms::is_data_key_envelope;
use rustfs_s3_types::S3ErrorCode;
use rustfs_utils::http::object_encryption_keys::{INTERNAL_ENCRYPTION_KEY_HEADER, SSEType, normalize_managed_metadata};
use serde_json::Value;
use std::collections::{BTreeSet, HashMap};
use std::sync::{Arc, LazyLock, Mutex, Weak};
/// Tag keys carrying the KMS summary on an S3 audit entry.
///
/// Audit consumers key off these strings, so they are a wire contract: append
/// new keys rather than renaming existing ones.
const KMS_AUDIT_TAG_SSE_TYPE: &str = "sseType";
const KMS_AUDIT_TAG_KEY_ID: &str = "kmsKeyId";
const KMS_AUDIT_TAG_KEY_VERSION: &str = "kmsKeyVersion";
const KMS_AUDIT_TAG_OUTCOME: &str = "kmsOutcome";
const KMS_AUDIT_TAG_ERROR_CLASS: &str = "kmsErrorClass";
/// Separator for the rare request that touched more than one key or scheme.
const KMS_AUDIT_VALUE_SEPARATOR: &str = ",";
/// What the data path did with KMS while serving one S3 request.
///
/// This rides on the request's existing S3 audit entry instead of becoming its
/// own event: the entry already carries the principal, request ID and API, so
/// attaching the KMS outcome costs no extra event volume and needs no second
/// correlation key.
///
/// # Redaction
///
/// Only the fields below may ever be recorded. The S3 audit entry fans out to
/// every configured target, several of which sit outside the KMS trust
/// boundary, so nothing derived from a data key — plaintext, ciphertext,
/// envelope, nonce — nor any caller-supplied encryption-context value belongs
/// here. Key identifiers and scheme names are configuration, not secrets.
#[derive(Debug, Default)]
struct KmsRequestAuditState {
sse_types: BTreeSet<&'static str>,
key_ids: BTreeSet<String>,
key_versions: BTreeSet<u32>,
/// Set by the first failure. A request that failed any KMS interaction is
/// reported as failed even if others succeeded: a partially completed
/// envelope operation is not a success for an audit reader.
error_class: Option<&'static str>,
recorded: bool,
}
/// Shared accumulator for one request's KMS summary.
///
/// Written by the managed-SSE code paths through the request's principal, read
/// once through [`KmsRequestAuditScope::audit_tags`] by whoever owns the
/// request's audit entry.
#[derive(Debug, Default)]
pub(crate) struct KmsRequestAudit(Mutex<KmsRequestAuditState>);
impl KmsRequestAudit {
pub(crate) fn record(
&self,
sse_type: SSEType,
key_id: Option<&str>,
key_version: Option<u32>,
error_class: Option<&'static str>,
) {
// A poisoned lock costs the audit entry its KMS tags; it must never cost
// the request its result.
let Ok(mut state) = self.0.lock() else {
return;
};
state.recorded = true;
state.sse_types.insert(sse_type.audit_label());
if let Some(key_id) = key_id.filter(|value| !value.is_empty()) {
state.key_ids.insert(key_id.to_string());
}
if let Some(key_version) = key_version {
state.key_versions.insert(key_version);
}
if state.error_class.is_none() {
state.error_class = error_class;
}
}
/// Render the summary as audit tags, or nothing when the request performed
/// no KMS work at all (SSE-C and unencrypted objects never reach KMS).
pub fn audit_tags(&self) -> Vec<(&'static str, Value)> {
let Ok(state) = self.0.lock() else {
return Vec::new();
};
if !state.recorded {
return Vec::new();
}
let mut tags = Vec::with_capacity(5);
tags.push((KMS_AUDIT_TAG_SSE_TYPE, join_audit_values(state.sse_types.iter().copied())));
if !state.key_ids.is_empty() {
tags.push((KMS_AUDIT_TAG_KEY_ID, join_audit_values(state.key_ids.iter().map(String::as_str))));
}
if !state.key_versions.is_empty() {
tags.push((
KMS_AUDIT_TAG_KEY_VERSION,
join_audit_values(state.key_versions.iter().map(u32::to_string)),
));
}
let outcome = if state.error_class.is_some() { "failure" } else { "success" };
tags.push((KMS_AUDIT_TAG_OUTCOME, Value::String(outcome.to_string())));
if let Some(error_class) = state.error_class {
tags.push((KMS_AUDIT_TAG_ERROR_CLASS, Value::String(error_class.to_string())));
}
tags
}
}
/// Render a set of values as one tag value.
///
/// Always a string, including for the single-value case: a consumer that would
/// have to branch on the JSON type of a tag is a consumer that will get it
/// wrong for the request that happens to touch two keys.
fn join_audit_values(values: impl Iterator<Item = impl AsRef<str>>) -> Value {
let joined = values.map(|value| value.as_ref().to_string()).collect::<Vec<_>>();
Value::String(joined.join(KMS_AUDIT_VALUE_SEPARATOR))
}
/// Slots of the requests currently being audited, keyed by canonical request ID.
///
/// Only a weak reference is held: the owning [`KmsRequestAuditScope`] decides the
/// lifetime, so a scope that is somehow not dropped cannot keep a slot alive.
static KMS_REQUEST_AUDITS: LazyLock<Mutex<HashMap<String, Weak<KmsRequestAudit>>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
/// Registration of one request's KMS audit slot, dropped with the request's
/// audit entry.
pub struct KmsRequestAuditScope {
request_id: String,
audit: Arc<KmsRequestAudit>,
}
impl KmsRequestAuditScope {
/// Open a slot for `request_id`, so managed-SSE operations served under it can
/// be summarised onto its audit entry.
pub fn register(request_id: &str) -> Self {
let audit = Arc::new(KmsRequestAudit::default());
if let Ok(mut registry) = KMS_REQUEST_AUDITS.lock() {
registry.insert(request_id.to_string(), Arc::downgrade(&audit));
}
Self {
request_id: request_id.to_string(),
audit,
}
}
/// Tags describing the KMS work recorded under this request.
pub fn audit_tags(&self) -> Vec<(&'static str, Value)> {
self.audit.audit_tags()
}
}
impl Drop for KmsRequestAuditScope {
fn drop(&mut self) {
if let Ok(mut registry) = KMS_REQUEST_AUDITS.lock() {
registry.remove(&self.request_id);
}
}
}
/// Resolve the audit slot opened for `request_id`, if the request is being audited.
pub(crate) fn kms_request_audit(request_id: &str) -> Option<Arc<KmsRequestAudit>> {
KMS_REQUEST_AUDITS.lock().ok()?.get(request_id)?.upgrade()
}
/// Failure classes for data-path failures that never reached a KMS backend.
///
/// Backend failures carry the classification defined by the KMS audit contract;
/// everything else is classified at the S3 boundary it surfaced through.
pub(crate) fn kms_data_plane_error_class(error: &SseError) -> &'static str {
if let Some(failure) = error
.source
.as_ref()
.and_then(|source| source.downcast_ref::<KmsDataPlaneFailure>())
{
return failure.class;
}
match error.code {
S3ErrorCode::AccessDenied => "access_denied",
S3ErrorCode::InvalidArgument | S3ErrorCode::InvalidRequest => "invalid_argument",
_ => "sse_internal",
}
}
/// Carries a KMS failure class across the conversion to an S3-facing error.
///
/// The class is decided while the `KmsError` is still typed; re-deriving it from
/// a rendered message downstream would be guesswork.
#[derive(Debug)]
pub(crate) struct KmsDataPlaneFailure {
pub(crate) class: &'static str,
pub(crate) source: Option<Box<dyn std::error::Error + Send + Sync>>,
}
impl std::fmt::Display for KmsDataPlaneFailure {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.source {
Some(source) => source.fmt(formatter),
None => formatter.write_str(self.class),
}
}
}
impl std::error::Error for KmsDataPlaneFailure {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source
.as_ref()
.map(|source| source.as_ref() as &(dyn std::error::Error + 'static))
}
}
/// Record the outcome of one managed-SSE operation on the request's audit entry.
///
/// A `None` principal marks an internal caller — replication, lifecycle, heal —
/// which has no S3 audit entry to attach to. `key_version` is a closure for
/// exactly that caller: extracting the version means base64-decoding and
/// parsing the stored envelope, work that must not run on the internal hot
/// paths that discard it.
pub(crate) fn record_managed_kms_outcome(
principal: Option<&SseKmsPrincipal>,
sse_type: SSEType,
key_id: Option<&str>,
key_version: impl FnOnce() -> Option<u32>,
result: Result<(), &SseError>,
) {
let Some(audit) = principal.and_then(|principal| principal.request_audit.as_ref()) else {
return;
};
audit.record(sse_type, key_id, key_version(), result.err().map(kms_data_plane_error_class));
}
/// Master-key version recorded in a managed-SSE data-key envelope, if the
/// wrapping backend recorded one.
///
/// `None` is the honest answer for every other shape: Transit and AWS keep
/// the version inside their own opaque ciphertext, Local records no version,
/// and pre-versioning envelopes never carried the field. The single field is
/// read through `serde_json::Value` rather than a full `DataKeyEnvelope`
/// parse, so the audit path cannot double-count the envelope's unknown-field
/// observability and touches nothing else in the envelope.
pub(crate) fn envelope_master_key_version(envelope_bytes: &[u8]) -> Option<u32> {
if !is_data_key_envelope(envelope_bytes) {
return None;
}
u32::try_from(
serde_json::from_slice::<Value>(envelope_bytes)
.ok()?
.get("master_key_version")?
.as_u64()?,
)
.ok()
}
/// Master-key version of the envelope stored on an object, for the audit
/// summary of a read against that object.
pub(crate) fn stored_envelope_master_key_version(metadata: &HashMap<String, String>) -> Option<u32> {
// No context recoder: the recode only ever inserts the context key, which
// this lookup never reads, so the normalized result is identical without it.
let encoded = normalize_managed_metadata(metadata, None);
let encoded = encoded.get(INTERNAL_ENCRYPTION_KEY_HEADER)?;
let envelope = BASE64_STANDARD.decode_to_vec(encoded).ok()?;
envelope_master_key_version(&envelope)
}
-67
View File
@@ -1,67 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The encryption context a data key is bound to.
use crate::error::SseError;
use base64_simd::STANDARD as BASE64_STANDARD;
use rustfs_kms::types::ObjectEncryptionContext;
use rustfs_utils::http::object_encryption_keys::MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER;
use rustfs_utils::path::path_join_buf;
use std::collections::HashMap;
pub(crate) fn canonical_kms_bucket_path(bucket: &str, key: &str) -> String {
path_join_buf(&[bucket, key])
}
pub(crate) fn build_kms_request_context(
bucket: &str,
key: &str,
provided_context: Option<&HashMap<String, String>>,
) -> HashMap<String, String> {
let mut context = provided_context.cloned().unwrap_or_default();
context
.entry(bucket.to_string())
.or_insert_with(|| canonical_kms_bucket_path(bucket, key));
context
}
pub(crate) fn build_object_encryption_context(
bucket: &str,
key: &str,
provided_context: Option<&HashMap<String, String>>,
) -> ObjectEncryptionContext {
let mut context = ObjectEncryptionContext::new(bucket.to_string(), key.to_string());
for (ctx_key, ctx_value) in build_kms_request_context(bucket, key, provided_context) {
context = context.with_encryption_context(ctx_key, ctx_value);
}
context
}
pub(crate) fn encode_minio_kms_context(context: &HashMap<String, String>) -> Result<String, SseError> {
let encoded = serde_json::to_vec(context).map_err(|e| SseError::internal(format!("Failed to serialize KMS context: {e}")))?;
Ok(BASE64_STANDARD.encode_to_string(encoded))
}
pub(crate) fn decode_minio_kms_context(metadata: &HashMap<String, String>) -> Result<Option<HashMap<String, String>>, SseError> {
let Some(encoded) = metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER) else {
return Ok(None);
};
let decoded = BASE64_STANDARD
.decode_to_vec(encoded)
.map_err(|e| SseError::internal(format!("Failed to decode MinIO KMS context: {e}")))?;
serde_json::from_slice(&decoded)
.map(Some)
.map_err(|e| SseError::internal(format!("Failed to parse MinIO KMS context: {e}")))
}
-212
View File
@@ -1,212 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Direct keying: the data key encrypts the object itself, under a stored base nonce.
#[cfg(not(feature = "rio-v2"))]
use crate::core::keying::NewObjectKey;
#[cfg(not(feature = "rio-v2"))]
use crate::core::keying::material::EncryptionKeyKind;
use crate::core::keying::{StoredDataKey, StoredKeyMode};
use crate::error::SseError;
use crate::host::SseHost;
use base64_simd::STANDARD as BASE64_STANDARD;
use md5::{Digest as Md5Digest, Md5};
#[cfg(not(feature = "rio-v2"))]
use rand::Rng;
#[cfg(not(feature = "rio-v2"))]
use rustfs_kms::DataKey;
#[cfg(not(feature = "rio-v2"))]
use rustfs_utils::http::object_encryption_keys::SSEType;
use rustfs_utils::http::object_encryption_keys::{
INTERNAL_ENCRYPTION_ALGORITHM_HEADER, INTERNAL_ENCRYPTION_IV_HEADER, INTERNAL_ENCRYPTION_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_IV_HEADER,
};
use std::collections::HashMap;
/// SSE-C: record the base nonce the object is encrypted under.
///
/// The nonce is random, so decrypt reads it back instead of recomputing a
/// deterministic value. It is written under both the RustFS and the MinIO key per
/// repo convention. This covers a single PUT and a multipart session alike:
/// CreateMultipartUpload builds the session metadata through the same call.
pub(crate) fn record_customer_key_nonce(metadata: &mut HashMap<String, String>, base_nonce: [u8; 12]) {
metadata.insert(INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string(base_nonce));
metadata.insert(
MINIO_INTERNAL_ENCRYPTION_IV_HEADER.to_string(),
BASE64_STANDARD.encode_to_string(base_nonce),
);
}
/// Managed SSE: record the wrapped data key, the nonce issued with it, and the cipher.
pub(crate) fn record_wrapped_data_key(
metadata: &mut HashMap<String, String>,
wrapped_data_key: &[u8],
base_nonce: [u8; 12],
algorithm: &str,
) {
metadata.insert(
INTERNAL_ENCRYPTION_KEY_HEADER.to_string(),
BASE64_STANDARD.encode_to_string(wrapped_data_key),
);
metadata.insert(INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string(base_nonce));
metadata.insert(INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(), algorithm.to_string());
}
/// Managed SSE: read back what [`record_wrapped_data_key`] stored.
///
/// `normalized_metadata` is the object's metadata with the managed keys normalized.
pub(crate) async fn read_wrapped_data_key(
host: &dyn SseHost,
normalized_metadata: &HashMap<String, String>,
) -> Result<StoredDataKey, SseError> {
let (wrapped, iv, algorithm) = if let Some(service) = host.encryption_service().await {
// Production mode: use service for metadata parsing
let parsed = service
.headers_to_metadata(normalized_metadata)
.map_err(|e| SseError::internal(format!("Failed to parse encryption metadata: {e}")))?;
(parsed.encrypted_data_key, parsed.iv, parsed.algorithm)
} else {
// Test mode: parse metadata manually
let encrypted_key_b64 = normalized_metadata
.get(INTERNAL_ENCRYPTION_KEY_HEADER)
.ok_or_else(|| SseError::internal("Missing encrypted key in metadata"))?;
let encrypted_data_key = BASE64_STANDARD
.decode_to_vec(encrypted_key_b64)
.map_err(|e| SseError::internal(format!("Failed to decode encrypted key: {e}")))?;
let iv_b64 = normalized_metadata
.get(INTERNAL_ENCRYPTION_IV_HEADER)
.ok_or_else(|| SseError::internal("Missing IV in metadata"))?;
let iv = BASE64_STANDARD
.decode_to_vec(iv_b64)
.map_err(|e| SseError::internal(format!("Failed to decode IV: {e}")))?;
let algorithm = normalized_metadata
.get(INTERNAL_ENCRYPTION_ALGORITHM_HEADER)
.cloned()
.unwrap_or_else(|| "AES256".to_string());
(encrypted_data_key, iv, algorithm)
};
let base_nonce = <[u8; 12]>::try_from(iv.as_slice())
.map_err(|_| SseError::internal("Invalid encryption nonce length; expected 12 bytes"))?;
Ok(StoredDataKey {
wrapped,
algorithm,
mode: StoredKeyMode::Direct { base_nonce },
})
}
/// Resolve the SSE-C Direct base nonce for decryption.
///
/// New objects persist a random nonce at encryption time (see
/// [`record_customer_key_nonce`]) under `INTERNAL_ENCRYPTION_IV_HEADER` (preferred) or,
/// for MinIO interop, `MINIO_INTERNAL_ENCRYPTION_IV_HEADER`. Legacy objects written before
/// random nonces were persisted carry no stored IV; for those we fall back to the
/// deterministic `generate_ssec_nonce(bucket, key)` value they were originally encrypted
/// with, so previously stored objects still decrypt correctly.
pub(crate) fn read_stored_ssec_nonce(metadata: &HashMap<String, String>, bucket: &str, key: &str) -> [u8; 12] {
metadata
.get(INTERNAL_ENCRYPTION_IV_HEADER)
.or_else(|| metadata.get(MINIO_INTERNAL_ENCRYPTION_IV_HEADER))
.and_then(|encoded| BASE64_STANDARD.decode_to_vec(encoded).ok())
.and_then(|bytes| <[u8; 12]>::try_from(bytes.as_slice()).ok())
.unwrap_or_else(|| generate_ssec_nonce(bucket, key))
}
/// Generate deterministic nonce for SSE-C encryption
///
/// The nonce is derived from the bucket and key to ensure:
/// 1. Same object always gets the same nonce (required for SSE-C)
/// 2. Different objects get different nonces
pub(crate) fn generate_ssec_nonce(bucket: &str, key: &str) -> [u8; 12] {
let nonce_source = format!("{bucket}-{key}");
let nonce_hash: [u8; 16] = Md5::digest(nonce_source.as_bytes()).into();
let mut nonce = [0u8; 12];
nonce.copy_from_slice(&nonce_hash[..12]);
nonce
}
/// Whether a multipart session needs the customer key when it is created.
///
/// Direct mode records only a nonce for the session; the customer key is checked
/// per part, against what the session recorded.
#[cfg(not(feature = "rio-v2"))]
pub(crate) const SESSION_KEY_NEEDS_CUSTOMER_KEY: bool = false;
#[cfg(not(feature = "rio-v2"))]
fn random_base_nonce() -> [u8; 12] {
let mut base_nonce = [0u8; 12];
rand::rng().fill_bytes(&mut base_nonce);
base_nonce
}
/// SSE-C object: the customer key encrypts the object itself.
///
/// Uses a fresh random nonce per encryption. A deterministic nonce derived from
/// (bucket, key) would repeat whenever the same object is overwritten under the same
/// SSE-C key, reusing an identical (key, nonce) pair and catastrophically breaking
/// AES-256-GCM. The nonce is persisted (see [`record_customer_key_nonce`]) and read
/// back on decrypt (see [`read_stored_ssec_nonce`]).
#[cfg(not(feature = "rio-v2"))]
pub(crate) fn new_key_under_customer_key(customer_key: [u8; 32], _bucket: &str, _key: &str) -> Result<NewObjectKey, SseError> {
Ok(NewObjectKey {
key_bytes: customer_key,
base_nonce: random_base_nonce(),
key_kind: EncryptionKeyKind::Direct,
sealed_key: None,
})
}
/// SSE-C multipart session: a nonce every part of the upload shares.
///
/// Generates a real random nonce for the session and persists it (see
/// [`record_customer_key_nonce`]). Every part of this upload reads the same
/// persisted nonce back, so all parts share one nonce without reintroducing the
/// deterministic (bucket, key) reuse hazard. `key_bytes` stays a placeholder: it is
/// neither used for encryption nor persisted; the real customer key is validated per
/// part on upload.
#[cfg(not(feature = "rio-v2"))]
pub(crate) fn new_session_key_under_customer_key(
_customer_key: Option<[u8; 32]>,
_bucket: &str,
_key: &str,
) -> Result<NewObjectKey, SseError> {
Ok(NewObjectKey {
key_bytes: [0; 32],
base_nonce: random_base_nonce(),
key_kind: EncryptionKeyKind::Direct,
sealed_key: None,
})
}
/// Managed SSE: the data key encrypts the object itself, under the nonce issued with it.
#[cfg(not(feature = "rio-v2"))]
pub(crate) fn new_key_under_data_key(
data_key: &DataKey,
_sse_type: SSEType,
_bucket: &str,
_key: &str,
) -> Result<NewObjectKey, SseError> {
Ok(NewObjectKey {
key_bytes: data_key.plaintext_key,
base_nonce: data_key.nonce,
key_kind: EncryptionKeyKind::Direct,
sealed_key: None,
})
}
-115
View File
@@ -1,115 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The key material an encrypted write or read runs on.
#[cfg(feature = "rio-v2")]
use crate::core::keying::object::{SEALED_KEY_IV_SIZE, SEALED_KEY_SIZE};
use rustfs_utils::http::object_encryption_keys::SSEType;
use std::collections::HashMap;
/// Encryption material returned by [`sse_encryption`] / [`sse_prepare_encryption`].
pub struct EncryptionMaterial {
#[allow(unused)]
pub sse_type: SSEType,
pub server_side_encryption: String,
pub kms_key_id: Option<String>,
#[allow(unused)]
pub algorithm: String,
/// Encryption key bytes
pub key_bytes: [u8; 32],
/// Base nonce/IV used by rio to derive block/part nonces.
pub base_nonce: [u8; 12],
/// Encrypted DEK for managed SSE. Absent for SSE-C.
pub encrypted_data_key: Option<Vec<u8>>,
/// SSE-C key MD5 if customer-managed encryption is in use.
pub customer_key_md5: Option<String>,
/// Original plaintext size when it should be persisted alongside metadata.
pub original_size: Option<i64>,
/// Indicates whether `key_bytes` is a direct stream key or a MinIO-style object key.
pub key_kind: EncryptionKeyKind,
/// Original client-provided SSE-KMS context, stored in MinIO-compatible metadata.
pub managed_kms_context: Option<HashMap<String, String>>,
/// MinIO-compatible sealed object-key metadata for managed SSE object-key mode.
#[cfg_attr(not(feature = "rio-v2"), allow(dead_code))]
pub managed_sealed_key: Option<ManagedSealedKey>,
}
/// Decryption material returned by [`sse_decryption`].
pub struct DecryptionMaterial {
#[allow(unused)]
pub sse_type: SSEType,
pub server_side_encryption: String,
pub kms_key_id: Option<String>,
#[allow(unused)]
pub algorithm: String,
pub customer_key_md5: Option<String>, // if use SSE-C, check key md5
/// Decryption key bytes
pub key_bytes: [u8; 32],
/// Base nonce/IV used by rio to derive block/part nonces.
pub base_nonce: [u8; 12],
/// Indicates whether `key_bytes` is a direct stream key or a MinIO-style object key.
pub key_kind: EncryptionKeyKind,
}
impl std::fmt::Debug for EncryptionMaterial {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EncryptionMaterial")
.field("sse_type", &self.sse_type)
.field("server_side_encryption", &self.server_side_encryption)
.field("original_size", &self.original_size)
.finish_non_exhaustive()
}
}
impl std::fmt::Debug for DecryptionMaterial {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DecryptionMaterial")
.field("sse_type", &self.sse_type)
.field("server_side_encryption", &self.server_side_encryption)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EncryptionKeyKind {
Direct,
Object,
}
#[derive(Debug, Clone)]
pub struct ManagedSealedKey {
#[cfg(feature = "rio-v2")]
pub iv: [u8; SEALED_KEY_IV_SIZE],
#[cfg(feature = "rio-v2")]
pub sealed_key: [u8; SEALED_KEY_SIZE],
}
impl EncryptionMaterial {
/// The KMS key id a write response may advertise.
///
/// `kms_key_id` is always set for managed SSE because SSE-S3 also wraps
/// its data key under the service default key, but that key is an
/// internal detail of an `AES256` object: only an `aws:kms` object names
/// a key the caller can act on, and `x-amz-server-side-encryption-aws-kms-key-id`
/// is defined only for that scheme.
pub fn response_kms_key_id(&self) -> Option<String> {
matches!(self.sse_type, SSEType::SseKms)
.then(|| self.kms_key_id.clone())
.flatten()
}
}
-270
View File
@@ -1,270 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Encryption metadata as it is stored with the object.
use crate::core::keying::context::encode_minio_kms_context;
use crate::core::keying::direct::{record_customer_key_nonce, record_wrapped_data_key};
use crate::core::keying::material::{EncryptionKeyKind, EncryptionMaterial};
#[cfg(feature = "rio-v2")]
use crate::core::keying::object::{record_data_key_in_minio_slots, record_sealed_customer_key};
use crate::error::SseError;
use base64_simd::STANDARD as BASE64_STANDARD;
use rustfs_utils::http::object_encryption_keys::{
INTERNAL_ENCRYPTION_ALGORITHM_HEADER, INTERNAL_ENCRYPTION_CONTEXT_HEADER, INTERNAL_ENCRYPTION_IV_HEADER,
INTERNAL_ENCRYPTION_KEY_HEADER, INTERNAL_ENCRYPTION_KEY_ID_HEADER, INTERNAL_ENCRYPTION_ORIGINAL_SIZE_HEADER,
INTERNAL_ENCRYPTION_TAG_HEADER, MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER, MINIO_INTERNAL_ENCRYPTION_IV_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_MULTIPART_HEADER, MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER, SSEC_ORIGINAL_SIZE_HEADER, SSEType,
};
use std::borrow::Cow;
use std::collections::HashMap;
/// Two spellings of one encryption metadata key carry different values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConflictingEncryptionMetadata {
/// The canonical key whose case-variants disagree.
pub key: &'static str,
}
impl std::fmt::Display for ConflictingEncryptionMetadata {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "conflicting object encryption metadata for {}", self.key)
}
}
impl std::error::Error for ConflictingEncryptionMetadata {}
/// Fold case-variant spellings of the encryption metadata keys onto their canonical names.
///
/// # Errors
///
/// When two spellings of the same key hold different values: picking either
/// would decrypt with material the object may not have been written under.
pub fn normalize_encryption_metadata_case(
metadata: &HashMap<String, String>,
) -> Result<Cow<'_, HashMap<String, String>>, ConflictingEncryptionMetadata> {
const CANONICAL_KEYS: &[&str] = &[
"x-amz-server-side-encryption",
"x-amz-server-side-encryption-aws-kms-key-id",
"x-amz-server-side-encryption-customer-algorithm",
"x-amz-server-side-encryption-customer-key-md5",
SSEC_ORIGINAL_SIZE_HEADER,
INTERNAL_ENCRYPTION_KEY_ID_HEADER,
INTERNAL_ENCRYPTION_KEY_HEADER,
INTERNAL_ENCRYPTION_ALGORITHM_HEADER,
INTERNAL_ENCRYPTION_IV_HEADER,
INTERNAL_ENCRYPTION_CONTEXT_HEADER,
INTERNAL_ENCRYPTION_TAG_HEADER,
INTERNAL_ENCRYPTION_ORIGINAL_SIZE_HEADER,
MINIO_INTERNAL_ENCRYPTION_MULTIPART_HEADER,
MINIO_INTERNAL_ENCRYPTION_IV_HEADER,
MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER,
MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER,
];
let needs_normalization = metadata.keys().any(|key| {
CANONICAL_KEYS
.iter()
.any(|canonical| key != canonical && key.eq_ignore_ascii_case(canonical))
});
if !needs_normalization {
return Ok(Cow::Borrowed(metadata));
}
let mut normalized = metadata.clone();
for canonical in CANONICAL_KEYS {
let mut matching_values = metadata
.iter()
.filter_map(|(key, value)| key.eq_ignore_ascii_case(canonical).then_some(value));
let Some(value) = matching_values.next() else {
continue;
};
if matching_values.any(|candidate| candidate != value) {
return Err(ConflictingEncryptionMetadata { key: canonical });
}
if !normalized.contains_key(*canonical) {
normalized.insert((*canonical).to_string(), value.clone());
}
}
Ok(Cow::Owned(normalized))
}
/// Turn the material of an encrypted write into the metadata stored with the object.
///
/// The scheme is recorded here. How the key itself is recorded belongs to the mode
/// that formed it, in `direct.rs` and `object.rs`, next to the code that reads it back.
pub fn encryption_material_to_metadata(material: &EncryptionMaterial) -> Result<HashMap<String, String>, SseError> {
let mut metadata = HashMap::new();
match material.sse_type {
SSEType::SseC => {
record_ssec_scheme(&mut metadata, material);
// A `rio-v2` build seals an object key instead, so a Direct key there is a
// multipart session created without its customer key.
if material.key_kind == EncryptionKeyKind::Direct {
record_customer_key_nonce(&mut metadata, material.base_nonce);
}
#[cfg(feature = "rio-v2")]
if let Some(sealed) = &material.managed_sealed_key {
record_sealed_customer_key(&mut metadata, sealed);
}
}
SSEType::SseS3 | SSEType::SseKms => {
let wrapped_data_key = material
.encrypted_data_key
.as_deref()
.ok_or_else(|| SseError::internal("managed SSE materials must carry an encrypted data key"))?;
record_managed_scheme(&mut metadata, material);
if material.key_kind == EncryptionKeyKind::Direct {
record_wrapped_data_key(&mut metadata, wrapped_data_key, material.base_nonce, material.algorithm.as_str());
}
#[cfg(feature = "rio-v2")]
record_data_key_in_minio_slots(&mut metadata, material, wrapped_data_key);
}
}
Ok(metadata)
}
/// SSE-C: the scheme, the fingerprint of the customer key, and the plaintext size.
fn record_ssec_scheme(metadata: &mut HashMap<String, String>, material: &EncryptionMaterial) {
metadata.insert(
"x-amz-server-side-encryption".to_string(),
material.server_side_encryption.as_str().to_string(),
);
metadata.insert(
"x-amz-server-side-encryption-customer-algorithm".to_string(),
material.algorithm.as_str().to_string(),
);
if let Some(customer_key_md5) = &material.customer_key_md5 {
metadata.insert("x-amz-server-side-encryption-customer-key-md5".to_string(), customer_key_md5.to_string());
}
if let Some(original_size) = material.original_size {
metadata.insert(SSEC_ORIGINAL_SIZE_HEADER.to_string(), original_size.to_string());
}
}
/// Managed SSE: the scheme, the key the data key is wrapped under, the plaintext
/// size, and the encryption context of the request.
fn record_managed_scheme(metadata: &mut HashMap<String, String>, material: &EncryptionMaterial) {
metadata.insert(
"x-amz-server-side-encryption".to_string(),
material.server_side_encryption.as_str().to_string(),
);
let internal_key_id = material.kms_key_id.clone().unwrap_or_else(|| "default".to_string());
metadata.insert(INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), internal_key_id.clone());
if matches!(material.sse_type, SSEType::SseKms) {
metadata.insert("x-amz-server-side-encryption-aws-kms-key-id".to_string(), internal_key_id);
}
if let Some(original_size) = material.original_size {
metadata.insert(INTERNAL_ENCRYPTION_ORIGINAL_SIZE_HEADER.to_string(), original_size.to_string());
}
if let Some(kms_context) = &material.managed_kms_context
&& !kms_context.is_empty()
{
if let Ok(serialized) = serde_json::to_string(kms_context) {
metadata.insert(INTERNAL_ENCRYPTION_CONTEXT_HEADER.to_string(), serialized);
}
if matches!(material.sse_type, SSEType::SseKms)
&& let Ok(encoded) = encode_minio_kms_context(kms_context)
{
metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER.to_string(), encoded);
}
}
}
/// Strip source encryption metadata before constructing metadata for a copy destination.
///
/// Encryption metadata describes the physical source representation and must never be
/// inherited by a plaintext destination or by a destination using a different key.
pub fn strip_managed_encryption_metadata(metadata: &mut HashMap<String, String>) {
const KEYS: [&str; 21] = [
"x-amz-server-side-encryption",
"x-amz-server-side-encryption-aws-kms-key-id",
"x-amz-server-side-encryption-customer-algorithm",
"x-amz-server-side-encryption-customer-key-md5",
SSEC_ORIGINAL_SIZE_HEADER,
INTERNAL_ENCRYPTION_KEY_ID_HEADER,
INTERNAL_ENCRYPTION_ALGORITHM_HEADER,
INTERNAL_ENCRYPTION_IV_HEADER,
INTERNAL_ENCRYPTION_TAG_HEADER,
INTERNAL_ENCRYPTION_KEY_HEADER,
INTERNAL_ENCRYPTION_CONTEXT_HEADER,
INTERNAL_ENCRYPTION_ORIGINAL_SIZE_HEADER,
MINIO_INTERNAL_ENCRYPTION_MULTIPART_HEADER,
MINIO_INTERNAL_ENCRYPTION_IV_HEADER,
MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER,
MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER,
];
for key in KEYS.iter() {
metadata.remove(*key);
}
rustfs_utils::http::metadata_compat::remove_str(metadata, rustfs_utils::http::SUFFIX_OPAQUE_ENCRYPTED_ETAG);
}
pub fn mark_encrypted_multipart_metadata(metadata: &mut HashMap<String, String>) {
metadata.insert(MINIO_INTERNAL_ENCRYPTION_MULTIPART_HEADER.to_string(), String::new());
}
/// True when the stored metadata marks the object as SSE-C protected.
///
/// RustFS persists the public `x-amz-server-side-encryption-customer-algorithm`
/// key on SSE-C writes. MinIO persists only its internal sealed-key slot and
/// synthesizes the public header onto responses (backlog#1638), so the slot is
/// the only durable evidence on a MinIO-written object. That shape is readable
/// solely through the rio-v2 sealed-object-key path, so it participates in
/// detection only in builds that can actually read it — default builds keep
/// the resolver's fail-closed diagnosis instead of demanding customer keys
/// they could not use.
pub fn stored_ssec_metadata(metadata: &HashMap<String, String>) -> bool {
metadata.contains_key("x-amz-server-side-encryption-customer-algorithm") || minio_sealed_ssec_metadata(metadata)
}
/// True when the object carries MinIO's SSE-C sealed-key slot — the shape that
/// stores no customer-key MD5 and proves the key through the AEAD unseal
/// instead.
pub(crate) fn minio_sealed_ssec_metadata(metadata: &HashMap<String, String>) -> bool {
cfg!(feature = "rio-v2") && metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER)
}
/// Recodes a stored MinIO KMS context value (base64-wrapped JSON) into the
/// plain-JSON form RustFS stores under [`INTERNAL_ENCRYPTION_CONTEXT_HEADER`].
///
/// Injected into the shared [`normalize_managed_metadata`] because the shared
/// crate carries no JSON codec; any decode failure returns `None`, which skips
/// the context mapping exactly like the historical inline `if let Ok` chain.
pub(crate) fn recode_minio_kms_context(value: &str) -> Option<String> {
let decoded = BASE64_STANDARD.decode_to_vec(value).ok()?;
let context = serde_json::from_slice::<HashMap<String, String>>(&decoded).ok()?;
serde_json::to_string(&context).ok()
}
-67
View File
@@ -1,67 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The internal keying modes: how an object's key is formed and how it is stored.
pub(crate) mod context;
pub(crate) mod direct;
pub(crate) mod material;
pub(crate) mod metadata;
#[cfg(feature = "rio-v2")]
pub(crate) mod object;
pub(crate) mod stored;
use crate::core::keying::material::{EncryptionKeyKind, ManagedSealedKey};
/// The key a new object is encrypted with, in the mode this build writes.
pub(crate) struct NewObjectKey {
/// Key handed to the stream cipher.
pub(crate) key_bytes: [u8; 32],
/// Base nonce the stream cipher derives its block nonces from.
pub(crate) base_nonce: [u8; 12],
/// The mode `key_bytes` belongs to.
pub(crate) key_kind: EncryptionKeyKind,
/// The sealed form to store, in a mode that seals a separate object key.
pub(crate) sealed_key: Option<ManagedSealedKey>,
}
/// A managed-SSE data key as a stored object recorded it, still wrapped.
pub(crate) struct StoredDataKey {
/// The data key, wrapped by the provider that issued it.
pub(crate) wrapped: Vec<u8>,
/// The cipher the object recorded.
pub(crate) algorithm: String,
/// What the data key is to the object once it is unwrapped.
pub(crate) mode: StoredKeyMode,
}
/// The mode a stored key was recorded in.
pub(crate) enum StoredKeyMode {
/// The data key is the object's key, under the nonce stored beside it.
Direct { base_nonce: [u8; 12] },
/// The data key unseals the object's key.
#[cfg(feature = "rio-v2")]
Object { sealed_key: ManagedSealedKey },
}
// The mode new objects are written in. Every build reads every mode it can
// recognize; writing picks exactly one, and this is the only place that says which.
#[cfg(not(feature = "rio-v2"))]
pub(crate) use direct::{
SESSION_KEY_NEEDS_CUSTOMER_KEY, new_key_under_customer_key, new_key_under_data_key, new_session_key_under_customer_key,
};
#[cfg(feature = "rio-v2")]
pub(crate) use object::{
SESSION_KEY_NEEDS_CUSTOMER_KEY, new_key_under_customer_key, new_key_under_data_key, new_session_key_under_customer_key,
};
-436
View File
@@ -1,436 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Object keying: a derived object key, sealed in the MinIO-compatible format.
use crate::core::keying::material::{EncryptionKeyKind, EncryptionMaterial, ManagedSealedKey};
use crate::core::keying::{NewObjectKey, StoredDataKey, StoredKeyMode};
use crate::error::SseError;
use aes_gcm::aead::{Aead, KeyInit, Payload};
use aes_gcm::{Aes256Gcm, Nonce};
use base64_simd::STANDARD as BASE64_STANDARD;
use chacha20poly1305::ChaCha20Poly1305;
use hmac::{Hmac, Mac};
use rand::RngExt;
use rustfs_kms::DataKey;
use rustfs_utils::http::object_encryption_keys::{
INTERNAL_ENCRYPTION_ALGORITHM_HEADER, INTERNAL_ENCRYPTION_IV_HEADER, INTERNAL_ENCRYPTION_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER, MINIO_INTERNAL_ENCRYPTION_IV_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER, MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER, SSEType,
};
use sha2::Sha256;
use std::collections::HashMap;
pub(crate) const MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM: &str = "DAREv2-HMAC-SHA256";
const DARE_VERSION_20: u8 = 0x20;
pub(crate) const DARE_CIPHER_AES_256_GCM: u8 = 0x00;
pub(crate) const DARE_CIPHER_CHACHA20_POLY1305: u8 = 0x01;
const DARE_HEADER_SIZE: usize = 16;
const DARE_TAG_SIZE: usize = 16;
pub(crate) const SEALED_KEY_IV_SIZE: usize = 32;
pub(crate) const SEALED_KEY_SIZE: usize = DARE_HEADER_SIZE + 32 + DARE_TAG_SIZE;
const OBJECT_KEY_DERIVATION_CONTEXT: &[u8] = b"object-encryption-key generation";
pub(crate) type HmacSha256 = Hmac<Sha256>;
fn managed_sse_domain(sse_type: SSEType) -> &'static str {
match sse_type {
SSEType::SseS3 => "SSE-S3",
SSEType::SseKms => "SSE-KMS",
SSEType::SseC => "SSE-C",
}
}
pub(crate) fn is_supported_sealed_object_key_cipher(cipher: u8) -> bool {
matches!(cipher, DARE_CIPHER_AES_256_GCM | DARE_CIPHER_CHACHA20_POLY1305)
}
fn decrypt_sealed_object_key_payload(sealing_key: [u8; 32], header: &[u8], sealed_key: &[u8]) -> Result<Vec<u8>, SseError> {
let nonce = &header[4..16];
let ciphertext = &sealed_key[DARE_HEADER_SIZE..];
let aad = &header[..4];
match header[1] {
DARE_CIPHER_AES_256_GCM => {
let cipher = Aes256Gcm::new_from_slice(&sealing_key)
.map_err(|err| SseError::internal(format!("Invalid AES-GCM sealing key: {err}")))?;
let nonce = Nonce::try_from(nonce).map_err(|_| SseError::internal("Invalid sealed object-key package nonce"))?;
cipher.decrypt(&nonce, Payload { msg: ciphertext, aad })
}
DARE_CIPHER_CHACHA20_POLY1305 => {
let cipher = ChaCha20Poly1305::new_from_slice(&sealing_key)
.map_err(|err| SseError::internal(format!("Invalid ChaCha20-Poly1305 sealing key: {err}")))?;
let nonce = chacha20poly1305::Nonce::try_from(nonce)
.map_err(|_| SseError::internal("Invalid sealed object-key package nonce"))?;
cipher.decrypt(&nonce, Payload { msg: ciphertext, aad })
}
_ => return Err(SseError::internal("Unsupported sealed object-key DARE header")),
}
.map_err(|err| SseError::internal(format!("Failed to unseal object key: {err}")))
}
fn canonical_sse_path(bucket: &str, object: &str) -> String {
let bucket = bucket.trim_matches('/');
let object = object.trim_matches('/');
if object.is_empty() {
bucket.to_string()
} else if bucket.is_empty() {
object.to_string()
} else {
format!("{bucket}/{object}")
}
}
pub(crate) fn derive_object_key(external_key: [u8; 32]) -> Result<[u8; 32], SseError> {
let mut random = [0u8; 32];
rand::rng().fill(&mut random);
let mut mac = HmacSha256::new_from_slice(&external_key)
.map_err(|err| SseError::internal(format!("Invalid HMAC key for object-key derivation: {err}")))?;
mac.update(OBJECT_KEY_DERIVATION_CONTEXT);
mac.update(&random);
let mut object_key = [0u8; 32];
object_key.copy_from_slice(mac.finalize().into_bytes().as_slice());
Ok(object_key)
}
fn derive_sealing_key(
external_key: [u8; 32],
iv: [u8; SEALED_KEY_IV_SIZE],
domain: &str,
bucket: &str,
object: &str,
) -> Result<[u8; 32], SseError> {
let mut mac = HmacSha256::new_from_slice(&external_key)
.map_err(|err| SseError::internal(format!("Invalid HMAC key for sealing-key derivation: {err}")))?;
mac.update(&iv);
mac.update(domain.as_bytes());
mac.update(MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM.as_bytes());
mac.update(canonical_sse_path(bucket, object).as_bytes());
let mut sealing_key = [0u8; 32];
sealing_key.copy_from_slice(mac.finalize().into_bytes().as_slice());
Ok(sealing_key)
}
pub(crate) fn seal_object_key(
object_key: [u8; 32],
external_key: [u8; 32],
sse_type: SSEType,
bucket: &str,
object: &str,
) -> Result<ManagedSealedKey, SseError> {
let mut iv = [0u8; SEALED_KEY_IV_SIZE];
rand::rng().fill(&mut iv);
let sealing_key = derive_sealing_key(external_key, iv, managed_sse_domain(sse_type), bucket, object)?;
let mut header = [0u8; DARE_HEADER_SIZE];
header[0] = DARE_VERSION_20;
header[1] = DARE_CIPHER_AES_256_GCM;
header[2..4].copy_from_slice(&(31u16).to_le_bytes());
let mut stream_nonce = [0u8; 12];
rand::rng().fill(&mut stream_nonce);
stream_nonce[0] |= 0x80;
header[4..16].copy_from_slice(&stream_nonce);
let cipher =
Aes256Gcm::new_from_slice(&sealing_key).map_err(|err| SseError::internal(format!("Invalid sealing key: {err}")))?;
let nonce =
Nonce::try_from(stream_nonce.as_slice()).map_err(|_| SseError::internal("Invalid sealed object-key stream nonce"))?;
let ciphertext = cipher
.encrypt(
&nonce,
aes_gcm::aead::Payload {
msg: &object_key,
aad: &header[..4],
},
)
.map_err(|err| SseError::internal(format!("Failed to seal object key: {err}")))?;
let mut sealed_key = [0u8; SEALED_KEY_SIZE];
sealed_key[..DARE_HEADER_SIZE].copy_from_slice(&header);
sealed_key[DARE_HEADER_SIZE..].copy_from_slice(&ciphertext);
Ok(ManagedSealedKey { iv, sealed_key })
}
pub(crate) fn unseal_object_key(
sealed: &ManagedSealedKey,
external_key: [u8; 32],
sse_type: SSEType,
bucket: &str,
object: &str,
) -> Result<[u8; 32], SseError> {
let header = &sealed.sealed_key[..DARE_HEADER_SIZE];
if header[0] != DARE_VERSION_20 || !is_supported_sealed_object_key_cipher(header[1]) {
return Err(SseError::internal("Unsupported sealed object-key DARE header"));
}
if u16::from_le_bytes([header[2], header[3]]) != 31 || header[4] & 0x80 == 0 {
return Err(SseError::internal("Invalid sealed object-key payload header"));
}
let sealing_key = derive_sealing_key(external_key, sealed.iv, managed_sse_domain(sse_type), bucket, object)?;
let plaintext = decrypt_sealed_object_key_payload(sealing_key, header, &sealed.sealed_key)?;
let object_key: [u8; 32] = plaintext
.as_slice()
.try_into()
.map_err(|_| SseError::internal("Sealed object key must decrypt to 32 bytes"))?;
Ok(object_key)
}
fn try_decode_minio_sealed_key(bytes: &str) -> Result<Option<[u8; SEALED_KEY_SIZE]>, SseError> {
let decoded = BASE64_STANDARD
.decode_to_vec(bytes)
.map_err(|e| SseError::internal(format!("Failed to decode sealed object key: {e}")))?;
match decoded.as_slice().try_into() {
Ok(sealed_key) => Ok(Some(sealed_key)),
Err(_) => Ok(None),
}
}
fn try_decode_minio_sealing_iv(bytes: &str) -> Result<Option<[u8; SEALED_KEY_IV_SIZE]>, SseError> {
let decoded = BASE64_STANDARD
.decode_to_vec(bytes)
.map_err(|e| SseError::internal(format!("Failed to decode sealing IV: {e}")))?;
match decoded.as_slice().try_into() {
Ok(iv) => Ok(Some(iv)),
Err(_) => Ok(None),
}
}
pub(crate) fn is_legacy_rustfs_managed_metadata(metadata: &HashMap<String, String>) -> bool {
metadata.contains_key(INTERNAL_ENCRYPTION_KEY_HEADER)
&& metadata.contains_key(INTERNAL_ENCRYPTION_IV_HEADER)
&& !metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER)
&& !metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER)
}
/// Infer the managed SSE scheme from the MinIO sealed-key slot that is present.
///
/// Returns `None` when no managed MinIO slot is present, which keeps callers on
/// their fail-closed path. SSE-C is not a managed scheme and is handled by the
/// SSE-C read path, so its slot is not considered here.
pub(crate) fn infer_minio_managed_sse_type(metadata: &HashMap<String, String>) -> Option<SSEType> {
if metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER) {
Some(SSEType::SseS3)
} else if metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER) {
Some(SSEType::SseKms)
} else {
None
}
}
pub(crate) fn parse_minio_managed_sealed_key(
metadata: &HashMap<String, String>,
sse_type: SSEType,
) -> Result<Option<ManagedSealedKey>, SseError> {
let algorithm = match metadata.get(MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER) {
Some(algorithm) => algorithm,
None => return Ok(None),
};
if algorithm != MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM {
return Ok(None);
}
let iv = match metadata.get(MINIO_INTERNAL_ENCRYPTION_IV_HEADER) {
Some(iv) => match try_decode_minio_sealing_iv(iv)? {
Some(iv) => iv,
None => return Ok(None),
},
None => return Ok(None),
};
let header_key = match sse_type {
SSEType::SseS3 => MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER,
SSEType::SseKms => MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER,
SSEType::SseC => MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER,
};
let sealed_key = match metadata.get(header_key) {
Some(value) => match try_decode_minio_sealed_key(value)? {
Some(sealed_key) => sealed_key,
None => return Ok(None),
},
None => return Ok(None),
};
Ok(Some(ManagedSealedKey { iv, sealed_key }))
}
/// SSE-C: record the object key sealed under the customer key.
pub(crate) fn record_sealed_customer_key(metadata: &mut HashMap<String, String>, sealed: &ManagedSealedKey) {
metadata.insert(
MINIO_INTERNAL_ENCRYPTION_IV_HEADER.to_string(),
BASE64_STANDARD.encode_to_string(sealed.iv),
);
metadata.insert(
MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(),
MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM.to_string(),
);
metadata.insert(
MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER.to_string(),
BASE64_STANDARD.encode_to_string(sealed.sealed_key),
);
}
/// Managed SSE: record the wrapped data key in MinIO's slots.
///
/// With a sealed object key the slots hold what MinIO itself writes. Without one
/// the key was formed in Direct mode, and the slots mirror its wrapped data key and
/// nonce: [`parse_minio_managed_sealed_key`] turns that shape down by its length, so
/// the object is read back in Direct mode.
pub(crate) fn record_data_key_in_minio_slots(
metadata: &mut HashMap<String, String>,
material: &EncryptionMaterial,
wrapped_data_key: &[u8],
) {
metadata.insert(
MINIO_INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(),
MINIO_INTERNAL_ENCRYPTION_SEAL_ALGORITHM.to_string(),
);
if let Some(kms_key_id) = &material.kms_key_id {
metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER.to_string(), kms_key_id.to_string());
}
let encoded_data_key = BASE64_STANDARD.encode_to_string(wrapped_data_key);
match &material.managed_sealed_key {
Some(sealed) => {
metadata.insert(
MINIO_INTERNAL_ENCRYPTION_IV_HEADER.to_string(),
BASE64_STANDARD.encode_to_string(sealed.iv),
);
match material.sse_type {
SSEType::SseS3 => {
metadata.insert(
MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER.to_string(),
BASE64_STANDARD.encode_to_string(sealed.sealed_key),
);
}
SSEType::SseKms => {
metadata.insert(
MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_string(),
BASE64_STANDARD.encode_to_string(sealed.sealed_key),
);
}
SSEType::SseC => {}
}
metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), encoded_data_key);
}
None => {
metadata.insert(
MINIO_INTERNAL_ENCRYPTION_IV_HEADER.to_string(),
BASE64_STANDARD.encode_to_string(material.base_nonce),
);
match material.sse_type {
SSEType::SseS3 => {
metadata.insert(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER.to_string(), encoded_data_key);
}
SSEType::SseKms => {
metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER.to_string(), encoded_data_key.clone());
metadata.insert(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER.to_string(), encoded_data_key);
}
SSEType::SseC => {}
}
}
}
}
/// Managed SSE: read back the wrapped data key that seals `sealed_key`.
///
/// `normalized_metadata` is `metadata` with the managed keys normalized.
pub(crate) fn read_sealed_data_key(
metadata: &HashMap<String, String>,
normalized_metadata: &HashMap<String, String>,
sealed_key: ManagedSealedKey,
) -> Result<StoredDataKey, SseError> {
let encrypted_key_b64 = normalized_metadata
.get(INTERNAL_ENCRYPTION_KEY_HEADER)
.or_else(|| metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER))
.ok_or_else(|| SseError::internal("Missing encrypted key in metadata"))?;
let wrapped = BASE64_STANDARD
.decode_to_vec(encrypted_key_b64)
.map_err(|e| SseError::internal(format!("Failed to decode encrypted key: {e}")))?;
Ok(StoredDataKey {
wrapped,
algorithm: normalized_metadata
.get(INTERNAL_ENCRYPTION_ALGORITHM_HEADER)
.cloned()
.unwrap_or_else(|| "AES256".to_string()),
mode: StoredKeyMode::Object { sealed_key },
})
}
/// Whether a multipart session needs the customer key when it is created.
///
/// Object mode seals the session's object key under the customer key, so the key
/// has to be present, and valid, at that point.
pub(crate) const SESSION_KEY_NEEDS_CUSTOMER_KEY: bool = true;
/// Derive a fresh object key from `external_key` and seal it under the same key.
fn new_sealed_object_key(external_key: [u8; 32], sse_type: SSEType, bucket: &str, key: &str) -> Result<NewObjectKey, SseError> {
let object_key = derive_object_key(external_key)?;
let sealed_key = seal_object_key(object_key, external_key, sse_type, bucket, key)?;
Ok(NewObjectKey {
key_bytes: object_key,
base_nonce: [0; 12],
key_kind: EncryptionKeyKind::Object,
sealed_key: Some(sealed_key),
})
}
/// SSE-C object: an object key sealed under the customer key.
pub(crate) fn new_key_under_customer_key(customer_key: [u8; 32], bucket: &str, key: &str) -> Result<NewObjectKey, SseError> {
new_sealed_object_key(customer_key, SSEType::SseC, bucket, key)
}
/// SSE-C multipart session: an object key sealed under the customer key.
///
/// A session created without its customer key has nothing to seal and records a
/// placeholder instead.
pub(crate) fn new_session_key_under_customer_key(
customer_key: Option<[u8; 32]>,
bucket: &str,
key: &str,
) -> Result<NewObjectKey, SseError> {
match customer_key {
Some(customer_key) => new_sealed_object_key(customer_key, SSEType::SseC, bucket, key),
None => Ok(NewObjectKey {
key_bytes: [0; 32],
base_nonce: [0; 12],
key_kind: EncryptionKeyKind::Direct,
sealed_key: None,
}),
}
}
/// Managed SSE: an object key sealed under the data key.
pub(crate) fn new_key_under_data_key(
data_key: &DataKey,
sse_type: SSEType,
bucket: &str,
key: &str,
) -> Result<NewObjectKey, SseError> {
new_sealed_object_key(data_key.plaintext_key, sse_type, bucket, key)
}
-253
View File
@@ -1,253 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Reading: recognize how a stored object was keyed, and recover its key.
//!
//! What an object recorded is the only source of truth here. The scheme a request
//! advertises and whether a KMS is running now are write policy and runtime state;
//! neither says how an object written earlier was keyed.
use crate::core::keying::context::{build_object_encryption_context, decode_minio_kms_context};
use crate::core::keying::direct::{read_stored_ssec_nonce, read_wrapped_data_key};
use crate::core::keying::material::EncryptionKeyKind;
use crate::core::keying::metadata::recode_minio_kms_context;
#[cfg(feature = "rio-v2")]
use crate::core::keying::object::{
infer_minio_managed_sse_type, is_legacy_rustfs_managed_metadata, parse_minio_managed_sealed_key, read_sealed_data_key,
unseal_object_key,
};
use crate::core::keying::{StoredDataKey, StoredKeyMode};
use crate::error::SseError;
use crate::host::SseHost;
use crate::kms::local::is_local_sse_dek;
#[cfg(feature = "rio-v2")]
use crate::kms::local::is_rustfs_managed_data_key;
#[cfg(feature = "rio-v2")]
use crate::kms::provider::decrypt_unenveloped_sealed_dek;
use crate::kms::provider::{SseDekProvider, bare_data_key_kms_provider, get_local_sse_dek_provider, kms_sse_dek_provider};
use rustfs_kms::is_data_key_envelope;
use rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS;
use rustfs_utils::http::object_encryption_keys::{
INTERNAL_ENCRYPTION_KEY_ID_HEADER, SSEType, contains_managed_encryption_metadata, normalize_managed_metadata,
};
use std::collections::HashMap;
use std::sync::Arc;
/// The key a stored object is decrypted with, recovered from what the object recorded.
pub(crate) struct OpenedObjectKey {
/// Key handed to the stream cipher.
pub(crate) key_bytes: [u8; 32],
/// Base nonce the stream cipher derives its block nonces from.
pub(crate) base_nonce: [u8; 12],
/// The mode the object was written in.
pub(crate) key_kind: EncryptionKeyKind,
}
/// The managed scheme a stored object was written under, or `None` when this build
/// cannot establish it.
fn stored_managed_sse_type(metadata: &HashMap<String, String>) -> Option<SSEType> {
match metadata.get("x-amz-server-side-encryption").map(String::as_str) {
Some(AMZ_ENCRYPTION_KMS) => Some(SSEType::SseKms),
Some(_) => Some(SSEType::SseS3),
// MinIO never persists the public scheme header: `crypto.S3.CreateMetadata`
// writes only the `X-Minio-Internal-*` family and the public header is
// synthesized onto the response by `DecryptObjectInfo`. Requiring it here
// is what made every MinIO-encrypted object unreadable (backlog#1638).
//
// Inferring from the sealed-key slot is self-consistent by construction:
// the slot decides which header the unseal reads AND which domain string
// the sealing key is derived under, so a scheme that disagrees with the
// slot cannot silently derive a wrong key — it finds no key at all.
// Inferring from the KMS key id would NOT be safe: MinIO writes
// `-S3-Kms-Key-Id` on SSE-S3 objects too.
//
// An object whose scheme cannot be established stays fail-closed, and
// deliberately not through an error raised here: the read plan independently
// classifies the object as encrypted from its markers and refuses to serve
// it without material, so it never degrades into a plaintext read.
#[cfg(feature = "rio-v2")]
None => infer_minio_managed_sse_type(metadata),
// Without the rio-v2 reader there is no MinIO-format read path to serve
// such an object with, so it stays on the fail-closed branch.
#[cfg(not(feature = "rio-v2"))]
None => None,
}
}
/// SSE-C: recover the object's key from the customer key.
///
/// A sealed object key recorded in MinIO's slot is unsealed under the customer key;
/// otherwise the customer key is the object's key, under the nonce the object recorded.
pub(crate) fn open_under_customer_key(
metadata: &HashMap<String, String>,
customer_key: [u8; 32],
bucket: &str,
key: &str,
) -> Result<OpenedObjectKey, SseError> {
#[cfg(feature = "rio-v2")]
if let Some(sealed_key) = parse_minio_managed_sealed_key(metadata, SSEType::SseC)? {
return Ok(OpenedObjectKey {
key_bytes: unseal_object_key(&sealed_key, customer_key, SSEType::SseC, bucket, key)?,
base_nonce: [0; 12],
key_kind: EncryptionKeyKind::Object,
});
}
Ok(OpenedObjectKey {
key_bytes: customer_key,
base_nonce: read_stored_ssec_nonce(metadata, bucket, key),
key_kind: EncryptionKeyKind::Direct,
})
}
/// A stored managed-SSE object, as recognized from its metadata alone.
pub(crate) struct StoredManagedKey<'a> {
/// The object's metadata as stored.
metadata: &'a HashMap<String, String>,
/// The same metadata with the managed keys normalized.
normalized_metadata: HashMap<String, String>,
/// The scheme the object was written under.
pub(crate) sse_type: SSEType,
/// The KMS key id the object recorded, if it recorded one.
pub(crate) recorded_kms_key_id: Option<String>,
}
/// Recognize a stored managed-SSE object.
///
/// `None` means the object carries no managed-SSE metadata, or carries some whose
/// scheme this build cannot establish.
pub(crate) fn recognize_stored_managed_key(metadata: &HashMap<String, String>) -> Option<StoredManagedKey<'_>> {
if !contains_managed_encryption_metadata(metadata) {
return None;
}
let sse_type = stored_managed_sse_type(metadata)?;
let normalized_metadata = normalize_managed_metadata(metadata, Some(recode_minio_kms_context));
let recorded_kms_key_id = normalized_metadata
.get(INTERNAL_ENCRYPTION_KEY_ID_HEADER)
.or_else(|| metadata.get("x-amz-server-side-encryption-aws-kms-key-id"))
.cloned();
Some(StoredManagedKey {
metadata,
normalized_metadata,
sse_type,
recorded_kms_key_id,
})
}
/// Managed SSE: unwrap the stored data key and recover the object's key from it.
///
/// `kms_key_id` is the key the read was authorized against. Returns the object's key
/// together with the algorithm the object recorded.
pub(crate) async fn open_under_stored_data_key(
host: &dyn SseHost,
bucket: &str,
key: &str,
stored: &StoredManagedKey<'_>,
kms_key_id: &str,
) -> Result<(OpenedObjectKey, String), SseError> {
let record = read_stored_data_key(host, stored).await?;
let data_key = unwrap_stored_data_key(host, bucket, key, stored, &record, kms_key_id).await?;
let opened = match record.mode {
StoredKeyMode::Direct { base_nonce } => OpenedObjectKey {
key_bytes: data_key,
base_nonce,
key_kind: EncryptionKeyKind::Direct,
},
#[cfg(feature = "rio-v2")]
StoredKeyMode::Object { sealed_key } => OpenedObjectKey {
key_bytes: unseal_object_key(&sealed_key, data_key, stored.sse_type, bucket, key)?,
base_nonce: [0u8; 12],
key_kind: EncryptionKeyKind::Object,
},
};
Ok((opened, record.algorithm))
}
/// Read the stored data key in the mode the object recorded.
///
/// This is the recognition order: a mode listed earlier claims the object first, and
/// Direct takes whatever no other mode recognizes. A mode this build cannot read is
/// not listed, so its objects fail in the Direct reader instead of being misread.
async fn read_stored_data_key(host: &dyn SseHost, stored: &StoredManagedKey<'_>) -> Result<StoredDataKey, SseError> {
#[cfg(feature = "rio-v2")]
if let Some(sealed_key) = parse_minio_managed_sealed_key(stored.metadata, stored.sse_type)? {
return read_sealed_data_key(stored.metadata, &stored.normalized_metadata, sealed_key);
}
read_wrapped_data_key(host, &stored.normalized_metadata).await
}
/// Unwrap the stored data key with the provider its own bytes identify.
async fn unwrap_stored_data_key(
host: &dyn SseHost,
bucket: &str,
key: &str,
stored: &StoredManagedKey<'_>,
record: &StoredDataKey,
kms_key_id: &str,
) -> Result<[u8; 32], SseError> {
let kms_context = if matches!(stored.sse_type, SSEType::SseKms) {
decode_minio_kms_context(stored.metadata)?
} else {
None
};
let object_context = build_object_encryption_context(bucket, key, kms_context.as_ref());
let wrapped = record.wrapped.as_slice();
// Persisted wrapping format is the read-side source of truth. The
// advertised SSE scheme and current KMS availability are write policy
// and runtime state, neither of which identifies the historical provider.
//
// The one shape that cannot name its provider is a backend-native blob
// stored without an envelope. It is offered to the KMS only when the
// local provider could not have written those bytes and the active
// backend is one whose released versions persisted them that way.
let bare_kms = if is_data_key_envelope(wrapped) || is_local_sse_dek(wrapped) {
None
} else {
bare_data_key_kms_provider(host).await
};
// A MinIO sealed key alone does not mean MinIO wrote the object: RustFS's own
// writer fills MinIO's metadata slots too, while still storing a RustFS
// envelope in them, so neither the slot nor the header name distinguishes the
// two. The data key's own shape does. RustFS envelopes are strictly-parsed
// JSON; MinIO's builtin-KMS ciphertext is opaque bytes that match neither, so
// recognizing RustFS positively — and treating only the remainder as MinIO —
// keeps a RustFS envelope from ever reaching MinIO's decoder.
#[cfg(feature = "rio-v2")]
if matches!(record.mode, StoredKeyMode::Object { .. }) && !is_rustfs_managed_data_key(wrapped) {
return decrypt_unenveloped_sealed_dek(bare_kms, get_local_sse_dek_provider(), wrapped, kms_key_id, &object_context)
.await;
}
let provider: Arc<dyn SseDekProvider> = if is_data_key_envelope(wrapped) {
kms_sse_dek_provider(host).await?
} else if let Some(kms_provider) = bare_kms {
kms_provider
} else {
get_local_sse_dek_provider()?
};
#[cfg(feature = "rio-v2")]
if is_legacy_rustfs_managed_metadata(&stored.normalized_metadata) {
return provider.decrypt_legacy_sse_dek(wrapped, kms_key_id, &object_context).await;
}
provider.decrypt_sse_dek(wrapped, kms_key_id, &object_context).await
}
-23
View File
@@ -1,23 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! SSE key resolution: the S3-defined schemes, the internal keying modes, and the entry points that join them.
pub(crate) mod audit;
pub(crate) mod keying;
pub(crate) mod read;
pub(crate) mod request;
pub(crate) mod rewrap;
pub(crate) mod s3;
pub(crate) mod write;
-303
View File
@@ -1,303 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Read entry points: resolve the decryption material, or the response headers, for a stored object.
use crate::core::audit::{record_managed_kms_outcome, stored_envelope_master_key_version};
use crate::core::keying::material::DecryptionMaterial;
use crate::core::keying::metadata::stored_ssec_metadata;
use crate::core::keying::stored::{
StoredManagedKey, open_under_customer_key, open_under_stored_data_key, recognize_stored_managed_key,
};
use crate::core::request::SseKmsPrincipal;
use crate::core::s3::authorization::authorize_sse_kms_key;
use crate::core::s3::headers::{SseReadResponseHeaders, managed_sse_public_header};
use crate::core::s3::scheme::resolve_stored_kms_key_id;
use crate::core::s3::ssec::{SsecParams, require_matching_ssec_key, stored_ssec_algorithm, validate_ssec_params};
use crate::error::SseError;
use crate::host::SseHost;
use rustfs_policy::policy::action::KmsAction;
use rustfs_utils::http::headers::AMZ_ENCRYPTION_AES;
use rustfs_utils::http::object_encryption_keys::{SSEType, contains_managed_encryption_metadata, stored_managed_encryption_key};
use std::collections::HashMap;
impl std::fmt::Debug for DecryptionRequest<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DecryptionRequest").finish_non_exhaustive()
}
}
/// Request parameters for unified decryption
pub struct DecryptionRequest<'a> {
/// Bucket name
pub bucket: &'a str,
/// Object key
pub key: &'a str,
/// Object metadata containing encryption headers
pub metadata: &'a HashMap<String, String>,
/// SSE-C key (Base64-encoded) - required if object was encrypted with SSE-C
pub sse_customer_key: Option<&'a String>,
/// SSE-C key MD5 (Base64-encoded) - required if object was encrypted with SSE-C
pub sse_customer_key_md5: Option<&'a String>,
/// Caller the SSE-KMS key usage is authorized as. `None` marks an internal caller.
pub principal: Option<&'a SseKmsPrincipal>,
}
/// **Core API**: Apply decryption based on stored metadata
///
/// This function automatically detects the encryption type from metadata:
/// - SSE-C if customer key is provided
/// - SSE-S3/SSE-KMS if managed encryption metadata is found
/// - None if object is not encrypted
///
/// # Arguments
/// * `request` - Decryption request with metadata and optional customer key
///
/// # Returns
/// * `Ok(Some(material))` - Decryption should be applied with the returned material
/// * `Ok(None)` - Object is not encrypted
/// * `Err` - Decryption configuration error or key mismatch
///
/// # Example
/// ```rust,ignore
/// let request = DecryptionRequest {
/// bucket: &bucket,
/// key: &key,
/// metadata: &metadata,
/// sse_customer_key: sse_customer_key.as_deref(),
/// sse_customer_key_md5: sse_customer_key_md5.as_deref(),
/// };
///
/// if let Some(material) = sse_decryption(host, request).await? {
/// content_size = material.original_size.unwrap_or(actual_size);
/// }
/// ```
pub async fn sse_decryption(host: &dyn SseHost, request: DecryptionRequest<'_>) -> Result<Option<DecryptionMaterial>, SseError> {
// Check for SSE-C encryption
if stored_ssec_metadata(request.metadata) {
let (key, key_md5) = require_matching_ssec_key(request.metadata, request.sse_customer_key, request.sse_customer_key_md5)?;
let mut material = apply_ssec_decryption_material(request.bucket, request.key, request.metadata, key, key_md5).await?;
material.customer_key_md5 = Some(key_md5.clone());
return Ok(Some(material));
}
// Check for managed SSE encryption
if contains_managed_encryption_metadata(request.metadata) {
return apply_managed_decryption_material(host, request.bucket, request.key, request.metadata, request.principal).await;
}
// No encryption detected
Ok(None)
}
/// Read-side response classification for an object whose payload the object
/// layer's encryption resolver already decrypted.
///
/// [`sse_decryption`] both unwraps the data key and derives the response
/// headers. The GET path only needs the latter — its stream comes out of the
/// object layer decrypted (see [`SseObjectEncryptionResolver`]) — so calling
/// [`sse_decryption`] there performed a second KMS `Decrypt` per request whose
/// key bytes were discarded. This function reproduces that call's header,
/// validation, authorization and audit behavior from stored metadata alone.
///
/// Contract, mirrored from [`sse_decryption`] item by item:
/// - SSE-C: missing request key/MD5 and stored/request MD5 mismatch fail with
/// the same errors and precedence, and the provided key is fully validated.
/// - Managed SSE: per-key `kms:Decrypt` authorization runs ahead of every other
/// failure mode, and the request's KMS audit summary records the same
/// scheme/key/version/outcome fields the unwrap-based path recorded. The
/// success outcome is honest because a failed unwrap aborts the read in the
/// object layer before response classification is ever reached.
/// - Objects without SSE metadata — and managed metadata whose scheme cannot
/// be established in this build — classify as `None`, exactly where
/// [`sse_decryption`] returned `None`.
pub async fn classify_sse_read_response(
host: &dyn SseHost,
request: DecryptionRequest<'_>,
) -> Result<Option<SseReadResponseHeaders>, SseError> {
if stored_ssec_metadata(request.metadata) {
let (key, key_md5) = require_matching_ssec_key(request.metadata, request.sse_customer_key, request.sse_customer_key_md5)?;
let algorithm = stored_ssec_algorithm(request.metadata);
validate_ssec_params(SsecParams {
algorithm: algorithm.to_string(),
key: key.to_string(),
key_md5: key_md5.to_string(),
})?;
return Ok(Some(SseReadResponseHeaders {
server_side_encryption: String::from(AMZ_ENCRYPTION_AES),
sse_customer_algorithm: Some(String::from(algorithm)),
sse_customer_key_md5: Some(key_md5.clone()),
ssekms_key_id: None,
}));
}
// Same scheme and key resolution as the unwrap path, so authorization and the
// response header name the same key.
let Some((stored, kms_key_id)) = resolve_stored_managed_key(host, request.metadata).await else {
return Ok(None);
};
// Ahead of every other failure mode, so a denied caller learns nothing
// about the key beyond "not yours".
if let Err(error) =
authorize_sse_kms_key(host, request.principal, stored.sse_type, KmsAction::DecryptAction, &kms_key_id).await
{
if let Some((sse_type, key_id)) = stored_managed_encryption_key(request.metadata) {
record_managed_kms_outcome(
request.principal,
sse_type,
Some(&key_id),
|| stored_envelope_master_key_version(request.metadata),
Err(&error),
);
}
return Err(error);
}
record_managed_kms_outcome(
request.principal,
stored.sse_type,
Some(&kms_key_id),
|| stored_envelope_master_key_version(request.metadata),
Ok(()),
);
Ok(Some(SseReadResponseHeaders {
server_side_encryption: managed_sse_public_header(stored.sse_type).to_string(),
sse_customer_algorithm: None,
sse_customer_key_md5: None,
// The key id was needed above to authorize the read, but an AES256
// object's wrapping key is internal: only aws:kms objects advertise it.
ssekms_key_id: matches!(stored.sse_type, SSEType::SseKms).then_some(kms_key_id),
}))
}
/// Recognize a stored managed-SSE object and name the key it is read under.
///
/// One resolution for every read: authorization, the response headers and the
/// unwrap all name the key this returns. `None` means the object carries no
/// managed-SSE metadata, or carries some whose scheme this build cannot establish.
async fn resolve_stored_managed_key<'m>(
host: &dyn SseHost,
metadata: &'m HashMap<String, String>,
) -> Option<(StoredManagedKey<'m>, String)> {
let stored = recognize_stored_managed_key(metadata)?;
let kms_key_id = resolve_stored_kms_key_id(host, stored.recorded_kms_key_id.clone()).await;
Some((stored, kms_key_id))
}
pub(crate) async fn apply_ssec_decryption_material(
bucket: &str,
key: &str,
metadata: &HashMap<String, String>,
sse_key: &str,
sse_key_md5: &str,
) -> Result<DecryptionMaterial, SseError> {
// Validate provided key
let algorithm = stored_ssec_algorithm(metadata);
let params = SsecParams {
algorithm: algorithm.to_string(),
key: sse_key.to_string(),
key_md5: sse_key_md5.to_string(),
};
let validated = validate_ssec_params(params)?;
let opened = open_under_customer_key(metadata, validated.key_bytes, bucket, key)?;
Ok(DecryptionMaterial {
sse_type: SSEType::SseC,
server_side_encryption: String::from(AMZ_ENCRYPTION_AES), // const
kms_key_id: None,
algorithm: String::from(algorithm),
customer_key_md5: None,
key_bytes: opened.key_bytes,
base_nonce: opened.base_nonce,
key_kind: opened.key_kind,
})
}
pub(crate) async fn apply_managed_decryption_material(
host: &dyn SseHost,
bucket: &str,
key: &str,
metadata: &HashMap<String, String>,
principal: Option<&SseKmsPrincipal>,
) -> Result<Option<DecryptionMaterial>, SseError> {
let result = apply_managed_decryption_material_inner(host, bucket, key, metadata, principal).await;
match &result {
// `None` means the object carries no managed-SSE metadata — SSE-C and
// plaintext objects never reach KMS and must not appear in the summary.
Ok(None) => {}
Ok(Some(material)) => record_managed_kms_outcome(
principal,
material.sse_type,
material.kms_key_id.as_deref(),
|| stored_envelope_master_key_version(metadata),
Ok(()),
),
Err(error) => {
if let Some((sse_type, key_id)) = stored_managed_encryption_key(metadata) {
record_managed_kms_outcome(
principal,
sse_type,
Some(&key_id),
|| stored_envelope_master_key_version(metadata),
Err(error),
);
}
}
}
result
}
async fn apply_managed_decryption_material_inner(
host: &dyn SseHost,
bucket: &str,
key: &str,
metadata: &HashMap<String, String>,
principal: Option<&SseKmsPrincipal>,
) -> Result<Option<DecryptionMaterial>, SseError> {
let Some((stored, kms_key_id)) = resolve_stored_managed_key(host, metadata).await else {
return Ok(None);
};
// Ahead of every other failure mode below, so a denied caller learns nothing about the
// key beyond "not yours" — not whether it is disabled, pending deletion, or unreadable.
authorize_sse_kms_key(host, principal, stored.sse_type, KmsAction::DecryptAction, &kms_key_id).await?;
let (opened, algorithm) = open_under_stored_data_key(host, bucket, key, &stored, &kms_key_id).await?;
Ok(Some(DecryptionMaterial {
sse_type: stored.sse_type,
// Synthesized from the resolved scheme rather than read back from
// metadata: a MinIO-written object has no stored scheme header, which is
// exactly why the scheme had to be inferred. MinIO synthesizes the same
// header onto its own responses.
server_side_encryption: managed_sse_public_header(stored.sse_type).to_string(),
kms_key_id: Some(kms_key_id),
algorithm,
customer_key_md5: None,
key_bytes: opened.key_bytes,
base_nonce: opened.base_nonce,
key_kind: opened.key_kind,
}))
}
-148
View File
@@ -1,148 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The caller an SSE operation is authorized as.
use crate::core::audit::{KmsRequestAudit, kms_request_audit};
#[cfg(any(test, feature = "test-util"))]
use crate::host::KmsKeyAuthorizer;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
/// Identity a data-path KMS key operation is attributed to.
///
/// Only requests that crossed the S3 authorization boundary carry one. Internal
/// callers — replication, lifecycle transition, heal, scanner — enter the object
/// layer directly and run with server credentials, so they never build a principal
/// and are exempt by construction; `None` therefore means "system principal".
#[derive(Debug, Clone)]
pub struct SseKmsPrincipal {
pub(crate) account: String,
groups: Option<Vec<String>>,
is_owner: bool,
claims: HashMap<String, Value>,
conditions: HashMap<String, Vec<String>>,
/// Audit slot of the S3 request this principal was built for, when the request
/// is being audited. The principal is the only request-derived value that reaches
/// the managed-SSE code paths, so it doubles as the carrier for the slot.
pub(crate) request_audit: Option<Arc<KmsRequestAudit>>,
/// Test-only decision overrides. Carried per principal rather than in a global slot so
/// concurrent tests cannot observe each other's injection.
#[cfg(any(test, feature = "test-util"))]
pub(crate) test_hooks: Option<TestAuthorizationHooks>,
}
impl SseKmsPrincipal {
/// Build the principal of a request that crossed the S3 authorization boundary.
///
/// Anonymous requests use an empty account, matching the bucket-policy authorization
/// path. This keeps every request that crossed the S3 boundary distinct from trusted
/// internal callers, which are represented by `None`.
pub fn new(
account: String,
groups: Option<Vec<String>>,
is_owner: bool,
claims: HashMap<String, Value>,
conditions: HashMap<String, Vec<String>>,
) -> Self {
Self {
account,
groups,
is_owner,
claims,
conditions,
request_audit: None,
#[cfg(any(test, feature = "test-util"))]
test_hooks: None,
}
}
/// The access key the request authenticated with; empty for an anonymous request.
pub fn account(&self) -> &str {
&self.account
}
pub fn groups(&self) -> &Option<Vec<String>> {
&self.groups
}
pub fn is_owner(&self) -> bool {
self.is_owner
}
pub fn claims(&self) -> &HashMap<String, Value> {
&self.claims
}
/// Policy condition values of the request that do not depend on the resource.
pub fn conditions(&self) -> &HashMap<String, Vec<String>> {
&self.conditions
}
/// Attach the audit slot opened for `request_id`, if that request is being audited
/// (see [`KmsRequestAuditScope::register`]).
#[must_use]
pub fn with_request_id(mut self, request_id: &str) -> Self {
self.request_audit = kms_request_audit(request_id);
self
}
/// Override the enforcement switch and the authorizer for this principal only.
#[cfg(any(test, feature = "test-util"))]
#[must_use]
pub fn with_test_hooks(mut self, hooks: Option<TestAuthorizationHooks>) -> Self {
self.test_hooks = hooks;
self
}
#[cfg(test)]
pub(crate) fn for_test(account: &str, enforced: bool, authorizer: Arc<dyn KmsKeyAuthorizer>) -> Self {
Self {
account: account.to_string(),
groups: None,
is_owner: false,
claims: HashMap::new(),
conditions: HashMap::new(),
request_audit: None,
test_hooks: Some(TestAuthorizationHooks { enforced, authorizer }),
}
}
/// Bind this principal to `audit` so managed-SSE operations performed for it are
/// summarised onto the request's S3 audit entry.
#[cfg(test)]
pub(crate) fn with_request_audit(mut self, audit: Arc<KmsRequestAudit>) -> Self {
self.request_audit = Some(audit);
self
}
}
/// Per-principal override of SSE-KMS key authorization, for tests.
#[cfg(any(test, feature = "test-util"))]
#[derive(Clone)]
pub struct TestAuthorizationHooks {
pub enforced: bool,
pub authorizer: Arc<dyn KmsKeyAuthorizer>,
}
#[cfg(any(test, feature = "test-util"))]
impl std::fmt::Debug for TestAuthorizationHooks {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("TestAuthorizationHooks")
.field("enforced", &self.enforced)
.finish_non_exhaustive()
}
}
-144
View File
@@ -1,144 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Re-wrap a stored data key onto its master key's current version.
use crate::core::keying::context::{build_object_encryption_context, decode_minio_kms_context};
use crate::core::keying::metadata::recode_minio_kms_context;
use crate::error::SseError;
use crate::host::SseHost;
use crate::kms::provider::kms_sse_dek_provider;
use base64_simd::STANDARD as BASE64_STANDARD;
use rustfs_kms::is_data_key_envelope;
use rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS;
use rustfs_utils::http::object_encryption_keys::{
INTERNAL_ENCRYPTION_KEY_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER, MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER, SSEType,
contains_managed_encryption_metadata, normalize_managed_metadata,
};
use std::collections::HashMap;
/// Outcome of a single object's DEK rewrap attempt.
// Consumed by the bulk rekey sweep in the follow-up PR; tests exercise it now.
#[allow(dead_code)]
#[derive(Debug)]
pub enum ObjectDekRewrapOutcome {
/// The object carries no KMS-wrapped RustFS data-key envelope this build
/// can rewrap: plaintext, SSE-C, or a MinIO-sealed data key.
NotApplicable,
/// The envelope is already on the current master key version and format;
/// the caller must persist nothing, so a sweep re-run converges.
AlreadyCurrent,
/// The envelope was rewrapped. `metadata` holds the overrides to merge
/// into the object's user-defined metadata — every stored copy of the old
/// envelope, replaced — via `ObjectLayer::put_object_metadata`.
Rewrapped { metadata: HashMap<String, String> },
}
/// Rewrap the KMS-wrapped data key in an object's stored metadata onto its
/// master key's current version (and current envelope format), without
/// touching the object's data or its plaintext DEK.
///
/// Mirrors the managed decrypt path byte for byte where it matters: the
/// envelope is located through the same normalized-header resolution, and the
/// encryption context is rebuilt with the same helpers, so an envelope the
/// read path can open is exactly an envelope this can rewrap. The KMS backend
/// owns the format and the no-op decision.
///
/// The returned overrides replace every stored copy of the old envelope
/// (RustFS's internal header and the MinIO-compatible slots that the writer
/// fills with the same bytes). A copy left behind would win a read-path
/// fallback and resurrect the old wrapping, so finding no replaceable copy is
/// an error, never a silent success.
pub async fn rewrap_object_encryption_metadata(
host: &dyn SseHost,
bucket: &str,
key: &str,
metadata: &HashMap<String, String>,
) -> Result<ObjectDekRewrapOutcome, SseError> {
if !contains_managed_encryption_metadata(metadata) {
return Ok(ObjectDekRewrapOutcome::NotApplicable);
}
let encryption_type = match metadata.get("x-amz-server-side-encryption").map(String::as_str) {
Some(AMZ_ENCRYPTION_KMS) => SSEType::SseKms,
Some(_) => SSEType::SseS3,
// MinIO-written objects synthesize the public header on read; their
// sealed data keys are not RustFS envelopes and fall out below.
None => SSEType::SseS3,
};
let normalized_metadata = normalize_managed_metadata(metadata, Some(recode_minio_kms_context));
let Some(envelope_b64) = normalized_metadata
.get(INTERNAL_ENCRYPTION_KEY_HEADER)
.or_else(|| metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER))
else {
return Ok(ObjectDekRewrapOutcome::NotApplicable);
};
let encrypted_data_key = BASE64_STANDARD
.decode_to_vec(envelope_b64)
.map_err(|e| SseError::internal(format!("Failed to decode encrypted key: {e}")))?;
// Only RustFS envelopes are rewrappable here; MinIO's builtin-KMS
// ciphertext is opaque bytes owned by a different root of trust.
if !is_data_key_envelope(&encrypted_data_key) {
return Ok(ObjectDekRewrapOutcome::NotApplicable);
}
let kms_context = if matches!(encryption_type, SSEType::SseKms) {
decode_minio_kms_context(metadata)?
} else {
None
};
let object_context = build_object_encryption_context(bucket, key, kms_context.as_ref());
// The same provider selection as the managed decrypt path.
let provider = kms_sse_dek_provider(host).await?;
let response = provider.rewrap_sse_dek(&encrypted_data_key, &object_context).await?;
if !response.rewrapped {
return Ok(ObjectDekRewrapOutcome::AlreadyCurrent);
}
// Replace every stored copy of the old envelope, keyed by value and
// matched case-insensitively: metadata key casing drifts through the
// storage layer, and an override inserted under a differently-cased name
// would sit beside the old copy instead of replacing it. The MinIO
// sealed-key slots can instead hold a sealed *object* key (rio-v2 writer);
// those bytes differ from the envelope and are untouched — the data key
// they seal is unchanged by a rewrap.
const REWRAP_ENVELOPE_HEADERS: [&str; 4] = [
INTERNAL_ENCRYPTION_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_DATA_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER,
];
let old_envelope_b64 = envelope_b64.clone();
let new_envelope_b64 = BASE64_STANDARD.encode_to_string(&response.ciphertext);
let mut overrides = HashMap::new();
for (stored_name, stored_value) in metadata {
let is_envelope_slot = REWRAP_ENVELOPE_HEADERS
.iter()
.any(|header| stored_name.eq_ignore_ascii_case(header));
if is_envelope_slot && *stored_value == old_envelope_b64 {
overrides.insert(stored_name.clone(), new_envelope_b64.clone());
}
}
if overrides.is_empty() {
return Err(SseError::internal(
"rewrapped a data-key envelope but found no stored metadata copy to replace; refusing a write that would \
leave the old wrapping live",
));
}
Ok(ObjectDekRewrapOutcome::Rewrapped { metadata: overrides })
}
-177
View File
@@ -1,177 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Per-key KMS authorization on the SSE-KMS data path.
use crate::core::audit::{record_managed_kms_outcome, stored_envelope_master_key_version};
use crate::core::request::SseKmsPrincipal;
use crate::error::SseError;
use crate::host::SseHost;
use crate::{LOG_COMPONENT_STORAGE, LOG_SUBSYSTEM_SSE};
use rustfs_config::ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY;
use rustfs_policy::policy::action::KmsAction;
use rustfs_s3_types::S3ErrorCode;
use rustfs_utils::http::object_encryption_keys::{SSEType, stored_managed_encryption_key};
use std::collections::HashMap;
use tracing::debug;
/// Ask the authorizer that decides for `principal`: the host's, unless a test overrode it.
async fn is_kms_key_allowed(
host: &dyn SseHost,
principal: &SseKmsPrincipal,
action: KmsAction,
key_id: &str,
) -> Result<bool, SseError> {
#[cfg(any(test, feature = "test-util"))]
if let Some(hooks) = principal.test_hooks.as_ref() {
return hooks.authorizer.is_allowed(principal, action, key_id).await;
}
host.kms_key_authorizer().is_allowed(principal, action, key_id).await
}
/// Whether per-key KMS authorization is enforced on the SSE-KMS data path.
fn sse_kms_key_policy_enforced(principal: Option<&SseKmsPrincipal>) -> bool {
#[cfg(any(test, feature = "test-util"))]
if let Some(hooks) = principal.and_then(|candidate| candidate.test_hooks.as_ref()) {
return hooks.enforced;
}
#[cfg(not(any(test, feature = "test-util")))]
let _ = principal;
crate::startup::key_policy_enforced()
}
/// The principal whose KMS key permissions this operation must satisfy, if any.
///
/// Scoping is limited to SSE-KMS, matching AWS: SSE-S3 wraps its data key with a
/// server-owned key the caller never names, and SSE-C never reaches KMS at all.
pub(crate) fn kms_authorization_subject(
enforced: bool,
principal: Option<&SseKmsPrincipal>,
sse_type: SSEType,
) -> Option<&SseKmsPrincipal> {
if !enforced || !matches!(sse_type, SSEType::SseKms) {
return None;
}
principal
}
/// Authorize `action` against `key_id` for the caller behind this SSE operation.
///
/// Runs before the key is used, so a denied request cannot distinguish an unauthorized
/// key from a disabled or pending-deletion one.
pub(crate) async fn authorize_sse_kms_key(
host: &dyn SseHost,
principal: Option<&SseKmsPrincipal>,
sse_type: SSEType,
action: KmsAction,
key_id: &str,
) -> Result<(), SseError> {
let Some(principal) = kms_authorization_subject(sse_kms_key_policy_enforced(principal), principal, sse_type) else {
return Ok(());
};
if is_kms_key_allowed(host, principal, action, key_id).await? {
return Ok(());
}
debug!(
component = LOG_COMPONENT_STORAGE,
subsystem = LOG_SUBSYSTEM_SSE,
event = "sse_kms_key_authorization_denied",
account = %principal.account,
action = ?action,
"Principal is not authorized for the KMS key resolved for this request"
);
// One warn per process, not per request: anonymous denials are driven by
// unauthenticated traffic, so a per-request warn would let anyone flood the
// log. Per-request detail stays on the audit entry and the debug event above.
if principal.account.is_empty() {
static ANONYMOUS_DENIAL_WARNED: std::sync::Once = std::sync::Once::new();
ANONYMOUS_DENIAL_WARNED.call_once(|| {
tracing::warn!(
component = LOG_COMPONENT_STORAGE,
subsystem = LOG_SUBSYSTEM_SSE,
event = "sse_kms_anonymous_key_authorization_denied",
action = ?action,
"Anonymous requests are being denied by SSE-KMS per-key authorization: anonymous \
callers hold no kms grants, so a public bucket serving SSE-KMS objects is \
incompatible with {ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY}=true. Reported once per \
process; per-request denials are on audit entries and at debug level."
);
});
}
Err(SseError {
code: S3ErrorCode::AccessDenied,
message: "Access Denied".to_string(),
source: None,
})
}
/// Authorize `kms:Decrypt` for an object whose stored encryption material is unwrapped
/// outside [`sse_decryption`].
///
/// The copy-source read resolves its material inside the object layer, which has no
/// request identity, so the S3 layer has to run the check itself.
pub async fn authorize_sse_kms_object_read(
host: &dyn SseHost,
principal: Option<&SseKmsPrincipal>,
metadata: &HashMap<String, String>,
) -> Result<(), SseError> {
let Some((sse_type, key_id)) = stored_managed_encryption_key(metadata) else {
return Ok(());
};
let result = authorize_sse_kms_key(host, principal, sse_type, KmsAction::DecryptAction, &key_id).await;
// Only a denial is recorded here: an allowed read goes on to unwrap the key,
// and that operation reports its own outcome.
if let Err(error) = &result {
record_managed_kms_outcome(
principal,
sse_type,
Some(&key_id),
|| stored_envelope_master_key_version(metadata),
Err(error),
);
}
result
}
/// Authorize the current request to write under the upload's stored KMS key.
/// Upload IDs do not confer the creator's KMS permissions on another caller.
pub async fn authorize_sse_kms_multipart_write(
host: &dyn SseHost,
principal: Option<&SseKmsPrincipal>,
metadata: &HashMap<String, String>,
) -> Result<(), SseError> {
let Some((sse_type, key_id)) = stored_managed_encryption_key(metadata) else {
return Ok(());
};
let result = authorize_sse_kms_key(host, principal, sse_type, KmsAction::GenerateDataKeyAction, &key_id).await;
if let Err(error) = &result {
record_managed_kms_outcome(
principal,
sse_type,
Some(&key_id),
|| stored_envelope_master_key_version(metadata),
Err(error),
);
}
result
}
-454
View File
@@ -1,454 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! SSE request headers in, SSE response headers out.
use crate::core::keying::metadata::{normalize_encryption_metadata_case, recode_minio_kms_context, stored_ssec_metadata};
use crate::core::s3::ssec::ssec_invalid_request;
use crate::error::SseError;
use base64_simd::STANDARD as BASE64_STANDARD;
use http::{HeaderMap, HeaderName, HeaderValue};
use rustfs_s3_types::S3ErrorCode;
use rustfs_utils::http::headers::{
AMZ_ENCRYPTION_AES, AMZ_ENCRYPTION_KMS, AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM,
AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY, AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5, AMZ_SERVER_SIDE_ENCRYPTION_KMS_CONTEXT,
SSEC_ALGORITHM_HEADER, SSEC_KEY_MD5_HEADER,
};
use rustfs_utils::http::object_encryption_keys::{
INTERNAL_ENCRYPTION_CONTEXT_HEADER, INTERNAL_ENCRYPTION_KEY_ID_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER,
MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER, MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER,
MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER, MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER, SSEType,
normalize_managed_metadata,
};
use std::collections::HashMap;
// The same header names s3s publishes. Owned so this module does not import s3s.
pub(crate) const X_AMZ_SERVER_SIDE_ENCRYPTION: HeaderName = HeaderName::from_static("x-amz-server-side-encryption");
pub(crate) const X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID: HeaderName =
HeaderName::from_static("x-amz-server-side-encryption-aws-kms-key-id");
pub(crate) const X_AMZ_SERVER_SIDE_ENCRYPTION_CONTEXT: HeaderName =
HeaderName::from_static("x-amz-server-side-encryption-context");
pub(crate) const X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM: HeaderName =
HeaderName::from_static("x-amz-server-side-encryption-customer-algorithm");
pub(crate) const X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5: HeaderName =
HeaderName::from_static("x-amz-server-side-encryption-customer-key-md5");
#[inline]
pub(crate) fn sse_invalid_argument(message: &str) -> SseError {
SseError {
code: S3ErrorCode::InvalidArgument,
message: message.to_string(),
source: None,
}
}
/// SSE-C parameters extracted from headers (algorithm, key, key MD5).
pub type SsecParamsFromHeaders = (Option<String>, Option<String>, Option<String>);
/// Extract SSE-C parameters from request headers.
/// Used as fallback when the S3 layer does not populate them in the input struct.
///
/// Returns an error if an SSE-C header is present but cannot be parsed as valid UTF-8,
/// ensuring malformed headers do not bypass validation.
pub fn extract_ssec_params_from_headers(headers: &HeaderMap) -> Result<SsecParamsFromHeaders, SseError> {
let algorithm = match headers.get("x-amz-server-side-encryption-customer-algorithm") {
None => Ok(None),
Some(v) => v
.to_str()
.map(|s| Some(s.to_string()))
.map_err(|_| sse_invalid_argument("The x-amz-server-side-encryption-customer-algorithm header must be valid UTF-8.")),
}?;
let key = match headers.get("x-amz-server-side-encryption-customer-key") {
None => Ok(None),
Some(v) => v
.to_str()
.map(|s| Some(s.to_string()))
.map_err(|_| sse_invalid_argument("The x-amz-server-side-encryption-customer-key header must be valid UTF-8.")),
}?;
let key_md5 = match headers.get("x-amz-server-side-encryption-customer-key-md5") {
None => Ok(None),
Some(v) => v
.to_str()
.map(|s| Some(s.to_string()))
.map_err(|_| sse_invalid_argument("The x-amz-server-side-encryption-customer-key-md5 header must be valid UTF-8.")),
}?;
Ok((algorithm, key, key_md5))
}
/// Extract x-amz-server-side-encryption from request headers.
/// Used as fallback when the S3 layer does not populate it in the input struct.
///
/// Returns an error if the header is present but cannot be parsed as valid UTF-8,
/// ensuring malformed headers do not bypass validation.
pub fn extract_server_side_encryption_from_headers(headers: &HeaderMap) -> Result<Option<String>, SseError> {
match headers.get("x-amz-server-side-encryption") {
None => Ok(None),
Some(v) => v
.to_str()
.map(|s| Some(s.to_string()))
.map_err(|_| sse_invalid_argument("The x-amz-server-side-encryption header must be valid UTF-8.")),
}
}
pub fn extract_ssekms_context_from_headers(headers: &HeaderMap) -> Result<Option<HashMap<String, String>>, SseError> {
let Some(v) = headers.get(AMZ_SERVER_SIDE_ENCRYPTION_KMS_CONTEXT) else {
return Ok(None);
};
let value = v
.to_str()
.map_err(|_| sse_invalid_argument("The x-amz-server-side-encryption-context header must be valid UTF-8."))?;
let decoded = BASE64_STANDARD.decode_to_vec(value).map_err(|_| {
sse_invalid_argument("The x-amz-server-side-encryption-context header must be valid base64-encoded JSON.")
})?;
serde_json::from_slice(&decoded).map(Some).map_err(|_| {
sse_invalid_argument("The x-amz-server-side-encryption-context header must be a base64-encoded JSON object.")
})
}
/// Rejects a client encryption context that would replace the location binding.
///
/// The request context binds the data key to `{bucket: bucket/key}` only when the
/// client supplied no entry under that name, and only the client context is
/// persisted. A client entry keyed by the bucket name therefore travels with the
/// object and replaces the binding on every read, so the envelope would no longer
/// be tied to the object's location. Only the write side rejects it: objects stored
/// with such an entry stay readable because the read side rebuilds the context
/// unchanged.
pub(crate) fn reject_kms_context_location_override(
bucket: &str,
ssekms_context: Option<&HashMap<String, String>>,
) -> Result<(), SseError> {
if ssekms_context.is_some_and(|context| context.contains_key(bucket)) {
return Err(sse_invalid_argument(&format!(
"The x-amz-server-side-encryption-context header contains the key \"{bucket}\", which equals the bucket name; \
that key is reserved for binding the data key to the object's location."
)));
}
Ok(())
}
#[inline]
pub fn validate_sse_headers_for_write(
server_side_encryption: Option<&str>,
ssekms_key_id: Option<&String>,
ssekms_context: Option<&HashMap<String, String>>,
sse_customer_algorithm: Option<&String>,
sse_customer_key: Option<&String>,
sse_customer_key_md5: Option<&String>,
require_sse_customer_key: bool,
) -> Result<(), SseError> {
if let Some(sse) = server_side_encryption {
let s = sse;
if s != AMZ_ENCRYPTION_AES && s != AMZ_ENCRYPTION_KMS {
return Err(sse_invalid_argument(
"The SSE algorithm specified is not supported. The valid values are AES256 or aws:kms.",
));
}
}
let has_ssec_headers = sse_customer_algorithm.is_some() || sse_customer_key.is_some() || sse_customer_key_md5.is_some();
let has_managed_headers = server_side_encryption.is_some() || ssekms_key_id.is_some() || ssekms_context.is_some();
if has_ssec_headers {
if has_managed_headers {
return Err(sse_invalid_argument(
"The SSE-C and managed server-side encryption headers cannot be used together.",
));
}
let has_valid_ssec_headers = if require_sse_customer_key {
matches!(
(sse_customer_algorithm, sse_customer_key, sse_customer_key_md5),
(Some(_), Some(_), Some(_))
)
} else {
matches!((sse_customer_algorithm, sse_customer_key_md5), (Some(_), Some(_)))
};
if !has_valid_ssec_headers {
let message = if require_sse_customer_key {
"Missing SSE-C parameters. Algorithm, customer key and customer key MD5 are all required."
} else {
"Missing SSE-C parameters. Algorithm and customer key MD5 are required."
};
return Err(ssec_invalid_request(message));
}
}
if ssekms_key_id.is_some() && server_side_encryption.is_none_or(|sse| sse != AMZ_ENCRYPTION_KMS) {
return Err(sse_invalid_argument(
"The SSE-KMS key ID header can only be used when x-amz-server-side-encryption is set to aws:kms.",
));
}
if ssekms_context.is_some() && server_side_encryption.is_none_or(|sse| sse != AMZ_ENCRYPTION_KMS) {
return Err(sse_invalid_argument(
"The SSE-KMS context header can only be used when x-amz-server-side-encryption is set to aws:kms.",
));
}
Ok(())
}
#[inline]
pub fn validate_sse_headers_for_read(metadata: &HashMap<String, String>, headers: &HeaderMap) -> Result<(), SseError> {
let has_req_ssec = headers.contains_key("x-amz-server-side-encryption-customer-algorithm")
|| headers.contains_key("x-amz-server-side-encryption-customer-key")
|| headers.contains_key("x-amz-server-side-encryption-customer-key-md5");
let has_req_sse = headers.contains_key("x-amz-server-side-encryption")
|| headers.contains_key("x-amz-server-side-encryption-aws-kms-key-id")
|| headers.contains_key("x-amz-server-side-encryption-context");
let is_object_ssec = stored_ssec_metadata(metadata);
let is_object_sse = metadata.contains_key("x-amz-server-side-encryption");
if is_object_ssec {
if has_req_sse {
return Err(sse_invalid_argument(
"Server-side encryption headers cannot be used with an object encrypted using SSE-C.",
));
}
return Ok(());
}
if is_object_sse && has_req_ssec {
return Err(sse_invalid_argument(
"SSE-C headers cannot be used with an object encrypted using server-side managed encryption.",
));
}
if has_req_ssec {
return Err(ssec_invalid_request(
"The object was stored without SSE-C. The correct SSE-C parameters must not be provided.",
));
}
if has_req_sse {
return Err(sse_invalid_argument(
"The object is not encrypted with server-side encryption. Do not provide server-side encryption headers.",
));
}
Ok(())
}
/// The public `x-amz-server-side-encryption` value a managed scheme reports.
pub(crate) fn managed_sse_public_header(sse_type: SSEType) -> &'static str {
match sse_type {
SSEType::SseKms => AMZ_ENCRYPTION_KMS,
// SSE-C never reaches the managed path; reporting AES256 keeps this
// total without inventing a third public value.
SSEType::SseS3 | SSEType::SseC => AMZ_ENCRYPTION_AES,
}
}
pub fn build_ssec_read_headers(algorithm: Option<&String>, key: Option<&String>, key_md5: Option<&String>) -> HeaderMap {
let mut headers = HeaderMap::new();
if let Some(algorithm) = algorithm
&& let Ok(mut value) = HeaderValue::from_str(algorithm.as_str())
{
value.set_sensitive(true);
headers.insert(AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM, value);
}
if let Some(key) = key
&& let Ok(mut value) = HeaderValue::from_str(key.as_str())
{
value.set_sensitive(true);
headers.insert(AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY, value);
}
if let Some(key_md5) = key_md5
&& let Ok(mut value) = HeaderValue::from_str(key_md5.as_str())
{
value.set_sensitive(true);
headers.insert(AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5, value);
}
headers
}
/// Response headers derived for a decrypted read without unwrapping the data key.
#[derive(Debug)]
pub struct SseReadResponseHeaders {
pub server_side_encryption: String,
pub sse_customer_algorithm: Option<String>,
pub sse_customer_key_md5: Option<String>,
pub ssekms_key_id: Option<String>,
}
fn invalid_sse_response_metadata() -> SseError {
SseError {
code: S3ErrorCode::InternalError,
message: "Persisted object encryption metadata is invalid.".to_string(),
source: None,
}
}
fn insert_sse_response_header(headers: &mut HeaderMap, name: HeaderName, value: &str) -> Result<(), SseError> {
let value = HeaderValue::from_str(value).map_err(|_| invalid_sse_response_metadata())?;
headers.insert(name, value);
Ok(())
}
/// Project response headers after the caller has completed its existing read
/// validation and KMS authorization path.
pub fn project_sse_read_response_headers(
metadata: &HashMap<String, String>,
sse_customer_algorithm: Option<&String>,
sse_customer_key_md5: Option<&String>,
) -> Result<HeaderMap, SseError> {
if metadata.keys().any(|key| {
key.eq_ignore_ascii_case(AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY)
|| key.eq_ignore_ascii_case(AMZ_SERVER_SIDE_ENCRYPTION_KMS_CONTEXT)
}) {
return Err(invalid_sse_response_metadata());
}
let metadata = normalize_encryption_metadata_case(metadata).map_err(|_| invalid_sse_response_metadata())?;
let public_mode = metadata.get("x-amz-server-side-encryption").map(String::as_str);
let customer_algorithm = metadata.get(SSEC_ALGORITHM_HEADER).map(String::as_str);
let public_mode = match public_mode {
Some(AMZ_ENCRYPTION_AES) => Some(SSEType::SseS3),
Some(AMZ_ENCRYPTION_KMS) => Some(SSEType::SseKms),
Some(_) => return Err(invalid_sse_response_metadata()),
None => None,
};
if customer_algorithm.is_some_and(|algorithm| algorithm != AMZ_ENCRYPTION_AES) {
return Err(invalid_sse_response_metadata());
}
let mode = if customer_algorithm.is_some() {
if public_mode == Some(SSEType::SseKms) {
return Err(invalid_sse_response_metadata());
}
Some(SSEType::SseC)
} else {
public_mode
};
for marker_mode in [
metadata
.contains_key(MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER)
.then_some(SSEType::SseC),
metadata
.contains_key(MINIO_INTERNAL_ENCRYPTION_S3_SEALED_KEY_HEADER)
.then_some(SSEType::SseS3),
metadata
.contains_key(MINIO_INTERNAL_ENCRYPTION_KMS_SEALED_KEY_HEADER)
.then_some(SSEType::SseKms),
]
.into_iter()
.flatten()
{
if mode != Some(marker_mode) {
return Err(invalid_sse_response_metadata());
}
}
let Some(mode) = mode else {
if metadata
.keys()
.any(|key| rustfs_utils::http::is_object_encryption_marker(key))
{
return Err(invalid_sse_response_metadata());
}
return Ok(HeaderMap::new());
};
let mut key_id = None;
for value in [
metadata.get("x-amz-server-side-encryption-aws-kms-key-id"),
metadata.get(INTERNAL_ENCRYPTION_KEY_ID_HEADER),
metadata.get(MINIO_INTERNAL_ENCRYPTION_KMS_KEY_ID_HEADER),
]
.into_iter()
.flatten()
{
if key_id.is_some_and(|current| current != value) {
return Err(invalid_sse_response_metadata());
}
key_id = Some(value);
}
let normalized_managed = normalize_managed_metadata(metadata.as_ref(), Some(recode_minio_kms_context));
let mut response_headers = HeaderMap::with_capacity(3);
match mode {
SSEType::SseS3 => {
if metadata.contains_key("x-amz-server-side-encryption-aws-kms-key-id") || metadata.contains_key(SSEC_KEY_MD5_HEADER)
{
return Err(invalid_sse_response_metadata());
}
response_headers.insert(X_AMZ_SERVER_SIDE_ENCRYPTION, HeaderValue::from_static(AMZ_ENCRYPTION_AES));
}
SSEType::SseKms => {
if metadata.contains_key(SSEC_KEY_MD5_HEADER) {
return Err(invalid_sse_response_metadata());
}
let key_id = key_id
.map(String::as_str)
.filter(|value| !value.is_empty())
.ok_or_else(invalid_sse_response_metadata)?;
response_headers.insert(X_AMZ_SERVER_SIDE_ENCRYPTION, HeaderValue::from_static(AMZ_ENCRYPTION_KMS));
insert_sse_response_header(&mut response_headers, X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID, key_id)?;
if metadata.contains_key(MINIO_INTERNAL_ENCRYPTION_KMS_CONTEXT_HEADER)
&& !normalized_managed.contains_key(INTERNAL_ENCRYPTION_CONTEXT_HEADER)
{
return Err(invalid_sse_response_metadata());
}
if let Some(context) = normalized_managed.get(INTERNAL_ENCRYPTION_CONTEXT_HEADER) {
serde_json::from_str::<HashMap<String, String>>(context).map_err(|_| invalid_sse_response_metadata())?;
let encoded = BASE64_STANDARD.encode_to_string(context);
insert_sse_response_header(&mut response_headers, X_AMZ_SERVER_SIDE_ENCRYPTION_CONTEXT, &encoded)?;
}
}
SSEType::SseC => {
if key_id.is_some() || normalized_managed.contains_key(INTERNAL_ENCRYPTION_CONTEXT_HEADER) {
return Err(invalid_sse_response_metadata());
}
let algorithm = sse_customer_algorithm
.map(|value| value.as_ref())
.filter(|value| *value == AMZ_ENCRYPTION_AES)
.ok_or_else(|| {
ssec_invalid_request(
"The object was stored using a form of Server Side Encryption. The correct parameters must be provided to retrieve the object.",
)
})?;
let key_md5 = sse_customer_key_md5
.map(|value| value.as_ref())
.ok_or_else(|| ssec_invalid_request("Missing SSE-C customer key MD5."))?;
let stored_md5 = metadata.get(SSEC_KEY_MD5_HEADER).ok_or_else(invalid_sse_response_metadata)?;
if stored_md5 != key_md5 {
return Err(ssec_invalid_request(
"The provided encryption parameters did not match the ones used originally to encrypt the object.",
));
}
insert_sse_response_header(&mut response_headers, X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM, algorithm)?;
insert_sse_response_header(&mut response_headers, X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5, key_md5)?;
}
}
Ok(response_headers)
}
-20
View File
@@ -1,20 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The schemes S3 defines: SSE-S3, SSE-KMS and SSE-C, as a request names them and a response reports them.
pub(crate) mod authorization;
pub(crate) mod headers;
pub(crate) mod scheme;
pub(crate) mod ssec;
-288
View File
@@ -1,288 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Which SSE scheme and which key a request resolves to: the request first, then the bucket default.
use crate::core::s3::headers::validate_sse_headers_for_write;
use crate::error::SseError;
use crate::host::SseHost;
use crate::{LOG_COMPONENT_STORAGE, LOG_SUBSYSTEM_SSE};
use rustfs_utils::http::headers::{AMZ_ENCRYPTION_AES, AMZ_ENCRYPTION_KMS};
use rustfs_utils::http::object_encryption_keys::SSEType;
use std::collections::HashMap;
use tracing::debug;
pub const DEFAULT_SSE_ALGORITHM: &str = "AES256";
pub(crate) const SUPPORT_SSE_ALGORITHMS: &[&str] = &[DEFAULT_SSE_ALGORITHM];
/// SSE configuration resolved from request and bucket defaults
#[derive(Debug)]
pub(crate) struct SseConfiguration {
/// Effective server-side encryption algorithm (after considering bucket defaults)
pub effective_sse: String,
/// Effective KMS key ID (after considering bucket defaults)
pub effective_kms_key_id: Option<String>,
}
/// Managed SSE resolved from a bucket default encryption rule on a write path.
///
/// The single mapping shared by every writer: the resolver in this crate, and
/// the server's PUT, COPY and extract paths. Unknown algorithms fall back to AES256 rather
/// than to `None`. Resolving `None` instead lets a same-name copy under a
/// malformed bucket default pass the `copy_changes_encryption` guard and take
/// the metadata-only shortcut while this layer still encrypts: fresh DEK
/// metadata is committed beside the untouched plaintext blocks and the object
/// becomes unreadable. PutBucketEncryption refuses unknown algorithms, so this
/// is reachable only through a configuration stored before that check or
/// through hand-edited bucket metadata (backlog#1826).
pub fn bucket_default_write_sse(sse_algorithm: &str) -> String {
match sse_algorithm {
"AES256" => String::from(AMZ_ENCRYPTION_AES),
"aws:kms" => String::from(AMZ_ENCRYPTION_KMS),
_ => String::from(AMZ_ENCRYPTION_AES),
}
}
/// Prepare SSE configuration by resolving request parameters with bucket defaults
///
/// This function:
/// 1. Queries bucket default encryption configuration
/// 2. Resolves effective encryption (request overrides bucket default)
/// 3. Prepares metadata headers for managed SSE
///
/// # Arguments
/// * `bucket` - Bucket name
/// * `server_side_encryption` - SSE algorithm from request (SSE-S3 or SSE-KMS)
/// * `ssekms_key_id` - KMS key ID from request
/// * `sse_customer_algorithm` - SSE-C algorithm from request
///
/// # Returns
/// `SseConfiguration` with resolved encryption parameters and metadata headers
pub(crate) async fn prepare_sse_configuration(
host: &dyn SseHost,
bucket: &str,
server_side_encryption: Option<String>,
ssekms_key_id: Option<String>,
) -> Result<Option<SseConfiguration>, SseError> {
if let Some(server_side_encryption) = server_side_encryption.clone()
&& server_side_encryption.as_str() == AMZ_ENCRYPTION_AES
{
return Ok(Some(SseConfiguration {
effective_sse: server_side_encryption,
effective_kms_key_id: None,
}));
}
if let Some(server_side_encryption) = server_side_encryption.clone()
&& let Some(ssekms_key_id) = ssekms_key_id
{
return Ok(Some(SseConfiguration {
effective_sse: server_side_encryption,
effective_kms_key_id: Some(ssekms_key_id),
}));
}
// Get bucket default encryption configuration.
let bucket_encryption = host.bucket_encryption(bucket).await;
debug!(
component = LOG_COMPONENT_STORAGE,
subsystem = LOG_SUBSYSTEM_SSE,
event = "bucket_sse_config_lookup",
bucket = %bucket,
found = matches!(bucket_encryption, Ok(Some(_))),
"Bucket SSE configuration lookup completed"
);
let Some(bucket_encryption) = bucket_encryption? else {
// The bucket has no SSE config. If the user explicitly requested
// aws:kms, we must honor that — return the explicit SSE header so
// downstream logic can try (and fail if KMS is unavailable).
return Ok(server_side_encryption.map(|sse| SseConfiguration {
effective_sse: sse,
effective_kms_key_id: ssekms_key_id,
}));
};
let default_rule = bucket_encryption.default_rule.as_ref();
let effective_sse = server_side_encryption.clone().or_else(|| {
default_rule.map(|sse| {
debug!(
component = LOG_COMPONENT_STORAGE,
subsystem = LOG_SUBSYSTEM_SSE,
event = "bucket_sse_default_applied",
bucket = %bucket,
algorithm = sse.sse_algorithm.as_str(),
has_kms_key_id = sse.kms_master_key_id.is_some(),
"Bucket SSE default resolved"
);
bucket_default_write_sse(&sse.sse_algorithm)
})
});
let Some(effective_sse) = effective_sse else {
return Ok(None);
};
debug!(
component = LOG_COMPONENT_STORAGE,
subsystem = LOG_SUBSYSTEM_SSE,
event = "effective_sse_resolved",
bucket = %bucket,
requested = ?server_side_encryption,
effective = ?effective_sse,
"Resolved effective SSE configuration"
);
let effective_kms_key_id = resolve_effective_kms_key_id(Some(&effective_sse), ssekms_key_id, || {
default_rule.and_then(|sse| sse.kms_master_key_id.clone())
});
Ok(Some(SseConfiguration {
effective_sse,
effective_kms_key_id,
}))
}
pub(crate) fn resolve_effective_kms_key_id<F>(
effective_sse: Option<&str>,
requested_kms_key_id: Option<String>,
bucket_default_kms_key_id: F,
) -> Option<String>
where
F: FnOnce() -> Option<String>,
{
if effective_sse.is_none_or(|sse| sse != AMZ_ENCRYPTION_KMS) {
return requested_kms_key_id;
}
requested_kms_key_id.or_else(bucket_default_kms_key_id)
}
/// The SSE headers of a write request, as the S3 layer received them.
pub(crate) struct WriteSchemeHeaders<'a> {
pub(crate) server_side_encryption: Option<String>,
pub(crate) ssekms_key_id: Option<String>,
pub(crate) ssekms_context: Option<&'a HashMap<String, String>>,
pub(crate) sse_customer_algorithm: Option<String>,
pub(crate) sse_customer_key: Option<String>,
pub(crate) sse_customer_key_md5: Option<String>,
}
/// The scheme a write resolved to, in S3's terms.
#[derive(Clone)]
pub(crate) enum WriteScheme {
/// `AES256`: the server chooses the wrapping key and the caller names none.
SseS3,
/// `aws:kms`, under the key the request or the bucket default named, if either did.
SseKms { key_id: Option<String> },
/// A key the client supplies; only its MD5 is ever stored.
SseC {
algorithm: String,
key: String,
key_md5: String,
},
}
impl std::fmt::Debug for WriteScheme {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::SseS3 => "SseS3",
Self::SseKms { .. } => "SseKms(..)",
Self::SseC { .. } => "SseC(..)",
})
}
}
/// Decide the scheme of a write: validate the headers, then the request first and the
/// bucket default second.
///
/// Every write goes through here, an object and a multipart session alike, so the two
/// cannot resolve the same headers differently.
pub(crate) async fn resolve_write_scheme(
host: &dyn SseHost,
bucket: &str,
headers: WriteSchemeHeaders<'_>,
) -> Result<Option<WriteScheme>, SseError> {
validate_sse_headers_for_write(
headers.server_side_encryption.as_deref(),
headers.ssekms_key_id.as_ref(),
headers.ssekms_context,
headers.sse_customer_algorithm.as_ref(),
headers.sse_customer_key.as_ref(),
headers.sse_customer_key_md5.as_ref(),
true,
)?;
// Validation admits SSE-C headers only as a complete set, and never beside the
// managed ones, so their presence alone decides.
if let (Some(algorithm), Some(key), Some(key_md5)) =
(headers.sse_customer_algorithm, headers.sse_customer_key, headers.sse_customer_key_md5)
{
return Ok(Some(WriteScheme::SseC { algorithm, key, key_md5 }));
}
let Some(config) = prepare_sse_configuration(host, bucket, headers.server_side_encryption, headers.ssekms_key_id).await?
else {
return Ok(None);
};
Ok(match config.effective_sse.as_str() {
AMZ_ENCRYPTION_AES => {
// Validation admits a key id only beside `aws:kms`, and the bucket default's
// key is consulted only for `aws:kms`.
debug_assert!(config.effective_kms_key_id.is_none(), "SSE-S3 never names a KMS key");
Some(WriteScheme::SseS3)
}
AMZ_ENCRYPTION_KMS => Some(WriteScheme::SseKms {
key_id: config.effective_kms_key_id,
}),
_ => None,
})
}
/// Scheme a managed-SSE header names, defaulting to SSE-S3 the same way the
/// encryption and decryption paths do.
pub(crate) fn managed_sse_type(server_side_encryption: &str) -> SSEType {
match server_side_encryption {
AMZ_ENCRYPTION_KMS => SSEType::SseKms,
_ => SSEType::SseS3,
}
}
/// Key id an SSE-KMS read authorizes and reports when the stored metadata
/// carries none (legacy envelopes and MinIO-written objects predate the
/// explicit key-id headers).
///
/// The KMS service's configured default key is the key such envelopes were
/// actually wrapped under, so per-key authorization must target it — the bare
/// literal `default` would silently escape any policy narrowed to real key
/// ids. The literal remains only as the last resort when no service is
/// running, matching what the legacy write path recorded implicitly.
pub(crate) async fn resolve_stored_kms_key_id(host: &dyn SseHost, stored: Option<String>) -> String {
if let Some(key_id) = stored {
return key_id;
}
if let Some(service) = host.encryption_service().await
&& let Some(key_id) = service.get_default_key_id()
{
return key_id.clone();
}
"default".to_string()
}
/// Check if the server_side_encryption is a managed SSE type (SSE-S3 or SSE-KMS)
#[inline]
pub(crate) fn is_managed_sse(server_side_encryption: &str) -> bool {
matches!(server_side_encryption, "AES256" | "aws:kms")
}
-217
View File
@@ -1,217 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! SSE-C: validating the customer-provided key and matching it against the stored object.
use crate::core::keying::metadata::{minio_sealed_ssec_metadata, stored_ssec_metadata};
use crate::core::s3::scheme::{DEFAULT_SSE_ALGORITHM, SUPPORT_SSE_ALGORITHMS};
use crate::error::SseError;
use base64_simd::STANDARD as BASE64_STANDARD;
use md5::{Digest as Md5Digest, Md5};
use rustfs_s3_types::S3ErrorCode;
use std::collections::HashMap;
use tracing::error;
fn md5_bytes(input: impl AsRef<[u8]>) -> [u8; 16] {
let mut hasher = Md5::new();
hasher.update(input.as_ref());
hasher.finalize().into()
}
pub(crate) fn md5_base64(input: impl AsRef<[u8]>) -> String {
BASE64_STANDARD.encode_to_string(md5_bytes(input))
}
/// Validated SSE-C parameters
#[derive(Debug, Clone)]
pub(crate) struct ValidatedSsecParams {
/// Encryption algorithm (always "AES256" for SSE-C)
pub algorithm: String,
/// Decoded encryption key bytes (32 bytes for AES-256)
pub key_bytes: [u8; 32],
/// Base64-encoded MD5 of the key
pub key_md5: String,
}
/// SSE-C parameters from client request
#[derive(Debug, Clone)]
pub(crate) struct SsecParams {
/// Encryption algorithm
pub algorithm: String,
/// Base64-encoded encryption key
pub key: String,
/// Base64-encoded MD5 of the key
pub key_md5: String,
}
/// Validate SSE-C parameters from client request
///
/// Validates:
/// 1. Algorithm is "AES256"
/// 2. Key is valid Base64 and exactly 32 bytes
/// 3. MD5 hash matches the key
///
/// # Returns
/// `ValidatedSsecParams` with decoded key bytes
pub(crate) fn validate_ssec_params(params: SsecParams) -> Result<ValidatedSsecParams, SseError> {
if !SUPPORT_SSE_ALGORITHMS.contains(&params.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(&params.key).map_err(|e| {
error!("Failed to decode SSE-C key: {}", e);
ssec_invalid_request("Invalid SSE-C key: not valid Base64.")
})?;
if key_bytes.len() != 32 {
return Err(ssec_invalid_request(&format!(
"SSE-C key must be 32 bytes (256 bits), got {} bytes.",
key_bytes.len()
)));
}
let computed_md5 = md5_base64(&key_bytes);
if computed_md5 != params.key_md5 {
return Err(ssec_invalid_request(
"The calculated MD5 hash of the key did not match the hash that was provided.",
));
}
let key_array: [u8; 32] = key_bytes
.try_into()
.map_err(|_| ssec_invalid_request("SSE-C key must be exactly 32 bytes."))?;
Ok(ValidatedSsecParams {
algorithm: params.algorithm,
key_bytes: key_array,
key_md5: params.key_md5,
})
}
/// Verify SSE-C key matches the stored metadata.
///
/// Used during GetObject/HeadObject to ensure the client provided the correct key.
/// Returns 400 InvalidRequest on mismatch, consistent with AWS S3 behavior.
pub(crate) fn verify_ssec_key_match(
provided_md5: &str,
stored_md5: Option<&String>,
minio_sealed_ssec: bool,
) -> Result<(), SseError> {
match stored_md5 {
Some(stored) if stored == provided_md5 => Ok(()),
Some(_) => Err(ssec_invalid_request(
"The provided encryption parameters did not match the ones used originally to encrypt the object.",
)),
// MinIO never persists the customer-key MD5, so this early check has
// nothing to compare against on a migrated object. The key itself is
// still proven: a wrong key fails the AEAD unseal of the sealed object
// key. The check exists only for the friendlier early error, so its
// absence is tolerated for exactly that shape and no other.
None if minio_sealed_ssec => Ok(()),
None => Err(ssec_invalid_request("Object has no stored SSE-C key metadata.")),
}
}
/// Algorithm an SSE-C object recorded; objects that recorded none were written as `AES256`.
pub(crate) fn stored_ssec_algorithm(metadata: &HashMap<String, String>) -> &str {
metadata
.get("x-amz-server-side-encryption-customer-algorithm")
.map(|s| s.as_str())
.unwrap_or("AES256")
}
/// The customer key and MD5 of a read of an SSE-C object, once both are present and
/// the MD5 matches what the object recorded.
///
/// The key itself is not validated here; the caller does that next, so a request
/// that names the wrong key learns of the mismatch before anything else.
pub(crate) fn require_matching_ssec_key<'r>(
metadata: &HashMap<String, String>,
sse_customer_key: Option<&'r String>,
sse_customer_key_md5: Option<&'r String>,
) -> Result<(&'r String, &'r String), SseError> {
let (key, key_md5) = match (sse_customer_key, sse_customer_key_md5) {
(Some(k), Some(md5)) => (k, md5),
_ => {
return Err(ssec_invalid_request(
"The object was stored using a form of Server Side Encryption. \
The correct parameters must be provided to retrieve the object.",
));
}
};
// Verify that the provided key MD5 matches the stored MD5 for security
let stored_md5 = metadata.get("x-amz-server-side-encryption-customer-key-md5");
verify_ssec_key_match(key_md5, stored_md5, minio_sealed_ssec_metadata(metadata))?;
Ok((key, key_md5))
}
/// Validate that the SSE-C headers required for reading an SSE-C encrypted object
/// are present in the request. This is used by HeadObject which does not decrypt
/// the data but still must verify the caller holds the correct key.
///
/// Performs full validation: decodes the customer key, recomputes its MD5,
/// verifies the client-provided MD5 header matches the key, then compares
/// the computed MD5 against the stored metadata. This prevents a client from
/// bypassing validation by guessing/obtaining only the stored MD5 without
/// possessing the actual encryption key.
///
/// Returns `Ok(())` if either the object is not SSE-C encrypted, or valid SSE-C
/// headers are provided and the key matches. Returns 400 InvalidRequest otherwise.
pub fn validate_ssec_for_read(
metadata: &HashMap<String, String>,
sse_customer_key: Option<&String>,
sse_customer_key_md5: Option<&String>,
) -> Result<(), SseError> {
if !stored_ssec_metadata(metadata) {
return Ok(());
}
let (key, key_md5) = match (sse_customer_key, sse_customer_key_md5) {
(Some(k), Some(md5)) => (k, md5),
_ => {
return Err(ssec_invalid_request(
"The object was stored using a form of Server Side Encryption. \
The correct parameters must be provided to retrieve the object.",
));
}
};
// Full param validation: decode key, verify 32 bytes, recompute MD5
// from actual key bytes and compare to the client-provided MD5 header.
let algorithm = metadata
.get("x-amz-server-side-encryption-customer-algorithm")
.cloned()
.unwrap_or_else(|| DEFAULT_SSE_ALGORITHM.to_string());
let validated = validate_ssec_params(SsecParams {
algorithm,
key: key.to_string(),
key_md5: key_md5.clone(),
})?;
let stored_md5 = metadata.get("x-amz-server-side-encryption-customer-key-md5");
verify_ssec_key_match(&validated.key_md5, stored_md5, minio_sealed_ssec_metadata(metadata))
}
/// Build an `SseError` with `InvalidRequest` (HTTP 400) for SSE-C related errors.
pub fn ssec_invalid_request(message: &str) -> SseError {
SseError {
code: S3ErrorCode::InvalidRequest,
message: message.to_string(),
source: None,
}
}
-550
View File
@@ -1,550 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Write entry points: resolve the encryption material for a new object or multipart upload.
use crate::core::audit::{envelope_master_key_version, record_managed_kms_outcome};
use crate::core::keying::context::build_object_encryption_context;
use crate::core::keying::material::EncryptionMaterial;
use crate::core::keying::{
SESSION_KEY_NEEDS_CUSTOMER_KEY, new_key_under_customer_key, new_key_under_data_key, new_session_key_under_customer_key,
};
use crate::core::request::SseKmsPrincipal;
use crate::core::s3::authorization::authorize_sse_kms_key;
use crate::core::s3::headers::reject_kms_context_location_override;
use crate::core::s3::scheme::{
DEFAULT_SSE_ALGORITHM, WriteScheme, WriteSchemeHeaders, is_managed_sse, managed_sse_type, resolve_write_scheme,
};
use crate::core::s3::ssec::{SsecParams, ssec_invalid_request, validate_ssec_params, verify_ssec_key_match};
use crate::error::SseError;
use crate::host::SseHost;
use crate::kms::provider::get_sse_dek_provider;
use base64_simd::STANDARD as BASE64_STANDARD;
use rustfs_kms::KmsUnavailableError;
use rustfs_policy::policy::action::KmsAction;
use rustfs_s3_types::S3ErrorCode;
use rustfs_utils::http::headers::{AMZ_ENCRYPTION_AES, AMZ_ENCRYPTION_KMS};
use rustfs_utils::http::object_encryption_keys::SSEType;
use std::collections::HashMap;
/// Request parameters for unified encryption
#[derive(Clone)]
pub struct EncryptionRequest<'a> {
/// Bucket name
pub bucket: &'a str,
/// Object key
pub key: &'a str,
/// Server-side encryption algorithm (SSE-S3 or SSE-KMS)
pub server_side_encryption: Option<String>,
/// KMS key ID (for SSE-KMS)
pub ssekms_key_id: Option<String>,
/// Optional client-provided KMS context for SSE-KMS.
pub ssekms_context: Option<HashMap<String, String>>,
/// SSE-C algorithm (customer-provided key)
pub sse_customer_algorithm: Option<String>,
/// SSE-C key (Base64-encoded)
pub sse_customer_key: Option<String>,
/// SSE-C key MD5 (Base64-encoded)
pub sse_customer_key_md5: Option<String>,
/// Content size (for metadata)
pub content_size: i64,
/// Caller the SSE-KMS key usage is authorized as. `None` marks an internal caller.
pub principal: Option<&'a SseKmsPrincipal>,
}
impl std::fmt::Debug for EncryptionRequest<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EncryptionRequest")
.field("server_side_encryption", &self.server_side_encryption)
.field("content_size", &self.content_size)
.finish_non_exhaustive()
}
}
impl EncryptionRequest<'_> {
pub fn validate_complete_multipart_ssec(&self, user_defined: &HashMap<String, String>) -> Result<(), SseError> {
let request_uses_ssec =
self.sse_customer_algorithm.is_some() || self.sse_customer_key.is_some() || self.sse_customer_key_md5.is_some();
if !request_uses_ssec {
let stored_algorithm = user_defined.get("x-amz-server-side-encryption-customer-algorithm");
let stored_key_md5 = user_defined.get("x-amz-server-side-encryption-customer-key-md5");
return match (stored_algorithm, stored_key_md5) {
(None, None) => Ok(()),
(Some(algorithm), Some(key_md5))
if algorithm == DEFAULT_SSE_ALGORITHM
&& BASE64_STANDARD
.decode_to_vec(key_md5)
.is_ok_and(|decoded| decoded.len() == 16) =>
{
if rustfs_utils::http::contains_key_str(user_defined, rustfs_utils::http::SUFFIX_PLAINTEXT_CHECKSUM) {
return Err(ssec_invalid_request(
"SSE-C multipart uploads with additional checksums require the customer key for completion.",
));
}
Ok(())
}
_ => Err(ssec_invalid_request("The multipart upload contains invalid SSE-C metadata.")),
};
}
self.validate_multipart_ssec(user_defined)
}
pub fn validate_multipart_ssec(&self, user_defined: &HashMap<String, String>) -> Result<(), SseError> {
let stored_algorithm = user_defined.get("x-amz-server-side-encryption-customer-algorithm");
let stored_key_md5 = user_defined.get("x-amz-server-side-encryption-customer-key-md5");
let session_uses_ssec = stored_algorithm.is_some() || stored_key_md5.is_some();
let request_uses_ssec =
self.sse_customer_algorithm.is_some() || self.sse_customer_key.is_some() || self.sse_customer_key_md5.is_some();
if !session_uses_ssec {
return if request_uses_ssec {
Err(ssec_invalid_request(
"SSE-C parameters cannot be used for a multipart upload that was not initiated with SSE-C.",
))
} else {
Ok(())
};
}
let (Some(algorithm), Some(key), Some(key_md5)) = (
self.sse_customer_algorithm.as_ref(),
self.sse_customer_key.as_ref(),
self.sse_customer_key_md5.as_ref(),
) else {
return Err(ssec_invalid_request(
"Missing SSE-C parameters. Algorithm, customer key and customer key MD5 are all required.",
));
};
let validated = validate_ssec_params(SsecParams {
algorithm: algorithm.to_string(),
key: key.to_string(),
key_md5: key_md5.to_string(),
})?;
if stored_algorithm.map(String::as_str) != Some(validated.algorithm.as_str()) {
return Err(ssec_invalid_request(
"The provided encryption parameters did not match the multipart upload.",
));
}
// Multipart session metadata is written by our own CreateMultipartUpload,
// which always records the MD5 — the MinIO no-stored-MD5 shape cannot occur.
verify_ssec_key_match(&validated.key_md5, stored_key_md5, false)
}
}
/// **Core API**: Apply encryption based on request parameters
///
/// This function automatically routes to the appropriate encryption method:
/// - SSE-C if customer key is provided
/// - SSE-S3/SSE-KMS if server-side encryption is requested
/// - None if no encryption is requested
///
/// # Arguments
/// * `request` - Encryption request with all possible encryption parameters
///
/// # Returns
/// * `Ok(Some(material))` - Encryption should be applied with the returned material
/// * `Ok(None)` - No encryption requested
/// * `Err` - Encryption configuration error
///
/// # Example
/// ```rust,ignore
/// let request = EncryptionRequest {
/// bucket: &bucket,
/// key: &key,
/// server_side_encryption: effective_sse.as_ref(),
/// ssekms_key_id: effective_kms_key_id.as_deref(),
/// sse_customer_algorithm: sse_customer_algorithm.as_ref(),
/// sse_customer_key: sse_customer_key.as_deref(),
/// sse_customer_key_md5: sse_customer_key_md5.as_deref(),
/// content_size: actual_size,
/// part_number: None,
/// };
///
/// if let Some(material) = sse_encryption(host, request).await? {
/// reader = material.wrap_reader(reader);
/// metadata.extend(material.metadata);
/// }
/// ```
pub async fn sse_encryption(host: &dyn SseHost, request: EncryptionRequest<'_>) -> Result<Option<EncryptionMaterial>, SseError> {
let scheme = resolve_write_scheme(
host,
request.bucket,
WriteSchemeHeaders {
server_side_encryption: request.server_side_encryption,
ssekms_key_id: request.ssekms_key_id,
ssekms_context: request.ssekms_context.as_ref(),
sse_customer_algorithm: request.sse_customer_algorithm,
sse_customer_key: request.sse_customer_key,
sse_customer_key_md5: request.sse_customer_key_md5,
},
)
.await?;
let (server_side_encryption, kms_key_id) = match scheme {
None => return Ok(None),
Some(WriteScheme::SseC { algorithm, key, key_md5 }) => {
return apply_ssec_encryption_material(request.bucket, request.key, algorithm, key, key_md5, request.content_size)
.await
.map(Some);
}
Some(WriteScheme::SseS3) => (String::from(AMZ_ENCRYPTION_AES), None),
Some(WriteScheme::SseKms { key_id }) => (String::from(AMZ_ENCRYPTION_KMS), key_id),
};
apply_managed_encryption_material(
host,
ManagedEncryptionRequest {
bucket: request.bucket,
key: request.key,
server_side_encryption,
kms_key_id,
ssekms_context: request.ssekms_context,
content_size: request.content_size,
principal: request.principal,
},
)
.await
.map(Some)
}
/// **Core API**: Apply encryption based on request parameters
///
/// sse_prepare_encryption, support SSE-C, SSE-S3, SSE-KMS
pub struct PrepareEncryptionRequest<'a> {
/// Bucket name
pub bucket: &'a str,
/// Object key
pub key: &'a str,
/// Server-side encryption algorithm (SSE-S3 or SSE-KMS)
pub server_side_encryption: Option<String>,
/// KMS key ID (for SSE-KMS)
pub ssekms_key_id: Option<String>,
/// Optional client-provided KMS context for SSE-KMS.
pub ssekms_context: Option<HashMap<String, String>>,
/// SSE-C algorithm (customer-provided key)
pub sse_customer_algorithm: Option<String>,
/// SSE-C key (Base64-encoded)
pub sse_customer_key: Option<String>,
/// SSE-C key MD5 (Base64-encoded)
pub sse_customer_key_md5: Option<String>,
/// Caller the SSE-KMS key usage is authorized as. `None` marks an internal caller.
///
/// This is the only point at which a multipart upload evaluates KMS key permissions:
/// it is where the session data key is generated. `UploadPart`, `UploadPartCopy` and
/// `CompleteMultipartUpload` reuse that envelope and are not re-authorized.
pub principal: Option<&'a SseKmsPrincipal>,
}
pub async fn sse_prepare_encryption(
host: &dyn SseHost,
request: PrepareEncryptionRequest<'_>,
) -> Result<Option<EncryptionMaterial>, SseError> {
let scheme = resolve_write_scheme(
host,
request.bucket,
WriteSchemeHeaders {
server_side_encryption: request.server_side_encryption,
ssekms_key_id: request.ssekms_key_id,
ssekms_context: request.ssekms_context.as_ref(),
sse_customer_algorithm: request.sse_customer_algorithm,
sse_customer_key: request.sse_customer_key,
sse_customer_key_md5: request.sse_customer_key_md5,
},
)
.await?;
let (server_side_encryption, kms_key_id) = match scheme {
None => return Ok(None),
Some(WriteScheme::SseC { algorithm, key, key_md5 }) => {
return apply_ssec_prepare_encryption_material(request.bucket, request.key, algorithm, Some(key), key_md5)
.await
.map(Some);
}
Some(WriteScheme::SseS3) => (String::from(AMZ_ENCRYPTION_AES), None),
Some(WriteScheme::SseKms { key_id }) => (String::from(AMZ_ENCRYPTION_KMS), key_id),
};
// A session records no plaintext size: the parts decide it.
apply_managed_encryption_material(
host,
ManagedEncryptionRequest {
bucket: request.bucket,
key: request.key,
server_side_encryption,
kms_key_id,
ssekms_context: request.ssekms_context,
content_size: 0,
principal: request.principal,
},
)
.await
.map(Some)
}
async fn apply_ssec_prepare_encryption_material(
bucket: &str,
key: &str,
algorithm: String,
sse_key: Option<String>,
sse_key_md5: String,
) -> Result<EncryptionMaterial, SseError> {
// The customer key is validated here only in a mode that seals the session's
// key under it. Otherwise it is validated per part, against what the session
// records.
let customer_key = match sse_key {
Some(sse_key) if SESSION_KEY_NEEDS_CUSTOMER_KEY => Some(
validate_ssec_params(SsecParams {
algorithm: algorithm.clone(),
key: sse_key,
key_md5: sse_key_md5.clone(),
})?
.key_bytes,
),
_ => None,
};
let object_key = new_session_key_under_customer_key(customer_key, bucket, key)?;
Ok(EncryptionMaterial {
sse_type: SSEType::SseC,
server_side_encryption: String::from(AMZ_ENCRYPTION_AES),
kms_key_id: None,
algorithm,
key_bytes: object_key.key_bytes,
base_nonce: object_key.base_nonce,
encrypted_data_key: None,
customer_key_md5: Some(sse_key_md5),
original_size: None,
key_kind: object_key.key_kind,
managed_kms_context: None,
managed_sealed_key: object_key.sealed_key,
})
}
async fn apply_ssec_encryption_material(
bucket: &str,
key: &str,
algorithm: String,
sse_key: String,
sse_key_md5: String,
content_size: i64,
) -> Result<EncryptionMaterial, SseError> {
let params = SsecParams {
algorithm,
key: sse_key,
key_md5: sse_key_md5,
};
let validated = validate_ssec_params(params)?;
let object_key = new_key_under_customer_key(validated.key_bytes, bucket, key)?;
// Build metadata
Ok(EncryptionMaterial {
sse_type: SSEType::SseC,
server_side_encryption: String::from(AMZ_ENCRYPTION_AES),
kms_key_id: None,
algorithm: validated.algorithm,
key_bytes: object_key.key_bytes,
base_nonce: object_key.base_nonce,
encrypted_data_key: None,
customer_key_md5: Some(validated.key_md5),
original_size: Some(content_size),
key_kind: object_key.key_kind,
managed_kms_context: None,
managed_sealed_key: object_key.sealed_key,
})
}
/// A managed-SSE (SSE-S3 / SSE-KMS) write, once its effective scheme is known.
pub(crate) struct ManagedEncryptionRequest<'a> {
pub(crate) bucket: &'a str,
pub(crate) key: &'a str,
pub(crate) server_side_encryption: String,
pub(crate) kms_key_id: Option<String>,
pub(crate) ssekms_context: Option<HashMap<String, String>>,
pub(crate) content_size: i64,
pub(crate) principal: Option<&'a SseKmsPrincipal>,
}
pub(crate) async fn apply_managed_encryption_material(
host: &dyn SseHost,
request: ManagedEncryptionRequest<'_>,
) -> Result<EncryptionMaterial, SseError> {
// Request validation, not a KMS operation: reject before the KMS is called
// and before an audit outcome is recorded.
reject_kms_context_location_override(request.bucket, request.ssekms_context.as_ref())?;
let principal = request.principal;
let requested_sse_type = managed_sse_type(request.server_side_encryption.as_str());
let requested_key_id = request.kms_key_id.clone();
let result = apply_managed_encryption_material_inner(host, request).await;
match &result {
// The resolved key is only known on success: it may come from the request,
// the bucket default or the KMS service default. On failure the audit entry
// records what the caller asked for, which is what a reader needs to see.
Ok(material) => record_managed_kms_outcome(
principal,
material.sse_type,
material.kms_key_id.as_deref(),
|| material.encrypted_data_key.as_deref().and_then(envelope_master_key_version),
Ok(()),
),
Err(error) => record_managed_kms_outcome(principal, requested_sse_type, requested_key_id.as_deref(), || None, Err(error)),
}
result
}
pub(crate) async fn apply_managed_encryption_material_inner(
host: &dyn SseHost,
request: ManagedEncryptionRequest<'_>,
) -> Result<EncryptionMaterial, SseError> {
let ManagedEncryptionRequest {
bucket,
key,
server_side_encryption,
kms_key_id,
ssekms_context,
content_size,
principal,
} = request;
if !is_managed_sse(&server_side_encryption) {
return Err(SseError::internal(format!(
"Unsupported server-side encryption: {}",
server_side_encryption.as_str()
)));
}
let encryption_type = match server_side_encryption.as_str() {
"AES256" => SSEType::SseS3,
"aws:kms" => SSEType::SseKms,
_ => SSEType::SseS3,
};
// Determine KMS key ID to use for internal key wrapping.
let mut kms_key_candidate = kms_key_id.clone();
if kms_key_candidate.is_none() {
// Try to get default key from KMS service (if available)
if let Some(service) = host.encryption_service().await {
kms_key_candidate = service.get_default_key_id().cloned();
tracing::debug!(
default_key_id = ?kms_key_candidate,
"SSE-S3: KMS service available, default_key_id from config"
);
} else {
tracing::debug!("SSE-S3: KMS encryption service not available");
}
}
let kms_key_to_use = match (encryption_type, kms_key_candidate.clone()) {
(SSEType::SseS3, Some(kms_key_id)) => kms_key_id,
(SSEType::SseS3, None) => {
tracing::debug!("SSE-S3: no KMS key configured, falling back to \"default\" key ID");
"default".to_string()
}
(SSEType::SseKms, Some(kms_key_id)) => kms_key_id,
(SSEType::SseKms, None) => {
// Neither the request nor the bucket default named a key and no
// service default filled in. Without a service this is the same
// outage/misconfiguration the provider check below reports, so it
// must carry the same 503/400 split rather than an untyped
// internal error; with a running service that has no default key
// the caller simply has to name one.
if host.encryption_service().await.is_none() {
return Err(sse_kms_unavailable_error(kms_configured_but_unavailable(host).await));
}
return Err(SseError {
code: S3ErrorCode::InvalidRequest,
message: "SSE-KMS requires a KMS key id: the request named none and the KMS service has no default key"
.to_string(),
source: None,
});
}
_ => unreachable!("managed SSE branch only supports SSE-S3 or SSE-KMS"),
};
// The key is fully resolved here (request header, then bucket default, then the KMS
// service default), so this is the first point at which the caller can be held to the
// key it will actually be encrypted under.
authorize_sse_kms_key(host, principal, encryption_type, KmsAction::GenerateDataKeyAction, &kms_key_to_use).await?;
// A node-local master key is the explicit SSE-S3 fallback. Letting it serve
// an SSE-KMS request would persist an `aws:kms` marker and a KMS key id
// that never wrapped the data key, so refuse rather than downgrade.
//
// The refusal sits after the authorization gate so an unauthorized caller
// still sees AccessDenied whatever the KMS runtime state is, and it asks
// the resolved provider rather than a parallel availability signal,
// because the provider is what actually wraps the DEK.
let provider = match get_sse_dek_provider(host).await {
Ok(provider) => {
if matches!(encryption_type, SSEType::SseKms) && provider.wraps_dek_with_local_master_key() {
return Err(sse_kms_unavailable_error(kms_configured_but_unavailable(host).await));
}
provider
}
// With no master key set the local fallback fails with an SSE-S3-worded
// configuration error. An SSE-KMS request never asked for that provider,
// so it gets the SSE-KMS refusal instead of a message naming the wrong
// scheme.
Err(err) => {
if matches!(encryption_type, SSEType::SseKms) && host.encryption_service().await.is_none() {
return Err(sse_kms_unavailable_error(kms_configured_but_unavailable(host).await));
}
return Err(err);
}
};
let object_context = build_object_encryption_context(bucket, key, ssekms_context.as_ref());
let (data_key, encrypted_data_key) = provider.generate_sse_dek(&object_context, &kms_key_to_use).await?;
let algorithm = server_side_encryption.as_str().to_string();
let object_key = new_key_under_data_key(&data_key, encryption_type, bucket, key)?;
Ok(EncryptionMaterial {
sse_type: encryption_type,
server_side_encryption,
kms_key_id: Some(kms_key_to_use),
algorithm,
key_bytes: object_key.key_bytes,
base_nonce: object_key.base_nonce,
encrypted_data_key: Some(encrypted_data_key),
customer_key_md5: None,
original_size: Some(content_size),
key_kind: object_key.key_kind,
managed_kms_context: matches!(encryption_type, SSEType::SseKms).then_some(ssekms_context.unwrap_or_default()),
managed_sealed_key: object_key.sealed_key,
})
}
/// Whether this node has a KMS configured that is not currently serving, which
/// separates a transient outage (retryable, 503) from a deployment that never
/// configured KMS at all (a client-side configuration error, 400).
async fn kms_configured_but_unavailable(host: &dyn SseHost) -> bool {
match host.kms_service_manager() {
Some(manager) => !matches!(manager.get_status().await, rustfs_kms::KmsServiceStatus::NotConfigured),
None => false,
}
}
pub(crate) fn sse_kms_unavailable_error(configured_but_unavailable: bool) -> SseError {
if configured_but_unavailable {
return SseError::internal(KmsUnavailableError);
}
SseError {
code: S3ErrorCode::InvalidRequest,
message: "SSE-KMS requires a configured and running KMS service".to_string(),
source: None,
}
}
-176
View File
@@ -1,176 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The error every SSE operation reports, already classified for the S3 data path.
use rustfs_kms::{KmsError, KmsUnavailableError};
use rustfs_s3_types::S3ErrorCode;
type BoxError = Box<dyn std::error::Error + Send + Sync>;
/// S3 error code a KMS key that does not exist is reported under.
pub const KMS_KEY_NOT_FOUND_ERROR_CODE: &str = "KMS.NotFoundException";
pub(crate) const INTERNAL_ERROR_MESSAGE: &str = "We encountered an internal error, please try again.";
const SERVICE_UNAVAILABLE_MESSAGE: &str = "The service is unavailable. Please retry.";
const ACCESS_DENIED_MESSAGE: &str = "Access Denied.";
/// A failed SSE operation, carrying the S3 error code and message the caller answers with.
///
/// `source` keeps the underlying failure for logs and for classification by
/// callers; it is never part of the response.
#[derive(Debug)]
pub struct SseError {
pub code: S3ErrorCode,
pub message: String,
pub source: Option<BoxError>,
}
impl SseError {
/// Classify a failure that did not originate from the request itself.
///
/// A [`KmsUnavailableError`] is a retryable `ServiceUnavailable`, a
/// [`KmsError`] follows [`data_plane_kms_error`], and everything else is an
/// `InternalError` whose detail stays in `source` and out of the response.
pub fn internal(error: impl Into<BoxError>) -> Self {
let source = error.into();
let (code, message) = if source.downcast_ref::<KmsUnavailableError>().is_some() {
(S3ErrorCode::ServiceUnavailable, SERVICE_UNAVAILABLE_MESSAGE.to_string())
} else if let Some(classified) = source.downcast_ref::<KmsError>().and_then(data_plane_kms_error) {
classified
} else {
(S3ErrorCode::InternalError, INTERNAL_ERROR_MESSAGE.to_string())
};
Self {
code,
message,
source: Some(source),
}
}
}
impl std::fmt::Display for SseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for SseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_deref().map(|source| source as _)
}
}
/// Map a KMS failure that surfaced on the S3 data path to its S3 error code.
///
/// The contract deliberately differs from the admin key-lifecycle handlers:
/// there a key id is the resource being addressed, so a missing key is `404`.
/// Here the key id arrives inside a request header or a bucket default, so a
/// key that is missing, disabled, or otherwise unusable is configuration the
/// caller has to correct — AWS answers `400`, and reporting `500` instead both
/// misfiles the failure as a server fault and makes SDKs back off and retry a
/// request that cannot succeed.
///
/// `None` keeps the caller's fallthrough, which is the `500` that integrity
/// faults — damaged, unreadable, or unknown-format key material — must keep.
///
/// Messages either name what the caller asked for or stay generic; detail that
/// belongs to the deployment rather than the request stays in `source`, which
/// the caller attaches and the logs retain.
pub fn data_plane_kms_error(error: &KmsError) -> Option<(S3ErrorCode, String)> {
use KmsError as Kms;
match error {
Kms::KeyNotFound { key_id } => Some((
S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into()),
format!("KMS key not found: {key_id}"),
)),
Kms::KeyVersionNotFound { key_id, version } => Some((
S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into()),
format!("KMS key version {version} not found for key {key_id}"),
)),
// The key exists but its state forbids the operation (disabled,
// pending deletion). AWS treats an invalid key state as a request
// error, not a server fault.
Kms::InvalidOperation { .. } => Some((S3ErrorCode::InvalidRequest, error.to_string())),
// A policy decision needs a human, so it must be distinguishable from
// the transient classes an SDK retries.
Kms::AccessDenied { .. } => Some((S3ErrorCode::AccessDenied, ACCESS_DENIED_MESSAGE.to_string())),
// Request-side faults: what was asked for cannot be served as asked.
Kms::ContextMismatch { .. }
| Kms::InvalidKey { .. }
| Kms::ValidationError { .. }
| Kms::UnsupportedAlgorithm { .. }
| Kms::InvalidKeySize { .. } => Some((S3ErrorCode::InvalidRequest, error.to_string())),
// A deployment whose KMS configuration cannot serve the request (for
// example no key named and no default). Actionable, but the detail
// describes the deployment, so it stays out of the response body.
Kms::ConfigurationError { .. } => {
Some((S3ErrorCode::InvalidRequest, "The KMS configuration cannot serve this request".to_string()))
}
// Transient: worth retrying, and must be counted against availability
// rather than against the caller. `IoError` belongs here because it is
// how a backend reports that its key store itself was unreachable —
// rustfs/rustfs#7470 separated that from a missing key precisely so the
// two stop looking alike, and leaving it on the 500 fallthrough would
// erase that distinction again at the S3 boundary.
Kms::BackendError { .. }
| Kms::IoError { .. }
| Kms::OperationTimedOut { .. }
| Kms::OperationCancelled { .. }
| Kms::CredentialsUnavailable { .. }
| Kms::CacheError { .. } => Some((S3ErrorCode::ServiceUnavailable, SERVICE_UNAVAILABLE_MESSAGE.to_string())),
// A permanent gap in the configured backend, never a missing resource.
Kms::UnsupportedCapability { .. } => Some((S3ErrorCode::NotImplemented, error.to_string())),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn internal_keeps_request_free_failures_generic() {
let error = SseError::internal("Failed to decode IV: bad base64");
assert_eq!(error.code, S3ErrorCode::InternalError);
assert_eq!(error.message, INTERNAL_ERROR_MESSAGE);
assert!(
error
.source
.as_ref()
.is_some_and(|source| source.to_string().contains("Failed to decode IV"))
);
}
#[test]
fn internal_reports_an_unavailable_kms_as_retryable() {
let error = SseError::internal(KmsUnavailableError);
assert_eq!(error.code, S3ErrorCode::ServiceUnavailable);
assert_eq!(error.message, SERVICE_UNAVAILABLE_MESSAGE);
}
#[test]
fn internal_classifies_kms_errors_for_the_data_path() {
let missing = SseError::internal(KmsError::key_not_found("absent-key"));
assert_eq!(missing.code, S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into()));
assert_eq!(missing.message, "KMS key not found: absent-key");
let damaged = SseError::internal(KmsError::cryptographic_error("decrypt", "authentication failed"));
assert_eq!(damaged.code, S3ErrorCode::InternalError);
assert_eq!(damaged.message, INTERNAL_ERROR_MESSAGE);
}
}
-85
View File
@@ -1,85 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! What SSE needs from the server it runs in.
//!
//! This crate reaches the running server only through [`SseHost`]: it holds no
//! handle to the storage engine, to IAM, or to the bucket metadata system. Every
//! entry point that consults the server takes the host as its first argument, so
//! a caller cannot reach key selection without saying which server it speaks for.
use crate::{SseError, SseKmsPrincipal};
use async_trait::async_trait;
use rustfs_kms::KmsServiceManager;
use rustfs_kms::service::ObjectEncryptionService;
use rustfs_policy::policy::action::KmsAction;
use std::sync::Arc;
/// The server capabilities SSE key resolution depends on.
#[async_trait]
pub trait SseHost: Send + Sync {
/// The KMS object-encryption service currently serving, if one is.
///
/// Resolved on every call: the KMS backend can be reconfigured while the
/// server runs, so a service handle must not outlive the operation it serves.
async fn encryption_service(&self) -> Option<Arc<ObjectEncryptionService>>;
/// The KMS service manager, when the server has one.
///
/// Only its status is read, to tell a configured KMS that is not serving
/// (retryable) from a deployment that never configured one (a request error).
fn kms_service_manager(&self) -> Option<Arc<KmsServiceManager>>;
/// The bucket's default-encryption configuration.
///
/// `Ok(None)` means the bucket has no encryption configuration.
///
/// # Errors
///
/// Any failure to read the configuration, already classified for the S3
/// response. A write must not proceed as if the bucket had no default when
/// the configuration could not be read.
async fn bucket_encryption(&self, bucket: &str) -> Result<Option<BucketEncryption>, SseError>;
/// The authorizer deciding per-key KMS permissions on the data path.
fn kms_key_authorizer(&self) -> &dyn KmsKeyAuthorizer;
}
/// A bucket's stored encryption configuration, reduced to what a write consults.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BucketEncryption {
/// The default-encryption rule of the first configuration rule, if it has one.
pub default_rule: Option<BucketDefaultEncryption>,
}
/// The `ApplyServerSideEncryptionByDefault` element of a bucket encryption rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BucketDefaultEncryption {
/// The stored algorithm, exactly as persisted (`AES256`, `aws:kms`, or an unknown value).
pub sse_algorithm: String,
pub kms_master_key_id: Option<String>,
}
/// Decides whether a principal may use a specific KMS key on the data path.
///
/// Behind a trait so tests can pin the allow/deny contract of the SSE call sites
/// without a running IAM subsystem.
#[async_trait]
pub trait KmsKeyAuthorizer: Send + Sync {
/// # Errors
///
/// When the decision itself could not be made, for example because the
/// policy subsystem is not ready. A denial is `Ok(false)`.
async fn is_allowed(&self, principal: &SseKmsPrincipal, action: KmsAction, key_id: &str) -> Result<bool, SseError>;
}
-180
View File
@@ -1,180 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The provider that wraps and unwraps data keys through the KMS service.
use crate::core::audit::KmsDataPlaneFailure;
use crate::error::SseError;
use crate::host::SseHost;
use crate::kms::provider::SseDekProvider;
use async_trait::async_trait;
use rustfs_kms::types::ObjectEncryptionContext;
use rustfs_kms::{DataKey, KmsUnavailableError};
use rustfs_s3_types::S3ErrorCode;
use std::sync::Arc;
/// Production KMS-backed DEK provider
/// Resolves the latest ObjectEncryptionService on each call.
pub(crate) struct KmsSseDekProvider<'a> {
service_source: KmsServiceSource<'a>,
}
/// Where a [`KmsSseDekProvider`] finds the service that is serving right now.
enum KmsServiceSource<'a> {
Host(&'a dyn SseHost),
#[cfg(test)]
Manager(Arc<rustfs_kms::KmsServiceManager>),
}
pub(crate) fn kms_operation_error(error: rustfs_kms::KmsError) -> SseError {
let class = rustfs_kms::audit::error_class(&error);
let mut api_error = SseError::internal(error);
// Wrap rather than replace the source so the original chain stays intact for
// logging; the wrapper only adds the class the audit attachment needs.
let source = api_error.source.take();
api_error.source = Some(Box::new(KmsDataPlaneFailure { class, source }));
api_error
}
/// Classification for a failed data-key unwrap.
///
/// An AEAD failure stays `500` (the envelope is an integrity fault, not a
/// request a retry or a different header can fix), but the generic internal
/// error text hides the one diagnosis an operator needs: the configured
/// backend holds different key material under this key id than the one that
/// wrapped the object, typically after re-creating a key of the same name or
/// switching backends.
pub(crate) fn kms_unwrap_error(error: rustfs_kms::KmsError) -> SseError {
let unwrap_rejected = matches!(error, rustfs_kms::KmsError::CryptographicError { .. });
let mut api_error = kms_operation_error(error);
if unwrap_rejected && api_error.code == S3ErrorCode::InternalError {
api_error.message = "The object's data key envelope could not be unwrapped by the configured KMS backend: the \
key material under this key id differs from the one that wrapped it, or the envelope is damaged"
.to_string();
}
api_error
}
impl<'a> KmsSseDekProvider<'a> {
/// Create a new KMS-backed provider
pub async fn new(host: &'a dyn SseHost) -> Result<Self, SseError> {
let provider = Self {
service_source: KmsServiceSource::Host(host),
};
provider
.current_service()
.await
.ok_or_else(|| SseError::internal(KmsUnavailableError))?;
Ok(provider)
}
#[cfg(test)]
pub(crate) async fn new_with_service_manager(service_manager: Arc<rustfs_kms::KmsServiceManager>) -> Result<Self, SseError> {
let provider = Self {
service_source: KmsServiceSource::Manager(service_manager),
};
provider
.current_service()
.await
.ok_or_else(|| SseError::internal(KmsUnavailableError))?;
Ok(provider)
}
async fn current_service(&self) -> Option<Arc<rustfs_kms::service::ObjectEncryptionService>> {
match &self.service_source {
KmsServiceSource::Host(host) => host.encryption_service().await,
#[cfg(test)]
KmsServiceSource::Manager(service_manager) => service_manager.get_encryption_service().await,
}
}
}
#[async_trait]
impl SseDekProvider for KmsSseDekProvider<'_> {
async fn generate_sse_dek(
&self,
context: &ObjectEncryptionContext,
kms_key_id: &str,
) -> Result<(DataKey, Vec<u8>), SseError> {
let kms_key_option = Some(kms_key_id.to_string());
let service = self
.current_service()
.await
.ok_or_else(|| SseError::internal(KmsUnavailableError))?;
let (data_key, encrypted_data_key) = service
.create_data_key(&kms_key_option, context)
.await
.map_err(kms_operation_error)?;
Ok((data_key, encrypted_data_key))
}
async fn reads_bare_data_key_ciphertext(&self) -> bool {
self.current_service()
.await
.is_some_and(|service| service.reads_bare_data_key_ciphertext())
}
async fn rewrap_sse_dek(
&self,
encrypted_dek: &[u8],
context: &ObjectEncryptionContext,
) -> Result<rustfs_kms::types::RewrapDataKeyResponse, SseError> {
let service = self
.current_service()
.await
.ok_or_else(|| SseError::internal(KmsUnavailableError))?;
service
.rewrap_data_key(encrypted_dek, context)
.await
.map_err(kms_operation_error)
}
async fn decrypt_sse_dek(
&self,
encrypted_dek: &[u8],
_kms_key_id: &str,
context: &ObjectEncryptionContext,
) -> Result<[u8; 32], SseError> {
let service = self
.current_service()
.await
.ok_or_else(|| SseError::internal(KmsUnavailableError))?;
let data_key = service
.decrypt_data_key(encrypted_dek, context)
.await
.map_err(kms_unwrap_error)?;
Ok(data_key.plaintext_key)
}
#[cfg(feature = "rio-v2")]
async fn decrypt_legacy_sse_dek(
&self,
encrypted_dek: &[u8],
_kms_key_id: &str,
_context: &ObjectEncryptionContext,
) -> Result<[u8; 32], SseError> {
let service = self
.current_service()
.await
.ok_or_else(|| SseError::internal(KmsUnavailableError))?;
let data_key = service
.decrypt_legacy_data_key(encrypted_dek)
.await
.map_err(kms_unwrap_error)?;
Ok(data_key.plaintext_key)
}
}
-323
View File
@@ -1,323 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The provider that wraps data keys with a node-local master key when no KMS is configured.
use crate::error::SseError;
#[cfg(feature = "rio-v2")]
use crate::kms::minio::{decrypt_minio_kms_data_key, minio_kms_associated_data};
use crate::kms::provider::SseDekProvider;
use aes_gcm::aead::{Aead, KeyInit};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use async_trait::async_trait;
use base64_simd::STANDARD as BASE64_STANDARD;
use rand::Rng;
use rustfs_kms::DataKey;
use rustfs_kms::types::ObjectEncryptionContext;
use rustfs_s3_types::S3ErrorCode;
use rustfs_utils::get_env_opt_str;
use serde::{Deserialize, Serialize};
/// Local SSE DEK provider for deployments without a KMS.
///
/// Uses `RUSTFS_SSE_S3_MASTER_KEY` (base64-encoded 32-byte key) to wrap
/// data-encryption keys with AES-256-GCM. This is the production fallback
/// when no KMS service is configured.
///
/// # Environment Variable
///
/// ```text
/// RUSTFS_SSE_S3_MASTER_KEY=<base64_encoded_32_byte_key>
/// ```
pub struct LocalSseDekProvider {
master_key: [u8; 32],
}
pub(crate) const LOCAL_SSE_DEK_FORMAT_VERSION: u8 = 1;
/// Environment variable that carries the local SSE-S3 master key.
pub(crate) const ENV_SSE_S3_MASTER_KEY: &str = "RUSTFS_SSE_S3_MASTER_KEY";
/// The configured local master key, still encoded; `None` when unset or blank.
fn local_master_key_env_value() -> Option<String> {
get_env_opt_str(ENV_SSE_S3_MASTER_KEY).filter(|value| !value.trim().is_empty())
}
/// Whether the operator configured a local SSE-S3 master key at all.
///
/// Says nothing about whether the value is usable; loading it decides that.
pub(crate) fn local_master_key_configured() -> bool {
local_master_key_env_value().is_some()
}
#[cfg(feature = "rio-v2")]
/// Returns true when a managed-SSE data key is one RustFS itself wrote.
///
/// Both RustFS envelope shapes are strict JSON — the KMS envelope
/// ([`rustfs_kms::is_data_key_envelope`]) and the local provider's
/// [`LocalSseDekEnvelope`], whose `deny_unknown_fields` keeps it from accepting
/// anything else. Recognition is deliberately positive: an unrecognized payload
/// is left to MinIO's decoder rather than guessed at, and neither decoder is
/// ever handed the other's format.
pub(crate) fn is_rustfs_managed_data_key(encrypted_dek: &[u8]) -> bool {
if rustfs_kms::is_data_key_envelope(encrypted_dek) {
return true;
}
std::str::from_utf8(encrypted_dek)
.ok()
.is_some_and(|text| serde_json::from_str::<LocalSseDekEnvelope<'_>>(text).is_ok())
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct LocalSseDekEnvelope<'a> {
pub(crate) version: u8,
pub(crate) nonce: &'a str,
ciphertext: &'a str,
}
/// Whether [`LocalSseDekProvider`] could have written these bytes.
///
/// Covers both shapes [`LocalSseDekProvider::decrypt_dek`] accepts — anything
/// presented as a JSON object, so a damaged local envelope keeps its own
/// diagnosis, and the deprecated `nonce:ciphertext` base64 pair. Everything
/// else is bytes the local provider can only reject.
pub(crate) fn is_local_sse_dek(encrypted_dek: &[u8]) -> bool {
let Ok(text) = std::str::from_utf8(encrypted_dek) else {
return false;
};
if text.trim_start().starts_with('{') {
return true;
}
let is_base64 = |part: &str| BASE64_STANDARD.decode_to_vec(part).is_ok();
text.split_once(':')
.is_some_and(|(nonce, ciphertext)| is_base64(nonce) && is_base64(ciphertext))
}
/// Test-only alias so existing test code that references `TestSseDekProvider`
/// continues to compile without changes.
#[cfg(any(test, feature = "test-util"))]
#[allow(non_camel_case_types)]
pub type TestSseDekProvider = LocalSseDekProvider;
/// Parse the base64-encoded 32-byte master key from `__RUSTFS_SSE_SIMPLE_CMK`.
///
/// Returns an error (never crashes) for a missing, non-base64, wrong-length, or
/// all-zero key so callers on the request path can fail the request instead of
/// taking the whole server down (backlog#806).
#[cfg(any(test, feature = "test-util"))]
pub(crate) fn parse_simple_sse_cmk(cmk_value: &str) -> Result<[u8; 32], SseError> {
let trimmed = cmk_value.trim();
if trimmed.is_empty() {
return Err(SseError::internal(
"SSE simple mode requires __RUSTFS_SSE_SIMPLE_CMK to be set to a base64-encoded 32-byte key",
));
}
let decoded = BASE64_STANDARD
.decode_to_vec(trimmed)
.map_err(|e| SseError::internal(format!("__RUSTFS_SSE_SIMPLE_CMK must be valid base64: {e}")))?;
let master_key: [u8; 32] = decoded.try_into().map_err(|v: Vec<u8>| {
SseError::internal(format!("__RUSTFS_SSE_SIMPLE_CMK must decode to exactly 32 bytes, got {} bytes", v.len()))
})?;
if master_key == [0u8; 32] {
return Err(SseError::internal("__RUSTFS_SSE_SIMPLE_CMK must not be an all-zero key"));
}
Ok(master_key)
}
impl LocalSseDekProvider {
/// Create a LocalSseDekProvider with a predefined key (for testing)
#[cfg(any(test, feature = "test-util"))]
pub fn new_with_key(master_key: [u8; 32]) -> Self {
Self { master_key }
}
/// Create a TestSseDekProvider from `__RUSTFS_SSE_SIMPLE_CMK` (test-only).
#[cfg(any(test, feature = "test-util"))]
pub fn new() -> Result<Self, SseError> {
let cmk_value = std::env::var("__RUSTFS_SSE_SIMPLE_CMK").unwrap_or_default();
// A missing/invalid key must surface as a request error, never crash the
// whole server: `LocalSseDekProvider::new` is reached from the SSE request
// path (get_sse_dek_provider), so `process::exit(1)` here turned a bad
// `__RUSTFS_SSE_SIMPLE_CMK` into a process crash-loop DoS (backlog#806).
let master_key = parse_simple_sse_cmk(&cmk_value)?;
tracing::info!("Successfully loaded SSE master key (32 bytes) from __RUSTFS_SSE_SIMPLE_CMK");
Ok(Self { master_key })
}
/// Create a local SSE DEK provider for SSE-S3 when KMS is not configured.
/// Requires RUSTFS_SSE_S3_MASTER_KEY to be a valid base64-encoded 32-byte key.
///
/// The failures here are server configuration problems, not internal
/// faults: surface them as `InvalidRequest` (HTTP 400) so a managed-SSE
/// request against an unconfigured server does not report 500 (rustfs#4844).
pub fn new_from_env() -> Result<Self, SseError> {
fn sse_not_configured(message: impl Into<String>) -> SseError {
SseError {
code: S3ErrorCode::InvalidRequest,
message: message.into(),
source: None,
}
}
let Some(raw_value) = local_master_key_env_value() else {
return Err(sse_not_configured(
"SSE-S3 requires RUSTFS_SSE_S3_MASTER_KEY to be set to a base64-encoded 32-byte key when KMS is not configured",
));
};
let decoded = BASE64_STANDARD.decode_to_vec(raw_value.trim()).map_err(|err| {
sse_not_configured(format!(
"RUSTFS_SSE_S3_MASTER_KEY must be valid base64 for SSE-S3 when KMS is not configured: {err}"
))
})?;
let master_key: [u8; 32] = decoded.try_into().map_err(|_| {
sse_not_configured("RUSTFS_SSE_S3_MASTER_KEY must decode to exactly 32 bytes for SSE-S3 when KMS is not configured")
})?;
Ok(Self { master_key })
}
// Simple encryption of DEK
pub fn encrypt_dek(dek: [u8; 32], cmk_value: [u8; 32]) -> Result<String, SseError> {
// Use AES-256-GCM to encrypt DEK
let key = Key::<Aes256Gcm>::from(cmk_value);
let cipher = Aes256Gcm::new(&key);
let mut nonce_bytes = [0u8; 12];
rand::rng().fill_bytes(&mut nonce_bytes);
let nonce = Nonce::from(nonce_bytes);
let ciphertext = cipher
.encrypt(&nonce, dek.as_slice())
.map_err(|_| SseError::internal("Failed to encrypt DEK"))?;
let nonce = BASE64_STANDARD.encode_to_string(nonce);
let ciphertext = BASE64_STANDARD.encode_to_string(ciphertext);
serde_json::to_string(&LocalSseDekEnvelope {
version: LOCAL_SSE_DEK_FORMAT_VERSION,
nonce: &nonce,
ciphertext: &ciphertext,
})
.map_err(|e| SseError::internal(format!("Failed to serialize encrypted DEK: {e}")))
}
// Simple decryption of DEK
pub fn decrypt_dek(encrypted_dek: &str, cmk_value: [u8; 32]) -> Result<[u8; 32], SseError> {
let envelope = serde_json::from_str::<LocalSseDekEnvelope<'_>>(encrypted_dek);
let (nonce, ciphertext) = match envelope {
Ok(envelope) => {
if envelope.version != LOCAL_SSE_DEK_FORMAT_VERSION {
return Err(SseError::internal(format!(
"Unsupported encrypted DEK format version: {}",
envelope.version
)));
}
(envelope.nonce, envelope.ciphertext)
}
Err(json_error) if encrypted_dek.trim_start().starts_with('{') => {
return Err(SseError::internal(format!("Invalid encrypted DEK JSON format: {json_error}")));
}
Err(_) => {
// DEPRECATED: read-only compatibility for persisted colon-delimited DEKs.
// RUSTFS_COMPAT_TODO(sse-local-dek-json-v1): Remove after all supported upgrades have rewritten legacy DEKs.
let Some((nonce, ciphertext)) = encrypted_dek.split_once(':') else {
return Err(SseError::internal("Invalid encrypted DEK format"));
};
if ciphertext.contains(':') {
return Err(SseError::internal("Invalid encrypted DEK format"));
}
(nonce, ciphertext)
}
};
let nonce_vec = BASE64_STANDARD
.decode_to_vec(nonce)
.map_err(|_| SseError::internal("Invalid nonce format"))?;
let ciphertext = BASE64_STANDARD
.decode_to_vec(ciphertext)
.map_err(|_| SseError::internal("Invalid ciphertext format"))?;
let key = Key::<Aes256Gcm>::from(cmk_value);
let cipher = Aes256Gcm::new(&key);
let nonce_array: [u8; 12] = nonce_vec.try_into().map_err(|_| SseError::internal("Invalid nonce length"))?;
let nonce = Nonce::from(nonce_array);
let plaintext = cipher
.decrypt(&nonce, ciphertext.as_slice())
.map_err(|e| SseError::internal(format!("Failed to decrypt DEK: {e}")))?;
let dek: [u8; 32] = plaintext
.try_into()
.map_err(|_| SseError::internal("Decrypted DEK has invalid length"))?;
Ok(dek)
}
}
#[async_trait]
impl SseDekProvider for LocalSseDekProvider {
fn wraps_dek_with_local_master_key(&self) -> bool {
true
}
async fn generate_sse_dek(
&self,
_context: &ObjectEncryptionContext,
_kms_key_id: &str,
) -> Result<(DataKey, Vec<u8>), SseError> {
// Generate a 32-byte array as data key
let mut dek = [0u8; 32];
rand::rng().fill_bytes(&mut dek);
// Generate a 12-byte array as IV
let mut nonce = [0u8; 12];
rand::rng().fill_bytes(&mut nonce);
// Encrypt data key with master key
let encrypted_dek = Self::encrypt_dek(dek, self.master_key)?;
// Return data key and IV
Ok((
DataKey {
plaintext_key: dek,
nonce,
},
encrypted_dek.into_bytes(),
))
}
async fn decrypt_sse_dek(
&self,
encrypted_dek: &[u8],
_kms_key_id: &str,
_context: &ObjectEncryptionContext,
) -> Result<[u8; 32], SseError> {
// Decrypt data key with master key
let encrypted_dek_str =
std::str::from_utf8(encrypted_dek).map_err(|_| SseError::internal("Invalid UTF-8 in encrypted DEK"))?;
let dek = Self::decrypt_dek(encrypted_dek_str, self.master_key)?;
Ok(dek)
}
#[cfg(feature = "rio-v2")]
async fn decrypt_minio_sse_dek(
&self,
encrypted_dek: &[u8],
_kms_key_id: &str,
context: &ObjectEncryptionContext,
) -> Result<[u8; 32], SseError> {
let aad = minio_kms_associated_data(context)?;
decrypt_minio_kms_data_key(encrypted_dek, &self.master_key, &aad)
}
}
-151
View File
@@ -1,151 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Reading data keys sealed by MinIO's builtin KMS.
use crate::core::keying::context::canonical_kms_bucket_path;
use crate::core::keying::object::HmacSha256;
use crate::error::SseError;
use base64_simd::STANDARD as BASE64_STANDARD;
use hmac::Mac;
use rustfs_kms::types::ObjectEncryptionContext;
use serde::Deserialize;
/// Associated data MinIO binds when sealing a data key.
///
/// MinIO passes the object's encryption context as the AEAD's associated data,
/// serialized as canonical JSON with sorted keys — the same canonicalization
/// [`rustfs_kms::context_aad`] performs, which is why the context RustFS
/// already rebuilds for the read can be reused verbatim. For SSE-S3 that
/// context is `{bucket: "bucket/object"}`; for SSE-KMS it is whatever the
/// request supplied, recovered from the stored MinIO context header.
pub(crate) fn minio_kms_associated_data(context: &ObjectEncryptionContext) -> Result<Vec<u8>, SseError> {
let mut ctx = context.encryption_context.clone();
ctx.entry(context.bucket.clone())
.or_insert_with(|| canonical_kms_bucket_path(&context.bucket, &context.object_key));
rustfs_kms::context_aad(&ctx).map_err(|e| SseError::internal(format!("Failed to canonicalize MinIO KMS context: {e}")))
}
/// MinIO's builtin-KMS ciphertext in its JSON encoding.
///
/// Deliberately its own type rather than a relaxation of
/// [`LocalSseDekEnvelope`]: widening that envelope's `deny_unknown_fields`
/// to admit this shape would also admit malformed RustFS envelopes, which
/// backlog#1567 requires to keep failing closed.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct MinioKmsCiphertextJson {
aead: String,
#[allow(
dead_code,
reason = "present in MinIO's encoding; the key is identified by metadata instead"
)]
#[serde(default)]
id: String,
iv: String,
nonce: String,
bytes: String,
}
/// Bytes of trailing randomness every MinIO builtin-KMS ciphertext carries:
/// a 16-byte IV followed by a 12-byte nonce, *after* the sealed bytes.
const MINIO_KMS_RANDOM_LEN: usize = 28;
const MINIO_KMS_IV_LEN: usize = 16;
const MINIO_KMS_AEAD_AES_GCM: &str = "AES-256-GCM-HMAC-SHA-256";
const MINIO_KMS_AEAD_CHACHA20: &str = "ChaCha20Poly1305";
/// Unwrap a data key sealed by MinIO's builtin (static-secret) KMS.
///
/// The wire format is `sealed_bytes || iv[16] || nonce[12]` — the randomness
/// trails the ciphertext rather than leading it, and MinIO's own decoder
/// normalizes its legacy JSON encoding into exactly that byte order before
/// opening it (`internal/kms/secret-key.go`, `parseCiphertext`). A raw
/// (non-JSON) ciphertext is AES-256-GCM by definition there; the JSON form
/// names its algorithm.
///
/// The sealing key is derived per ciphertext rather than being the master key:
/// `HMAC-SHA256(master, iv)` for AES-256-GCM, `HChaCha20(master, iv)` for
/// ChaCha20-Poly1305. The encryption context is bound as associated data.
pub(crate) fn decrypt_minio_kms_data_key(encrypted_dek: &[u8], master_key: &[u8; 32], aad: &[u8]) -> Result<[u8; 32], SseError> {
let (body, algorithm) = match std::str::from_utf8(encrypted_dek) {
// MinIO only treats a payload as JSON when it both starts and ends like
// an object, and falls back to the raw layout when it does not parse —
// mirrored here so a ciphertext that merely looks like JSON is not
// rejected outright.
Ok(text)
if text.starts_with('{')
&& text.ends_with('}')
&& let Ok(json) = serde_json::from_str::<MinioKmsCiphertextJson>(text) =>
{
let decode = |what: &str, value: &str| -> Result<Vec<u8>, SseError> {
BASE64_STANDARD
.decode_to_vec(value)
.map_err(|e| SseError::internal(format!("Invalid MinIO KMS {what}: {e}")))
};
let mut body = decode("ciphertext", &json.bytes)?;
body.extend_from_slice(&decode("iv", &json.iv)?);
body.extend_from_slice(&decode("nonce", &json.nonce)?);
(body, json.aead)
}
_ => (encrypted_dek.to_vec(), MINIO_KMS_AEAD_AES_GCM.to_string()),
};
if body.len() <= MINIO_KMS_RANDOM_LEN {
return Err(SseError::internal("MinIO KMS ciphertext is too short to carry its IV and nonce"));
}
let (sealed, random) = body.split_at(body.len() - MINIO_KMS_RANDOM_LEN);
let (iv, nonce) = random.split_at(MINIO_KMS_IV_LEN);
let plaintext = match algorithm.as_str() {
MINIO_KMS_AEAD_AES_GCM => {
use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};
let mut mac = HmacSha256::new_from_slice(master_key)
.map_err(|_| SseError::internal("MinIO KMS sealing key derivation failed"))?;
mac.update(iv);
let sealing_key: [u8; 32] = mac.finalize().into_bytes().into();
let cipher = Aes256Gcm::new_from_slice(&sealing_key)
.map_err(|_| SseError::internal("MinIO KMS sealing key is not a valid AES-256 key"))?;
let nonce = aes_gcm::Nonce::try_from(nonce).map_err(|_| SseError::internal("MinIO KMS nonce is not 12 bytes"))?;
cipher.decrypt(&nonce, aes_gcm::aead::Payload { msg: sealed, aad })
}
MINIO_KMS_AEAD_CHACHA20 => {
use chacha20poly1305::{KeyInit, XChaCha20Poly1305, aead::Aead};
// MinIO derives this branch's key with HChaCha20 over the 16-byte
// IV, which is exactly XChaCha20-Poly1305's own construction, so the
// extended-nonce cipher does the derivation rather than hand-rolling it.
let mut extended = Vec::with_capacity(MINIO_KMS_IV_LEN + nonce.len());
extended.extend_from_slice(iv);
extended.extend_from_slice(nonce);
let cipher = XChaCha20Poly1305::new_from_slice(master_key)
.map_err(|_| SseError::internal("MinIO KMS master key is not a valid ChaCha20 key"))?;
let nonce = chacha20poly1305::XNonce::try_from(extended.as_slice())
.map_err(|_| SseError::internal("MinIO KMS extended nonce is not 24 bytes"))?;
cipher.decrypt(&nonce, chacha20poly1305::aead::Payload { msg: sealed, aad })
}
other => {
return Err(SseError::internal(format!("Unsupported MinIO KMS AEAD algorithm: {other}")));
}
}
// An AEAD failure here is authentication, not a decode slip: a wrong master
// key, a tampered ciphertext, and an encryption context that does not match
// what sealed it all land here and must all fail closed.
.map_err(|_| SseError::internal("MinIO KMS data key failed authentication"))?;
plaintext
.try_into()
.map_err(|value: Vec<u8>| SseError::internal(format!("MinIO KMS data key must be 32 bytes, got {}", value.len())))
}
-21
View File
@@ -1,21 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Data-key providers: where a data key is wrapped and unwrapped.
pub(crate) mod kms_backed;
pub(crate) mod local;
#[cfg(feature = "rio-v2")]
pub(crate) mod minio;
pub(crate) mod provider;
-288
View File
@@ -1,288 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The data-key provider interface and the per-request choice between the KMS and the local master key.
use crate::error::SseError;
use crate::host::SseHost;
use crate::kms::kms_backed::KmsSseDekProvider;
use crate::kms::local::LocalSseDekProvider;
use async_trait::async_trait;
use rustfs_kms::DataKey;
use rustfs_kms::types::ObjectEncryptionContext;
use std::sync::{Arc, LazyLock, RwLock};
use tracing::debug;
/// Trait for SSE data encryption key management
/// Abstracts the source of encryption keys (KMS, test provider, etc.)
#[async_trait]
pub trait SseDekProvider: Send + Sync {
/// Generate an SSE data encryption key
async fn generate_sse_dek(&self, context: &ObjectEncryptionContext, kms_key_id: &str)
-> Result<(DataKey, Vec<u8>), SseError>;
/// Decrypt an SSE data encryption key (returns only plaintext key, nonce should be read from metadata)
async fn decrypt_sse_dek(
&self,
encrypted_dek: &[u8],
kms_key_id: &str,
context: &ObjectEncryptionContext,
) -> Result<[u8; 32], SseError>;
/// Whether this provider may own a stored data key that is not a RustFS
/// envelope — see `KmsBackend::reads_bare_data_key_ciphertext`.
async fn reads_bare_data_key_ciphertext(&self) -> bool {
false
}
/// Re-wrap a KMS-wrapped DEK envelope onto its master key's current
/// version without exposing the plaintext DEK to the caller.
///
/// Defaults to refusing: only the KMS-backed provider can rewrap, and a
/// provider that cannot must say so rather than hand back the input as if
/// it had been re-protected.
async fn rewrap_sse_dek(
&self,
_encrypted_dek: &[u8],
_context: &ObjectEncryptionContext,
) -> Result<rustfs_kms::types::RewrapDataKeyResponse, SseError> {
Err(SseError::internal("This DEK provider cannot rewrap KMS-wrapped data keys"))
}
/// Whether this provider wraps data keys with a node-local master key
/// instead of a KMS service.
///
/// SSE-KMS must never be served by such a provider: the stored object would
/// claim `aws:kms` and name a KMS key id that never wrapped anything.
/// Defaults to false so only the local fallback has to declare itself.
fn wraps_dek_with_local_master_key(&self) -> bool {
false
}
/// Decrypt a DEK from positively identified legacy managed metadata.
#[cfg(feature = "rio-v2")]
async fn decrypt_legacy_sse_dek(
&self,
encrypted_dek: &[u8],
kms_key_id: &str,
context: &ObjectEncryptionContext,
) -> Result<[u8; 32], SseError> {
self.decrypt_sse_dek(encrypted_dek, kms_key_id, context).await
}
/// Unwrap a data key that MinIO's builtin KMS sealed.
///
/// A separate entry point rather than a shape sniff inside
/// [`Self::decrypt_sse_dek`]: the caller already knows the object carries a
/// MinIO sealed key, and MinIO's raw ciphertext is unstructured bytes that
/// no parser can reliably tell apart from anything else. Routing on the
/// caller's knowledge keeps a RustFS envelope from ever reaching MinIO's
/// decoder, and vice versa.
///
/// Defaults to refusing: only a provider holding the MinIO master secret
/// can serve these, and a provider that cannot must fail rather than fall
/// back to a decoder that would misread the bytes.
#[cfg(feature = "rio-v2")]
async fn decrypt_minio_sse_dek(
&self,
_encrypted_dek: &[u8],
_kms_key_id: &str,
_context: &ObjectEncryptionContext,
) -> Result<[u8; 32], SseError> {
Err(SseError::internal(
"This KMS provider cannot unwrap a data key sealed by MinIO's builtin KMS",
))
}
}
/// Unwrap the data key of an object that carries a sealed object key but no
/// RustFS envelope.
///
/// Two writers produce that shape, and nothing in the bytes tells them apart:
/// MinIO, whose data key is sealed under the static master key, and a RustFS
/// `rio-v2` build on a backend that persisted its native ciphertext bare.
/// MinIO's sealing is authenticated, so opening it under the local master key
/// is a proof rather than a guess: the bare blob is offered to the KMS only
/// once that has failed, or when no local master key exists to try. Without a
/// backend that reads bare ciphertext the MinIO route is the only one, exactly
/// as before.
#[cfg(feature = "rio-v2")]
pub(crate) async fn decrypt_unenveloped_sealed_dek(
bare_kms: Option<Arc<dyn SseDekProvider + '_>>,
local: Result<Arc<dyn SseDekProvider>, SseError>,
encrypted_dek: &[u8],
kms_key_id: &str,
context: &ObjectEncryptionContext,
) -> Result<[u8; 32], SseError> {
let Some(kms) = bare_kms else {
return local?.decrypt_minio_sse_dek(encrypted_dek, kms_key_id, context).await;
};
if let Ok(local) = local
&& let Ok(data_key) = local.decrypt_minio_sse_dek(encrypted_dek, kms_key_id, context).await
{
return Ok(data_key);
}
kms.decrypt_sse_dek(encrypted_dek, kms_key_id, context).await
}
/// The provider that unwraps KMS-wrapped data keys.
///
/// A provider registered through `set_sse_dek_provider_for_test` stands in for
/// the fresh [`KmsSseDekProvider`], which cannot resolve a KMS service from a
/// host that has none. Only `GLOBAL_KMS_DEK_PROVIDER` is consulted, never
/// `GLOBAL_SSE_DEK_PROVIDER`, so a local provider cached by an earlier
/// `get_local_sse_dek_provider` call cannot be selected to unwrap a KMS envelope.
pub(crate) async fn kms_sse_dek_provider<'a>(host: &'a dyn SseHost) -> Result<Arc<dyn SseDekProvider + 'a>, SseError> {
if let Some(cached) = GLOBAL_KMS_DEK_PROVIDER.read().ok().and_then(|guard| guard.as_ref().cloned()) {
return Ok(cached);
}
Ok(Arc::new(KmsSseDekProvider::new(host).await?))
}
/// The KMS provider, when its backend may own a stored data key that is not a
/// RustFS envelope. `None` without a running KMS, which leaves such a key to
/// the local provider exactly as before.
pub(crate) async fn bare_data_key_kms_provider<'a>(host: &'a dyn SseHost) -> Option<Arc<dyn SseDekProvider + 'a>> {
let provider = kms_sse_dek_provider(host).await.ok()?;
provider.reads_bare_data_key_ciphertext().await.then_some(provider)
}
/// Global SSE DEK provider cache for local / test providers.
///
/// Populated by `get_local_sse_dek_provider` and (for backward-compat in tests)
/// `set_sse_dek_provider_for_test`. Read by `get_local_sse_dek_provider` only —
/// the KMS-envelope decrypt path uses `GLOBAL_KMS_DEK_PROVIDER` so that a cached
/// local provider can never be selected for a KMS-wrapped data-key.
pub(crate) static GLOBAL_SSE_DEK_PROVIDER: LazyLock<RwLock<Option<Arc<dyn SseDekProvider>>>> =
LazyLock::new(|| RwLock::new(None));
/// Global KMS DEK provider cache for test-injected KMS providers.
///
/// Populated **only** by `set_sse_dek_provider_for_test` (test-only).
/// Read **only** by the KMS-envelope branch of `apply_managed_decryption_material`.
/// Separation from `GLOBAL_SSE_DEK_PROVIDER` prevents a previously-cached local
/// provider from being selected to unwrap a KMS data-key envelope.
static GLOBAL_KMS_DEK_PROVIDER: LazyLock<RwLock<Option<Arc<dyn SseDekProvider>>>> = LazyLock::new(|| RwLock::new(None));
/// Get or initialize the global SSE DEK provider
///
/// Factory function that automatically selects the appropriate provider:
/// - If `__RUSTFS_SSE_SIMPLE_CMK` environment variable exists: use SimpleSseDekProvider (test mode)
/// - Otherwise: use KmsSseDekProvider (production mode with real KMS)
///
/// # Returns
/// Arc to the global SSE DEK provider instance
///
/// # Example
/// ```rust,ignore
/// let provider = get_sse_dek_provider(host).await?;
/// let (data_key, encrypted_dek) = provider
/// .generate_sse_dek("bucket", "key", "kms-key-id")
/// .await?;
/// ```
pub(crate) async fn get_sse_dek_provider<'a>(host: &'a dyn SseHost) -> Result<Arc<dyn SseDekProvider + 'a>, SseError> {
if host.encryption_service().await.is_some() {
debug!("Using KmsSseDekProvider (KMS configured)");
return Ok(Arc::new(KmsSseDekProvider::new(host).await?));
}
get_local_sse_dek_provider()
}
/// Get the local data-key provider, loading and caching it on first use.
///
/// Startup calls this to check the local master key ahead of traffic; a request
/// that arrives without that step loads it the same way and gets the same error.
pub(crate) fn get_local_sse_dek_provider() -> Result<Arc<dyn SseDekProvider>, SseError> {
// An explicitly injected test provider overrides both the cache and the
// environment-based selection below.
#[cfg(any(test, feature = "test-util"))]
if let Some(injected) = test_injected_sse_dek_provider() {
return Ok(injected);
}
// Check if already initialized
if let Some(provider) = GLOBAL_SSE_DEK_PROVIDER
.read()
.map_err(|_| SseError::internal("Failed to read global SSE DEK provider cache"))?
.as_ref()
.cloned()
{
return Ok(provider);
}
// In test mode, prefer the simple CMK provider when the env var is set.
#[cfg(any(test, feature = "test-util"))]
{
if std::env::var("__RUSTFS_SSE_SIMPLE_CMK").is_ok() {
debug!("Using LocalSseDekProvider (test mode) based on __RUSTFS_SSE_SIMPLE_CMK");
let provider: Arc<dyn SseDekProvider> = Arc::new(LocalSseDekProvider::new()?);
let mut slot = GLOBAL_SSE_DEK_PROVIDER
.write()
.map_err(|_| SseError::internal("Failed to update global SSE DEK provider cache"))?;
if let Some(existing) = slot.as_ref() {
return Ok(existing.clone());
}
*slot = Some(provider.clone());
return Ok(provider);
}
}
// Production fallback: local SSE-S3 provider (no KMS configured).
debug!("Using local SSE-S3 provider (KMS not configured)");
let provider: Arc<dyn SseDekProvider> = Arc::new(LocalSseDekProvider::new_from_env()?);
let mut slot = GLOBAL_SSE_DEK_PROVIDER
.write()
.map_err(|_| SseError::internal("Failed to update global SSE DEK provider cache"))?;
if let Some(existing) = slot.as_ref() {
return Ok(existing.clone());
}
*slot = Some(provider.clone());
Ok(provider)
}
/// Reset both global SSE DEK provider caches (for testing only)
///
/// Clears GLOBAL_SSE_DEK_PROVIDER (local/test providers) and
/// GLOBAL_KMS_DEK_PROVIDER (test-injected KMS providers).
#[cfg(any(test, feature = "test-util"))]
pub fn reset_sse_dek_provider() {
if let Ok(mut slot) = GLOBAL_SSE_DEK_PROVIDER.write() {
*slot = None;
}
if let Ok(mut slot) = GLOBAL_KMS_DEK_PROVIDER.write() {
*slot = None;
}
}
#[cfg(any(test, feature = "test-util"))]
pub fn set_sse_dek_provider_for_test(provider: Arc<dyn SseDekProvider>) {
if let Ok(mut slot) = GLOBAL_KMS_DEK_PROVIDER.write() {
*slot = Some(provider.clone());
}
if let Ok(mut slot) = GLOBAL_SSE_DEK_PROVIDER.write() {
*slot = Some(provider);
}
}
/// Provider explicitly injected via `set_sse_dek_provider_for_test`, if any.
///
/// Reads `GLOBAL_KMS_DEK_PROVIDER` because that slot is populated *only* by the
/// test setter, so a hit here always means an explicit test injection.
#[cfg(any(test, feature = "test-util"))]
fn test_injected_sse_dek_provider() -> Option<Arc<dyn SseDekProvider>> {
GLOBAL_KMS_DEK_PROVIDER.read().ok().and_then(|guard| guard.as_ref().cloned())
}
-110
View File
@@ -1,110 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! S3 server-side encryption: which key encrypts an object, and what is stored to find it again.
//!
//! Covers the three S3 schemes:
//! - SSE-S3 (`AES256`): a data key wrapped by a key the server owns
//! - SSE-KMS (`aws:kms`): a data key wrapped by a KMS key the caller names
//! - SSE-C: a key the client supplies on every request and the server never stores
//!
//! ## Where this crate sits
//!
//! Between the S3 layer and the storage engine, depending on neither. It decides
//! the effective scheme of a write, obtains and unwraps data keys, authorizes the
//! use of a KMS key, and encodes and reads the encryption metadata of an object.
//! It does not transform object bytes: it hands back key material
//! ([`EncryptionMaterial`], [`DecryptionMaterial`]) and the caller applies it.
//!
//! What it needs from the running server — the KMS service, a bucket's default
//! encryption, a key-permission decision — arrives through [`SseHost`], passed
//! to every entry point that consults the server. Failures are reported as
//! [`SseError`], already classified with the S3 error code the caller answers with.
//!
//! ## Entry points
//!
//! - [`sse_encryption`] and [`sse_prepare_encryption`] resolve the material of a write;
//! [`encryption_material_to_metadata`] turns it into the metadata to store.
//! - [`sse_decryption`] resolves the material of a read from stored metadata;
//! [`classify_sse_read_response`] derives the response headers without unwrapping a key.
//! - [`rewrap_object_encryption_metadata`] moves a stored data key onto the current
//! version of its KMS key.
//! - [`startup::init`] settles the environment-driven configuration once per process
//! and reports it; calling it is optional.
//!
//! ```rust,ignore
//! let request = EncryptionRequest {
//! bucket: &bucket,
//! key: &key,
//! server_side_encryption: effective_sse,
//! ssekms_key_id: effective_kms_key_id,
//! ssekms_context: None,
//! sse_customer_algorithm: None,
//! sse_customer_key: None,
//! sse_customer_key_md5: None,
//! content_size: actual_size,
//! principal: principal.as_ref(),
//! };
//!
//! if let Some(material) = sse_encryption(host, request).await? {
//! metadata.extend(encryption_material_to_metadata(&material)?);
//! }
//! ```
mod core;
mod error;
mod host;
mod kms;
pub mod startup;
#[cfg(any(test, feature = "test-util"))]
pub mod testing;
#[cfg(test)]
#[allow(unused_imports)]
mod tests;
pub use crate::core::audit::KmsRequestAuditScope;
pub use crate::core::keying::material::{DecryptionMaterial, EncryptionKeyKind, EncryptionMaterial, ManagedSealedKey};
pub use crate::core::keying::metadata::{
ConflictingEncryptionMetadata, encryption_material_to_metadata, mark_encrypted_multipart_metadata,
normalize_encryption_metadata_case, stored_ssec_metadata, strip_managed_encryption_metadata,
};
pub use crate::core::read::{DecryptionRequest, classify_sse_read_response, sse_decryption};
pub use crate::core::request::SseKmsPrincipal;
#[cfg(any(test, feature = "test-util"))]
pub use crate::core::request::TestAuthorizationHooks;
pub use crate::core::rewrap::{ObjectDekRewrapOutcome, rewrap_object_encryption_metadata};
pub use crate::core::s3::authorization::{authorize_sse_kms_multipart_write, authorize_sse_kms_object_read};
pub use crate::core::s3::headers::{
SseReadResponseHeaders, SsecParamsFromHeaders, build_ssec_read_headers, extract_server_side_encryption_from_headers,
extract_ssec_params_from_headers, extract_ssekms_context_from_headers, project_sse_read_response_headers,
validate_sse_headers_for_read, validate_sse_headers_for_write,
};
pub use crate::core::s3::scheme::{DEFAULT_SSE_ALGORITHM, bucket_default_write_sse};
pub use crate::core::s3::ssec::{ssec_invalid_request, validate_ssec_for_read};
pub use crate::core::write::{EncryptionRequest, PrepareEncryptionRequest, sse_encryption, sse_prepare_encryption};
pub use crate::error::{KMS_KEY_NOT_FOUND_ERROR_CODE, SseError, data_plane_kms_error};
pub use crate::host::{BucketDefaultEncryption, BucketEncryption, KmsKeyAuthorizer, SseHost};
pub use crate::kms::local::LocalSseDekProvider;
#[cfg(any(test, feature = "test-util"))]
pub use crate::kms::local::TestSseDekProvider;
pub use crate::kms::provider::SseDekProvider;
#[cfg(any(test, feature = "test-util"))]
pub use crate::kms::provider::{reset_sse_dek_provider, set_sse_dek_provider_for_test};
// The managed-SSE classifier lives in the shared encryption-keys module so the
// scanner can reuse it; re-exported here so SSE callers find it beside the rest.
pub use rustfs_utils::http::object_encryption_keys::SSEType;
pub use rustfs_utils::http::object_encryption_keys::contains_managed_encryption_metadata;
pub(crate) const LOG_COMPONENT_STORAGE: &str = "storage";
pub(crate) const LOG_SUBSYSTEM_SSE: &str = "sse";
-250
View File
@@ -1,250 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The crate's process-startup step.
//!
//! [`init`] settles the two things that cannot change without a restart, both
//! read from the environment, and reports them once:
//!
//! - whether SSE-KMS requests are authorized against the key they name;
//! - whether the local SSE-S3 master key is usable.
//!
//! Nothing that follows the KMS service is decided here. The KMS can be
//! configured, started, restarted, and stopped while the server runs, so the
//! choice between the KMS and the local master key is made per request, and no
//! KMS state is cached by this crate.
//!
//! Calling [`init`] is optional. A process that never calls it reads the same
//! switch and loads the same master key on first use, with the same errors; it
//! only goes without the startup report.
use crate::error::SseError;
use crate::kms::local::{ENV_SSE_S3_MASTER_KEY, local_master_key_configured};
use crate::kms::provider::get_local_sse_dek_provider;
use crate::{LOG_COMPONENT_STORAGE, LOG_SUBSYSTEM_SSE};
use rustfs_config::{DEFAULT_KMS_ENFORCE_SSE_KEY_POLICY, ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY};
use rustfs_utils::get_env_bool;
use std::sync::{LazyLock, OnceLock};
const EVENT_SSE_KMS_KEY_POLICY_MODE: &str = "sse_kms_key_policy_mode";
const EVENT_SSE_LOCAL_MASTER_KEY: &str = "sse_local_master_key";
/// State of the local SSE-S3 master key at startup.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LocalMasterKeyStatus {
/// Configured and usable; SSE-S3 works without a KMS.
Loaded,
/// Not configured; SSE-S3 requires a running KMS.
NotSet,
/// Configured but unusable; SSE-S3 requests that need it are rejected.
Invalid,
}
impl LocalMasterKeyStatus {
fn as_str(self) -> &'static str {
match self {
Self::Loaded => "loaded",
Self::NotSet => "not_set",
Self::Invalid => "invalid",
}
}
}
/// What [`init`] settled for this process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StartupReport {
/// Whether SSE-KMS requests are authorized against the KMS key they name.
pub key_policy_enforced: bool,
/// State of the local SSE-S3 master key.
pub local_master_key: LocalMasterKeyStatus,
}
/// Settle the process-wide SSE configuration and report it.
///
/// Idempotent: the first call does the work and logs; later calls, such as a
/// second embedded server in the same process, return the same report silently.
/// An unusable master key does not fail startup, because a server whose KMS is
/// running never needs it.
pub fn init() -> StartupReport {
static REPORT: OnceLock<StartupReport> = OnceLock::new();
*REPORT.get_or_init(|| {
let key_policy_enforced = key_policy_enforced();
log_key_policy_mode(key_policy_enforced);
let local_master_key = load_local_master_key();
log_local_master_key(&local_master_key);
StartupReport {
key_policy_enforced,
local_master_key: local_master_key.unwrap_or(LocalMasterKeyStatus::Invalid),
}
})
}
/// Whether per-key KMS authorization is enforced on the SSE-KMS data path.
///
/// Frozen on first read, by [`init`] or by the first request, so one process
/// never answers the same question two ways.
pub(crate) fn key_policy_enforced() -> bool {
static ENFORCED: LazyLock<bool> =
LazyLock::new(|| get_env_bool(ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY, DEFAULT_KMS_ENFORCE_SSE_KEY_POLICY));
*ENFORCED
}
/// Load the local master key through the loader the request path uses.
///
/// An absent key is a state, not a failure: only a configured key is loaded, so
/// the error case is exactly "configured but unusable".
fn load_local_master_key() -> Result<LocalMasterKeyStatus, SseError> {
if !local_master_key_configured() {
return Ok(LocalMasterKeyStatus::NotSet);
}
get_local_sse_dek_provider().map(|_| LocalMasterKeyStatus::Loaded)
}
/// Report the configured SSE-KMS authorization mode.
///
/// The disabled case warns rather than logs: while enforcement is off, any identity
/// allowed to write an object can encrypt it under any key, and operators should hear
/// about that even though disabled is the long-term default.
fn log_key_policy_mode(enforced: bool) {
if enforced {
tracing::info!(
event = EVENT_SSE_KMS_KEY_POLICY_MODE,
component = LOG_COMPONENT_STORAGE,
subsystem = LOG_SUBSYSTEM_SSE,
enforced = true,
"SSE-KMS requests are authorized against the resolved KMS key (kms:GenerateDataKey / kms:Decrypt)"
);
return;
}
tracing::warn!(
event = EVENT_SSE_KMS_KEY_POLICY_MODE,
component = LOG_COMPONENT_STORAGE,
subsystem = LOG_SUBSYSTEM_SSE,
enforced = false,
"SSE-KMS requests are not authorized against the KMS key they name; any identity allowed to \
write an object may encrypt it under any key, and any identity allowed to read it may have it \
decrypted. Grant kms:GenerateDataKey and kms:Decrypt on the keys your workloads use, then set \
{ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY}=true."
);
}
/// Report the local master key's state.
///
/// The failure text is the one a request is answered with. It describes the
/// configuration problem and never carries the configured value.
fn log_local_master_key(outcome: &Result<LocalMasterKeyStatus, SseError>) {
match outcome {
Ok(status @ LocalMasterKeyStatus::Loaded) => tracing::info!(
event = EVENT_SSE_LOCAL_MASTER_KEY,
component = LOG_COMPONENT_STORAGE,
subsystem = LOG_SUBSYSTEM_SSE,
state = status.as_str(),
"{ENV_SSE_S3_MASTER_KEY} is loaded; SSE-S3 uses it whenever no KMS is running"
),
Ok(status) => tracing::info!(
event = EVENT_SSE_LOCAL_MASTER_KEY,
component = LOG_COMPONENT_STORAGE,
subsystem = LOG_SUBSYSTEM_SSE,
state = status.as_str(),
"{ENV_SSE_S3_MASTER_KEY} is not set; SSE-S3 requires a running KMS"
),
Err(error) => tracing::error!(
event = EVENT_SSE_LOCAL_MASTER_KEY,
component = LOG_COMPONENT_STORAGE,
subsystem = LOG_SUBSYSTEM_SSE,
state = LocalMasterKeyStatus::Invalid.as_str(),
reason = %error.message,
"{ENV_SSE_S3_MASTER_KEY} is set but unusable; SSE-S3 requests are rejected while no KMS is running"
),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::kms::provider::reset_sse_dek_provider;
use crate::tests::lock_sse_test_state;
use base64_simd::STANDARD as BASE64_STANDARD;
use rustfs_s3_types::S3ErrorCode;
use temp_env::with_vars;
/// Run `check` with the local master key set to `value` and nothing cached or injected.
async fn with_master_key<T>(value: Option<&str>, check: impl FnOnce() -> T) -> T {
let _guard = lock_sse_test_state().await;
reset_sse_dek_provider();
let outcome = with_vars([(ENV_SSE_S3_MASTER_KEY, value), ("__RUSTFS_SSE_SIMPLE_CMK", None)], check);
reset_sse_dek_provider();
outcome
}
#[tokio::test]
async fn an_absent_master_key_is_reported_as_not_set() {
let status = with_master_key(None, load_local_master_key)
.await
.expect("an absent key is a state, not a failure");
assert_eq!(status, LocalMasterKeyStatus::NotSet);
let blank = with_master_key(Some(" "), load_local_master_key)
.await
.expect("a blank value counts as absent");
assert_eq!(blank, LocalMasterKeyStatus::NotSet);
}
#[tokio::test]
async fn a_valid_master_key_is_loaded_and_cached_for_requests() {
let encoded = BASE64_STANDARD.encode_to_string([7u8; 32]);
let cached = with_master_key(Some(&encoded), || {
let status = load_local_master_key().expect("a 32-byte key should load");
assert_eq!(status, LocalMasterKeyStatus::Loaded);
// The request path must find the provider startup loaded, not load a second one.
crate::kms::provider::GLOBAL_SSE_DEK_PROVIDER
.read()
.expect("provider cache lock")
.is_some()
})
.await;
assert!(cached, "startup should leave the provider cached for the request path");
}
#[tokio::test]
async fn an_unusable_master_key_fails_the_way_a_request_would() {
let short = BASE64_STANDARD.encode_to_string([7u8; 16]);
for unusable in ["not base64 at all!", short.as_str()] {
let error = with_master_key(Some(unusable), load_local_master_key)
.await
.expect_err("an unusable key must not load");
assert_eq!(error.code, S3ErrorCode::InvalidRequest);
assert!(
!error.message.contains(unusable),
"the failure text must not carry the configured value: {}",
error.message
);
}
}
#[tokio::test]
async fn init_reports_once_and_repeats_the_same_report() {
let encoded = BASE64_STANDARD.encode_to_string([9u8; 32]);
let (first, second) = with_master_key(Some(&encoded), || (init(), init())).await;
assert_eq!(first, second, "a second call must return the first report");
assert_eq!(first.key_policy_enforced, key_policy_enforced());
// The report is settled once per process, so this holds whether this test
// or another caller of `init` ran first.
assert_eq!(init(), first);
}
}
-70
View File
@@ -1,70 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Fixtures for tests of SSE call sites, in this crate and in its dependents.
use crate::{KmsKeyAuthorizer, SseError, SseKmsPrincipal};
use async_trait::async_trait;
use base64_simd::STANDARD as BASE64_STANDARD;
use rustfs_policy::policy::action::KmsAction;
use rustfs_utils::http::headers::AMZ_ENCRYPTION_KMS;
use rustfs_utils::http::object_encryption_keys::{
INTERNAL_ENCRYPTION_ALGORITHM_HEADER, INTERNAL_ENCRYPTION_IV_HEADER, INTERNAL_ENCRYPTION_KEY_HEADER,
INTERNAL_ENCRYPTION_KEY_ID_HEADER,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
/// An authorizer that answers every request the same way and records what it was asked.
pub struct RecordingKmsKeyAuthorizer {
allowed: bool,
calls: Mutex<Vec<(KmsAction, String)>>,
}
impl RecordingKmsKeyAuthorizer {
pub fn new(allowed: bool) -> Arc<Self> {
Arc::new(Self {
allowed,
calls: Mutex::new(Vec::new()),
})
}
/// The `(action, key id)` pairs this authorizer was asked about, in order.
pub fn calls(&self) -> Vec<(KmsAction, String)> {
self.calls.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
}
#[async_trait]
impl KmsKeyAuthorizer for RecordingKmsKeyAuthorizer {
async fn is_allowed(&self, _principal: &SseKmsPrincipal, action: KmsAction, key_id: &str) -> Result<bool, SseError> {
self.calls
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push((action, key_id.to_string()));
Ok(self.allowed)
}
}
/// Stored metadata of an SSE-KMS object wrapped under the key `finance-key`.
pub fn sse_kms_object_metadata() -> HashMap<String, String> {
HashMap::from([
("x-amz-server-side-encryption".to_string(), AMZ_ENCRYPTION_KMS.to_string()),
("x-amz-server-side-encryption-aws-kms-key-id".to_string(), "finance-key".to_string()),
(INTERNAL_ENCRYPTION_KEY_ID_HEADER.to_string(), "finance-key".to_string()),
(INTERNAL_ENCRYPTION_KEY_HEADER.to_string(), BASE64_STANDARD.encode_to_string([7u8; 48])),
(INTERNAL_ENCRYPTION_IV_HEADER.to_string(), BASE64_STANDARD.encode_to_string([9u8; 12])),
(INTERNAL_ENCRYPTION_ALGORITHM_HEADER.to_string(), "aws:kms".to_string()),
])
}
File diff suppressed because it is too large Load Diff
-2
View File
@@ -30,11 +30,9 @@ Contract crates stay below implementation crates. Forbidden edges:
| `security-governance -> rustfs` | Governance contracts stay below the binary crate | | `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 -> rustfs` | The extension schema is consumed by the binary, never the reverse |
| `extension-schema -> ecstore` | The extension schema must not reach storage internals | | `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. - `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. - 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. - 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 ## ECStore Access Boundary
+1 -1
View File
@@ -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. | | `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. | | `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. | | `CONCURRENCY_MANAGER` | `rustfs/src/storage/concurrency/manager.rs` | Storage concurrency scheduler state stays inside the concurrency owner. |
| `GLOBAL_KMS_DEK_PROVIDER`, `GLOBAL_SSE_DEK_PROVIDER` | `crates/sse/src/kms/provider.rs` | DEK provider caches stay private to the SSE owner. | | `GLOBAL_KMS_DEK_PROVIDER`, `GLOBAL_SSE_DEK_PROVIDER` | `rustfs/src/storage/sse.rs` | DEK provider caches stay private to the SSE owner. |
| `ECSTORE_EVENT_DISPATCH_HOOK` | `rustfs/src/server/event.rs` | Event bridge registration goes through the storage facade. | | `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. | | `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. | | `RUNTIME_CONFIG_RELOAD_MUTEX` | `rustfs/src/admin/service/config.rs` | Serializes dynamic config reload fanout. |
+3 -3
View File
@@ -1,7 +1,7 @@
# KMS Bulk Rekey Job Contract # 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. **Use this when:** changing the bulk envelope re-wrap sweep (`rustfs/src/kms_rekey.rs`), its admin endpoints (`rustfs/src/admin/handlers/kms_rekey.rs`), the re-wrap primitive, or anything that decides which objects a rekey may touch.
**Source of truth:** `rustfs/src/kms_rekey.rs`, `rustfs/src/admin/handlers/kms_rekey.rs`, `rewrap_object_encryption_metadata` in `crates/sse/src/core/rewrap.rs`, `KmsManager::rewrap_data_key` / `KmsManager::describe_data_key_wrapping` in `crates/kms/src/manager.rs`, `put_object_metadata` in `crates/ecstore/src/set_disk/ops/object.rs`. **Source of truth:** `rustfs/src/kms_rekey.rs`, `rustfs/src/admin/handlers/kms_rekey.rs`, `rewrap_object_encryption_metadata` in `rustfs/src/storage/sse.rs`, `KmsManager::rewrap_data_key` / `KmsManager::describe_data_key_wrapping` in `crates/kms/src/manager.rs`, `put_object_metadata` in `crates/ecstore/src/set_disk/ops/object.rs`.
The bulk rekey job re-wraps stored data-key envelopes under the current key-encryption key (KEK) without rewriting object bodies. This document is the acceptance bar; where the shipped v1 sweep deliberately narrows it, [Implementation Status](#implementation-status-v1-sweep) records the deviation. 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 ### Reading the wrapping KEK version
There is no key-version metadata key. Object metadata carries the key id (`x-rustfs-encryption-key-id`) and the sealed blob under `x-rustfs-encryption-key`; `DecryptResponse` in `crates/kms/src/types.rs` does not report a version either. The version is recoverable because the sealed blob is structured: for every backend that builds one, the ciphertext is the JSON of `DataKeyEnvelope` (`crates/kms/src/encryption/dek.rs`), and the read path already discriminates on it via `is_data_key_envelope` in `crates/sse/src/core/read.rs`. There is no key-version metadata key. Object metadata carries the key id (`x-rustfs-encryption-key-id`) and the sealed blob under `x-rustfs-encryption-key`; `DecryptResponse` in `crates/kms/src/types.rs` does not report a version either. The version is recoverable because the sealed blob is structured: for every backend that builds one, the ciphertext is the JSON of `DataKeyEnvelope` (`crates/kms/src/encryption/dek.rs`), and the read path already discriminates on it via `is_data_key_envelope` in `rustfs/src/storage/sse.rs`.
| Backend | Rotates | Where the wrapping version lives | Recoverable by a scan | | 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: Three properties of `put_object_metadata` (`crates/ecstore/src/set_disk/ops/object.rs`) constrain the re-wrap write:
- **The merge is additive; it cannot remove keys.** Overwriting a key that keeps its name is safe; a re-wrap that changes *which* keys describe the envelope leaves the old keys behind. This is a live hazard: `parse_minio_managed_sealed_key` in `crates/sse/src/core/keying/object.rs` selects the MinIO decrypt branch on the mere presence of the MinIO seal-algorithm header, so a RustFS-native envelope written onto MinIO-compatible headers without neutralizing them steers reads down the stale branch. Any envelope-shape change must neutralize superseded keys in the same write. - **The merge is additive; it cannot remove keys.** Overwriting a key that keeps its name is safe; a re-wrap that changes *which* keys describe the envelope leaves the old keys behind. This is a live hazard: `parse_minio_managed_sealed_key` in `rustfs/src/storage/sse.rs` selects the MinIO decrypt branch on the mere presence of the MinIO seal-algorithm header, so a RustFS-native envelope written onto MinIO-compatible headers without neutralizing them steers reads down the stale branch. Any envelope-shape change must neutralize superseded keys in the same write.
- **Object-lock retention is enforced before the merge.** `check_object_lock_retention_update` (`crates/ecstore/src/set_disk/mod.rs`) runs first; rekey inherits its decision and must not acquire a bypass. - **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. - **`mod_time` is preserved unless the caller sets it.** The re-wrap path leaves it unset so age-based lifecycle rules are not perturbed.
@@ -1,13 +1,13 @@
# MinIO On-Disk Format Interoperability # 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. **Use this when:** deciding whether a MinIO drive set, bucket-metadata blob, or SSE object can be read or imported by a given RustFS build, or before touching any constant or codec listed under Version Anchors.
**Source of truth:** `crates/filemeta/src/filemeta.rs`, `crates/filemeta/src/filemeta/codec.rs`, `crates/ecstore/src/bucket/metadata.rs`, `crates/ecstore/src/bucket/migration.rs`, `crates/sse/src/core/`, `crates/sse/src/kms/`, `rustfs/Cargo.toml` `[features]`, `.github/workflows/ci.yml`, `.github/workflows/minio-interop.yml`. **Source of truth:** `crates/filemeta/src/filemeta.rs`, `crates/filemeta/src/filemeta/codec.rs`, `crates/ecstore/src/bucket/metadata.rs`, `crates/ecstore/src/bucket/migration.rs`, `rustfs/src/storage/sse.rs`, `rustfs/Cargo.toml` `[features]`, `.github/workflows/ci.yml`, `.github/workflows/minio-interop.yml`.
This is an interop contract, not a plan. Migration is one-way (MinIO to RustFS). Erasure-coding internals are owned by [erasure-coding.md](erasure-coding.md); this document owns the interop claim, the fixture evidence, and the out-of-scope list. 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 ## Scope Matrix By Build Variant
Build variants are the `rustfs` crate features in `rustfs/Cargo.toml`: `default`, `full`, and `rio-v2` (which enables `rustfs-ecstore/rio-v2` and `rustfs-sse/rio-v2`, and pulls in `crates/rio-v2`). `rio-v2` is absent from both `default` and `full`. Build variants are the `rustfs` crate features in `rustfs/Cargo.toml`: `default`, `full`, and `rio-v2` (which enables `rustfs-ecstore/rio-v2` and pulls in `crates/rio-v2`). `rio-v2` is absent from both `default` and `full`.
| MinIO artifact | `default` / `full` build | `rio-v2` build | Notes | | 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 ### Seams
The cryptography (DARE v2 stream format, object-key derivation, sealing) was never the gap. Three metadata seams above it rejected MinIO objects; all are closed in `rio-v2` builds. Symbols are under `crates/sse/src/core/` unless noted. The cryptography (DARE v2 stream format, object-key derivation, sealing) was never the gap. Three metadata seams above it rejected MinIO objects; all are closed in `rio-v2` builds. Symbols are in `rustfs/src/storage/sse.rs` unless noted.
| Seam | Resolution | | Seam | Resolution |
|---|---| |---|---|
@@ -113,10 +113,10 @@ Inventory the source first: bucket default encryption means objects can be encry
| Fact | Value | | 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`. | | Shipping status | Ships in no default build: absent from `default` and `full` in `rustfs/Cargo.toml`; released binaries and container images never include it. Enable with `--features rio-v2`. |
| Pull-request coverage | `test-and-lint-rio-v2` in `.github/workflows/ci.yml`: clippy plus `cargo nextest` for `rustfs`, `rustfs-ecstore`, and `rustfs-sse` with `--features rio-v2`. This is the cfg-seam guard; it keeps the feature compiling and its unit suite green on every pull request. | | Pull-request coverage | `test-and-lint-rio-v2` in `.github/workflows/ci.yml`: clippy plus `cargo nextest` for `rustfs` and `rustfs-ecstore` with `--features rio-v2`. This is the cfg-seam guard; it keeps the feature compiling and its unit suite green on every pull request. |
| Full-suite lane | `build-rustfs-debug-binary-rio-v2` and `e2e-tests-rio-v2` in `ci.yml` run only on the nightly schedule and manual dispatch (`cache-warm.yml` keeps the `ci-feat-rio` cache warm so the scheduled build fits its timeout). | | 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`. | | Interop evidence | `.github/workflows/minio-interop.yml` (nightly plus manual) regenerates real MinIO backend trees via `crates/rio-v2/tests/minio_fixture_lab/` and runs the `#[ignore]` reader tests in `rustfs/src/storage/minio_generated_read_test.rs` with `--features rio-v2`. Its freshness is tracked in `.github/scheduled-validations.json`. |
| Promote-or-delete condition | The variant stays dormant until one of two things happens. **Promote**: a release commits to shipping MinIO SSE migration as a supported capability; then `rio-v2` joins `default`/`full`, the scheduled lanes run on every pull request, and this section is rewritten. **Delete**: no release commits to it and the scheduled lanes are not kept green; then the feature flag, `crates/rio-v2`, the cfg seams under `crates/sse/src/`, the three `ci.yml` jobs, the `cache-warm.yml` warm step, `minio-interop.yml`, and its `scheduled-validations.json` entry are removed in one change. Either outcome must update `ARCHITECTURE.md` and the `ci.yml` job comments that cite this section. | | Promote-or-delete condition | The variant stays dormant until one of two things happens. **Promote**: a release commits to shipping MinIO SSE migration as a supported capability; then `rio-v2` joins `default`/`full`, the scheduled lanes run on every pull request, and this section is rewritten. **Delete**: no release commits to it and the scheduled lanes are not kept green; then the feature flag, `crates/rio-v2`, the cfg seams in `rustfs/src/storage/sse.rs`, the three `ci.yml` jobs, the `cache-warm.yml` warm step, `minio-interop.yml`, and its `scheduled-validations.json` entry are removed in one change. Either outcome must update `ARCHITECTURE.md` and the `ci.yml` job comments that cite this section. |
## Fixture Evidence ## Fixture Evidence
+1 -1
View File
@@ -1,7 +1,7 @@
# AWS KMS backend: setup, verification, and operations # 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. **Use this when:** connecting RustFS to AWS KMS for the first time, verifying an existing AWS-backed deployment, upgrading one from 1.0.4 or 1.0.5, or deciding how to run and protect the AWS keys RustFS depends on.
**Source of truth:** `crates/kms/src/backends/aws.rs` (backend behavior and its deviations), `crates/kms/src/config.rs` (`ENV_KMS_AWS_*`), `crates/kms/src/policy.rs` (retry, deadline and circuit breaker), `crates/sse/src/core/` (SSE data path). 中文版: [kms-aws-backend-guide.zh-CN.md](kms-aws-backend-guide.zh-CN.md). **Source of truth:** `crates/kms/src/backends/aws.rs` (backend behavior and its deviations), `crates/kms/src/config.rs` (`ENV_KMS_AWS_*`), `crates/kms/src/policy.rs` (retry, deadline and circuit breaker), `rustfs/src/storage/sse.rs` (SSE data path). 中文版: [kms-aws-backend-guide.zh-CN.md](kms-aws-backend-guide.zh-CN.md).
The statements about behavior on this page were observed against the real AWS KMS service (region `eu-north-1`) and, for failures AWS cannot be asked to produce on demand, against a loopback stand-in that speaks the AWS KMS wire protocol. Where a statement is guidance that was not exercised, it says so. For the contract-level differences between AWS and the other backends, see [KMS backend security properties](kms-backend-security.md#aws-kms-deviations-from-the-shared-backend-contract). The statements about behavior on this page were observed against the real AWS KMS service (region `eu-north-1`) and, for failures AWS cannot be asked to produce on demand, against a loopback stand-in that speaks the AWS KMS wire protocol. Where a statement is guidance that was not exercised, it says so. For the contract-level differences between AWS and the other backends, see [KMS backend security properties](kms-backend-security.md#aws-kms-deviations-from-the-shared-backend-contract).
@@ -1,7 +1,7 @@
# AWS KMS 后端:接入、验证与运维 # AWS KMS 后端:接入、验证与运维
**适用场景:** 首次把 RustFS 接入 AWS KMS、验证已有的 AWS 后端部署、从 1.0.4 或 1.0.5 升级,或者规划如何运维并保护 RustFS 所依赖的 AWS 密钥。 **适用场景:** 首次把 RustFS 接入 AWS KMS、验证已有的 AWS 后端部署、从 1.0.4 或 1.0.5 升级,或者规划如何运维并保护 RustFS 所依赖的 AWS 密钥。
**事实来源:** `crates/kms/src/backends/aws.rs`(后端行为及其差异)、`crates/kms/src/config.rs`(`ENV_KMS_AWS_*`)、`crates/kms/src/policy.rs`(重试、超时与熔断)、`crates/sse/src/core/`(SSE 数据面)。English: [kms-aws-backend-guide.md](kms-aws-backend-guide.md)。 **事实来源:** `crates/kms/src/backends/aws.rs`(后端行为及其差异)、`crates/kms/src/config.rs`(`ENV_KMS_AWS_*`)、`crates/kms/src/policy.rs`(重试、超时与熔断)、`rustfs/src/storage/sse.rs`(SSE 数据面)。English: [kms-aws-backend-guide.md](kms-aws-backend-guide.md)。
本页关于行为的描述,均来自对真实 AWS KMS 服务(区域 `eu-north-1`)的实测;对于无法让 AWS 按需产生的故障,则使用一个实现了 AWS KMS 线上协议的本机替身来实测。属于未经实测的建议之处,文中会明确标注。AWS 与其它后端在契约层面的差异,见 [KMS backend security properties](kms-backend-security.md#aws-kms-deviations-from-the-shared-backend-contract)。 本页关于行为的描述,均来自对真实 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)。
+2 -4
View File
@@ -80,7 +80,7 @@ e2e-test-hooks = ["rustfs-ecstore/e2e-test-hooks", "rustfs-scanner/e2e-test-hook
connect-e2e-short-credentials = [] connect-e2e-short-credentials = []
# Builds the dedicated rustfs-cli-e2e target with a build-time public enrollment root. # Builds the dedicated rustfs-cli-e2e target with a build-time public enrollment root.
offline-enrollment-e2e-root = [] offline-enrollment-e2e-root = []
rio-v2 = ["rustfs-ecstore/rio-v2", "rustfs-sse/rio-v2"] rio-v2 = ["rustfs-ecstore/rio-v2"]
# Linux-only cuObject S3-over-RDMA GET into client (GPU) memory; needs libcuobjserver. # Linux-only cuObject S3-over-RDMA GET into client (GPU) memory; needs libcuobjserver.
cuobject = ["dep:rustfs-cuobject", "rustfs-cuobject/server"] cuobject = ["dep:rustfs-cuobject", "rustfs-cuobject/server"]
# NIXL/UCX transport for S3-over-RDMA; replaces cuobject when both are enabled. # NIXL/UCX transport for S3-over-RDMA; replaces cuobject when both are enabled.
@@ -281,7 +281,6 @@ rustfs-rio = { workspace = true }
rustfs-s3-client = { workspace = true } rustfs-s3-client = { workspace = true }
rustfs-s3-types = { workspace = true, features = ["compat-s3s"] } rustfs-s3-types = { workspace = true, features = ["compat-s3s"] }
rustfs-s3-ops = { workspace = true } rustfs-s3-ops = { workspace = true }
rustfs-sse = { workspace = true }
rustfs-security-governance = { workspace = true } rustfs-security-governance = { workspace = true }
rustfs-data-usage = { workspace = true } rustfs-data-usage = { workspace = true }
rustfs-s3select-api = { workspace = true } rustfs-s3select-api = { workspace = true }
@@ -384,7 +383,6 @@ pin-project-lite.workspace = true
parking_lot = { workspace = true } parking_lot = { workspace = true }
rust-embed = { workspace = true, features = ["interpolate-folder-path"] } rust-embed = { workspace = true, features = ["interpolate-folder-path"] }
s3s = { workspace = true, features = ["minio"] } s3s = { workspace = true, features = ["minio"] }
s3s-sigv4 = { workspace = true }
shadow-rs = { workspace = true, default-features = false, features = ["build", "metadata"] } shadow-rs = { workspace = true, default-features = false, features = ["build", "metadata"] }
sysinfo = { workspace = true, features = ["multithread"] } sysinfo = { workspace = true, features = ["multithread"] }
thiserror = { workspace = true } thiserror = { workspace = true }
@@ -425,7 +423,7 @@ h2.workspace = true
rustfs-targets = { workspace = true, features = ["test-support"] } rustfs-targets = { workspace = true, features = ["test-support"] }
uuid = { workspace = true, features = ["v4", "v5", "fast-rng", "macro-diagnostics"] } uuid = { workspace = true, features = ["v4", "v5", "fast-rng", "macro-diagnostics"] }
rustfs-iam = { workspace = true, features = ["test-util"] } rustfs-iam = { workspace = true, features = ["test-util"] }
rustfs-sse = { workspace = true, features = ["test-util"] } s3s-sigv4 = { workspace = true }
serial_test = { workspace = true } serial_test = { workspace = true }
tempfile = { workspace = true } tempfile = { workspace = true }
aws-config = { workspace = true } aws-config = { workspace = true }
+43 -64
View File
@@ -472,8 +472,7 @@ mod tests {
use crate::app::bucket_usecase::DefaultBucketUsecase; use crate::app::bucket_usecase::DefaultBucketUsecase;
use crate::app::gating_test_env::{run_large_stack_test, shared_gating_ecstore}; use crate::app::gating_test_env::{run_large_stack_test, shared_gating_ecstore};
use crate::app::storage_api::bucket_usecase::s3::{ use crate::app::storage_api::bucket_usecase::s3::{
GetObjectInput, ListObjectsInput, ListObjectsV2Input, ListObjectsV2Output, S3Request, S3Response, XmlSerialize, ListObjectsInput, ListObjectsV2Input, ListObjectsV2Output, S3Request, S3Response, XmlSerialize, XmlSerializer,
XmlSerializer,
}; };
use crate::app::storage_api::test::StoragePutObjReader; use crate::app::storage_api::test::StoragePutObjReader;
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions}; use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions};
@@ -1170,33 +1169,20 @@ mod tests {
let sys = OnDemandMigrationSys::get(); let sys = OnDemandMigrationSys::get();
let old = sys.state(&input.bucket).expect("original source state"); let old = sys.state(&input.bucket).expect("original source state");
let store = shared_gating_ecstore().await; let store = shared_gating_ecstore().await;
let get = S3Request { let object_envelope = |method, extensions| {
input: GetObjectInput { crate::app::RequestEnvelope::from_parts(
bucket: input.bucket.clone(), crate::app::RequestHead {
key: "missing".into(), method,
..Default::default() uri: http::Uri::from_static("/missing"),
}, headers: HeaderMap::new(),
method: http::Method::GET, credentials: None,
uri: http::Uri::from_static("/missing"), region: None,
headers: HeaderMap::new(), service: None,
extensions: http::Extensions::new(), },
credentials: None, extensions,
region: None, )
service: None,
trailing_headers: None,
}; };
// Method GET, URI `/missing`, empty headers, and empty extensions. let get_env = object_envelope(http::Method::GET, http::Extensions::new());
let get_env = crate::app::RequestEnvelope::from_parts(
crate::app::RequestHead {
method: get.method.clone(),
uri: get.uri.clone(),
headers: get.headers.clone(),
credentials: None,
region: None,
service: None,
},
get.extensions.clone(),
);
let authorized_generation = let authorized_generation =
super::super::storage_api::bucket_usecase::access::load_bucket_generation_from_store( super::super::storage_api::bucket_usecase::access::load_bucket_generation_from_store(
&store, &store,
@@ -1225,27 +1211,13 @@ mod tests {
.expect("replacement identity"); .expect("replacement identity");
assert_ne!(replacement, old.incarnation_id()); assert_ne!(replacement, old.incarnation_id());
sys.remove(&input.bucket); sys.remove(&input.bucket);
let mut without_source = get.clone(); let mut without_source_env = object_envelope(http::Method::GET, http::Extensions::new());
let mut without_source_env = crate::app::RequestEnvelope::from_parts(
crate::app::RequestHead {
method: without_source.method.clone(),
uri: without_source.uri.clone(),
headers: without_source.headers.clone(),
credentials: None,
region: None,
service: None,
},
without_source.extensions.clone(),
);
super::super::storage_api::bucket_usecase::access::prepare_odm_read_generation( super::super::storage_api::bucket_usecase::access::prepare_odm_read_generation(
&store, &store,
&mut without_source_env, &mut without_source_env,
&input.bucket, &input.bucket,
) )
.await; .await;
if let Some(guard) = without_source_env.odm_read_generation().cloned() {
without_source.extensions.insert(guard);
}
for state_incarnation in [old.incarnation_id(), replacement] { for state_incarnation in [old.incarnation_id(), replacement] {
sys.apply_for_incarnation(&input.bucket, state_incarnation, Some(old.config())) sys.apply_for_incarnation(&input.bucket, state_incarnation, Some(old.config()))
.await; .await;
@@ -1255,31 +1227,38 @@ mod tests {
if capture == 0 && state_incarnation == replacement { if capture == 0 && state_incarnation == replacement {
continue; continue;
} }
let mut get = if capture == 2 { without_source.clone() } else { get.clone() }; let mut extensions = http::Extensions::new();
if capture == 1 { if capture == 1 {
get.extensions.insert(authorized_generation.clone()); extensions.insert(authorized_generation.clone());
} else if capture == 2
&& let Some(guard) = without_source_env.odm_read_generation().cloned()
{
extensions.insert(guard);
} }
let head_envelope = crate::app::RequestEnvelope::from_parts( let get_envelope = object_envelope(http::Method::GET, extensions.clone());
crate::app::RequestHead { let head_envelope = object_envelope(http::Method::HEAD, extensions.clone());
method: http::Method::HEAD, let get = crate::app::test_seams::get_object_input(&input.bucket, "missing", None);
uri: get.uri.clone(),
headers: get.headers.clone(),
credentials: None,
region: None,
service: None,
},
get.extensions.clone(),
);
let head = crate::app::test_seams::head_object_input(&input.bucket, "missing", None); let head = crate::app::test_seams::head_object_input(&input.bucket, "missing", None);
let mut list = get.clone().map_input(|_| input.clone()); let list = S3Request {
list.uri = http::Uri::from_static("/?list-type=2"); input: input.clone(),
method: http::Method::GET,
uri: http::Uri::from_static("/?list-type=2"),
headers: HeaderMap::new(),
extensions,
credentials: None,
region: None,
service: None,
trailing_headers: None,
};
let usecase = crate::app::object::DefaultObjectUsecase::from_global(); let usecase = crate::app::object::DefaultObjectUsecase::from_global();
let get_error = let get_error = tokio::time::timeout(
tokio::time::timeout(Duration::from_secs(10), crate::app::test_seams::get_object(&usecase, get)) Duration::from_secs(10),
.await crate::app::test_seams::get_object_gateway(&usecase, get_envelope, get),
.expect("GET stays local") )
.expect_err("local object is absent"); .await
assert_eq!(*get_error.code(), S3ErrorCode::NoSuchKey); .expect("GET stays local")
.expect_err("local object is absent");
assert_eq!(get_error.code(), &rustfs_s3_types::S3ErrorCode::NoSuchKey);
let head_error = tokio::time::timeout( let head_error = tokio::time::timeout(
Duration::from_secs(10), Duration::from_secs(10),
crate::app::test_seams::head_object_gateway(&usecase, head_envelope, head), crate::app::test_seams::head_object_gateway(&usecase, head_envelope, head),
+12 -2
View File
@@ -56,7 +56,6 @@ use super::storage_api::bucket_usecase::contract::list::{
}; };
use super::storage_api::bucket_usecase::error::StorageError; use super::storage_api::bucket_usecase::error::StorageError;
use super::storage_api::bucket_usecase::helper::{OperationHelper, spawn_background_with_context}; use super::storage_api::bucket_usecase::helper::{OperationHelper, spawn_background_with_context};
use super::storage_api::bucket_usecase::object_utils::to_s3s_xml_etag;
use super::storage_api::bucket_usecase::s3_api::bucket::{ use super::storage_api::bucket_usecase::s3_api::bucket::{
ListObjectVersionsParams, ListObjectsV2Params, encode_list_objects_v2_continuation_token, parse_list_object_versions_params, ListObjectVersionsParams, ListObjectsV2Params, encode_list_objects_v2_continuation_token, parse_list_object_versions_params,
parse_list_objects_v2_params, rustfs_owner, parse_list_objects_v2_params, rustfs_owner,
@@ -999,7 +998,18 @@ mod tests {
}, },
); );
let envelope = RequestEnvelope::from_s3s(&req); // Same facts `RequestEnvelope::from_s3s` copies. Credentials, region, and service stay absent.
let envelope = RequestEnvelope::from_parts(
crate::app::RequestHead {
method: req.method,
uri: req.uri,
headers: req.headers,
credentials: None,
region: None,
service: None,
},
req.extensions,
);
assert!(envelope.req_info().expect("req info should be present").is_owner); assert!(envelope.req_info().expect("req info should be present").is_owner);
} }
-1
View File
@@ -16,7 +16,6 @@
use super::*; use super::*;
use crate::app::storage_api::bucket_usecase::access::requested_bucket_force_delete; use crate::app::storage_api::bucket_usecase::access::requested_bucket_force_delete;
use crate::app::storage_api::s3::S3Error;
use rustfs_s3_types::Region; use rustfs_s3_types::Region;
/// Whether `CreateBucket` may record `location`: the server's own region, or /// Whether `CreateBucket` may record `location`: the server's own region, or
+21 -4
View File
@@ -15,8 +15,8 @@
//! Bucket lifecycle configuration use-case operations. //! Bucket lifecycle configuration use-case operations.
use super::*; use super::*;
use crate::app::storage_api::s3::{S3Error, S3ErrorCode, s3_error};
use rustfs_gateway_types::persistence::{PersistedLifecycleRule, parse_lifecycle_dto}; use rustfs_gateway_types::persistence::{PersistedLifecycleRule, parse_lifecycle_dto};
use rustfs_s3_types::{S3Error, S3ErrorCode, s3_error};
const ERR_LIFECYCLE_RULE_STATUS: &str = "Rule status must be either Enabled or Disabled"; const ERR_LIFECYCLE_RULE_STATUS: &str = "Rule status must be either Enabled or Disabled";
@@ -271,7 +271,7 @@ impl DefaultBucketUsecase {
let mut input_cfg = prepared_configuration.map_err(to_internal_error)?; let mut input_cfg = prepared_configuration.map_err(to_internal_error)?;
assign_lifecycle_rule_ids(&mut input_cfg.rules); assign_lifecycle_rule_ids(&mut input_cfg.rules);
if let Err(err) = validate_lifecycle_config(&input_cfg, &rcfg).await { if let Err(err) = validate_lifecycle_config(&input_cfg, &rcfg).await {
return Err(lifecycle_validation_error(&err).into()); return Err(lifecycle_validation_error(&err));
} }
if let Err(err) = validate_transition_tier(&input_cfg).await { if let Err(err) = validate_transition_tier(&input_cfg).await {
@@ -695,7 +695,6 @@ mod tests {
) )
.await .await
.expect_err("a Filter And with one predicate is a schema violation"); .expect_err("a Filter And with one predicate is a schema violation");
assert_eq!(*lifecycle_validation_error(&malformed).code(), S3ErrorCode::MalformedXML);
let invalid_value = validate_lifecycle_config( let invalid_value = validate_lifecycle_config(
&rustfs_gateway_types::persistence::PersistedLifecycleConfiguration { &rustfs_gateway_types::persistence::PersistedLifecycleConfiguration {
@@ -722,7 +721,25 @@ mod tests {
) )
.await .await
.expect_err("a negative retention count is rejected"); .expect_err("a negative retention count is rejected");
assert_eq!(*lifecycle_validation_error(&invalid_value).code(), S3ErrorCode::InvalidArgument); for (failure, code, message) in [
(
malformed,
S3ErrorCode::MalformedXML,
"Malformed XML: Filter And must contain at least two predicates",
),
(
invalid_value,
S3ErrorCode::InvalidArgument,
"'NewerNoncurrentVersions' must be a non-negative integer",
),
] {
let error = lifecycle_validation_error(&failure);
assert_eq!(error.code(), &code);
assert_eq!(error.message(), Some(message));
assert_eq!(error.status_code(), Some(StatusCode::BAD_REQUEST));
assert!(error.headers().is_none());
assert!(std::error::Error::source(&error).is_none());
}
} }
#[test] #[test]
+391 -209
View File
@@ -14,17 +14,22 @@
//! Object and version listing use-case operations, including the metadata listing extension. //! Object and version listing use-case operations, including the metadata listing extension.
use super::list_objects::listed_etag;
use super::*; use super::*;
use crate::app::storage_api::bucket_usecase::contract::list::ListOperations as _; use crate::app::storage_api::bucket_usecase::contract::list::ListOperations as _;
#[cfg(test)] #[cfg(test)]
use crate::app::storage_api::s3::S3ErrorCode; use crate::app::storage_api::s3::S3ErrorCode;
use crate::app::storage_api::s3::S3Result;
use crate::app::storage_api::s3::dto::{ use crate::app::storage_api::s3::dto::{
CommonPrefix, DeleteMarkerEntry, EncodingType, ListObjectVersionsInput, ListObjectVersionsOutput, ListObjectsV2Input, CommonPrefix, EncodingType, ListObjectVersionsInput, ListObjectVersionsOutput, ListObjectsV2Input, ListObjectsV2Output,
ListObjectsV2Output, MetadataEntry, Object, ObjectStorageClass, ObjectVersion, ObjectVersionStorageClass, Owner, Timestamp, MetadataEntry, ObjectStorageClass, Owner, Timestamp, TimestampFormat, UserMetadata,
UserMetadata,
}; };
use crate::app::storage_api::s3::xml::{SerResult, SerializeContent}; use quick_xml::{
use crate::app::storage_api::s3::{S3Result, xml}; Writer,
events::{BytesDecl, BytesText, Event},
};
use rustfs_gateway_types::ETag;
use std::io;
type ListObjectVersionsInfo = StorageListObjectVersionsInfo<ObjectInfo>; type ListObjectVersionsInfo = StorageListObjectVersionsInfo<ObjectInfo>;
@@ -47,8 +52,8 @@ pub(crate) struct ObjectMetadataExtension {
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub(crate) enum ListObjectVersionMetadataEntry { pub(crate) enum ListObjectVersionMetadataEntry {
DeleteMarker(DeleteMarkerEntry, ObjectMetadataExtension), DeleteMarker(MetadataObject, ObjectMetadataExtension),
Version(ObjectVersion, ObjectMetadataExtension), Version(ObjectMetadataEntry),
} }
#[derive(Clone, Debug, Default, PartialEq)] #[derive(Clone, Debug, Default, PartialEq)]
@@ -57,9 +62,21 @@ pub(crate) struct ListObjectVersionsMetadataOutput {
pub entries: Vec<ListObjectVersionMetadataEntry>, pub entries: Vec<ListObjectVersionMetadataEntry>,
} }
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct MetadataObject {
key: String,
is_latest: Option<bool>,
last_modified: Option<Timestamp>,
owner: Option<Owner>,
size: Option<i64>,
storage_class: Option<String>,
version_id: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq)] #[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct ObjectMetadataEntry { pub(crate) struct ObjectMetadataEntry {
pub object: Object, pub object: MetadataObject,
pub e_tag: Option<ETag>,
pub extension: ObjectMetadataExtension, pub extension: ObjectMetadataExtension,
} }
@@ -69,137 +86,126 @@ pub(crate) struct ListObjectsV2MetadataOutput {
pub contents: Vec<ObjectMetadataEntry>, pub contents: Vec<ObjectMetadataEntry>,
} }
impl xml::Serialize for ListObjectVersionsMetadataOutput { type ListingWriter = Writer<Vec<u8>>;
fn serialize<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult {
s.content_with_ns("ListVersionsResult", XMLNS_S3, self) fn document(root: &str, content: impl FnOnce(&mut ListingWriter) -> io::Result<()>) -> io::Result<Vec<u8>> {
} let mut writer = Writer::new(Vec::with_capacity(1024));
writer.write_event(Event::Decl(BytesDecl::new("1.0", Some("UTF-8"), None)))?;
writer
.create_element(root)
.with_attribute(("xmlns", XMLNS_S3))
.write_inner_content(content)?;
Ok(writer.into_inner())
} }
impl SerializeContent for ListObjectVersionsMetadataOutput { fn text(xml: &mut Writer<impl Write>, name: &str, value: Option<&str>) -> io::Result<()> {
fn serialize_content<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult { if let Some(value) = value {
if let Some(iter) = &self.output.common_prefixes { xml.create_element(name).write_text_content(BytesText::new(value))?;
s.flattened_list("CommonPrefixes", iter)?; }
} Ok(())
if let Some(ref val) = self.output.delimiter { }
s.content("Delimiter", val)?;
} fn display_field(xml: &mut ListingWriter, name: &str, value: Option<impl Display>) -> io::Result<()> {
if let Some(ref val) = self.output.encoding_type { text(xml, name, value.map(|v| v.to_string()).as_deref())
s.content("EncodingType", val)?; }
}
if let Some(ref val) = self.output.is_truncated { fn write_prefixes(xml: &mut ListingWriter, prefixes: Option<&[CommonPrefix]>) -> io::Result<()> {
s.content("IsTruncated", val)?; for prefix in prefixes.unwrap_or_default() {
} xml.create_element("CommonPrefixes")
if let Some(ref val) = self.output.key_marker { .write_inner_content(|xml| text(xml, "Prefix", prefix.prefix.as_deref()))?;
s.content("KeyMarker", val)?; }
} Ok(())
if let Some(ref val) = self.output.max_keys { }
s.content("MaxKeys", val)?;
} impl ListObjectVersionsMetadataOutput {
if let Some(ref val) = self.output.name { pub(crate) fn to_xml(&self) -> io::Result<Vec<u8>> {
s.content("Name", val)?; let page = &self.output;
} document("ListVersionsResult", |xml| {
if let Some(ref val) = self.output.next_key_marker { write_prefixes(xml, page.common_prefixes.as_deref())?;
s.content("NextKeyMarker", val)?; text(xml, "Delimiter", page.delimiter.as_deref())?;
} text(xml, "EncodingType", page.encoding_type.as_ref().map(EncodingType::as_str))?;
if let Some(ref val) = self.output.next_version_id_marker { display_field(xml, "IsTruncated", page.is_truncated)?;
s.content("NextVersionIdMarker", val)?; text(xml, "KeyMarker", page.key_marker.as_deref())?;
} display_field(xml, "MaxKeys", page.max_keys)?;
if let Some(ref val) = self.output.prefix { text(xml, "Name", page.name.as_deref())?;
s.content("Prefix", val)?; text(xml, "NextKeyMarker", page.next_key_marker.as_deref())?;
} text(xml, "NextVersionIdMarker", page.next_version_id_marker.as_deref())?;
if let Some(ref val) = self.output.version_id_marker { text(xml, "Prefix", page.prefix.as_deref())?;
s.content("VersionIdMarker", val)?; text(xml, "VersionIdMarker", page.version_id_marker.as_deref())?;
} for entry in &self.entries {
for entry in &self.entries { match entry {
match entry { ListObjectVersionMetadataEntry::DeleteMarker(marker, extension) => {
ListObjectVersionMetadataEntry::DeleteMarker(marker, extension) => { xml.create_element("DeleteMarker").write_inner_content(|xml| {
s.content( marker.write_xml(xml)?;
"DeleteMarker", extension.write_xml(xml)
&VersionMetadataContent { })?;
value: marker, }
extension, ListObjectVersionMetadataEntry::Version(entry) => {
}, xml.create_element("Version")
)?; .write_inner_content(|xml| entry.write_xml(xml))?;
} }
ListObjectVersionMetadataEntry::Version(version, extension) => {
s.content(
"Version",
&VersionMetadataContent {
value: version,
extension,
},
)?;
} }
} }
} Ok(())
Ok(()) })
} }
} }
impl xml::Serialize for ListObjectsV2MetadataOutput { impl ListObjectsV2MetadataOutput {
fn serialize<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult { pub(crate) fn to_xml(&self) -> io::Result<Vec<u8>> {
s.content_with_ns("ListBucketResult", XMLNS_S3, self) let page = &self.output;
document("ListBucketResult", |xml| {
text(xml, "Name", page.name.as_deref())?;
text(xml, "Prefix", page.prefix.as_deref())?;
display_field(xml, "MaxKeys", page.max_keys)?;
display_field(xml, "KeyCount", page.key_count)?;
text(xml, "ContinuationToken", page.continuation_token.as_deref())?;
display_field(xml, "IsTruncated", page.is_truncated)?;
text(xml, "NextContinuationToken", page.next_continuation_token.as_deref())?;
for entry in &self.contents {
xml.create_element("Contents")
.write_inner_content(|xml| entry.write_xml(xml))?;
}
write_prefixes(xml, page.common_prefixes.as_deref())?;
text(xml, "Delimiter", page.delimiter.as_deref())?;
text(xml, "EncodingType", page.encoding_type.as_ref().map(EncodingType::as_str))?;
text(xml, "StartAfter", page.start_after.as_deref())
})
} }
} }
impl SerializeContent for ListObjectsV2MetadataOutput { impl ObjectMetadataEntry {
fn serialize_content<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult { fn write_xml(&self, xml: &mut ListingWriter) -> io::Result<()> {
if let Some(ref val) = self.output.name { if let Some(etag) = &self.e_tag {
s.content("Name", val)?; // The XML listing uses literal outer quotes even for a weak tag. The opaque text is escaped.
let quoted = format!("\"{}\"", quick_xml::escape::escape(etag.opaque_tag()));
xml.create_element("ETag")
.write_text_content(BytesText::from_escaped(quoted))?;
} }
if let Some(ref val) = self.output.prefix { self.object.write_xml(xml)?;
s.content("Prefix", val)?; self.extension.write_xml(xml)
}
if let Some(ref val) = self.output.max_keys {
s.content("MaxKeys", val)?;
}
if let Some(ref val) = self.output.key_count {
s.content("KeyCount", val)?;
}
if let Some(ref val) = self.output.continuation_token {
s.content("ContinuationToken", val)?;
}
if let Some(ref val) = self.output.is_truncated {
s.content("IsTruncated", val)?;
}
if let Some(ref val) = self.output.next_continuation_token {
s.content("NextContinuationToken", val)?;
}
for entry in &self.contents {
s.content("Contents", entry)?;
}
if let Some(iter) = &self.output.common_prefixes {
s.flattened_list("CommonPrefixes", iter)?;
}
if let Some(ref val) = self.output.delimiter {
s.content("Delimiter", val)?;
}
if let Some(ref val) = self.output.encoding_type {
s.content("EncodingType", val)?;
}
if let Some(ref val) = self.output.start_after {
s.content("StartAfter", val)?;
}
Ok(())
} }
} }
struct VersionMetadataContent<'a, T> { impl MetadataObject {
value: &'a T, fn write_xml(&self, xml: &mut ListingWriter) -> io::Result<()> {
extension: &'a ObjectMetadataExtension, display_field(xml, "IsLatest", self.is_latest)?;
} text(xml, "Key", Some(&self.key))?;
if let Some(date) = &self.last_modified {
impl<T: SerializeContent> SerializeContent for VersionMetadataContent<'_, T> { xml.create_element("LastModified").write_inner_content(|xml| {
fn serialize_content<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult { date.format(TimestampFormat::DateTime, xml.get_mut())
self.value.serialize_content(s)?; .map_err(io::Error::other)
self.extension.serialize_content(s) })?;
} }
} if let Some(owner) = &self.owner {
xml.create_element("Owner").write_inner_content(|xml| {
impl SerializeContent for ObjectMetadataEntry { text(xml, "DisplayName", owner.display_name.as_deref())?;
fn serialize_content<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult { text(xml, "ID", owner.id.as_deref())
self.object.serialize_content(s)?; })?;
self.extension.serialize_content(s) }
display_field(xml, "Size", self.size)?;
text(xml, "StorageClass", self.storage_class.as_deref())?;
text(xml, "VersionId", self.version_id.as_deref())
} }
} }
@@ -237,41 +243,31 @@ fn sanitize_xml_text(value: &str) -> Cow<'_, str> {
} }
} }
impl SerializeContent for ObjectMetadataExtension { impl ObjectMetadataExtension {
fn serialize_content<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult { fn write_xml(&self, xml: &mut ListingWriter) -> io::Result<()> {
if let Some(metadata) = &self.user_metadata { if let Some(metadata) = &self.user_metadata {
s.element("UserMetadata", |s| { xml.create_element("UserMetadata").write_inner_content(|xml| {
for entry in metadata { for entry in metadata {
if let (Some(name), Some(value)) = (&entry.name, &entry.value) { if let (Some(name), Some(value)) = (&entry.name, &entry.value)
// Skip entries whose key is not a valid XML element name and strip && is_valid_xml_name(name)
// XML-illegal control characters from the value, so a single poison {
// object can never corrupt the whole listing document. See issue #2743. text(xml, name, Some(&sanitize_xml_text(value)))?;
if is_valid_xml_name(name) {
let sanitized = sanitize_xml_text(value);
s.content(name, sanitized.as_ref())?;
}
} }
} }
Ok(()) Ok(())
})?; })?;
} }
if let Some(tags) = &self.user_tags { text(xml, "UserTags", self.user_tags.as_deref())?;
s.content("UserTags", tags)?;
}
if let Some(internal) = &self.internal { if let Some(internal) = &self.internal {
s.content("Internal", internal)?; xml.create_element("Internal").write_inner_content(|xml| {
display_field(xml, "K", Some(internal.k))?;
display_field(xml, "M", Some(internal.m))
})?;
} }
Ok(()) Ok(())
} }
} }
impl SerializeContent for ObjectInternalInfo {
fn serialize_content<W: Write>(&self, s: &mut xml::Serializer<W>) -> SerResult {
s.content("K", &self.k)?;
s.content("M", &self.m)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct ObjectMetadataPermissions { struct ObjectMetadataPermissions {
metadata_allowed: bool, metadata_allowed: bool,
@@ -441,38 +437,34 @@ fn build_list_object_versions_metadata_output(
if object.delete_marker { if object.delete_marker {
ListObjectVersionMetadataEntry::DeleteMarker( ListObjectVersionMetadataEntry::DeleteMarker(
DeleteMarkerEntry { MetadataObject {
key: Some(object_name), key: object_name,
last_modified: object.mod_time.map(Timestamp::from), last_modified: object.mod_time.map(Timestamp::from),
owner: Some(owner.clone()), owner: Some(owner.clone()),
version_id: Some(version_id), version_id: Some(version_id),
is_latest: Some(object.is_latest), is_latest: Some(object.is_latest),
},
extension,
)
} else {
ListObjectVersionMetadataEntry::Version(
ObjectVersion {
key: Some(object_name),
last_modified: object.mod_time.map(Timestamp::from),
size: Some(object.size),
version_id: Some(version_id),
is_latest: Some(object.is_latest),
e_tag: object
.etag
.as_ref()
.filter(|_| rustfs_utils::http::etag_can_be_listed(&object.user_defined))
.map(|etag| to_s3s_xml_etag(etag)),
storage_class: Some(ObjectVersionStorageClass::from(
object
.storage_class
.unwrap_or_else(|| ObjectVersionStorageClass::STANDARD.to_string()),
)),
owner: Some(owner.clone()),
..Default::default() ..Default::default()
}, },
extension, extension,
) )
} else {
ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry {
e_tag: listed_etag(&object),
object: MetadataObject {
key: object_name,
last_modified: object.mod_time.map(Timestamp::from),
size: Some(object.size),
version_id: Some(version_id),
is_latest: Some(object.is_latest),
storage_class: Some(
object
.storage_class
.unwrap_or_else(|| ObjectStorageClass::STANDARD.to_string()),
),
owner: Some(owner.clone()),
},
extension,
})
} }
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@@ -545,21 +537,17 @@ fn build_list_objects_v2_metadata_output(
}; };
ObjectMetadataEntry { ObjectMetadataEntry {
object: Object { e_tag: listed_etag(object),
key: Some(encode_list_objects_v2_value(&object.name, encoding_type)), object: MetadataObject {
key: encode_list_objects_v2_value(&object.name, encoding_type),
last_modified: object.mod_time.map(Timestamp::from), last_modified: object.mod_time.map(Timestamp::from),
size: Some(object.get_actual_size_or_physical()), size: Some(object.get_actual_size_or_physical()),
e_tag: object storage_class: Some(
.etag
.as_ref()
.filter(|_| rustfs_utils::http::etag_can_be_listed(&object.user_defined))
.map(|etag| to_s3s_xml_etag(etag)),
storage_class: Some(ObjectStorageClass::from(
object object
.storage_class .storage_class
.clone() .clone()
.unwrap_or_else(|| ObjectStorageClass::STANDARD.to_string()), .unwrap_or_else(|| ObjectStorageClass::STANDARD.to_string()),
)), ),
owner: fetch_owner.then_some(owner.clone()), owner: fetch_owner.then_some(owner.clone()),
..Default::default() ..Default::default()
}, },
@@ -743,14 +731,160 @@ mod tests {
use crate::app::bucket_usecase::test_support::owned_envelope; use crate::app::bucket_usecase::test_support::owned_envelope;
use http::Method; use http::Method;
/// Response bodies are not bucket configurations: they are written by the #[test]
/// s3s encoder itself, as the legacy stack does. fn metadata_listings_match_the_legacy_xml_bytes() {
fn serialize_s3s_response<T: xml::Serialize>(value: &T) -> Vec<u8> { let owner = Owner {
let mut buf = Vec::new(); display_name: Some("user<&".into()),
value id: Some("a'b".into()),
.serialize(&mut xml::Serializer::new(&mut buf)) };
.expect("metadata output should serialize"); let at = Timestamp::from(time::OffsetDateTime::from_unix_timestamp_nanos(1_700_000_000_123_456_789).unwrap());
buf let object = MetadataObject {
key: "key&".into(),
last_modified: Some(at),
owner: Some(owner),
..Default::default()
};
let extension = ObjectMetadataExtension {
user_metadata: Some(vec![
MetadataEntry {
name: Some("bad key".into()),
value: Some("absent".into()),
},
MetadataEntry {
name: Some("键名".into()),
value: Some("a\u{1}\t\n\r<&>\"'".into()),
},
]),
user_tags: Some("tag=x&z=y".into()),
internal: Some(ObjectInternalInfo { k: 4, m: 2 }),
};
let prefixes = Some(vec![CommonPrefix {
prefix: Some("dir/".into()),
}]);
let v2 = ListObjectsV2MetadataOutput {
output: ListObjectsV2Output {
name: Some("bucket".into()),
prefix: Some(String::new()),
max_keys: Some(3),
key_count: Some(2),
continuation_token: Some("a+b".into()),
is_truncated: Some(true),
next_continuation_token: Some("c=".into()),
common_prefixes: prefixes.clone(),
delimiter: Some("/".into()),
encoding_type: Some(EncodingType::from_static("url")),
start_after: Some("key\r".into()),
..Default::default()
},
contents: vec![ObjectMetadataEntry {
object: MetadataObject {
size: Some(9),
storage_class: Some("STANDARD".into()),
..object.clone()
},
e_tag: Some(ETag::from_stored("x<&\"'")),
extension: extension.clone(),
}],
};
let versions = ListObjectVersionsMetadataOutput {
output: ListObjectVersionsOutput {
common_prefixes: prefixes,
delimiter: Some("/".into()),
encoding_type: Some(EncodingType::from_static("url")),
is_truncated: Some(false),
key_marker: Some(String::new()),
max_keys: Some(3),
name: Some("bucket".into()),
next_key_marker: Some("mark".into()),
next_version_id_marker: Some("next".into()),
prefix: Some("prefix".into()),
version_id_marker: Some(String::new()),
..Default::default()
},
entries: vec![
ListObjectVersionMetadataEntry::DeleteMarker(
MetadataObject {
is_latest: Some(true),
version_id: Some("null".into()),
..object.clone()
},
ObjectMetadataExtension {
user_metadata: Some(vec![]),
..Default::default()
},
),
ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry {
object: MetadataObject {
is_latest: Some(false),
size: Some(99),
storage_class: Some("GLACIER".into()),
version_id: Some("v1".into()),
..object
},
e_tag: Some(ETag::new_weak("weak").unwrap()),
extension,
}),
],
};
// Complete documents captured from the metadata route's s3s serializer at 056e59af7.
assert_eq!(
v2.to_xml().unwrap(),
concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Name>bucket</Name>",
"<Prefix></Prefix><MaxKeys>3</MaxKeys><KeyCount>2</KeyCount>",
"<ContinuationToken>a+b</ContinuationToken><IsTruncated>true</IsTruncated>",
"<NextContinuationToken>c=</NextContinuationToken><Contents>",
"<ETag>\"x&lt;&amp;&quot;&apos;\"</ETag><Key>key&amp;</Key>",
"<LastModified>2023-11-14T22:13:20.123Z</LastModified><Owner>",
"<DisplayName>user&lt;&amp;</DisplayName><ID>a&apos;b</ID></Owner><Size>9</Size>",
"<StorageClass>STANDARD</StorageClass><UserMetadata>",
"<键名>a\t\n&#13;&lt;&amp;&gt;&quot;&apos;</键名></UserMetadata>",
"<UserTags>tag=x&amp;z=y</UserTags><Internal><K>4</K><M>2</M></Internal></Contents>",
"<CommonPrefixes><Prefix>dir/</Prefix></CommonPrefixes><Delimiter>/</Delimiter>",
"<EncodingType>url</EncodingType><StartAfter>key&#13;</StartAfter></ListBucketResult>",
)
.as_bytes()
);
assert_eq!(
versions.to_xml().unwrap(),
concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"<ListVersionsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><CommonPrefixes>",
"<Prefix>dir/</Prefix></CommonPrefixes><Delimiter>/</Delimiter>",
"<EncodingType>url</EncodingType><IsTruncated>false</IsTruncated><KeyMarker></KeyMarker>",
"<MaxKeys>3</MaxKeys><Name>bucket</Name><NextKeyMarker>mark</NextKeyMarker>",
"<NextVersionIdMarker>next</NextVersionIdMarker><Prefix>prefix</Prefix><VersionIdMarker>",
"</VersionIdMarker><DeleteMarker><IsLatest>true</IsLatest><Key>key&amp;</Key>",
"<LastModified>2023-11-14T22:13:20.123Z</LastModified><Owner>",
"<DisplayName>user&lt;&amp;</DisplayName><ID>a&apos;b</ID></Owner>",
"<VersionId>null</VersionId><UserMetadata></UserMetadata></DeleteMarker><Version>",
"<ETag>\"weak\"</ETag><IsLatest>false</IsLatest><Key>key&amp;</Key>",
"<LastModified>2023-11-14T22:13:20.123Z</LastModified><Owner>",
"<DisplayName>user&lt;&amp;</DisplayName><ID>a&apos;b</ID></Owner><Size>99</Size>",
"<StorageClass>GLACIER</StorageClass><VersionId>v1</VersionId><UserMetadata>",
"<键名>a\t\n&#13;&lt;&amp;&gt;&quot;&apos;</键名></UserMetadata>",
"<UserTags>tag=x&amp;z=y</UserTags><Internal><K>4</K><M>2</M></Internal></Version>",
"</ListVersionsResult>",
)
.as_bytes()
);
assert_eq!(
ListObjectsV2MetadataOutput::default().to_xml().unwrap(),
concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"></ListBucketResult>",
)
.as_bytes()
);
assert_eq!(
ListObjectVersionsMetadataOutput::default().to_xml().unwrap(),
concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"<ListVersionsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"></ListVersionsResult>",
)
.as_bytes()
);
} }
#[tokio::test] #[tokio::test]
@@ -806,6 +940,20 @@ mod tests {
user_defined: Arc::new(HashMap::from([("x-rustfs-encryption-original-size".to_owned(), "10485760".to_owned())])), user_defined: Arc::new(HashMap::from([("x-rustfs-encryption-original-size".to_owned(), "10485760".to_owned())])),
..Default::default() ..Default::default()
}, },
ObjectInfo {
name: "weak".to_owned(),
etag: Some(r#"W/"a&<b""#.to_owned()),
..Default::default()
},
ObjectInfo {
name: "stored-entities".to_owned(),
etag: Some(r#"x"'<>&amp;"#.to_owned()),
..Default::default()
},
ObjectInfo {
name: "no-etag".to_owned(),
..Default::default()
},
]; ];
let listings = build_list_objects_v2_metadata_output( let listings = build_list_objects_v2_metadata_output(
ListObjectsV2Info { ListObjectsV2Info {
@@ -826,15 +974,13 @@ mod tests {
false, false,
&HashMap::new(), &HashMap::new(),
); );
assert!(listings.contents[0].object.e_tag.is_none()); assert!(listings.contents[0].e_tag.is_none());
assert!(listings.contents[1].object.e_tag.is_some()); assert!(listings.contents[1].e_tag.is_some());
assert!(listings.contents[2].object.e_tag.is_some()); assert!(listings.contents[2].e_tag.is_some());
assert_eq!( assert_eq!(
listings.contents[3].object.e_tag, listings.contents[3].e_tag.as_ref().map(ETag::opaque_tag),
Some(to_s3s_xml_etag("1b8a77dff5845270a8d81d86a28f38ea-2")) Some("1b8a77dff5845270a8d81d86a28f38ea-2")
); );
let xml = String::from_utf8(serialize_s3s_response(&listings)).expect("UTF-8 objects");
assert!(!xml.contains(legacy_md5));
let versions = build_list_object_versions_metadata_output( let versions = build_list_object_versions_metadata_output(
ListObjectVersionsInfo { ListObjectVersionsInfo {
@@ -853,13 +999,41 @@ mod tests {
&HashMap::new(), &HashMap::new(),
); );
for (index, entry) in versions.entries.iter().enumerate() { for (index, entry) in versions.entries.iter().enumerate() {
let ListObjectVersionMetadataEntry::Version(version, _) = entry else { let ListObjectVersionMetadataEntry::Version(version) = entry else {
panic!("expected object version"); panic!("expected object version");
}; };
assert_eq!(version.e_tag, listings.contents[index].object.e_tag); assert_eq!(version.e_tag, listings.contents[index].e_tag);
}
#[derive(serde::Deserialize)]
struct Listing {
#[serde(rename = "Contents", alias = "Version")]
entries: Vec<Entry>,
}
#[derive(serde::Deserialize)]
struct Entry {
#[serde(rename = "ETag")]
e_tag: Option<String>,
}
for bytes in [listings.to_xml().unwrap(), versions.to_xml().unwrap()] {
let xml = std::str::from_utf8(&bytes).expect("UTF-8 listing");
assert!(!xml.contains(legacy_md5));
assert!(xml.contains(r#"<ETag>"a&amp;&lt;b"</ETag>"#));
assert!(xml.contains(r#"<ETag>"x&quot;&apos;&lt;&gt;&amp;amp;"</ETag>"#));
let listing: Listing = quick_xml::de::from_str(xml).expect("well-formed listing");
let tags: Vec<_> = listing.entries.iter().map(|entry| entry.e_tag.as_deref()).collect();
assert_eq!(
tags,
[
None,
Some(r#""0123456789abcdef0123456789abcdef""#),
Some(r#""9876543210abcdef9876543210abcdef""#),
Some(r#""1b8a77dff5845270a8d81d86a28f38ea-2""#),
Some(r#""a&<b""#),
Some(r#""x"'<>&amp;""#),
None,
]
);
} }
let xml = String::from_utf8(serialize_s3s_response(&versions)).expect("UTF-8 versions");
assert!(!xml.contains(legacy_md5));
} }
#[test] #[test]
@@ -941,7 +1115,7 @@ mod tests {
&permissions, &permissions,
); );
for (index, entry) in versions.entries.iter().enumerate() { for (index, entry) in versions.entries.iter().enumerate() {
let ListObjectVersionMetadataEntry::Version(_, extension) = entry else { let ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry { extension, .. }) = entry else {
panic!("expected version"); panic!("expected version");
}; };
assert_eq!(extension.user_metadata.is_some(), index >= 2); assert_eq!(extension.user_metadata.is_some(), index >= 2);
@@ -1025,8 +1199,12 @@ mod tests {
assert_eq!(output.entries.len(), 2); assert_eq!(output.entries.len(), 2);
match &output.entries[0] { match &output.entries[0] {
ListObjectVersionMetadataEntry::Version(version, extension) => { ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry {
assert_eq!(version.key.as_deref(), Some("obj-a")); object: version,
extension,
..
}) => {
assert_eq!(version.key, "obj-a");
// A null version's synthesized nil UUID must surface as the // A null version's synthesized nil UUID must surface as the
// literal `null`, never as `00000000-…` (issue #6745). // literal `null`, never as `00000000-…` (issue #6745).
assert_eq!(version.version_id.as_deref(), Some("null")); assert_eq!(version.version_id.as_deref(), Some("null"));
@@ -1045,7 +1223,7 @@ mod tests {
match &output.entries[1] { match &output.entries[1] {
ListObjectVersionMetadataEntry::DeleteMarker(marker, extension) => { ListObjectVersionMetadataEntry::DeleteMarker(marker, extension) => {
assert_eq!(marker.key.as_deref(), Some("obj-b")); assert_eq!(marker.key, "obj-b");
assert_eq!(marker.version_id.as_deref(), Some("null")); assert_eq!(marker.version_id.as_deref(), Some("null"));
assert!(extension.user_tags.is_none()); assert!(extension.user_tags.is_none());
assert_eq!( assert_eq!(
@@ -1107,8 +1285,12 @@ mod tests {
assert_eq!(output.output.next_version_id_marker, None); assert_eq!(output.output.next_version_id_marker, None);
match &output.entries[0] { match &output.entries[0] {
ListObjectVersionMetadataEntry::Version(version, extension) => { ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry {
assert_eq!(version.key.as_deref(), Some("logs%20and%20more%2Fobject%20one.txt")); object: version,
extension,
..
}) => {
assert_eq!(version.key, "logs%20and%20more%2Fobject%20one.txt");
assert!(extension.user_metadata.is_none()); assert!(extension.user_metadata.is_none());
assert!(extension.user_tags.is_none()); assert!(extension.user_tags.is_none());
assert!(extension.internal.is_none()); assert!(extension.internal.is_none());
@@ -1193,7 +1375,7 @@ mod tests {
assert_eq!(output.output.common_prefixes.as_ref().map(Vec::len), Some(1)); assert_eq!(output.output.common_prefixes.as_ref().map(Vec::len), Some(1));
let entry = output.contents.first().unwrap(); let entry = output.contents.first().unwrap();
assert_eq!(entry.object.key.as_deref(), Some("logs/obj%20a.txt")); assert_eq!(entry.object.key, "logs/obj%20a.txt");
assert_eq!(entry.extension.user_tags.as_deref(), Some("env=prod")); assert_eq!(entry.extension.user_tags.as_deref(), Some("env=prod"));
assert_eq!(entry.extension.internal, Some(ObjectInternalInfo { k: 4, m: 2 })); assert_eq!(entry.extension.internal, Some(ObjectInternalInfo { k: 4, m: 2 }));
assert!(entry.object.owner.is_some()); assert!(entry.object.owner.is_some());
@@ -1246,7 +1428,7 @@ mod tests {
}; };
let output = build_list_objects_v2_metadata_output(object_infos, "demo-bucket", &params, None, false, &permissions); let output = build_list_objects_v2_metadata_output(object_infos, "demo-bucket", &params, None, false, &permissions);
let xml = String::from_utf8(serialize_s3s_response(&output)).expect("metadata output should be UTF-8"); let xml = String::from_utf8(output.to_xml().unwrap()).expect("metadata output should be UTF-8");
assert!(xml.contains("<ListBucketResult")); assert!(xml.contains("<ListBucketResult"));
assert!(xml.contains("<Contents>")); assert!(xml.contains("<Contents>"));
@@ -1318,7 +1500,7 @@ mod tests {
}; };
let output = build_list_objects_v2_metadata_output(object_infos, "demo-bucket", &params, None, false, &permissions); let output = build_list_objects_v2_metadata_output(object_infos, "demo-bucket", &params, None, false, &permissions);
let xml = String::from_utf8(serialize_s3s_response(&output)).expect("metadata output should be UTF-8"); let xml = String::from_utf8(output.to_xml().unwrap()).expect("metadata output should be UTF-8");
// Good sibling metadata survives. // Good sibling metadata survives.
assert!(xml.contains("<project>alpha</project>"), "well-formed key must remain: {xml}"); assert!(xml.contains("<project>alpha</project>"), "well-formed key must remain: {xml}");
@@ -1388,7 +1570,7 @@ mod tests {
assert_eq!(output.output.encoding_type.as_ref().map(EncodingType::as_str), Some(EncodingType::URL)); assert_eq!(output.output.encoding_type.as_ref().map(EncodingType::as_str), Some(EncodingType::URL));
let entry = output.contents.first().unwrap(); let entry = output.contents.first().unwrap();
assert_eq!(entry.object.key.as_deref(), Some("logs%20and%20more/object%20one.txt")); assert_eq!(entry.object.key, "logs%20and%20more/object%20one.txt");
assert!(entry.object.owner.is_none()); assert!(entry.object.owner.is_none());
assert!(entry.extension.user_metadata.is_none()); assert!(entry.extension.user_metadata.is_none());
assert!(entry.extension.user_tags.is_none()); assert!(entry.extension.user_tags.is_none());
+21 -21
View File
@@ -16,14 +16,14 @@
//! //!
//! Responsible for: the bucket name, object key, timestamp, owner and stored-configuration //! Responsible for: the bucket name, object key, timestamp, owner and stored-configuration
//! conversions a use case needs to build a gateway output from what the store returned, under the //! conversions a use case needs to build a gateway output from what the store returned, under the
//! rule in [`crate::app`]; and [`seam_error`], the one answer for a value the s3s compatibility //! rule in [`crate::app`].
//! seam refused.
//! NOT responsible for: validating names a client sends (the edge that accepted the request did), //! NOT responsible for: validating names a client sends (the edge that accepted the request did),
//! or deciding what a use case lists. //! or deciding what a use case lists.
//! Upstream: the use cases in `crate::app`. Downstream: `rustfs_gateway_types`. //! Upstream: the use cases in `crate::app`. Downstream: `rustfs_gateway_types`.
use super::storage_api::bucket_usecase::bucket::utils::{BucketConfigXml, serialize}; use super::storage_api::bucket_usecase::bucket::utils::{BucketConfigXml, serialize};
use super::storage_api::bucket_usecase::s3_api::bucket::{RUSTFS_OWNER_DISPLAY_NAME, RUSTFS_OWNER_ID}; use super::storage_api::bucket_usecase::s3_api::bucket::{RUSTFS_OWNER_DISPLAY_NAME, RUSTFS_OWNER_ID};
#[cfg(test)]
use rustfs_gateway_types::compat::{ConversionError, NameRefusal}; use rustfs_gateway_types::compat::{ConversionError, NameRefusal};
use rustfs_gateway_types::dto::Owner; use rustfs_gateway_types::dto::Owner;
use rustfs_gateway_types::{BucketName, ETag, NamePolicy, NameValidator, ObjectKey, Stricter, Timestamp}; use rustfs_gateway_types::{BucketName, ETag, NamePolicy, NameValidator, ObjectKey, Stricter, Timestamp};
@@ -63,7 +63,7 @@ pub(crate) fn stored_bucket_name(name: &str) -> S3Result<BucketName> {
}) })
} }
/// What a legacy edge answers when the s3s compatibility seam refuses a value of an admitted request. /// The legacy error expected by compatibility tests when the s3s seam refuses an admitted value.
/// ///
/// - An object key below the gateway's key floor (empty, over 1024 bytes, a NUL) is refused as /// - An object key below the gateway's key floor (empty, over 1024 bytes, a NUL) is refused as
/// `validate_object_key` refuses one: `400 InvalidArgument`, with a fixed message. An edge whose /// `validate_object_key` refuses one: `400 InvalidArgument`, with a fixed message. An edge whose
@@ -71,6 +71,7 @@ pub(crate) fn stored_bucket_name(name: &str) -> S3Result<BucketName> {
/// - A bucket name below the bucket floor is a server fault: s3s admits only `[a-z0-9.-]{3,63}`, /// - A bucket name below the bucket floor is a server fault: s3s admits only `[a-z0-9.-]{3,63}`,
/// which the floor always accepts, so no bucket a request names reaches it. /// which the floor always accepts, so no bucket a request names reaches it.
/// - Any other refusal is a value the gateway shape cannot hold: a server fault. /// - Any other refusal is a value the gateway shape cannot hold: a server fault.
#[cfg(test)]
pub(crate) fn seam_error(error: ConversionError) -> S3Error { pub(crate) fn seam_error(error: ConversionError) -> S3Error {
match error.name_kind() { match error.name_kind() {
Some(NameRefusal::ObjectKey) => S3Error::with_message(S3ErrorCode::InvalidArgument, "Invalid object key"), Some(NameRefusal::ObjectKey) => S3Error::with_message(S3ErrorCode::InvalidArgument, "Invalid object key"),
@@ -117,7 +118,7 @@ pub(crate) fn owner() -> Owner {
/// The entity tag the store holds, as an answer carries it: every answer that carries a stored tag /// The entity tag the store holds, as an answer carries it: every answer that carries a stored tag
/// converts it here, and none drops, rewrites or refuses one. /// converts it here, and none drops, rewrites or refuses one.
/// ///
/// It reads the stored spelling exactly as the legacy edge always has (`to_s3s_etag`): `W/"…"` is /// It reads the stored spelling exactly as the legacy edge always has: `W/"…"` is
/// a weak tag and one surrounding quote pair is the store's spelling of a strong one; the tag /// a weak tag and one surrounding quote pair is the store's spelling of a strong one; the tag
/// inside is kept byte for byte, so the legacy stack's answer does not change. A weak tag whose /// inside is kept byte for byte, so the legacy stack's answer does not change. A weak tag whose
/// inside the gateway's reader refuses or rewrites cannot stay weak (the gateway has no lossless /// inside the gateway's reader refuses or rewrites cannot stay weak (the gateway has no lossless
@@ -323,31 +324,30 @@ mod tests {
/// Stored tag spellings retain their expected forms across conversions and renderers. /// Stored tag spellings retain their expected forms across conversions and renderers.
#[test] #[test]
fn a_stored_tag_is_answered_as_main_answers_it_on_both_edges() { fn a_stored_tag_is_answered_as_main_answers_it_on_both_edges() {
use crate::app::storage_api::object_usecase::object_utils::to_s3s_etag;
use rustfs_gateway_types::EtagRender; use rustfs_gateway_types::EtagRender;
use rustfs_gateway_types::compat::s3s_5761ddfe::leaf::etag_to_s3s; use rustfs_gateway_types::compat::s3s_5761ddfe::leaf::etag_to_s3s;
// Stored spelling, legacy header, gateway header, and XML text. // Stored spelling, opaque value, weakness, legacy header, gateway header, and XML text.
let rows: [(&str, &str, &str, &str); 11] = [ let rows = [
("abc", r#""abc""#, r#""abc""#, r#""abc""#), ("abc", "abc", false, r#""abc""#, r#""abc""#, r#""abc""#),
(r#""abc""#, r#""abc""#, r#""abc""#, r#""abc""#), (r#""abc""#, "abc", false, r#""abc""#, r#""abc""#, r#""abc""#),
(r#"W/"abc""#, r#"W/"abc""#, r#"W/"abc""#, r#""abc""#), (r#"W/"abc""#, "abc", true, r#"W/"abc""#, r#"W/"abc""#, r#""abc""#),
("abc-3", r#""abc-3""#, r#""abc-3""#, r#""abc-3""#), ("abc-3", "abc-3", false, r#""abc-3""#, r#""abc-3""#, r#""abc-3""#),
(r#""""#, r#""""#, r#""""#, r#""""#), (r#""""#, "", false, r#""""#, r#""""#, r#""""#),
("", r#""""#, r#""""#, r#""""#), ("", "", false, r#""""#, r#""""#, r#""""#),
("W/abc", r#""W/abc""#, r#""W/abc""#, r#""W/abc""#), ("W/abc", "W/abc", false, r#""W/abc""#, r#""W/abc""#, r#""W/abc""#),
("a&b", r#""a&b""#, r#""a&b""#, r#""a&b""#), ("a&b", "a&b", false, r#""a&b""#, r#""a&b""#, r#""a&b""#),
(r#""abc"#, r#"""abc""#, r#""\"abc""#, r#"""abc""#), (r#""abc"#, "\"abc", false, r#"""abc""#, r#""\"abc""#, r#"""abc""#),
(r#"""abc"""#, r#"""abc"""#, r#""\"abc\"""#, r#"""abc"""#), (r#"""abc"""#, "\"abc\"", false, r#"""abc"""#, r#""\"abc\"""#, r#"""abc"""#),
(r#"w/"abc""#, r#""w/"abc"""#, r#""w/\"abc\"""#, r#""w/"abc"""#), (r#"w/"abc""#, "w/\"abc\"", false, r#""w/"abc"""#, r#""w/\"abc\"""#, r#""w/"abc"""#),
]; ];
// Every row is checked before the test fails, so one run names every row that differs. // Every row is checked before the test fails, so one run names every row that differs.
let mut differing = Vec::new(); let mut differing = Vec::new();
for (stored, main_header, gateway_header, xml) in rows { for (stored, opaque, weak, main_header, gateway_header, xml) in rows {
let etag = stored_etag(stored); let etag = stored_etag(stored);
let legacy = to_s3s_etag(stored); let legacy = etag_to_s3s(&etag);
let answered = ( let answered = (
etag_to_s3s(&etag) == legacy, legacy.value() == opaque && legacy.as_weak().is_some() == weak,
legacy.to_http_header().is_ok_and(|header| header == main_header), legacy.to_http_header().is_ok_and(|header| header == main_header),
etag.render(EtagRender::HeaderQuoted) == gateway_header, etag.render(EtagRender::HeaderQuoted) == gateway_header,
etag.render(EtagRender::XmlQuoted) == xml, etag.render(EtagRender::XmlQuoted) == xml,
+10 -13
View File
@@ -28,7 +28,6 @@
use crate::app::RequestEnvelope; use crate::app::RequestEnvelope;
use crate::app::bucket_usecase::DefaultBucketUsecase; use crate::app::bucket_usecase::DefaultBucketUsecase;
use crate::app::storage_api::s3::dto::{EncodingType, ListObjectVersionsInput, ListObjectsV2Input}; use crate::app::storage_api::s3::dto::{EncodingType, ListObjectVersionsInput, ListObjectsV2Input};
use crate::app::storage_api::s3::xml;
use crate::storage::access_owned::listing_multipart::authorize_bucket_listing; use crate::storage::access_owned::listing_multipart::authorize_bucket_listing;
use crate::storage::authorization::AuthorizationRequest; use crate::storage::authorization::AuthorizationRequest;
use http::{HeaderMap, Uri}; use http::{HeaderMap, Uri};
@@ -78,25 +77,23 @@ pub(crate) async fn answer(envelope: &RequestEnvelope, listing: MetadataListing,
match listing { match listing {
MetadataListing::ListObjectVersions => { MetadataListing::ListObjectVersions => {
let input = list_object_versions_input(bucket, envelope.uri(), envelope.headers())?; let input = list_object_versions_input(bucket, envelope.uri(), envelope.headers())?;
render(&usecase.list_object_versions_metadata(envelope, input).await?) usecase
.list_object_versions_metadata(envelope, input)
.await?
.to_xml()
.map_err(S3Error::internal_error)
} }
MetadataListing::ListObjectsV2 => { MetadataListing::ListObjectsV2 => {
let input = list_objects_v2_input(bucket, envelope.uri(), envelope.headers())?; let input = list_objects_v2_input(bucket, envelope.uri(), envelope.headers())?;
render(&usecase.list_objects_v2_metadata(envelope, input).await?) usecase
.list_objects_v2_metadata(envelope, input)
.await?
.to_xml()
.map_err(S3Error::internal_error)
} }
} }
} }
fn render<T: xml::Serialize>(output: &T) -> S3Result<Vec<u8>> {
let mut body = Vec::with_capacity(1024);
let mut serializer = xml::Serializer::new(&mut body);
serializer
.decl()
.and_then(|()| output.serialize(&mut serializer))
.map_err(S3Error::internal_error)?;
Ok(body)
}
fn list_object_versions_input(bucket: String, uri: &Uri, headers: &HeaderMap) -> S3Result<ListObjectVersionsInput> { fn list_object_versions_input(bucket: String, uri: &Uri, headers: &HeaderMap) -> S3Result<ListObjectVersionsInput> {
let query = uri.query().unwrap_or_default(); let query = uri.query().unwrap_or_default();
+64 -45
View File
@@ -49,8 +49,6 @@ use super::storage_api::multipart_usecase::io::{DecryptReader, EncryptReader, Ha
use super::storage_api::multipart_usecase::io::{ use super::storage_api::multipart_usecase::io::{
EtagAlgorithm, HashReader, WriteEncryption, WritePlan, compression_metadata_value, EtagAlgorithm, HashReader, WriteEncryption, WritePlan, compression_metadata_value,
}; };
#[cfg(test)]
use super::storage_api::multipart_usecase::object_utils::{to_s3s_etag, to_s3s_xml_etag};
use super::storage_api::multipart_usecase::options::{ use super::storage_api::multipart_usecase::options::{
copy_src_opts, extract_metadata_from_mime, get_complete_multipart_upload_opts_with_replication_authorization, copy_src_opts, extract_metadata_from_mime, get_complete_multipart_upload_opts_with_replication_authorization,
get_content_sha256_with_query, get_opts, has_replication_retention_update, namespace_reserved_user_metadata, get_content_sha256_with_query, get_opts, has_replication_retention_update, namespace_reserved_user_metadata,
@@ -62,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::set_disk::is_valid_storage_class;
use super::storage_api::multipart_usecase::sse::{ use super::storage_api::multipart_usecase::sse::{
DecryptionRequest, EncryptionKeyKind, EncryptionRequest, PrepareEncryptionRequest, SseKmsPrincipal, SseKmsPrincipalExt, DecryptionRequest, EncryptionKeyKind, EncryptionRequest, PrepareEncryptionRequest, SseKmsPrincipal,
apply_bucket_default_lock_retention, authorize_sse_kms_multipart_write, authorize_sse_kms_object_read, 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, 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, extract_ssec_params_from_headers, extract_ssekms_context_from_headers, get_buffer_size_opt_in,
@@ -299,6 +297,32 @@ fn multipart_upload_api_error(err: StorageError) -> S3Error {
ApiError::from(err).into() ApiError::from(err).into()
} }
#[cfg(test)]
fn completion_part(number: i32, stored: Option<&str>) -> rustfs_gateway_types::dto::CompletedPart {
rustfs_gateway_types::dto::CompletedPart {
part_number: number,
e_tag: stored.map(crate::app::dto_values::stored_etag),
..Default::default()
}
}
#[cfg(test)]
fn completion_input(
bucket: &str,
key: &str,
upload_id: &str,
parts: Vec<rustfs_gateway_types::dto::CompletedPart>,
) -> rustfs_gateway_types::dto::CompleteMultipartUploadInput {
use rustfs_gateway_types::{BucketName, ObjectKey, UploadIdClaim, dto};
dto::CompleteMultipartUploadInput {
bucket: BucketName::new(bucket).expect("test bucket"),
key: ObjectKey::new(key).expect("test key"),
upload_id: UploadIdClaim::from_wire(upload_id),
multipart_upload: dto::CompletedMultipartUpload { parts },
..Default::default()
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::test_support::*; use super::test_support::*;
@@ -632,8 +656,7 @@ mod tests {
crate::app::gating_test_env::run_large_stack_test("mpu-kms-current-caller", || async { crate::app::gating_test_env::run_large_stack_test("mpu-kms-current-caller", || async {
use crate::app::storage_api::s3::S3ErrorCode; use crate::app::storage_api::s3::S3ErrorCode;
use crate::app::storage_api::s3::dto::{ use crate::app::storage_api::s3::dto::{
CompleteMultipartUploadInput, CompletedMultipartUpload, CompletedPart, CopySource, StreamingBlob, CompleteMultipartUploadInput, CompletedMultipartUpload, CompletedPart, StreamingBlob, UploadPartInput,
UploadPartCopyInput, UploadPartInput,
}; };
use crate::app::storage_api::test::ReqInfo; use crate::app::storage_api::test::ReqInfo;
use crate::app::storage_api::test::sse::{ use crate::app::storage_api::test::sse::{
@@ -700,26 +723,40 @@ mod tests {
let error = usecase let error = usecase
.execute_upload_part(denied_request(part, authorizer.clone())) .execute_upload_part(denied_request(part, authorizer.clone()))
.await .await
.expect_err("denied part"); .err()
.expect("denied part");
assert_eq!(error.code(), &S3ErrorCode::AccessDenied); assert_eq!(error.code(), &S3ErrorCode::AccessDenied);
let copy = UploadPartCopyInput::builder() let copy_envelope = crate::app::RequestEnvelope::from_s3s(&denied_request((), authorizer.clone()));
.bucket(bucket.clone())
.key(key.to_string())
.upload_id(upload.upload_id.clone())
.part_number(1)
.copy_source(CopySource::Bucket {
bucket: bucket.clone().into(),
key: "source".into(),
version_id: None,
})
.build()
.expect("copy");
let copy_req = denied_request(copy, authorizer.clone());
let error = usecase let error = usecase
.execute_upload_part_copy(copy_req) .execute_upload_part_copy_with_audit(
copy_envelope,
UploadPartCopyWriteInput {
target: UploadPartTarget::Legacy {
bucket: bucket.clone(),
key: key.to_string(),
upload_id: upload.upload_id.clone(),
},
part_number: 1,
copy_source: rustfs_gateway_types::CopySourceValue::Bucket {
bucket: bucket.clone(),
key: "source".to_owned(),
version_id: None,
},
copy_source_range: None,
copy_source_if_match: None,
copy_source_if_none_match: None,
sse_customer_algorithm: None,
sse_customer_key: None,
sse_customer_key_md5: None,
copy_source_sse_customer_algorithm: None,
copy_source_sse_customer_key: None,
copy_source_sse_customer_key_md5: None,
},
)
.await .await
.expect_err("denied destination copy"); .err()
assert_eq!(error.code(), &S3ErrorCode::AccessDenied); .expect("denied destination copy");
assert_eq!(error.code(), &rustfs_s3_types::S3ErrorCode::AccessDenied);
let complete = CompleteMultipartUploadInput::builder() let complete = CompleteMultipartUploadInput::builder()
.bucket(bucket.clone()) .bucket(bucket.clone())
.key(key.to_string()) .key(key.to_string())
@@ -810,10 +847,9 @@ mod tests {
requested_kms_key_id: Option<&str>, requested_kms_key_id: Option<&str>,
customer_key: Option<(&str, &str)>, customer_key: Option<(&str, &str)>,
) -> (Vec<(&'static str, SseResponseFields)>, Vec<String>) { ) -> (Vec<(&'static str, SseResponseFields)>, Vec<String>) {
use crate::app::storage_api::s3::dto::{CompletedPart, CopySource, StreamingBlob, UploadPartInput}; use crate::app::storage_api::s3::dto::{CopySource, StreamingBlob, UploadPartInput};
use crate::app::storage_api::test::contract::object::ObjectIO as _; use crate::app::storage_api::test::contract::object::ObjectIO as _;
use rustfs_gateway::{Limits, MetaView, OperationCodec, TargetKind, WireRequest}; use rustfs_gateway::{Limits, MetaView, OperationCodec, TargetKind, WireRequest};
use rustfs_gateway_types::compat::s3s_5761ddfe::generated::ops::complete_multipart_upload;
let store = crate::app::gating_test_env::shared_gating_ecstore().await; let store = crate::app::gating_test_env::shared_gating_ecstore().await;
let usecase = DefaultMultipartUsecase::from_global(); let usecase = DefaultMultipartUsecase::from_global();
@@ -905,27 +941,10 @@ mod tests {
.await .await
.expect("copy part"); .expect("copy part");
let mut complete_input = complete_multipart_upload::input_from_s3s(CompleteMultipartUploadInput { let mut complete_input = completion_input(bucket, key, &upload_id, vec![completion_part(1, part.e_tag.as_deref())]);
bucket: bucket.to_string(), complete_input.sse_customer_algorithm = customer_algorithm;
key: key.to_string(), complete_input.sse_customer_key = customer_key.map(rustfs_gateway_types::SseCustomerKey::new);
upload_id, complete_input.sse_customer_key_md5 = customer_key_md5;
multipart_upload: Some(CompletedMultipartUpload {
parts: Some(vec![CompletedPart {
part_number: Some(1),
..Default::default()
}]),
}),
sse_customer_algorithm: customer_algorithm,
sse_customer_key: customer_key,
sse_customer_key_md5: customer_key_md5,
..Default::default()
})
.map_err(crate::app::dto_values::seam_error)
.expect("owned completion input");
complete_input.multipart_upload.parts[0].e_tag = part
.e_tag
.as_deref()
.map(|tag| rustfs_gateway_types::ETag::from_stored(to_s3s_etag(tag).value().to_owned()));
let complete = Box::pin(usecase.execute_complete_multipart_upload(owned_envelope(Method::POST), complete_input)) let complete = Box::pin(usecase.execute_complete_multipart_upload(owned_envelope(Method::POST), complete_input))
.await .await
.expect("complete multipart upload"); .expect("complete multipart upload");
File diff suppressed because it is too large Load Diff
@@ -378,8 +378,7 @@ impl DefaultMultipartUsecase {
content_size: actual_size, content_size: actual_size,
principal: None, 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 (requested_sse, requested_kms_key_id) = if has_ssec {
let ssec_material = sse_decryption(DecryptionRequest { let ssec_material = sse_decryption(DecryptionRequest {
@@ -544,36 +543,13 @@ impl UploadPartWriteInput {
#[cfg(test)] #[cfg(test)]
impl DefaultMultipartUsecase { impl DefaultMultipartUsecase {
pub async fn execute_upload_part( pub(crate) async fn execute_upload_part(
&self, &self,
req: crate::app::storage_api::s3::S3Request<crate::app::storage_api::s3::dto::UploadPartInput>, req: crate::app::storage_api::s3::S3Request<crate::app::storage_api::s3::dto::UploadPartInput>,
) -> crate::app::storage_api::s3::S3Result< ) -> crate::app::storage_api::s3::S3Result<UploadPartWriteOutput> {
crate::app::storage_api::s3::S3Response<crate::app::storage_api::s3::dto::UploadPartOutput>,
> {
use crate::app::storage_api::s3::{
S3Response,
dto::{ServerSideEncryption, UploadPartOutput},
};
let envelope = RequestEnvelope::from_s3s(&req); let envelope = RequestEnvelope::from_s3s(&req);
let input = UploadPartWriteInput::from_legacy(req.input, req.trailing_headers); let input = UploadPartWriteInput::from_legacy(req.input, req.trailing_headers);
let output = self.execute_upload_part_with_audit(envelope, input).await?; self.execute_upload_part_with_audit(envelope, input).await.map_err(Into::into)
let mut response = S3Response::new(UploadPartOutput {
e_tag: output
.e_tag
.map(|tag| crate::app::storage_api::test::object_utils::to_s3s_etag(&tag)),
checksum_crc32: output.checksum_crc32,
checksum_crc32c: output.checksum_crc32c,
checksum_crc64nvme: output.checksum_crc64nvme,
checksum_sha1: output.checksum_sha1,
checksum_sha256: output.checksum_sha256,
server_side_encryption: output.server_side_encryption.map(ServerSideEncryption::from),
ssekms_key_id: output.ssekms_key_id,
sse_customer_algorithm: output.sse_customer_algorithm,
sse_customer_key_md5: output.sse_customer_key_md5,
..Default::default()
});
response.headers = output.headers;
Ok(response)
} }
} }
@@ -878,7 +854,8 @@ mod tests {
let error = usecase let error = usecase
.execute_upload_part(request) .execute_upload_part(request)
.await .await
.expect_err("unknown or negative logical size"); .err()
.expect("unknown or negative logical size");
assert_eq!( assert_eq!(
error.code(), error.code(),
&if capped || content_length.is_some() { &if capped || content_length.is_some() {
@@ -944,7 +921,8 @@ mod tests {
)); ));
control.advance_wait_for_test(Duration::from_secs(60)); control.advance_wait_for_test(Duration::from_secs(60));
sender.send(Ok(Frame::data(Bytes::from_static(b"x")))).unwrap(); sender.send(Ok(Frame::data(Bytes::from_static(b"x")))).unwrap();
assert_eq!(owner.await.unwrap().unwrap_err().code(), &LegacyErrorCode::RequestTimeout); let error = owner.await.unwrap().err().expect("stalled part must fail");
assert_eq!(error.code(), &LegacyErrorCode::RequestTimeout);
assert!(matches!( assert!(matches!(
manager.admit_put_object(65536).await.unwrap(), manager.admit_put_object(65536).await.unwrap(),
ForegroundWriteAdmission::Admitted(_) ForegroundWriteAdmission::Admitted(_)
@@ -195,7 +195,8 @@ async fn assert_body_timeout_storage_lifecycle(part_size: usize, partial_size: u
let error = tokio::time::timeout(Duration::from_secs(10), upload_future) let error = tokio::time::timeout(Duration::from_secs(10), upload_future)
.await .await
.expect("inline cleanup must complete") .expect("inline cleanup must complete")
.expect_err("stalled part"); .err()
.expect("stalled part");
assert_eq!( assert_eq!(
error.code(), error.code(),
&S3ErrorCode::RequestTimeout, &S3ErrorCode::RequestTimeout,
@@ -225,7 +226,7 @@ async fn assert_body_timeout_storage_lifecycle(part_size: usize, partial_size: u
.await .await
.expect("foreground and capped staging permits must be released") .expect("foreground and capped staging permits must be released")
.expect("same-number retry"); .expect("same-number retry");
old_etag = retry.output.e_tag.map(|etag| etag.value().to_owned()); old_etag = retry.e_tag;
} }
let parts = store let parts = store
.list_object_parts(&bucket, "object", &upload.upload_id, None, 1000, &ObjectOptions::default()) .list_object_parts(&bucket, "object", &upload.upload_id, None, 1000, &ObjectOptions::default())
@@ -352,10 +353,11 @@ fn presigned_part_checksum_survives_completion_and_rejects_bad_retry() {
let result = usecase.execute_upload_part(req).await; let result = usecase.execute_upload_part(req).await;
if payload == b"abc" { if payload == b"abc" {
let response = result.expect("hoisted SHA256 part must be accepted"); let response = result.expect("hoisted SHA256 part must be accepted");
assert_eq!(response.output.checksum_sha256.as_deref(), Some(checksum)); assert_eq!(response.checksum_sha256.as_deref(), Some(checksum));
etag = response.output.e_tag.map(|etag| etag.value().to_owned()); etag = response.e_tag;
} else { } else {
assert_eq!(*result.unwrap_err().code(), S3ErrorCode::BadDigest); let error = result.err().expect("bad checksum must fail");
assert_eq!(*error.code(), S3ErrorCode::BadDigest);
} }
} }
store store
@@ -16,12 +16,6 @@
//! Gateway and protocol clients supply request facts. Storage owns the multipart upload. //! Gateway and protocol clients supply request facts. Storage owns the multipart upload.
use super::*; use super::*;
#[cfg(test)]
use crate::app::storage_api::s3::dto::{
CopyPartResult, CopySource, ETag, ServerSideEncryption, Timestamp, UploadPartCopyInput, UploadPartCopyOutput,
};
#[cfg(test)]
use crate::app::storage_api::s3::{S3Request, S3Response};
use crate::app::{RequestEnvelope, object_usecase::CopySourceCondition}; use crate::app::{RequestEnvelope, object_usecase::CopySourceCondition};
use rustfs_gateway_types::CopySourceValue; use rustfs_gateway_types::CopySourceValue;
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result, s3_error}; use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result, s3_error};
@@ -100,57 +94,6 @@ fn validate_copy_source_range_not_exceeds(range_spec: &HTTPRangeSpec, object_siz
} }
impl DefaultMultipartUsecase { impl DefaultMultipartUsecase {
#[cfg(test)]
pub async fn execute_upload_part_copy(
&self,
req: S3Request<UploadPartCopyInput>,
) -> crate::app::storage_api::s3::S3Result<S3Response<UploadPartCopyOutput>> {
let envelope = RequestEnvelope::from_s3s(&req);
let input = req.input;
let condition = |value| match value {
crate::app::storage_api::s3::dto::ETagCondition::Any => CopySourceCondition::Any,
crate::app::storage_api::s3::dto::ETagCondition::ETag(ETag::Strong(value)) => CopySourceCondition::Strong(value),
crate::app::storage_api::s3::dto::ETagCondition::ETag(ETag::Weak(_)) => CopySourceCondition::Weak,
};
let input = UploadPartCopyWriteInput {
target: UploadPartTarget::Legacy {
bucket: input.bucket,
key: input.key,
upload_id: input.upload_id,
},
part_number: input.part_number,
copy_source: rustfs_gateway_types::compat::s3s_5761ddfe::copy_source::from_s3s(input.copy_source),
copy_source_range: input.copy_source_range,
copy_source_if_match: input.copy_source_if_match.map(condition),
copy_source_if_none_match: input.copy_source_if_none_match.map(condition),
sse_customer_algorithm: input.sse_customer_algorithm,
sse_customer_key: input.sse_customer_key,
sse_customer_key_md5: input.sse_customer_key_md5,
copy_source_sse_customer_algorithm: input.copy_source_sse_customer_algorithm,
copy_source_sse_customer_key: input.copy_source_sse_customer_key,
copy_source_sse_customer_key_md5: input.copy_source_sse_customer_key_md5,
};
let output = self.execute_upload_part_copy_with_audit(envelope, input).await?;
Ok(S3Response::new(UploadPartCopyOutput {
copy_part_result: Some(CopyPartResult {
e_tag: output.e_tag.as_deref().map(to_s3s_xml_etag),
last_modified: output.last_modified.map(Timestamp::from),
checksum_crc32: output.checksum_crc32,
checksum_crc32c: output.checksum_crc32c,
checksum_sha1: output.checksum_sha1,
checksum_sha256: output.checksum_sha256,
checksum_crc64nvme: output.checksum_crc64nvme,
..Default::default()
}),
copy_source_version_id: output.copy_source_version_id,
server_side_encryption: output.server_side_encryption.map(ServerSideEncryption::from),
ssekms_key_id: output.ssekms_key_id,
sse_customer_algorithm: output.sse_customer_algorithm,
sse_customer_key_md5: output.sse_customer_key_md5,
..Default::default()
}))
}
/// Copies plaintext into an existing upload without changing its recorded owner. /// Copies plaintext into an existing upload without changing its recorded owner.
/// Records the gateway audit. The protocol client records its own projected response. /// Records the gateway audit. The protocol client records its own projected response.
pub(crate) async fn execute_upload_part_copy_with_audit( pub(crate) async fn execute_upload_part_copy_with_audit(
@@ -313,8 +256,7 @@ impl DefaultMultipartUsecase {
content_size: 0, content_size: 0,
principal: None, 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_versioned = BucketVersioningSys::prefix_enabled(&src_bucket, &src_key).await;
let src_version_suspended = BucketVersioningSys::prefix_suspended(&src_bucket, &src_key).await; let src_version_suspended = BucketVersioningSys::prefix_suspended(&src_bucket, &src_key).await;
@@ -561,7 +503,7 @@ mod tests {
use super::*; use super::*;
use crate::app::multipart_usecase::UploadPartTarget; use crate::app::multipart_usecase::UploadPartTarget;
use crate::app::object_usecase::CopySourceCondition; use crate::app::object_usecase::CopySourceCondition;
use crate::app::storage_api::s3::dto::ETag; use crate::app::storage_api::s3::dto::{CopySource, ETag, UploadPartCopyInput};
#[tokio::test] #[tokio::test]
async fn execute_upload_part_copy_returns_internal_error_when_store_uninitialized() { async fn execute_upload_part_copy_returns_internal_error_when_store_uninitialized() {
@@ -148,12 +148,7 @@ fn upload_part_copy_shares_foreground_admission_with_upload_part() {
Some(0), Some(0),
"success releases the copy permit" "success releases the copy permit"
); );
let etag = copied let etag = copied.e_tag.expect("copy ETag");
.e_tag
.as_deref()
.map(crate::storage::storage_api::to_s3s_xml_etag)
.expect("copy ETag");
let etag = etag.value().trim_matches('"').to_owned();
Arc::clone(&store) Arc::clone(&store)
.complete_multipart_upload( .complete_multipart_upload(
&bucket, &bucket,
@@ -412,12 +407,7 @@ fn upload_part_copy_range_error_and_cancellation_release_foreground_permit() {
Ok(output) => output, Ok(output) => output,
Err(error) => panic!("range copy after failed request released its source and permit: {error:?}"), Err(error) => panic!("range copy after failed request released its source and permit: {error:?}"),
}; };
let etag = copied let etag = copied.e_tag.expect("range ETag");
.e_tag
.as_deref()
.map(crate::storage::storage_api::to_s3s_xml_etag)
.expect("range ETag");
let etag = etag.value().trim_matches('"').to_owned();
Arc::clone(&store) Arc::clone(&store)
.complete_multipart_upload( .complete_multipart_upload(
&bucket, &bucket,
+40 -19
View File
@@ -17,14 +17,43 @@
//! configuration must be set before either process initializes the store. //! configuration must be set before either process initializes the store.
use super::*; use super::*;
use crate::app::storage_api::s3::S3ErrorCode;
use crate::app::storage_api::s3::dto::GetObjectInput;
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions}; use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, MakeBucketOptions};
use futures::stream; use futures::stream;
use http::{HeaderValue, Method}; use http::{HeaderMap, HeaderValue, StatusCode};
use metrics_util::debugging::{DebugValue, DebuggingRecorder}; use metrics_util::debugging::{DebugValue, DebuggingRecorder};
use std::time::Instant; use std::time::Instant;
// The baseline installer replaces only this module to call that revision's GET API.
mod get_api {
use super::*;
use crate::app::test_seams::{get_envelope, get_object_gateway, get_object_input};
use rustfs_gateway_stream::PayloadRead;
use std::future::poll_fn;
pub(super) async fn get(
usecase: &DefaultObjectUsecase,
object: &str,
headers: HeaderMap,
) -> rustfs_s3_types::S3Result<crate::app::Answered<GetObjectOutputFacts>> {
let input = get_object_input("conditional-bench", object, None);
let envelope = get_envelope(headers, http::Extensions::new());
get_object_gateway(usecase, envelope, input).await
}
pub(super) async fn consume(body: GetObjectBody, actual: &mut Vec<u8>) {
match body {
GetObjectBody::Bytes(bytes) => actual.extend_from_slice(&bytes),
GetObjectBody::Stream(mut body) => {
while let PayloadRead::Chunk(chunk) =
poll_fn(|cx| body.as_mut().poll_read(cx)).await.expect("benchmark body chunk")
{
actual.extend_from_slice(&chunk);
}
}
}
}
}
fn percentile(samples: &mut [f64], percent: usize) -> f64 { fn percentile(samples: &mut [f64], percent: usize) -> f64 {
assert!(!samples.is_empty(), "benchmark must collect samples"); assert!(!samples.is_empty(), "benchmark must collect samples");
samples.sort_by(f64::total_cmp); samples.sort_by(f64::total_cmp);
@@ -33,33 +62,25 @@ fn percentile(samples: &mut [f64], percent: usize) -> f64 {
async fn read_once(usecase: &DefaultObjectUsecase, object: &str, etag: &str, kind: &str, expected: &[u8]) -> f64 { async fn read_once(usecase: &DefaultObjectUsecase, object: &str, etag: &str, kind: &str, expected: &[u8]) -> f64 {
let start = Instant::now(); let start = Instant::now();
let mut req = build_request( let mut headers = HeaderMap::new();
GetObjectInput::builder()
.bucket("conditional-bench".to_owned())
.key(object.to_owned())
.build()
.expect("benchmark input"),
Method::GET,
);
if kind != "unconditional" { if kind != "unconditional" {
let tag = if kind == "hit" { etag } else { "unmatched-benchmark-etag" }; let tag = if kind == "hit" { etag } else { "unmatched-benchmark-etag" };
req.headers.insert( headers.insert(
http::header::IF_NONE_MATCH, http::header::IF_NONE_MATCH,
HeaderValue::from_str(&format!("\"{tag}\"")).expect("benchmark condition"), HeaderValue::from_str(&format!("\"{tag}\"")).expect("benchmark condition"),
); );
} }
match usecase.execute_get_object_from_s3s(req).await { match get_api::get(usecase, object, headers).await {
Err(error) => { Err(error) => {
assert_eq!(kind, "hit"); assert_eq!(kind, "hit");
assert_eq!(error.code(), &S3ErrorCode::NotModified); assert_eq!(error.code().as_str(), "NotModified");
assert_eq!(error.status_code(), Some(StatusCode::NOT_MODIFIED));
} }
Ok(mut response) => { Ok(response) => {
assert_ne!(kind, "hit"); assert_ne!(kind, "hit");
let mut body = response.output.body.take().expect("benchmark body"); assert_eq!(response.status.unwrap_or(StatusCode::OK), StatusCode::OK);
let mut actual = Vec::with_capacity(expected.len()); let mut actual = Vec::with_capacity(expected.len());
while let Some(chunk) = body.next().await { get_api::consume(response.output.body.expect("benchmark body"), &mut actual).await;
actual.extend_from_slice(&chunk.expect("benchmark body chunk"));
}
assert_eq!(actual, expected, "benchmark must consume and validate the whole body"); assert_eq!(actual, expected, "benchmark must consume and validate the whole body");
} }
} }
+40 -68
View File
@@ -935,23 +935,25 @@ impl DefaultObjectUsecase {
mod tests { mod tests {
use super::*; use super::*;
/// CopyObject through the owned entry point the gateway handler calls, its error in the s3s fn copy_input(bucket: &str, source: &str, destination: &str, source_version: Option<String>) -> CopyObjectWriteInput {
/// form these tests compare. CopyObjectWriteInput {
async fn copy_owned( bucket: bucket.to_owned(),
usecase: &DefaultObjectUsecase, key: destination.to_owned(),
req: S3Request<CopyObjectInput>, copy_source: Some(CopySourceValue::Bucket {
) -> crate::app::storage_api::s3::S3Result<crate::app::object_usecase::CopyObjectWriteOutput> { bucket: bucket.to_owned(),
let (envelope, input) = crate::app::object_usecase::CopyObjectWriteInput::from_test_request(req); key: source.to_owned(),
usecase.execute_copy_object_owned(envelope, input).await.map_err(Into::into) version_id: source_version,
}),
..Default::default()
}
} }
/// Method-only envelope. `build_request` leaves the URI as `/`, the headers empty, and the trailing headers absent. fn copy_envelope(headers: HeaderMap) -> crate::app::RequestEnvelope {
fn method_only_copy_envelope() -> crate::app::RequestEnvelope {
crate::app::RequestEnvelope::from_parts( crate::app::RequestEnvelope::from_parts(
crate::app::RequestHead { crate::app::RequestHead {
method: Method::PUT, method: Method::PUT,
uri: http::Uri::from_static("/"), uri: http::Uri::from_static("/"),
headers: HeaderMap::new(), headers,
credentials: None, credentials: None,
region: None, region: None,
service: None, service: None,
@@ -966,7 +968,7 @@ mod tests {
) -> crate::app::storage_api::s3::S3Result<crate::app::object_usecase::CopyObjectWriteOutput> { ) -> crate::app::storage_api::s3::S3Result<crate::app::object_usecase::CopyObjectWriteOutput> {
let input = crate::app::object_usecase::CopyObjectWriteInput::from_legacy(input); let input = crate::app::object_usecase::CopyObjectWriteInput::from_legacy(input);
usecase usecase
.execute_copy_object_owned(method_only_copy_envelope(), input) .execute_copy_object_owned(copy_envelope(HeaderMap::new()), input)
.await .await
.map_err(Into::into) .map_err(Into::into)
} }
@@ -1209,21 +1211,13 @@ mod tests {
.await .await
.expect("publish self-copy test policy"); .expect("publish self-copy test policy");
let input = CopyObjectInput::builder() let input = CopyObjectWriteInput {
.copy_source(CopySource::Bucket { metadata_directive: Some("REPLACE".to_owned()),
bucket: bucket.clone().into(), metadata: Some(HashMap::from([("lock-order".to_owned(), "verified".to_owned())])),
key: bucket.clone().into(), ..copy_input(&bucket, &bucket, &bucket, None)
version_id: None, };
}) let mut envelope = copy_envelope(HeaderMap::new());
.bucket(bucket.clone()) envelope.install_req_info(crate::storage::req_info::ReqInfo::default());
.key(bucket.clone())
.metadata_directive(Some(MetadataDirective::from_static(MetadataDirective::REPLACE)))
.metadata(Some(HashMap::from([("lock-order".to_string(), "verified".to_string())])))
.build()
.expect("self-copy input should build");
let mut req = build_request(input, Method::PUT);
req.extensions.insert(crate::storage::req_info::ReqInfo::default());
let (mut envelope, input) = CopyObjectWriteInput::from_test_request(req);
let facts = CopyObjectAuthorization { let facts = CopyObjectAuthorization {
bucket: &bucket, bucket: &bucket,
key: &bucket, key: &bucket,
@@ -1371,26 +1365,18 @@ mod tests {
let source_version_id = old.version_id.expect("historical source should have a version id"); let source_version_id = old.version_id.expect("historical source should have a version id");
let current_version_id = current.version_id.expect("current destination should have a version id"); let current_version_id = current.version_id.expect("current destination should have a version id");
let input = CopyObjectInput::builder() let input = copy_input(&bucket, object, object, Some(source_version_id.to_string()));
.copy_source(CopySource::Bucket { let mut headers = HeaderMap::new();
bucket: bucket.clone().into(), headers.insert(
key: object.to_string().into(),
version_id: Some(source_version_id.to_string().into()),
})
.bucket(bucket.clone())
.key(object.to_string())
.build()
.expect("expected-current historical copy input should build");
let mut req = build_request(input, Method::PUT);
req.headers.insert(
RUSTFS_EXPECTED_CURRENT_VERSION_ID, RUSTFS_EXPECTED_CURRENT_VERSION_ID,
HeaderValue::from_str(&current_version_id.to_string()).expect("current version header should be valid"), HeaderValue::from_str(&current_version_id.to_string()).expect("current version header should be valid"),
); );
let envelope = copy_envelope(headers);
let response = temp_env::async_with_vars( let response = temp_env::async_with_vars(
[(rustfs_config::ENV_OBJECT_LOCK_OPTIMIZATION_ENABLE, Some("false"))], [(rustfs_config::ENV_OBJECT_LOCK_OPTIMIZATION_ENABLE, Some("false"))],
tokio::time::timeout( tokio::time::timeout(
Duration::from_secs(10), Duration::from_secs(10),
copy_owned(&DefaultObjectUsecase::with_context(Some(context)), req), DefaultObjectUsecase::with_context(Some(context)).execute_copy_object_owned(envelope, input),
), ),
) )
.await .await
@@ -1536,20 +1522,14 @@ mod tests {
.await .await
.expect("plaintext copy source should be written"); .expect("plaintext copy source should be written");
let mut input = CopyObjectInput::builder() let input = CopyObjectWriteInput {
.copy_source(CopySource::Bucket { sse_customer_algorithm: Some("AES256".to_owned()),
bucket: bucket.clone().into(), sse_customer_key: Some("KioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKio=".to_owned()),
key: "source.bin".into(), sse_customer_key_md5: Some(customer_key_md5.to_owned()),
version_id: None, ..copy_input(&bucket, "source.bin", "customer-encrypted.bin", None)
}) };
.bucket(bucket.clone()) let response = DefaultObjectUsecase::with_context(Some(context))
.key("customer-encrypted.bin".to_string()) .execute_copy_object_owned(copy_envelope(HeaderMap::new()), input)
.build()
.expect("SSE-C copy input should build");
input.sse_customer_algorithm = Some("AES256".to_string());
input.sse_customer_key = Some("KioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKio=".to_string());
input.sse_customer_key_md5 = Some(customer_key_md5.to_string());
let response = copy_owned(&DefaultObjectUsecase::with_context(Some(context)), build_request(input, Method::PUT))
.await .await
.expect("copying to an SSE-C destination should succeed"); .expect("copying to an SSE-C destination should succeed");
@@ -1617,26 +1597,18 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn execute_copy_object_rejects_expected_version_for_different_destination() { async fn execute_copy_object_rejects_expected_version_for_different_destination() {
let input = CopyObjectInput::builder() let input = copy_input("test-bucket", "source-key", "destination-key", Some(Uuid::new_v4().to_string()));
.copy_source(CopySource::Bucket { let mut headers = HeaderMap::new();
bucket: "test-bucket".into(), headers.insert(
key: "source-key".into(),
version_id: Some(Uuid::new_v4().to_string().into()),
})
.bucket("test-bucket".to_string())
.key("destination-key".to_string())
.build()
.unwrap();
let mut req = build_request(input, Method::PUT);
req.headers.insert(
RUSTFS_EXPECTED_CURRENT_VERSION_ID, RUSTFS_EXPECTED_CURRENT_VERSION_ID,
HeaderValue::from_str(&Uuid::new_v4().to_string()).unwrap(), HeaderValue::from_str(&Uuid::new_v4().to_string()).unwrap(),
); );
let envelope = copy_envelope(headers);
let err = Box::pin(copy_owned(&DefaultObjectUsecase::without_context(), req)) let err = Box::pin(DefaultObjectUsecase::without_context().execute_copy_object_owned(envelope, input))
.await .await
.unwrap_err(); .unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::InvalidRequest); assert_eq!(err.code(), &rustfs_s3_types::S3ErrorCode::InvalidRequest);
} }
#[tokio::test] #[tokio::test]
-8
View File
@@ -147,12 +147,4 @@ impl CopyObjectWriteInput {
checksum_algorithm: input.checksum_algorithm.map(|value| value.as_str().to_owned()), checksum_algorithm: input.checksum_algorithm.map(|value| value.as_str().to_owned()),
} }
} }
/// A test's s3s fixture request as the envelope and input a gateway handler hands the use case.
pub(crate) fn from_test_request(
req: crate::app::storage_api::s3::S3Request<crate::app::storage_api::s3::dto::CopyObjectInput>,
) -> (crate::app::RequestEnvelope, Self) {
let envelope = crate::app::RequestEnvelope::from_s3s(&req);
(envelope, Self::from_legacy(req.input))
}
} }
+39 -67
View File
@@ -1862,8 +1862,9 @@ mod tests {
} }
use super::*; use super::*;
use crate::app::storage_api::s3::dto::GetObjectInput; use crate::app::test_seams::{
use crate::app::test_seams::{head_envelope, head_object_gateway, head_object_input}; get_envelope, get_object_gateway, get_object_input, head_envelope, head_object_gateway, head_object_input, read_get_body,
};
use http::{HeaderMap, HeaderValue, Method}; use http::{HeaderMap, HeaderValue, Method};
use rustfs_gateway_types::dto::Status; use rustfs_gateway_types::dto::Status;
use rustfs_gateway_types::persistence::{ use rustfs_gateway_types::persistence::{
@@ -2246,16 +2247,12 @@ mod tests {
for explicit in [false, true] { for explicit in [false, true] {
let requested_version = explicit.then(|| marker_id.clone()); let requested_version = explicit.then(|| marker_id.clone());
let get = GetObjectInput::builder() let get = get_object_input(&bucket, key, requested_version.clone());
.bucket(bucket.clone())
.key(key.to_string())
.version_id(requested_version.clone())
.build()
.expect("GET request");
let head = head_object_input(&bucket, key, requested_version); let head = head_object_input(&bucket, key, requested_version);
let get_error = crate::app::test_seams::get_object_method_only(&usecase, get) let get_error =
.await get_object_gateway(&usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), get)
.expect_err("marker GET"); .await
.expect_err("marker GET");
let head_error = let head_error =
head_object_gateway(&usecase, head_envelope(HeaderMap::new(), http::Extensions::new()), head) head_object_gateway(&usecase, head_envelope(HeaderMap::new(), http::Extensions::new()), head)
.await .await
@@ -2305,22 +2302,13 @@ mod tests {
} }
let original_id = original.version_id.expect("historical version id").to_string(); let original_id = original.version_id.expect("historical version id").to_string();
let get = GetObjectInput::builder() let get = get_object_input(&bucket, key, Some(original_id.clone()));
.bucket(bucket.clone()) let response = get_object_gateway(&usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), get)
.key(key.to_string())
.version_id(Some(original_id.clone()))
.build()
.expect("historical GET request");
let response = crate::app::test_seams::get_object_method_only(&usecase, get)
.await .await
.expect("historical GET"); .expect("historical GET");
assert!(!response.headers.contains_key("x-amz-delete-marker")); assert!(!response.headers.contains_key("x-amz-delete-marker"));
let mut body = response.output.body.expect("historical body"); let body = response.output.body.expect("historical body");
let mut actual = Vec::new(); assert_eq!(read_get_body(body).await.as_ref(), payload);
while let Some(chunk) = body.next().await {
actual.extend_from_slice(&chunk.expect("historical data remains readable"));
}
assert_eq!(actual, payload);
let head = head_object_input(&bucket, key, Some(original_id.clone())); let head = head_object_input(&bucket, key, Some(original_id.clone()));
let response = head_object_gateway(&usecase, head_envelope(HeaderMap::new(), http::Extensions::new()), head) let response = head_object_gateway(&usecase, head_envelope(HeaderMap::new(), http::Extensions::new()), head)
.await .await
@@ -2330,16 +2318,12 @@ mod tests {
assert!(!response.headers.contains_key("x-amz-delete-marker")); assert!(!response.headers.contains_key("x-amz-delete-marker"));
for (absent_key, version) in [("missing", None), (key, Some(Uuid::new_v4().to_string()))] { for (absent_key, version) in [("missing", None), (key, Some(Uuid::new_v4().to_string()))] {
let get = GetObjectInput::builder() let get = get_object_input(&bucket, absent_key, version.clone());
.bucket(bucket.clone())
.key(absent_key.to_string())
.version_id(version.clone())
.build()
.expect("missing GET request");
let head = head_object_input(&bucket, absent_key, version); let head = head_object_input(&bucket, absent_key, version);
let get_error = crate::app::test_seams::get_object_method_only(&usecase, get) let get_error =
.await get_object_gateway(&usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), get)
.expect_err("missing GET"); .await
.expect_err("missing GET");
let head_error = let head_error =
head_object_gateway(&usecase, head_envelope(HeaderMap::new(), http::Extensions::new()), head) head_object_gateway(&usecase, head_envelope(HeaderMap::new(), http::Extensions::new()), head)
.await .await
@@ -2425,16 +2409,12 @@ mod tests {
assert!(marker.delete_marker); assert!(marker.delete_marker);
let marker_id = delete_response_version_id(marker.version_id, false).expect("marker has a version identity"); let marker_id = delete_response_version_id(marker.version_id, false).expect("marker has a version identity");
assert_eq!(marker_id == "null", suspended); assert_eq!(marker_id == "null", suspended);
let get = GetObjectInput::builder() let get = get_object_input(&bucket, key, Some(marker_id.clone()));
.bucket(bucket.clone()) let get_err =
.key(key.to_string()) Box::pin(get_object_gateway(&usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), get))
.version_id(Some(marker_id.clone())) .await
.build() .expect_err("GET of a marker remains forbidden");
.unwrap(); assert_eq!(get_err.code(), &rustfs_s3_types::S3ErrorCode::MethodNotAllowed);
let get_err = Box::pin(crate::app::test_seams::get_object_method_only(&usecase, get))
.await
.expect_err("GET of a marker remains forbidden");
assert_eq!(get_err.code(), &S3ErrorCode::MethodNotAllowed);
let head = head_object_input(&bucket, key, Some(marker_id.clone())); let head = head_object_input(&bucket, key, Some(marker_id.clone()));
let head_err = Box::pin(head_object_gateway( let head_err = Box::pin(head_object_gateway(
&usecase, &usecase,
@@ -2502,34 +2482,26 @@ mod tests {
assert_eq!(remaining.version_id, original.version_id); assert_eq!(remaining.version_id, original.version_id);
assert!(!remaining.delete_marker); assert!(!remaining.delete_marker);
assert_eq!(remaining.size, payload.len() as i64); assert_eq!(remaining.size, payload.len() as i64);
let removed = GetObjectInput::builder() let removed = get_object_input(&bucket, key, Some(marker_id));
.bucket(bucket.clone()) let missing = Box::pin(get_object_gateway(
.key(key.to_string()) &usecase,
.version_id(Some(marker_id)) get_envelope(HeaderMap::new(), http::Extensions::new()),
.build() removed,
.unwrap(); ))
let missing = Box::pin(crate::app::test_seams::get_object_method_only(&usecase, removed)) .await
.await .expect_err("the marker version must actually be gone");
.expect_err("the marker version must actually be gone");
assert_eq!( assert_eq!(
missing.code(), missing.code(),
&S3ErrorCode::NoSuchVersion, &rustfs_s3_types::S3ErrorCode::NoSuchVersion,
"pool_count={pool_count} suspended={suspended} batch={batch}: removed marker lookup returned {missing:?}" "pool_count={pool_count} suspended={suspended} batch={batch}: removed marker lookup returned {missing:?}"
); );
let get = GetObjectInput::builder() let get = get_object_input(&bucket, key, None);
.bucket(bucket.clone()) let response =
.key(key.to_string()) Box::pin(get_object_gateway(&usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), get))
.build() .await
.unwrap(); .expect("GET restores the historical payload");
let response = Box::pin(crate::app::test_seams::get_object_method_only(&usecase, get)) let body = response.output.body.expect("GET body");
.await assert_eq!(read_get_body(body).await.as_ref(), payload);
.expect("GET restores the historical payload");
let mut body = response.output.body.expect("GET body");
let mut actual = Vec::new();
while let Some(chunk) = body.next().await {
actual.extend_from_slice(&chunk.expect("historical data remains readable"));
}
assert_eq!(actual, payload);
} }
} }
}); });
File diff suppressed because it is too large Load Diff
+18
View File
@@ -36,6 +36,24 @@ pub(crate) struct GetObjectFields {
pub(crate) sse_customer_key_md5: Option<String>, pub(crate) sse_customer_key_md5: Option<String>,
} }
impl From<dto::GetObjectInput> for GetObjectFields {
fn from(input: dto::GetObjectInput) -> Self {
use rustfs_gateway_types::RangeParse;
Self {
bucket: input.bucket.as_str().to_owned(),
key: input.key.as_str().to_owned(),
version_id: input.version_id,
part_number: input.part_number,
range: input.range.and_then(|range| match RangeParse::parse(range.as_str()) {
RangeParse::One(range) => Some(range),
_ => None,
}),
sse_customer_key: input.sse_customer_key.map(|key| key.expose_secret().to_owned()),
sse_customer_key_md5: input.sse_customer_key_md5,
}
}
}
impl GetObjectFields { impl GetObjectFields {
/// The conditional-read wire format permits a wildcard, a quoted tag, or a bare S3 tag. /// The conditional-read wire format permits a wildcard, a quoted tag, or a bare S3 tag.
pub(crate) fn valid_etag_condition(value: &[u8]) -> bool { pub(crate) fn valid_etag_condition(value: &[u8]) -> bool {
+96 -88
View File
@@ -18,7 +18,11 @@
use super::*; use super::*;
use crate::app::storage_api::s3::dto::Range; use crate::app::storage_api::s3::dto::Range;
use crate::app::storage_api::test::ReqInfo; use crate::app::storage_api::test::ReqInfo;
use crate::app::test_seams::{get_envelope, get_http_body, get_object_gateway, get_object_input};
use http::Method; use http::Method;
use http_body_util::BodyExt as _;
use rustfs_gateway_types::{BucketName, ObjectKey, RangeSpec, dto};
use rustfs_s3_types::S3ErrorCode;
#[test] #[test]
fn website_and_object_lambda_ranges_match_the_legacy_wire_reader() { fn website_and_object_lambda_ranges_match_the_legacy_wire_reader() {
@@ -80,16 +84,15 @@ fn website_and_object_lambda_conditions_match_the_legacy_wire_reader() {
} }
} }
fn get_request(input: GetObjectInput) -> S3Request<GetObjectInput> { fn get_envelope_with_info(input: &dto::GetObjectInput, headers: HeaderMap) -> crate::app::RequestEnvelope {
let info = ReqInfo { let mut extensions = http::Extensions::new();
bucket: Some(input.bucket.clone()), extensions.insert(ReqInfo {
object: Some(input.key.clone()), bucket: Some(input.bucket.as_str().to_owned()),
object: Some(input.key.as_str().to_owned()),
version_id: input.version_id.clone(), version_id: input.version_id.clone(),
..Default::default() ..Default::default()
}; });
let mut request = build_request(input, Method::GET); get_envelope(headers, extensions)
request.extensions.insert(info);
request
} }
async fn wire_get( async fn wire_get(
@@ -98,7 +101,6 @@ async fn wire_get(
headers: &[(&str, &str)], headers: &[(&str, &str)],
admitted: bool, admitted: bool,
) -> http::Response<Bytes> { ) -> http::Response<Bytes> {
use http_body_util::BodyExt as _;
use hyper_util::rt::TokioIo; use hyper_util::rt::TokioIo;
let before = operation_counts(); let before = operation_counts();
let socket = tokio::net::TcpStream::connect(server.address()).await.unwrap(); let socket = tokio::net::TcpStream::connect(server.address()).await.unwrap();
@@ -213,15 +215,13 @@ fn get_boundary(stack: Option<&str>) {
) )
.await .await
.unwrap(); .unwrap();
let request = get_request(GetObjectInput { let input = get_object_input(bucket, &key, None);
bucket: bucket.to_owned(), let response = get_object_gateway(&usecase, get_envelope_with_info(&input, HeaderMap::new()), input)
key: key.clone(), .await
..Default::default() .unwrap();
}); let tag = response.output.etag.expect("unencoded GET retains its ETag");
let response = crate::app::test_seams::get_object(&usecase, request).await.unwrap(); assert_eq!(tag.opaque, ["abc", "", "a\\b", "a\"b", "é", "a\rb", "a\nb", "a\0b"][index]);
let tag = response.output.e_tag.unwrap(); assert_eq!(tag.weak, index == 1);
assert_eq!(tag.value(), ["abc", "", "a\\b", "a\"b", "é", "a\rb", "a\nb", "a\0b"][index]);
assert_eq!(tag.as_weak().is_some(), index == 1);
assert_eq!(response.status, None); assert_eq!(response.status, None);
for (case, suffix, headers) in [ for (case, suffix, headers) in [
("ordinary", String::new(), vec![]), ("ordinary", String::new(), vec![]),
@@ -235,33 +235,28 @@ fn get_boundary(stack: Option<&str>) {
("range", String::new(), vec![("range", "bytes=1-3")]), ("range", String::new(), vec![("range", "bytes=1-3")]),
("unsatisfied", String::new(), vec![("range", "bytes=99-100")]), ("unsatisfied", String::new(), vec![("range", "bytes=99-100")]),
] { ] {
let range = match case { let mut input =
"range" => Some(Range::Int { first: 1, last: Some(3) }), get_object_input(bucket, &key, (case == "version304").then(|| info.version_id.unwrap().to_string()));
"unsatisfied" => Some(Range::Int { input.range = match case {
first: 99, "range" => Some(RangeSpec::new("bytes=1-3")),
last: Some(100), "unsatisfied" => Some(RangeSpec::new("bytes=99-100")),
}),
_ => None, _ => None,
}; };
let input = GetObjectInput { let mut request_headers = HeaderMap::new();
bucket: bucket.to_owned(),
key: key.clone(),
range,
version_id: (case == "version304").then(|| info.version_id.unwrap().to_string()),
..Default::default()
};
let mut request = get_request(input);
for (name, value) in &headers { for (name, value) in &headers {
request.headers.insert( request_headers.insert(
http::header::HeaderName::from_bytes(name.as_bytes()).unwrap(), http::header::HeaderName::from_bytes(name.as_bytes()).unwrap(),
HeaderValue::from_str(value).unwrap(), HeaderValue::from_str(value).unwrap(),
); );
} }
match crate::app::test_seams::get_object(&usecase, request).await { match get_object_gateway(&usecase, get_envelope_with_info(&input, request_headers), input).await {
Ok(response) => { Ok(response) => {
assert!(matches!(case, "ordinary" | "range")); assert!(matches!(case, "ordinary" | "range"));
assert_eq!(response.status, None); assert_eq!(response.status, None);
assert_eq!(response.output.content_range.as_deref(), (case == "range").then_some("bytes 1-3/7")); assert_eq!(
response.output.dto.content_range.as_deref(),
(case == "range").then_some("bytes 1-3/7")
);
} }
Err(error) => { Err(error) => {
let expected = match case { let expected = match case {
@@ -356,16 +351,22 @@ fn get_boundary(stack: Option<&str>) {
for (key, part, range) in [ for (key, part, range) in [
("", Some(0), None), ("", Some(0), None),
("object-0", Some(0), None), ("object-0", Some(0), None),
("object-0", Some(1), Some(Range::Int { first: 0, last: Some(1) })), ("object-0", Some(1), Some(RangeSpec::new("bytes=0-1"))),
] { ] {
let input = GetObjectInput { let input = dto::GetObjectInput {
bucket: "missing-boundary-bucket".to_owned(), bucket: BucketName::new("missing-boundary-bucket").unwrap(),
key: key.to_owned(), // The DTO's missing-key placeholder exercises validation before the invalid part number.
key: if key.is_empty() {
ObjectKey::default()
} else {
ObjectKey::new(key).unwrap()
},
part_number: part, part_number: part,
range, range,
..Default::default() ..Default::default()
}; };
let Err(error) = crate::app::test_seams::get_object(&usecase, get_request(input)).await else { let Err(error) = get_object_gateway(&usecase, get_envelope_with_info(&input, HeaderMap::new()), input).await
else {
panic!("invalid input must fail") panic!("invalid input must fail")
}; };
assert_eq!(error.code(), &S3ErrorCode::InvalidArgument); assert_eq!(error.code(), &S3ErrorCode::InvalidArgument);
@@ -432,16 +433,14 @@ fn get_boundary(stack: Option<&str>) {
) )
.await .await
.unwrap(); .unwrap();
let typed = crate::app::test_seams::get_object( let input = dto::GetObjectInput {
&usecase, bucket: crate::app::dto_values::stored_bucket_name(reserved).unwrap(),
get_request(GetObjectInput { key: ObjectKey::new("object").unwrap(),
bucket: reserved.to_owned(), ..Default::default()
key: "object".to_owned(), };
..Default::default() let typed = get_object_gateway(&usecase, get_envelope_with_info(&input, HeaderMap::new()), input)
}), .await
) .unwrap();
.await
.unwrap();
let wire = wire_get(&server, &format!("/{reserved}/object"), &[], true).await; let wire = wire_get(&server, &format!("/{reserved}/object"), &[], true).await;
assert_eq!(typed.status, None); assert_eq!(typed.status, None);
assert_eq!(wire.status(), StatusCode::OK); assert_eq!(wire.status(), StatusCode::OK);
@@ -524,7 +523,7 @@ async fn signed_override_contract(server: &crate::embedded::RustFSServer, bucket
} }
async fn ssec_wire_contract(usecase: &DefaultObjectUsecase, server: &crate::embedded::RustFSServer, bucket: &str) { async fn ssec_wire_contract(usecase: &DefaultObjectUsecase, server: &crate::embedded::RustFSServer, bucket: &str) {
use crate::app::storage_api::s3::dto::PutObjectInput; use crate::app::object_usecase::PutObjectWriteInput;
use md5::{Digest as _, Md5}; use md5::{Digest as _, Md5};
let key = [0x2a_u8; 32]; let key = [0x2a_u8; 32];
let encoded = base64_simd::STANDARD.encode_to_string(key); let encoded = base64_simd::STANDARD.encode_to_string(key);
@@ -532,33 +531,28 @@ async fn ssec_wire_contract(usecase: &DefaultObjectUsecase, server: &crate::embe
let wrong = [0x2b_u8; 32]; let wrong = [0x2b_u8; 32];
let wrong_encoded = base64_simd::STANDARD.encode_to_string(wrong); let wrong_encoded = base64_simd::STANDARD.encode_to_string(wrong);
let wrong_digest = base64_simd::STANDARD.encode_to_string(Md5::digest(wrong)); let wrong_digest = base64_simd::STANDARD.encode_to_string(Md5::digest(wrong));
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket(bucket.to_owned()) bucket: bucket.to_owned(),
.key("encrypted".to_owned()) key: "encrypted".to_owned(),
.body(Some(StreamingBlob::from_bytes(Bytes::from_static(b"protected payload")))) body: Some(rustfs_gateway_stream::Body::from_bytes(Bytes::from_static(b"protected payload"))),
.content_length(Some(17)) content_length: Some(17),
.sse_customer_algorithm(Some("AES256".to_owned())) sse_customer_algorithm: Some("AES256".to_owned()),
.sse_customer_key(Some(encoded.clone())) sse_customer_key: Some(encoded.clone()),
.sse_customer_key_md5(Some(digest.clone())) sse_customer_key_md5: Some(digest.clone()),
.build() ..Default::default()
.unwrap(); };
{ let envelope = crate::app::RequestEnvelope::from_parts(
let envelope = crate::app::RequestEnvelope::from_parts( crate::app::RequestHead {
crate::app::RequestHead { method: Method::PUT,
method: Method::PUT, uri: http::Uri::from_static("/"),
uri: http::Uri::from_static("/"), headers: http::HeaderMap::new(),
headers: http::HeaderMap::new(), credentials: None,
credentials: None, region: None,
region: None, service: None,
service: None, },
}, http::Extensions::new(),
http::Extensions::new(), );
); crate::app::test_seams::put_object(usecase, envelope, input).await.unwrap();
let input = crate::app::object_usecase::PutObjectWriteInput::from_legacy(input, None);
crate::app::test_seams::put_object(usecase, envelope, input)
}
.await
.unwrap();
for (case, valid, wrong_key, condition, range) in [ for (case, valid, wrong_key, condition, range) in [
("ordinary", true, false, false, false), ("ordinary", true, false, false, false),
("missing", false, false, false, false), ("missing", false, false, false, false),
@@ -657,7 +651,7 @@ async fn get_reader_handoff_preserves_baseline_copy_count() {
remaining: length, remaining: length,
writes: Arc::clone(&writes), writes: Arc::clone(&writes),
}; };
let mut body = DefaultObjectUsecase::build_reader_blob( let blob = DefaultObjectUsecase::build_reader_blob(
reader, reader,
length as i64, length as i64,
"copy-probe", "copy-probe",
@@ -670,13 +664,17 @@ async fn get_reader_handoff_preserves_baseline_copy_count() {
None, None,
) )
.await .await
.unwrap() .unwrap();
.into_s3s(); let mut body = get_http_body(blob);
assert_eq!(http_body::Body::size_hint(&body).exact(), Some(length as u64));
let mut chunks = Vec::new(); let mut chunks = Vec::new();
let mut observed_writes = 0; let mut observed_writes = 0;
let mut retained = 0; let mut retained = 0;
while let Some(chunk) = body.next().await { while let Some(frame) = body.frame().await {
let chunk = chunk.unwrap(); let chunk = frame
.expect("reader body must succeed")
.into_data()
.expect("unexpected reader trailers");
let begin = chunk.as_ptr() as usize; let begin = chunk.as_ptr() as usize;
let end = begin + chunk.len(); let end = begin + chunk.len();
let writes = writes.lock().unwrap(); let writes = writes.lock().unwrap();
@@ -694,6 +692,8 @@ async fn get_reader_handoff_preserves_baseline_copy_count() {
observed_writes = writes.len(); observed_writes = writes.len();
chunks.push(chunk); chunks.push(chunk);
} }
assert!(body.frame().await.is_none(), "EOF must be terminal");
assert_eq!(http_body::Body::size_hint(&body).exact(), Some(0));
let writes = writes.lock().unwrap(); let writes = writes.lock().unwrap();
let total: usize = chunks.iter().map(Bytes::len).sum(); let total: usize = chunks.iter().map(Bytes::len).sum();
assert_eq!(total, length); assert_eq!(total, length);
@@ -713,19 +713,27 @@ async fn get_memory_handoff_retains_the_original_allocation() {
for once in ["false", "true"] { for once in ["false", "true"] {
let bytes = Bytes::from(vec![b'm'; 8193]); let bytes = Bytes::from(vec![b'm'; 8193]);
let address = bytes.as_ptr() as usize; let address = bytes.as_ptr() as usize;
let mut body = temp_env::with_var(ENV_RUSTFS_GET_SMALL_BODY_ONCE_ENABLE, Some(once), || { let blob = temp_env::with_var(ENV_RUSTFS_GET_SMALL_BODY_ONCE_ENABLE, Some(once), || {
DefaultObjectUsecase::build_memory_bytes_blob( DefaultObjectUsecase::build_memory_bytes_blob(
bytes.clone(), bytes.clone(),
bytes.len() as i64, bytes.len() as i64,
GET_MEMORY_BODY_SOURCE_BUFFERED_BODY, GET_MEMORY_BODY_SOURCE_BUFFERED_BODY,
GetObjectBodyLifecycle::disabled(), GetObjectBodyLifecycle::disabled(),
) )
}) });
.into_s3s(); let mut body = get_http_body(blob);
assert_eq!(http_body::Body::size_hint(&body).exact(), Some(bytes.len() as u64));
let mut chunks = Vec::new(); let mut chunks = Vec::new();
while let Some(chunk) = body.next().await { while let Some(frame) = body.frame().await {
chunks.push(chunk.unwrap()); chunks.push(
frame
.expect("memory body must succeed")
.into_data()
.expect("unexpected memory trailers"),
);
} }
assert!(body.frame().await.is_none(), "EOF must be terminal");
assert_eq!(http_body::Body::size_hint(&body).exact(), Some(0));
let retained: usize = chunks let retained: usize = chunks
.iter() .iter()
.map(|chunk| { .map(|chunk| {
+3 -3
View File
@@ -18,12 +18,12 @@ use super::veeam_sosapi;
use super::*; use super::*;
use crate::app::dto_values::{stored_etag, timestamp}; use crate::app::dto_values::{stored_etag, timestamp};
use crate::app::storage_api::s3::header::X_AMZ_RESTORE;
use crate::app::{Answered, RequestEnvelope}; use crate::app::{Answered, RequestEnvelope};
use rustfs_gateway_types::ByteRange; use rustfs_gateway_types::ByteRange;
use rustfs_gateway_types::RangeParse; use rustfs_gateway_types::RangeParse;
use rustfs_gateway_types::dto as gateway_dto; use rustfs_gateway_types::dto as gateway_dto;
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result, s3_error}; use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result, s3_error};
use rustfs_utils::http::headers::AMZ_RESTORE;
use crate::on_demand_migration::{ use crate::on_demand_migration::{
BucketOdmState, HeadPolicy, OdmLookup, OdmOp, OdmOutcome, OnDemandMigrationSys, SourceClient, SourceError, SourceHead, BucketOdmState, HeadPolicy, OdmLookup, OdmOp, OdmOutcome, OnDemandMigrationSys, SourceClient, SourceError, SourceHead,
@@ -809,12 +809,12 @@ impl DefaultObjectUsecase {
response.headers.insert(header_name, header_value); response.headers.insert(header_name, header_value);
} }
if let Some(amz_restore) = metadata_map.get(X_AMZ_RESTORE.as_str()) { if let Some(amz_restore) = metadata_map.get(AMZ_RESTORE) {
let Ok(restore_status) = parse_restore_obj_status(amz_restore) else { let Ok(restore_status) = parse_restore_obj_status(amz_restore) else {
return Err(S3Error::with_message(S3ErrorCode::Custom("ErrMeta".into()), "parse amz_restore failed.")); return Err(S3Error::with_message(S3ErrorCode::Custom("ErrMeta".into()), "parse amz_restore failed."));
}; };
if let Ok(header_value) = HeaderValue::from_str(restore_status.to_string2().as_str()) { if let Ok(header_value) = HeaderValue::from_str(restore_status.to_string2().as_str()) {
response.headers.insert(X_AMZ_RESTORE, header_value); response.headers.insert(AMZ_RESTORE, header_value);
} }
} }
if let Some(amz_restore_request_date) = metadata_map.get(AMZ_RESTORE_REQUEST_DATE) if let Some(amz_restore_request_date) = metadata_map.get(AMZ_RESTORE_REQUEST_DATE)
+57 -49
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//! Regression tests for the HeadObject response facts and their HTTP and legacy projections. //! Regression tests for the HeadObject response facts and their HTTP projection.
//! The existing completion probe exposes the AuditEntry before asynchronous delivery. //! The existing completion probe exposes the AuditEntry before asynchronous delivery.
use super::*; use super::*;
@@ -20,60 +20,68 @@ use crate::app::test_seams::{head_envelope, head_object_input};
use http::Method; use http::Method;
#[test] #[test]
fn head_stored_etag_facts_and_legacy_projection_preserve_spelling() { fn head_stored_etag_facts_and_http_projection_preserve_spelling() {
head_stored_etag_facts_preserve_spelling(); head_stored_etag_facts_preserve_spelling();
head_legacy_etag_projection_preserves_spelling(); head_etag_http_projection_preserves_spelling();
} }
#[test] #[test]
fn head_stored_etag_facts_preserve_spelling() { fn head_stored_etag_facts_preserve_spelling() {
for raw in [ for (raw, opaque, weak) in [
"abc", ("abc", "abc", false),
"\"abc\"", ("\"abc\"", "abc", false),
"W/\"abc\"", ("W/\"abc\"", "abc", true),
"W/\"\"", ("W/\"\"", "", true),
"\"\"", ("\"\"", "", false),
"", ("", "", false),
"*", ("*", "*", false),
" abc ", (" abc ", " abc ", false),
"abc_def", ("abc_def", "abc_def", false),
"a&b", ("a&b", "a&b", false),
"\"a&b\"", ("\"a&b\"", "a&b", false),
"\"a b\"", ("\"a b\"", "a b", false),
"\"a\\b\"", ("\"a\\b\"", "a\\b", false),
"\"a\"b\"", ("\"a\"b\"", "a\"b", false),
"w/\"abc\"", ("w/\"abc\"", "w/\"abc\"", false),
"\"abc", ("\"abc", "\"abc", false),
"W/abc", ("W/abc", "W/abc", false),
"a\rb", ("a\rb", "a\rb", false),
"a\nb", ("a\nb", "a\nb", false),
"a\0b", ("a\0b", "a\0b", false),
"é", ("é", "é", false),
("6af8d12c0c74b78094884349f3c8a079", "6af8d12c0c74b78094884349f3c8a079", false),
("\"6af8d12c0c74b78094884349f3c8a079\"", "6af8d12c0c74b78094884349f3c8a079", false),
("W/\"6af8d12c0c74b78094884349f3c8a079\"", "6af8d12c0c74b78094884349f3c8a079", true),
("\"incomplete", "\"incomplete", false),
("incomplete\"", "incomplete\"", false),
("W/\"incomplete", "incomplete", true),
] { ] {
let expected = to_s3s_etag(raw);
let fact = ResponseEtag::from_stored(raw); let fact = ResponseEtag::from_stored(raw);
assert_eq!(fact.opaque, expected.value(), "{raw:?}"); assert_eq!(fact.opaque, opaque, "{raw:?}");
assert_eq!(fact.weak, expected.as_weak().is_some(), "{raw:?}"); assert_eq!(fact.weak, weak, "{raw:?}");
} }
} }
#[test] #[test]
fn head_legacy_etag_projection_preserves_spelling() { fn head_etag_http_projection_preserves_spelling() {
for weak in [false, true] { for (opaque, strong, weak) in [
for opaque in ["", "abc", "a\\b", "a\"b", "a\rb", "é"] { ("", Some(&b"\"\""[..]), Some(&b"W/\"\""[..])),
("abc", Some(&b"\"abc\""[..]), Some(&b"W/\"abc\""[..])),
("a\\b", Some(&b"\"a\\b\""[..]), Some(&b"W/\"a\\b\""[..])),
("a\"b", Some(&b"\"a\"b\""[..]), Some(&b"W/\"a\"b\""[..])),
("a\rb", None, None),
("é", Some(&b"\"\xc3\xa9\""[..]), Some(&b"W/\"\xc3\xa9\""[..])),
] {
for (weak, expected) in [(false, strong), (true, weak)] {
let fact = ResponseEtag { let fact = ResponseEtag {
opaque: opaque.to_owned(), opaque: opaque.to_owned(),
weak, weak,
}; };
let output = HeadObjectOutputFacts { let actual = fact.to_http_header();
dto: gateway_dto::HeadObjectOutput::default(), match expected {
etag: Some(fact), Some(bytes) => assert_eq!(actual.unwrap().as_bytes(), bytes, "{opaque:?}, weak={weak}"),
None => assert!(actual.is_err(), "{opaque:?}, weak={weak}"),
} }
.into_s3s()
.unwrap();
let tag = output.e_tag.expect("legacy typed caller keeps the fact");
assert_eq!(tag.value(), opaque);
assert_eq!(tag.as_weak().is_some(), weak);
} }
} }
} }
@@ -105,11 +113,16 @@ fn head_proxy_etag_mapping_matches_the_legacy_parser() {
.build(); .build();
let facts = DefaultObjectUsecase::proxy_sdk_head_output(sdk); let facts = DefaultObjectUsecase::proxy_sdk_head_output(sdk);
assert!(facts.dto.e_tag.is_none(), "ETag is carried as a response fact"); assert!(facts.dto.e_tag.is_none(), "ETag is carried as a response fact");
assert_eq!(facts.into_s3s().unwrap().e_tag, expected, "{raw:?}"); assert_eq!(
facts.etag.as_ref().map(|tag| (tag.opaque.as_str(), tag.weak)),
expected.as_ref().map(|tag| (tag.value(), tag.as_weak().is_some())),
"{raw:?}"
);
} }
let absent = let absent =
DefaultObjectUsecase::proxy_sdk_head_output(aws_sdk_s3::operation::head_object::HeadObjectOutput::builder().build()); DefaultObjectUsecase::proxy_sdk_head_output(aws_sdk_s3::operation::head_object::HeadObjectOutput::builder().build());
assert!(absent.into_s3s().unwrap().e_tag.is_none()); assert!(absent.etag.is_none());
assert!(absent.dto.e_tag.is_none());
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@@ -263,14 +276,9 @@ fn head_etag_wire_and_audit(stack: Option<&'static str>, rows: &'static [HeadEta
let internal = crate::app::test_seams::head_object_gateway(&usecase, envelope, input) let internal = crate::app::test_seams::head_object_gateway(&usecase, envelope, input)
.await .await
.expect("unencoded HEAD response"); .expect("unencoded HEAD response");
let typed = internal let fact = internal.output.etag.expect("internal caller retains the ETag");
.output assert_eq!(fact.opaque, row.opaque, "{}", row.stored);
.into_s3s() assert_eq!(fact.weak, row.weak, "{}", row.stored);
.expect("legacy response projection")
.e_tag
.expect("internal caller retains the ETag");
assert_eq!(typed.value(), row.opaque, "{}", row.stored);
assert_eq!(typed.as_weak().is_some(), row.weak, "{}", row.stored);
expected_audits.push((Some("s3:HeadObject".to_owned()), Some("success".to_owned()), Some(200))); expected_audits.push((Some("s3:HeadObject".to_owned()), Some("success".to_owned()), Some(200)));
probe.wait_for(index * 3 + 1, 0).await; probe.wait_for(index * 3 + 1, 0).await;
for conditional in [false, true] { for conditional in [false, true] {
+4 -12
View File
@@ -94,8 +94,6 @@ use super::storage_api::object_usecase::object_cache::GetObjectBodySource;
#[cfg(test)] #[cfg(test)]
use super::storage_api::object_usecase::object_cache::lookup_get_object_body_cache_hook; use super::storage_api::object_usecase::object_cache::lookup_get_object_body_cache_hook;
use super::storage_api::object_usecase::object_cache::{GetObjectBodyCacheHookLookup, get_object_body_cache_plaintext_len}; use super::storage_api::object_usecase::object_cache::{GetObjectBodyCacheHookLookup, get_object_body_cache_plaintext_len};
#[cfg(test)]
use super::storage_api::object_usecase::object_utils::to_s3s_etag;
use super::storage_api::object_usecase::options::{ use super::storage_api::object_usecase::options::{
copy_dst_opts_with_replication_authorization, copy_src_opts, del_opts_with_versioning, extract_metadata, copy_dst_opts_with_replication_authorization, copy_src_opts, del_opts_with_versioning, extract_metadata,
extract_metadata_from_mime_with_object_name, filter_object_metadata, get_content_sha256_with_query, get_opts, extract_metadata_from_mime_with_object_name, filter_object_metadata, get_content_sha256_with_query, get_opts,
@@ -108,14 +106,12 @@ use super::storage_api::object_usecase::set_disk::{
get_lock_acquire_timeout, get_object_disk_read_timeout, is_valid_storage_class, get_lock_acquire_timeout, get_object_disk_read_timeout, is_valid_storage_class,
}; };
#[cfg(not(test))] #[cfg(not(test))]
use super::storage_api::object_usecase::sse::{DecryptionRequest, SseKmsPrincipal, SseKmsPrincipalExt}; use super::storage_api::object_usecase::sse::{DecryptionRequest, SseKmsPrincipal};
#[cfg(test)] #[cfg(test)]
pub(crate) use super::storage_api::object_usecase::sse::{ pub(crate) use super::storage_api::object_usecase::sse::{DecryptionRequest, SseKmsPrincipal, sse_decryption};
DecryptionRequest, SseKmsPrincipal, SseKmsPrincipalExt, sse_decryption,
};
use super::storage_api::object_usecase::sse::{ use super::storage_api::object_usecase::sse::{
EncryptionMaterialExt, EncryptionRequest, apply_bucket_default_lock_retention, authorize_sse_kms_object_read, EncryptionRequest, apply_bucket_default_lock_retention, authorize_sse_kms_object_read, bucket_default_write_sse,
bucket_default_write_sse, build_ssec_read_headers, classify_sse_read_response, encryption_material_to_metadata, 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, 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, get_buffer_size_opt_in, load_bucket_object_lock_config_state, map_get_object_reader_error, sse_encryption,
validate_bucket_object_lock_enabled_state, validate_bucket_object_lock_enabled_state,
@@ -187,8 +183,6 @@ use rustfs_utils::http::{
use rustfs_utils::path::{encode_dir_object, is_dir_object, path_join_buf}; use rustfs_utils::path::{encode_dir_object, is_dir_object, path_join_buf};
use rustfs_utils::retry::{DEFAULT_RETRY_CAP, DEFAULT_RETRY_UNIT, MAX_JITTER, RetryTimer}; use rustfs_utils::retry::{DEFAULT_RETRY_CAP, DEFAULT_RETRY_UNIT, MAX_JITTER, RetryTimer};
use rustfs_zip::{ArchiveLimits, CompressionFormat, ZipError}; use rustfs_zip::{ArchiveLimits, CompressionFormat, ZipError};
#[cfg(test)]
use s3s::{S3Request, S3Response};
/// Remove replication history owned by another source object before a local /// Remove replication history owned by another source object before a local
/// object-creation decision is made. Compatibility keys are case-insensitive, /// object-creation decision is made. Compatibility keys are case-insensitive,
@@ -240,8 +234,6 @@ pub(crate) use native_body::{BodyChunks, FrameTrailers, upload_frame_reader};
pub(crate) use put_input::{PutObjectWriteInput, PutObjectWriteOutput}; pub(crate) use put_input::{PutObjectWriteInput, PutObjectWriteOutput};
pub(crate) mod request_body; pub(crate) mod request_body;
mod restore; mod restore;
#[cfg(test)]
mod s3s_compat;
pub(crate) mod shared; pub(crate) mod shared;
#[cfg(test)] #[cfg(test)]
mod test_support; mod test_support;
@@ -299,7 +299,6 @@ impl OdmWriteBack for OnDemandMigrationWriteBack {
mod tests { mod tests {
use super::*; use super::*;
use crate::app::storage_api::multipart_usecase::contract::multipart::MultipartOperations as _; use crate::app::storage_api::multipart_usecase::contract::multipart::MultipartOperations as _;
use crate::app::storage_api::s3::dto::GetObjectInput;
use crate::app::storage_api::s3::{ use crate::app::storage_api::s3::{
PersistedOptionalReplicationStatus, PersistedReplicationConfiguration, PersistedReplicationDestination, PersistedOptionalReplicationStatus, PersistedReplicationConfiguration, PersistedReplicationDestination,
PersistedReplicationFilter, PersistedReplicationRule, PersistedReplicationTag, Status, PersistedReplicationFilter, PersistedReplicationRule, PersistedReplicationTag, Status,
@@ -307,6 +306,7 @@ mod tests {
use crate::app::storage_api::test::bucket::utils::serialize; use crate::app::storage_api::test::bucket::utils::serialize;
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions}; use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions};
use crate::app::storage_api::test::{get_global_bucket_metadata_sys, set_bucket_metadata}; use crate::app::storage_api::test::{get_global_bucket_metadata_sys, set_bucket_metadata};
use crate::app::test_seams::{get_envelope, get_object_gateway, get_object_input, read_get_body};
use crate::on_demand_migration::{PullFailureReason, SourceSse}; use crate::on_demand_migration::{PullFailureReason, SourceSse};
use rustfs_gateway_types::persistence::{ use rustfs_gateway_types::persistence::{
PersistedBucketEncryptionConfiguration as ServerSideEncryptionConfiguration, PersistedBucketEncryptionConfiguration as ServerSideEncryptionConfiguration,
@@ -420,20 +420,15 @@ mod tests {
} }
async fn get_via_app(bucket: &str, key: &str) -> Vec<u8> { async fn get_via_app(bucket: &str, key: &str) -> Vec<u8> {
let input = GetObjectInput::builder() let response = get_object_gateway(
.bucket(bucket.to_string()) &DefaultObjectUsecase::from_global(),
.key(key.to_string()) get_envelope(HeaderMap::new(), http::Extensions::new()),
.build() get_object_input(bucket, key, None),
.expect("GET input must build"); )
let mut response = crate::app::test_seams::get_object_method_only(&DefaultObjectUsecase::from_global(), input) .await
.await .expect("app-layer GET must succeed");
.expect("app-layer GET must succeed"); let body = response.output.body.expect("GET response must include a body");
let mut body = response.output.body.take().expect("GET response must include a body"); read_get_body(body).await.to_vec()
let mut actual = Vec::new();
while let Some(chunk) = body.next().await {
actual.extend_from_slice(&chunk.expect("GET body chunk"));
}
actual
} }
fn assert_provenance(metadata: &HashMap<String, String>, head: &SourceHead) { fn assert_provenance(metadata: &HashMap<String, String>, head: &SourceHead) {
+182 -197
View File
@@ -20,7 +20,8 @@ use super::*;
use crate::app::RequestEnvelope; use crate::app::RequestEnvelope;
#[cfg(test)] #[cfg(test)]
use crate::app::storage_api::s3::dto::{PutObjectInput, ServerSideEncryption, StorageClass, StreamingBlob}; use crate::app::storage_api::s3::dto::{PutObjectInput, ServerSideEncryption, StorageClass, StreamingBlob};
use crate::app::storage_api::s3::stream::{ByteStream, RemainingLength}; #[cfg(test)]
use crate::app::storage_api::s3::stream::ByteStream;
use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Result, StdError, s3_error}; use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Result, StdError, s3_error};
use futures::FutureExt; use futures::FutureExt;
use rustfs_gateway_stream::Body as NativeBody; use rustfs_gateway_stream::Body as NativeBody;
@@ -210,17 +211,6 @@ impl<S: Stream<Item = Result<Bytes, StdError>> + Unpin> Stream for MaxContentLen
} }
} }
impl<S: ByteStream<Item = Result<Bytes, StdError>> + Unpin> ByteStream for MaxContentLengthStream<S> {
fn remaining_length(&self) -> RemainingLength {
let remaining = usize::try_from(self.limit.saturating_sub(self.received)).unwrap_or(usize::MAX);
let inner = self.inner.remaining_length();
inner
.exact()
.map(|exact| RemainingLength::new_exact(exact.min(remaining)))
.unwrap_or_else(RemainingLength::unknown)
}
}
pub(super) struct PooledBufferReader { pub(super) struct PooledBufferReader {
buffer: PooledBuffer, buffer: PooledBuffer,
len: usize, len: usize,
@@ -2619,34 +2609,22 @@ mod tests {
} }
use super::*; use super::*;
use crate::app::storage_api::s3::dto::{GetObjectInput, ObjectLockRetentionMode}; use crate::app::storage_api::s3::dto::ObjectLockRetentionMode;
use crate::app::test_seams::{head_envelope, head_object_input}; use crate::app::test_seams::{
get_envelope, get_object_gateway, get_object_input, head_envelope, head_object_input, read_get_body,
};
use futures::StreamExt; use futures::StreamExt;
use http::{HeaderMap, HeaderName, HeaderValue, Method}; use http::{HeaderMap, HeaderName, HeaderValue, Method};
use rustfs_gateway_types::SseCustomerKey; use rustfs_gateway_types::SseCustomerKey;
use rustfs_s3_types::S3ErrorCode as OwnedS3ErrorCode; use rustfs_s3_types::S3ErrorCode as OwnedS3ErrorCode;
/// PutObject through the owned entry point the gateway handler calls, its error in the s3s fn write_envelope(method: Method, uri: http::Uri, headers: HeaderMap, mut extensions: http::Extensions) -> RequestEnvelope {
/// form these tests compare. if method == Method::POST {
async fn put_owned(usecase: &DefaultObjectUsecase, req: S3Request<PutObjectInput>) -> S3Result<PutObjectWriteOutput> { extensions.insert(PostObjectRequestMarker);
let (envelope, input) = PutObjectWriteInput::from_test_request(req); }
Box::pin(usecase.execute_put_object_owned(envelope, input))
.await
.map_err(S3Error::from)
}
/// As [`put_owned`], through the archive-extraction entry point.
async fn put_extract_owned(usecase: &DefaultObjectUsecase, req: S3Request<PutObjectInput>) -> S3Result<PutObjectWriteOutput> {
let (envelope, input) = PutObjectWriteInput::from_test_request(req);
Box::pin(usecase.execute_put_object_extract_owned(envelope, input))
.await
.map_err(S3Error::from)
}
fn put_envelope(uri: http::Uri, headers: HeaderMap, extensions: http::Extensions) -> RequestEnvelope {
RequestEnvelope::from_parts( RequestEnvelope::from_parts(
crate::app::RequestHead { crate::app::RequestHead {
method: Method::PUT, method,
uri, uri,
headers, headers,
credentials: None, credentials: None,
@@ -2658,7 +2636,7 @@ mod tests {
} }
fn method_only_put_envelope() -> RequestEnvelope { fn method_only_put_envelope() -> RequestEnvelope {
put_envelope(http::Uri::from_static("/"), HeaderMap::new(), http::Extensions::new()) write_envelope(Method::PUT, http::Uri::from_static("/"), HeaderMap::new(), http::Extensions::new())
} }
fn put_bytes(bucket: String, key: &str, bytes: Bytes) -> PutObjectWriteInput { fn put_bytes(bucket: String, key: &str, bytes: Bytes) -> PutObjectWriteInput {
@@ -2919,23 +2897,18 @@ mod tests {
{ {
for method in [Method::PUT, Method::POST] { for method in [Method::PUT, Method::POST] {
let key = format!("refused-{index}-{method}"); let key = format!("refused-{index}-{method}");
let input = PutObjectInput::builder() let input = put_bytes(bucket.clone(), &key, Bytes::from_static(b"quorum probe"));
.bucket(bucket.clone())
.key(key.clone())
.body(Some(StreamingBlob::from_bytes(Bytes::from_static(b"quorum probe"))))
.content_length(Some(12))
.build()
.expect("quorum probe input must build");
let probe = crate::app::storage_api::object_usecase::helper::MutationCompletionProbe::install(&bucket); let probe = crate::app::storage_api::object_usecase::helper::MutationCompletionProbe::install(&bucket);
let mut req = build_request(input, method.clone()); let envelope = write_envelope(
req.uri = format!("/{bucket}/{key}").parse().expect("PUT URI"); method.clone(),
if method == Method::POST { format!("/{bucket}/{key}").parse().expect("PUT URI"),
req.extensions.insert(PostObjectRequestMarker); HeaderMap::new(),
} http::Extensions::new(),
);
let err = PUT_STORAGE_TEST_FAILURE let err = PUT_STORAGE_TEST_FAILURE
.scope( .scope(
(stage, StorageError::InsufficientReadQuorum("bucket".into(), "object".into())), (stage, StorageError::InsufficientReadQuorum("bucket".into(), "object".into())),
put_owned(&usecase, req), Box::pin(usecase.execute_put_object_owned(envelope, input)),
) )
.await .await
.expect_err("read quorum failure must refuse the upload"); .expect_err("read quorum failure must refuse the upload");
@@ -2947,7 +2920,7 @@ mod tests {
assert_eq!(audits[0].api.status_code, Some(503)); assert_eq!(audits[0].api.status_code, Some(503));
assert!(probe.events.lock().expect("events").is_empty()); assert!(probe.events.lock().expect("events").is_empty());
} }
assert_eq!(err.code(), &S3ErrorCode::ServiceUnavailable, "stage {index}, method {method}"); assert_eq!(err.code(), &OwnedS3ErrorCode::ServiceUnavailable, "stage {index}, method {method}");
assert_eq!(err.status_code(), Some(http::StatusCode::SERVICE_UNAVAILABLE)); assert_eq!(err.status_code(), Some(http::StatusCode::SERVICE_UNAVAILABLE));
assert_eq!(err.message(), Some("The service is unavailable. Please retry.")); assert_eq!(err.message(), Some("The service is unavailable. Please retry."));
assert!(matches!( assert!(matches!(
@@ -3269,14 +3242,11 @@ mod tests {
Arc::clone(&metadata_entered), Arc::clone(&metadata_entered),
Arc::clone(&metadata_resume), Arc::clone(&metadata_resume),
); );
let metadata_input = GetObjectInput::builder() let metadata_input = get_object_input(&bucket, object, None);
.bucket(bucket.clone())
.key(object.to_string())
.build()
.expect("metadata GET input must build");
let metadata_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let metadata_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let metadata_get = let metadata_get = tokio::spawn(async move {
tokio::spawn(async move { crate::app::test_seams::get_object_method_only(&metadata_usecase, metadata_input).await }); get_object_gateway(&metadata_usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), metadata_input).await
});
tokio::time::timeout(Duration::from_secs(2), metadata_entered.wait()) tokio::time::timeout(Duration::from_secs(2), metadata_entered.wait())
.await .await
.expect("GET must enter the bucket metadata stage"); .expect("GET must enter the bucket metadata stage");
@@ -3298,13 +3268,11 @@ mod tests {
.get_write_lock(Duration::from_secs(5)) .get_write_lock(Duration::from_secs(5))
.await .await
.expect("read test namespace lock must be held"); .expect("read test namespace lock must be held");
let get_input = GetObjectInput::builder() let get_input = get_object_input(&bucket, object, None);
.bucket(bucket.clone())
.key(object.to_string())
.build()
.expect("GET input must build");
let get_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let get_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let get = tokio::spawn(async move { crate::app::test_seams::get_object_method_only(&get_usecase, get_input).await }); let get = tokio::spawn(async move {
get_object_gateway(&get_usecase, get_envelope(HeaderMap::new(), http::Extensions::new()), get_input).await
});
tokio::time::timeout(Duration::from_secs(2), async { tokio::time::timeout(Duration::from_secs(2), async {
while !object_traffic_health.read_storage_stalled_for_test() { while !object_traffic_health.read_storage_stalled_for_test() {
tokio::task::yield_now().await; tokio::task::yield_now().await;
@@ -3390,7 +3358,8 @@ mod tests {
let payload = Bytes::from_static(b"published despite caller cancellation"); let payload = Bytes::from_static(b"published despite caller cancellation");
let put_input = put_bytes(bucket.clone(), object, payload.clone()); let put_input = put_bytes(bucket.clone(), object, payload.clone());
let put_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let put_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let envelope = put_envelope( let envelope = write_envelope(
Method::PUT,
format!("/{bucket}/{object}").parse().expect("PUT URI"), format!("/{bucket}/{object}").parse().expect("PUT URI"),
HeaderMap::new(), HeaderMap::new(),
http::Extensions::new(), http::Extensions::new(),
@@ -3430,7 +3399,8 @@ mod tests {
assert_eq!(recovered.size, i64::try_from(payload.len()).expect("test payload length must fit i64")); assert_eq!(recovered.size, i64::try_from(payload.len()).expect("test payload length must fit i64"));
probe.wait_for(1, 1).await; probe.wait_for(1, 1).await;
let normal_input = put_bytes(bucket.clone(), "normal.bin", Bytes::from_static(b"normal")); let normal_input = put_bytes(bucket.clone(), "normal.bin", Bytes::from_static(b"normal"));
let envelope = put_envelope( let envelope = write_envelope(
Method::PUT,
format!("/{bucket}/normal.bin").parse().expect("URI"), format!("/{bucket}/normal.bin").parse().expect("URI"),
HeaderMap::new(), HeaderMap::new(),
http::Extensions::new(), http::Extensions::new(),
@@ -3467,8 +3437,12 @@ mod tests {
..put_bytes(bucket.clone(), extra_body_object, Bytes::from_static(b"x")) ..put_bytes(bucket.clone(), extra_body_object, Bytes::from_static(b"x"))
}; };
let extra_body_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let extra_body_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let extra_body_envelope = let extra_body_envelope = write_envelope(
put_envelope(http::Uri::from_static("/"), streaming_headers(Some("0")), http::Extensions::new()); Method::PUT,
http::Uri::from_static("/"),
streaming_headers(Some("0")),
http::Extensions::new(),
);
let extra_body_err = Box::pin(extra_body_usecase.execute_put_object_owned(extra_body_envelope, extra_body_input)) let extra_body_err = Box::pin(extra_body_usecase.execute_put_object_owned(extra_body_envelope, extra_body_input))
.await .await
.expect_err("decoded zero-byte PUT with body data must fail"); .expect_err("decoded zero-byte PUT with body data must fail");
@@ -3503,7 +3477,12 @@ mod tests {
..Default::default() ..Default::default()
}; };
let zero_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let zero_usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let zero_envelope = put_envelope(http::Uri::from_static("/"), streaming_headers(Some("0")), http::Extensions::new()); let zero_envelope = write_envelope(
Method::PUT,
http::Uri::from_static("/"),
streaming_headers(Some("0")),
http::Extensions::new(),
);
let zero_put = let zero_put =
tokio::spawn(async move { Box::pin(zero_usecase.execute_put_object_owned(zero_envelope, zero_input)).await }); tokio::spawn(async move { Box::pin(zero_usecase.execute_put_object_owned(zero_envelope, zero_input)).await });
@@ -4054,7 +4033,7 @@ mod tests {
}; };
let mut extensions = http::Extensions::new(); let mut extensions = http::Extensions::new();
extensions.insert(control.clone()); extensions.insert(control.clone());
let envelope = put_envelope(http::Uri::from_static("/"), HeaderMap::new(), extensions); let envelope = write_envelope(Method::PUT, http::Uri::from_static("/"), HeaderMap::new(), extensions);
let usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let owner = tokio::spawn(async move { Box::pin(usecase.execute_put_object_owned(envelope, input)).await }); let owner = tokio::spawn(async move { Box::pin(usecase.execute_put_object_owned(envelope, input)).await });
control.wait_until_pending_for_test().await; control.wait_until_pending_for_test().await;
@@ -4443,31 +4422,30 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn post_object_metadata_cannot_dispatch_legacy_archive_extraction() { async fn post_object_metadata_cannot_dispatch_legacy_archive_extraction() {
let mut req = build_request(PutObjectInput::default(), Method::POST); let input = PutObjectWriteInput::default();
req.extensions.insert(PostObjectRequestMarker); let envelope = write_envelope(Method::POST, http::Uri::from_static("/"), HeaderMap::new(), http::Extensions::new());
let err = Box::pin(put_extract_owned(&DefaultObjectUsecase::without_context(), req)) let err = Box::pin(DefaultObjectUsecase::without_context().execute_put_object_extract_owned(envelope, input))
.await .await
.expect_err("a legacy form cannot authorize archive replay"); .expect_err("a legacy form cannot authorize archive replay");
assert_eq!(err.code(), &S3ErrorCode::NotImplemented); assert_eq!(err.code(), &OwnedS3ErrorCode::NotImplemented);
} }
#[tokio::test] #[tokio::test]
async fn execute_put_object_rejects_post_object_etag_if_none_match_header() { async fn execute_put_object_rejects_post_object_etag_if_none_match_header() {
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket("test-bucket".to_string()) bucket: "test-bucket".to_owned(),
.key("test-key".to_string()) key: "test-key".to_owned(),
.build() ..Default::default()
.expect("POST-to-PUT input should build without conditional DTO fields"); };
let mut req = build_request(input, Method::POST); let mut headers = HeaderMap::new();
req.extensions.insert(PostObjectRequestMarker); headers.insert(http::header::IF_NONE_MATCH, HeaderValue::from_static("\"different-etag\""));
req.headers
.insert(http::header::IF_NONE_MATCH, HeaderValue::from_static("\"different-etag\""));
let envelope = write_envelope(Method::POST, http::Uri::from_static("/"), headers, http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)) let err = Box::pin(usecase.execute_put_object_owned(envelope, input))
.await .await
.expect_err("POST header-only ETag precondition must fail before storage access"); .expect_err("POST header-only ETag precondition must fail before storage access");
assert_eq!(err.code(), &S3ErrorCode::NotImplemented); assert_eq!(err.code(), &OwnedS3ErrorCode::NotImplemented);
} }
#[tokio::test] #[tokio::test]
@@ -4483,7 +4461,18 @@ mod tests {
let mut request = build_request(input, Method::POST); let mut request = build_request(input, Method::POST);
request.extensions.insert(PostObjectRequestMarker); request.extensions.insert(PostObjectRequestMarker);
request.headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true")); request.headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true"));
let mut envelope = RequestEnvelope::from_s3s(&request); // Same facts `RequestEnvelope::from_s3s` copies. Credentials, region, and service stay absent.
let mut envelope = RequestEnvelope::from_parts(
crate::app::RequestHead {
method: request.method.clone(),
uri: request.uri.clone(),
headers: request.headers.clone(),
credentials: None,
region: None,
service: None,
},
request.extensions.clone(),
);
assert!(!envelope.is_gateway_post(), "legacy provenance must remain distinct"); assert!(!envelope.is_gateway_post(), "legacy provenance must remain distinct");
envelope.mark_gateway_post(); envelope.mark_gateway_post();
assert!(envelope.fork_for_authorization().is_gateway_post()); assert!(envelope.fork_for_authorization().is_gateway_post());
@@ -4506,56 +4495,54 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn execute_put_object_rejects_post_object_sse_kms_from_input() { async fn execute_put_object_rejects_post_object_sse_kms_from_input() {
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket("test-bucket".to_string()) bucket: "test-bucket".to_owned(),
.key("test-key".to_string()) key: "test-key".to_owned(),
.server_side_encryption(Some(ServerSideEncryption::from_static(ServerSideEncryption::AWS_KMS))) server_side_encryption: Some(ServerSideEncryption::AWS_KMS.to_owned()),
.build() ..Default::default()
.unwrap(); };
let mut req = build_request(input, Method::POST);
req.extensions.insert(PostObjectRequestMarker);
let envelope = write_envelope(Method::POST, http::Uri::from_static("/"), HeaderMap::new(), http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)).await.unwrap_err(); let err = Box::pin(usecase.execute_put_object_owned(envelope, input)).await.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::NotImplemented); assert_eq!(err.code(), &OwnedS3ErrorCode::NotImplemented);
} }
#[tokio::test] #[tokio::test]
async fn execute_put_object_rejects_extract_sse_kms() { async fn execute_put_object_rejects_extract_sse_kms() {
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket("test-bucket".to_string()) bucket: "test-bucket".to_owned(),
.key("archive.tar".to_string()) key: "archive.tar".to_owned(),
.server_side_encryption(Some(ServerSideEncryption::from_static(ServerSideEncryption::AWS_KMS))) server_side_encryption: Some(ServerSideEncryption::AWS_KMS.to_owned()),
.build() ..Default::default()
.unwrap(); };
let mut headers = HeaderMap::new();
let mut req = build_request(input, Method::PUT); headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true"));
req.headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true"));
let envelope = write_envelope(Method::PUT, http::Uri::from_static("/"), headers, http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)).await.unwrap_err(); let err = Box::pin(usecase.execute_put_object_owned(envelope, input)).await.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::NotImplemented); assert_eq!(err.code(), &OwnedS3ErrorCode::NotImplemented);
} }
#[tokio::test] #[tokio::test]
async fn execute_put_object_extract_rejects_invalid_storage_class() { async fn execute_put_object_extract_rejects_invalid_storage_class() {
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket("test-bucket".to_string()) bucket: "test-bucket".to_owned(),
.key("archive.tar".to_string()) key: "archive.tar".to_owned(),
.storage_class(Some(StorageClass::from_static("INVALID"))) storage_class: Some("INVALID".to_owned()),
.build() ..Default::default()
.unwrap(); };
let mut headers = HeaderMap::new();
let mut req = build_request(input, Method::PUT); headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true"));
req.headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true"));
let envelope = write_envelope(Method::PUT, http::Uri::from_static("/"), headers, http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)).await.unwrap_err(); let err = Box::pin(usecase.execute_put_object_owned(envelope, input)).await.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::InvalidStorageClass); assert_eq!(err.code(), &OwnedS3ErrorCode::InvalidStorageClass);
} }
/// issue #7596: a single PUT whose declared length exceeds the 5 GiB /// issue #7596: a single PUT whose declared length exceeds the 5 GiB
@@ -4590,36 +4577,40 @@ mod tests {
let framing_overhead = 1_000_000; let framing_overhead = 1_000_000;
for (decoded, expect_too_large) in [(ceiling, false), (ceiling + 1, true)] { for (decoded, expect_too_large) in [(ceiling, false), (ceiling + 1, true)] {
let (body, polls) = PollCountingBody::streaming_blob(); let polls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let input = PutObjectInput::builder() let body_polls = Arc::clone(&polls);
.bucket("test-bucket".to_string()) let body = super::super::native_body::from_io_stream(futures::stream::repeat_with(move || {
.key("huge.bin".to_string()) body_polls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
.body(Some(body)) Ok(Bytes::from_static(b"x"))
.content_length(Some(decoded + framing_overhead)) }));
.build() let input = PutObjectWriteInput {
.unwrap(); bucket: "test-bucket".to_owned(),
key: "huge.bin".to_owned(),
let mut req = build_request(input, Method::PUT); body: Some(body),
req.headers content_length: Some(decoded + framing_overhead),
.insert(http::header::CONTENT_ENCODING, HeaderValue::from_static("aws-chunked")); ..Default::default()
req.headers.insert( };
let mut headers = HeaderMap::new();
headers.insert(http::header::CONTENT_ENCODING, HeaderValue::from_static("aws-chunked"));
headers.insert(
HeaderName::from_static("x-amz-content-sha256"), HeaderName::from_static("x-amz-content-sha256"),
HeaderValue::from_static("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"), HeaderValue::from_static("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"),
); );
req.headers.insert( headers.insert(
HeaderName::from_static("x-amz-decoded-content-length"), HeaderName::from_static("x-amz-decoded-content-length"),
HeaderValue::from_str(&decoded.to_string()).unwrap(), HeaderValue::from_str(&decoded.to_string()).unwrap(),
); );
let envelope = write_envelope(Method::PUT, http::Uri::from_static("/"), headers, http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)).await.unwrap_err(); let err = Box::pin(usecase.execute_put_object_owned(envelope, input)).await.unwrap_err();
if expect_too_large { if expect_too_large {
assert_eq!(err.code(), &S3ErrorCode::EntityTooLarge, "decoded {decoded}"); assert_eq!(err.code(), &OwnedS3ErrorCode::EntityTooLarge, "decoded {decoded}");
assert_eq!(polls.load(std::sync::atomic::Ordering::SeqCst), 0, "body must not be polled"); assert_eq!(polls.load(std::sync::atomic::Ordering::SeqCst), 0, "body must not be polled");
} else { } else {
assert_ne!( assert_ne!(
err.code(), err.code(),
&S3ErrorCode::EntityTooLarge, &OwnedS3ErrorCode::EntityTooLarge,
"framed wire length above the cap must not reject a decoded length at the cap" "framed wire length above the cap must not reject a decoded length at the cap"
); );
} }
@@ -4628,40 +4619,36 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn execute_put_object_rejects_post_object_sse_kms_from_headers() { async fn execute_put_object_rejects_post_object_sse_kms_from_headers() {
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket("test-bucket".to_string()) bucket: "test-bucket".to_owned(),
.key("test-key".to_string()) key: "test-key".to_owned(),
.build() ..Default::default()
.unwrap(); };
let mut headers = HeaderMap::new();
let mut req = build_request(input, Method::POST); headers.insert(AMZ_SERVER_SIDE_ENCRYPTION, HeaderValue::from_static("aws:kms"));
req.extensions.insert(PostObjectRequestMarker);
req.headers
.insert(AMZ_SERVER_SIDE_ENCRYPTION, HeaderValue::from_static("aws:kms"));
let envelope = write_envelope(Method::POST, http::Uri::from_static("/"), headers, http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)).await.unwrap_err(); let err = Box::pin(usecase.execute_put_object_owned(envelope, input)).await.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::NotImplemented); assert_eq!(err.code(), &OwnedS3ErrorCode::NotImplemented);
} }
#[tokio::test] #[tokio::test]
async fn execute_put_object_rejects_post_object_sse_kms_key_id_header() { async fn execute_put_object_rejects_post_object_sse_kms_key_id_header() {
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket("test-bucket".to_string()) bucket: "test-bucket".to_owned(),
.key("test-key".to_string()) key: "test-key".to_owned(),
.build() ..Default::default()
.unwrap(); };
let mut headers = HeaderMap::new();
let mut req = build_request(input, Method::POST); headers.insert(AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID, HeaderValue::from_static("test-kms-key-id"));
req.extensions.insert(PostObjectRequestMarker);
req.headers
.insert(AMZ_SERVER_SIDE_ENCRYPTION_KMS_ID, HeaderValue::from_static("test-kms-key-id"));
let envelope = write_envelope(Method::POST, http::Uri::from_static("/"), headers, http::Extensions::new());
let usecase = DefaultObjectUsecase::without_context(); let usecase = DefaultObjectUsecase::without_context();
let err = Box::pin(put_owned(&usecase, req)).await.unwrap_err(); let err = Box::pin(usecase.execute_put_object_owned(envelope, input)).await.unwrap_err();
assert_eq!(err.code(), &S3ErrorCode::NotImplemented); assert_eq!(err.code(), &OwnedS3ErrorCode::NotImplemented);
} }
#[tokio::test] #[tokio::test]
@@ -4928,27 +4915,24 @@ mod tests {
assert_eq!(head.output.dto.sse_customer_algorithm.as_deref(), Some("AES256")); assert_eq!(head.output.dto.sse_customer_algorithm.as_deref(), Some("AES256"));
assert_eq!(head.output.dto.sse_customer_key_md5.as_deref(), Some(key_md5.as_str())); assert_eq!(head.output.dto.sse_customer_key_md5.as_deref(), Some(key_md5.as_str()));
let get_input = GetObjectInput::builder() let get_input = rustfs_gateway_types::dto::GetObjectInput {
.bucket(bucket.clone()) sse_customer_algorithm: Some("AES256".to_owned()),
.key("ledger.csv".to_string()) sse_customer_key: Some(SseCustomerKey::new(encoded_key)),
.sse_customer_algorithm(Some("AES256".to_string())) sse_customer_key_md5: Some(key_md5.clone()),
.sse_customer_key(Some(encoded_key)) ..get_object_input(&bucket, "ledger.csv", None)
.sse_customer_key_md5(Some(key_md5.clone())) };
.build() let get = Box::pin(get_object_gateway(
.expect("SSE-C GET input must build"); &usecase,
let mut get_request = build_request(get_input, Method::GET); get_envelope(read_headers, http::Extensions::new()),
get_request.headers = read_headers; get_input,
let get = Box::pin(crate::app::test_seams::get_object(&usecase, get_request)) ))
.await .await
.expect("matching SSE-C key must authorize GET"); .expect("matching SSE-C key must authorize GET");
assert_eq!(get.output.server_side_encryption, None); assert_eq!(get.output.dto.server_side_encryption, None);
assert_eq!(get.output.sse_customer_algorithm.as_deref(), Some("AES256")); assert_eq!(get.output.dto.sse_customer_algorithm.as_deref(), Some("AES256"));
assert_eq!(get.output.sse_customer_key_md5.as_deref(), Some(key_md5.as_str())); assert_eq!(get.output.dto.sse_customer_key_md5.as_deref(), Some(key_md5.as_str()));
let mut body = get.output.body.expect("SSE-C GET must include the decrypted body"); let body = get.output.body.expect("SSE-C GET must include the decrypted body");
let mut plaintext = Vec::new(); let plaintext = read_get_body(body).await;
while let Some(chunk) = body.next().await {
plaintext.extend_from_slice(&chunk.expect("SSE-C body must decrypt completely"));
}
assert_eq!(plaintext, payload, "header classification must preserve the complete decrypted payload"); assert_eq!(plaintext, payload, "header classification must preserve the complete decrypted payload");
let stored = store let stored = store
@@ -4991,31 +4975,31 @@ mod tests {
crate::app::gating_test_env::durable_quota_test_bucket("ciphertext-replication-early-reject", 4096).await; crate::app::gating_test_env::durable_quota_test_bucket("ciphertext-replication-early-reject", 4096).await;
let body_polled = Arc::new(AtomicBool::new(false)); let body_polled = Arc::new(AtomicBool::new(false));
let body_polled_in_stream = Arc::clone(&body_polled); let body_polled_in_stream = Arc::clone(&body_polled);
let body = StreamingBlob::wrap(futures::stream::once(async move { let body = super::super::native_body::from_io_stream(futures::stream::once(async move {
body_polled_in_stream.store(true, Ordering::Release); body_polled_in_stream.store(true, Ordering::Release);
Ok::<Bytes, std::io::Error>(Bytes::from_static(b"ciphertext")) Ok::<Bytes, std::io::Error>(Bytes::from_static(b"ciphertext"))
})); }));
let input = PutObjectInput::builder() let input = PutObjectWriteInput {
.bucket(bucket) bucket,
.key("object".to_string()) key: "object".to_owned(),
.body(Some(body)) body: Some(body),
.content_length(Some(10)) content_length: Some(10),
.build() ..Default::default()
.expect("ciphertext replication PUT input should build"); };
let mut request = build_request(input, Method::PUT); let mut headers = HeaderMap::new();
insert_header(&mut request.headers, SUFFIX_SOURCE_REPLICATION_REQUEST, "true"); insert_header(&mut headers, SUFFIX_SOURCE_REPLICATION_REQUEST, "true");
request headers.insert(rustfs_utils::http::REPLICATION_SSEC_ALGORITHM_HEADER, HeaderValue::from_static("AES256"));
.headers let mut extensions = http::Extensions::new();
.insert(rustfs_utils::http::REPLICATION_SSEC_ALGORITHM_HEADER, HeaderValue::from_static("AES256")); extensions.insert(crate::storage::req_info::ReqInfo {
request.extensions.insert(crate::storage::req_info::ReqInfo {
replication_request_authorized: true, replication_request_authorized: true,
..Default::default() ..Default::default()
}); });
let err = put_owned(&DefaultObjectUsecase::from_global(), request) let envelope = write_envelope(Method::PUT, http::Uri::from_static("/"), headers, extensions);
let err = Box::pin(DefaultObjectUsecase::from_global().execute_put_object_owned(envelope, input))
.await .await
.expect_err("quota-enabled ciphertext replication should fail at ingress"); .expect_err("quota-enabled ciphertext replication should fail at ingress");
assert_eq!(err.code(), &S3ErrorCode::InvalidRequest); assert_eq!(err.code(), &OwnedS3ErrorCode::InvalidRequest);
assert!(!body_polled.load(Ordering::Acquire), "rejected ciphertext body must not be consumed"); assert!(!body_polled.load(Ordering::Acquire), "rejected ciphertext body must not be consumed");
} }
@@ -5669,9 +5653,10 @@ mod tests {
headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true")); headers.insert(AMZ_SNOWBALL_EXTRACT, HeaderValue::from_static("true"));
let usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context))); let usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let err = Box::pin( let err = Box::pin(usecase.execute_put_object_owned(
usecase.execute_put_object_owned(put_envelope(http::Uri::from_static("/"), headers, http::Extensions::new()), input), write_envelope(Method::PUT, http::Uri::from_static("/"), headers, http::Extensions::new()),
) input,
))
.await .await
.expect_err("an unreadable bucket encryption configuration must refuse the extract upload"); .expect_err("an unreadable bucket encryption configuration must refuse the extract upload");
-8
View File
@@ -135,12 +135,4 @@ impl PutObjectWriteInput {
checksum_crc64nvme: input.checksum_crc64nvme, checksum_crc64nvme: input.checksum_crc64nvme,
} }
} }
/// A test's s3s fixture request as the envelope and input a gateway handler hands the use case.
pub(crate) fn from_test_request(
req: crate::app::storage_api::s3::S3Request<crate::app::storage_api::s3::PutObjectInput>,
) -> (crate::app::RequestEnvelope, Self) {
let envelope = crate::app::RequestEnvelope::from_s3s(&req);
(envelope, Self::from_legacy(req.input, req.trailing_headers))
}
} }
-162
View File
@@ -1,162 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Compatibility conversions between owned Get/Head object facts and s3s DTOs.
//!
//! Retained for `admin/router.rs` (object-lambda), `app/website.rs`, and `app/test_seams` until
//! T4.2 removes the remaining `s3s` dependency from `admin/router.rs`.
#[cfg(test)]
use crate::app::object_usecase::HeadObjectOutputFacts;
use crate::app::object_usecase::{GetObjectBody, GetObjectFields, GetObjectOutputFacts};
use rustfs_gateway_stream::{BoxPayloadStream, PayloadRead, StreamError, StreamErrorKind};
use rustfs_gateway_types::ByteRange;
use rustfs_gateway_types::compat::ConversionError;
use rustfs_gateway_types::compat::s3s_5761ddfe::generated::ops::get_object;
#[cfg(test)]
use rustfs_gateway_types::compat::s3s_5761ddfe::generated::ops::head_object;
#[cfg(test)]
use s3s::dto::HeadObjectOutput;
use s3s::dto::{ETag, GetObjectInput, GetObjectOutput, Range, StreamingBlob};
use std::pin::Pin;
use std::sync::{Mutex, PoisonError};
use std::task::{Context, Poll};
#[cfg(test)]
impl HeadObjectOutputFacts {
pub(crate) fn into_s3s(self) -> Result<HeadObjectOutput, ConversionError> {
let mut output = head_object::output_to_s3s(self.dto)?;
output.e_tag = self.etag.map(|etag| {
if etag.weak {
ETag::Weak(etag.opaque)
} else {
ETag::Strong(etag.opaque)
}
});
Ok(output)
}
}
impl GetObjectFields {
pub(crate) fn from_s3s(input: GetObjectInput) -> Self {
Self {
bucket: input.bucket,
key: input.key,
version_id: input.version_id,
part_number: input.part_number,
range: input.range.map(|range| match range {
Range::Int { first, last: Some(last) } => ByteRange::FromTo { first, last },
Range::Int { first, last: None } => ByteRange::From { first },
Range::Suffix { length } => ByteRange::Suffix { length },
}),
sse_customer_key: input.sse_customer_key,
sse_customer_key_md5: input.sse_customer_key_md5,
}
}
}
impl GetObjectOutputFacts {
pub(crate) fn into_s3s(self) -> Result<GetObjectOutput, ConversionError> {
let mut output = get_object::output_to_s3s(self.dto)?;
output.e_tag = self.etag.map(|etag| {
if etag.weak {
ETag::Weak(etag.opaque)
} else {
ETag::Strong(etag.opaque)
}
});
output.body = self.body.map(GetObjectBody::into_s3s);
Ok(output)
}
}
impl GetObjectBody {
pub(crate) fn into_s3s(self) -> StreamingBlob {
match self {
Self::Bytes(bytes) => StreamingBlob::from_bytes(bytes),
Self::Stream(payload) => StreamingBlob::new(LegacyGetStream {
payload: Mutex::new(payload),
done: false,
}),
}
}
}
// The legacy body requires Sync. Polling uses exclusive access, not a mutex lock.
struct LegacyGetStream {
payload: Mutex<BoxPayloadStream>,
done: bool,
}
impl futures::Stream for LegacyGetStream {
type Item = Result<bytes::Bytes, Box<dyn std::error::Error + Send + Sync>>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
if this.done {
return Poll::Ready(None);
}
let event = std::task::ready!(
this.payload
.get_mut()
.unwrap_or_else(PoisonError::into_inner)
.as_mut()
.poll_read(cx)
);
Poll::Ready(match event {
Ok(PayloadRead::Chunk(bytes)) => Some(Ok(bytes)),
Ok(PayloadRead::Eof { trailers }) => {
this.done = true;
if trailers.is_empty() {
None
} else {
Some(Err(Box::new(ConversionError {
field: "body",
reason: "legacy GetObject cannot encode response trailers",
})))
}
}
Err(error) => {
this.done = true;
Some(Err(legacy_get_body_error(error)))
}
})
}
}
fn legacy_get_body_error(error: StreamError) -> Box<dyn std::error::Error + Send + Sync> {
if matches!(error.kind(), StreamErrorKind::Upstream(_)) {
let StreamErrorKind::Upstream(source) = error.into_kind() else {
unreachable!("the owned error kind was checked above")
};
source
} else {
Box::new(error)
}
}
impl s3s::stream::ByteStream for LegacyGetStream {
fn remaining_length(&self) -> s3s::stream::RemainingLength {
match self
.payload
.lock()
.unwrap_or_else(PoisonError::into_inner)
.len_hint()
.and_then(|length| usize::try_from(length).ok())
{
Some(length) => s3s::stream::RemainingLength::new_exact(length),
None => s3s::stream::RemainingLength::unknown(),
}
}
}
+1 -1
View File
@@ -20,9 +20,9 @@ use crate::app::storage_api::s3::dto::ObjectLockRetentionMode;
use crate::app::storage_api::s3::dto::{ChecksumAlgorithm, ServerSideEncryption, Timestamp, TimestampFormat}; use crate::app::storage_api::s3::dto::{ChecksumAlgorithm, ServerSideEncryption, Timestamp, TimestampFormat};
#[cfg(test)] #[cfg(test)]
use crate::app::storage_api::s3::dto::{ObjectLockLegalHoldStatus, ObjectLockMode}; use crate::app::storage_api::s3::dto::{ObjectLockLegalHoldStatus, ObjectLockMode};
use crate::app::storage_api::s3::header::{X_AMZ_DELETE_MARKER, X_AMZ_VERSION_ID};
use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Result, StdError, s3_error}; use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Result, StdError, s3_error};
use crate::on_demand_migration::{OdmStateError, PolicyConfig, SourceErrorPolicy, SourceHead}; use crate::on_demand_migration::{OdmStateError, PolicyConfig, SourceErrorPolicy, SourceHead};
use rustfs_s3_client::constants::{X_AMZ_DELETE_MARKER, X_AMZ_VERSION_ID};
pub(super) const RUSTFS_EXPECTED_CURRENT_VERSION_ID: &str = "x-rustfs-expected-current-version-id"; pub(super) const RUSTFS_EXPECTED_CURRENT_VERSION_ID: &str = "x-rustfs-expected-current-version-id";
+1 -1
View File
@@ -24,11 +24,11 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock}; use std::sync::{Arc, OnceLock};
use std::time::Duration; use std::time::Duration;
use super::super::storage_api::s3::{S3Error, S3ErrorCode, S3Result};
use bytes::Bytes; use bytes::Bytes;
use md5::Digest as _; use md5::Digest as _;
use md5::Md5; use md5::Md5;
use moka::{future::Cache as AsyncCache, sync::Cache as SyncCache}; use moka::{future::Cache as AsyncCache, sync::Cache as SyncCache};
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result};
use time::OffsetDateTime; use time::OffsetDateTime;
use tracing::debug; use tracing::debug;
+1 -1
View File
@@ -640,7 +640,7 @@ async fn owned_audit_only_operation_matches_the_recorded_entries() {
#[tokio::test] #[tokio::test]
#[serial(owned_audit_probe)] #[serial(owned_audit_probe)]
async fn owned_operation_attaches_the_sse_kms_summary_to_the_audit_entry() { async fn owned_operation_attaches_the_sse_kms_summary_to_the_audit_entry() {
use crate::app::object::{DecryptionRequest, SseKmsPrincipal, SseKmsPrincipalExt as _, sse_decryption}; use crate::app::object::{DecryptionRequest, SseKmsPrincipal, sse_decryption};
use crate::server::{refresh_audit_module_enabled, refresh_notify_module_enabled}; use crate::server::{refresh_audit_module_enabled, refresh_notify_module_enabled};
temp_env::async_with_vars( temp_env::async_with_vars(
+1 -3
View File
@@ -2,9 +2,7 @@
use super::storage_api::select_object::StorageError; use super::storage_api::select_object::StorageError;
use super::storage_api::select_object::options::get_opts; 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::request_context::spawn_traced;
use super::storage_api::select_object::sse::{ use super::storage_api::select_object::sse::{SseKmsPrincipal, authorize_sse_kms_object_read, project_sse_read_response_headers};
SseKmsPrincipal, SseKmsPrincipalExt, authorize_sse_kms_object_read, project_sse_read_response_headers,
};
use super::storage_api::select_object::{ use super::storage_api::select_object::{
StoragePrepareSelectObjectSnapshotError, StorageSelectObjectSnapshot, get_validated_store, validate_sse_headers_for_read, StoragePrepareSelectObjectSnapshotError, StorageSelectObjectSnapshot, get_validated_store, validate_sse_headers_for_read,
validate_ssec_for_read, validate_ssec_for_read,
+11 -20
View File
@@ -61,21 +61,22 @@ pub(crate) mod s3 {
pub(crate) use s3s::auth::Credentials; pub(crate) use s3s::auth::Credentials;
pub(crate) use s3s::dto; pub(crate) use s3s::dto;
#[cfg(test)] #[cfg(test)]
pub(crate) use s3s::dto::PutObjectInput;
#[cfg(test)]
pub(crate) use s3s::dto::{ pub(crate) use s3s::dto::{
BucketLocationConstraint, CreateBucketConfiguration, CreateBucketInput, CreateMultipartUploadInput, DeleteObjectInput, BucketLocationConstraint, CreateBucketConfiguration, CreateBucketInput, CreateMultipartUploadInput, DeleteObjectInput,
ObjectLockRetention, ObjectLockRetention,
}; };
#[cfg(test)] #[cfg(test)]
pub(crate) use s3s::dto::{GetObjectInput, ListObjectsV2Input, ListObjectsV2Output};
#[cfg(test)]
pub(crate) use s3s::dto::{GetObjectOutput, PutObjectInput};
#[cfg(test)]
pub(crate) use s3s::dto::{ListObjectsInput, StreamingBlob}; pub(crate) use s3s::dto::{ListObjectsInput, StreamingBlob};
pub(crate) use s3s::header; #[cfg(test)]
pub(crate) use s3s::dto::{ListObjectsV2Input, ListObjectsV2Output};
pub(crate) use s3s::s3_error; pub(crate) use s3s::s3_error;
#[cfg(test)]
pub(crate) use s3s::stream; pub(crate) use s3s::stream;
#[cfg(test)] #[cfg(test)]
pub(crate) use s3s::stream::upload_stream::UploadStreamError; pub(crate) use s3s::stream::upload_stream::UploadStreamError;
#[cfg(test)]
pub(crate) use s3s::xml; pub(crate) use s3s::xml;
#[cfg(test)] #[cfg(test)]
pub(crate) use s3s::xml::{Serialize as XmlSerialize, Serializer as XmlSerializer}; pub(crate) use s3s::xml::{Serialize as XmlSerialize, Serializer as XmlSerializer};
@@ -1663,12 +1664,6 @@ pub(crate) mod helper {
}; };
} }
pub(crate) mod object_utils {
#[cfg(test)]
pub(crate) use crate::storage::storage_api::to_s3s_etag;
pub(crate) use crate::storage::storage_api::to_s3s_xml_etag;
}
pub(crate) mod io { pub(crate) mod io {
#[cfg(test)] #[cfg(test)]
pub(crate) use crate::storage::storage_api::{DecryptReader, EncryptReader, HardLimitReader, boxed_reader}; pub(crate) use crate::storage::storage_api::{DecryptReader, EncryptReader, HardLimitReader, boxed_reader};
@@ -1703,9 +1698,9 @@ pub(crate) mod sse {
validate_bucket_object_lock_enabled_state, validate_bucket_object_lock_enabled_state,
}; };
pub(crate) use crate::storage::storage_api::sse_consumer::{ pub(crate) use crate::storage::storage_api::sse_consumer::{
EncryptionKeyKind, EncryptionMaterialExt, SseKmsPrincipalExt, bucket_default_write_sse, build_ssec_read_headers, EncryptionKeyKind, bucket_default_write_sse, build_ssec_read_headers, encryption_material_to_metadata,
encryption_material_to_metadata, extract_ssec_params_from_headers, extract_ssekms_context_from_headers, extract_ssec_params_from_headers, extract_ssekms_context_from_headers, map_get_object_reader_error,
map_get_object_reader_error, mark_encrypted_multipart_metadata, multipart_completion_authorization, stored_ssec_metadata, mark_encrypted_multipart_metadata, multipart_completion_authorization, stored_ssec_metadata,
}; };
} }
@@ -1778,7 +1773,7 @@ pub(crate) mod bucket_usecase {
} }
} }
pub(crate) use super::{access, bucket, error, helper, object_utils, request_context, s3, s3_api, sse}; pub(crate) use super::{access, bucket, error, helper, request_context, s3, s3_api, sse};
pub(crate) use crate::storage::storage_api::{ pub(crate) use crate::storage::storage_api::{
ECStore, StorageObjectInfo, StorageObjectOptions, get_validated_store, validate_list_object_unordered_with_delimiter, ECStore, StorageObjectInfo, StorageObjectOptions, get_validated_store, validate_list_object_unordered_with_delimiter,
validate_website_configuration, validate_website_configuration,
@@ -1844,8 +1839,6 @@ pub(crate) mod object_usecase {
} }
} }
#[cfg(test)]
pub(crate) use super::object_utils;
pub(crate) use super::{ pub(crate) use super::{
access, bucket, compression, concurrency, data_usage, deadlock_detector, error, head_prefix, helper, io, options, access, bucket, compression, concurrency, data_usage, deadlock_detector, error, head_prefix, helper, io, options,
request_context, s3_api, set_disk, sse, storage_class, timeout_wrapper, request_context, s3_api, set_disk, sse, storage_class, timeout_wrapper,
@@ -1910,8 +1903,6 @@ pub(crate) mod multipart_usecase {
} }
} }
#[cfg(test)]
pub(crate) use super::object_utils;
pub(crate) use super::{ pub(crate) use super::{
access, bucket, compression, data_usage, error, helper, io, options, request_context, s3_api, set_disk, sse, access, bucket, compression, data_usage, error, helper, io, options, request_context, s3_api, set_disk, sse,
}; };
@@ -2012,7 +2003,7 @@ pub(crate) mod test {
RecordingKmsKeyAuthorizer, TestAuthorizationHooks, sse_kms_object_metadata, RecordingKmsKeyAuthorizer, TestAuthorizationHooks, sse_kms_object_metadata,
}; };
} }
pub(crate) use super::{bucket, object_utils, runtime}; pub(crate) use super::{bucket, runtime};
pub(crate) mod data_usage { pub(crate) mod data_usage {
pub(crate) use super::super::data_usage::*; pub(crate) use super::super::data_usage::*;
} }
+3 -3
View File
@@ -18,8 +18,8 @@ use crate::app::storage_api::bucket_usecase::access::{
use crate::app::storage_api::bucket_usecase::contract::list::{ListObjectVersionsInfo, ListObjectsV2Info, ListOperations as _}; use crate::app::storage_api::bucket_usecase::contract::list::{ListObjectVersionsInfo, ListObjectsV2Info, ListOperations as _};
use crate::app::storage_api::bucket_usecase::{ECStore, StorageObjectInfo as ObjectInfo}; use crate::app::storage_api::bucket_usecase::{ECStore, StorageObjectInfo as ObjectInfo};
use crate::app::storage_api::multipart_usecase::contract::multipart::{ListMultipartsInfo, MultipartInfo}; use crate::app::storage_api::multipart_usecase::contract::multipart::{ListMultipartsInfo, MultipartInfo};
use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Result};
use crate::error::ApiError; use crate::error::ApiError;
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result};
use std::collections::HashSet; use std::collections::HashSet;
use std::sync::Arc; use std::sync::Arc;
use uuid::Uuid; use uuid::Uuid;
@@ -70,12 +70,12 @@ pub(crate) struct ListMultipartUploadsRequest<'a> {
fn table_list_scan_limit_error() -> S3Error { fn table_list_scan_limit_error() -> S3Error {
S3Error::with_message( S3Error::with_message(
S3ErrorCode::SlowDown, S3ErrorCode::SlowDown,
"Table listing exceeded the protected scan limit; retry with a narrower prefix".to_string(), "Table listing exceeded the protected scan limit; retry with a narrower prefix",
) )
} }
fn invalid_table_list_cursor() -> S3Error { fn invalid_table_list_cursor() -> S3Error {
S3Error::with_message(S3ErrorCode::InvalidArgument, "Invalid table listing continuation token".to_string()) S3Error::with_message(S3ErrorCode::InvalidArgument, "Invalid table listing continuation token")
} }
fn list_objects_v2_operation(incl_deleted: bool) -> &'static str { fn list_objects_v2_operation(incl_deleted: bool) -> &'static str {
+42 -40
View File
@@ -12,55 +12,57 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use crate::app::object::GetObjectBody;
use crate::app::object_usecase::DefaultObjectUsecase; use crate::app::object_usecase::DefaultObjectUsecase;
use crate::app::storage_api::s3::{GetObjectInput, GetObjectOutput, S3Request, S3Response, S3Result};
/// Calls `DefaultObjectUsecase::execute_get_object` with today's arguments. pub(crate) fn get_envelope(headers: http::HeaderMap, extensions: http::Extensions) -> crate::app::RequestEnvelope {
/// crate::app::RequestEnvelope::from_parts(
/// Owned by the GetObject batch (C). Tests outside that batch's files call this seam instead of the use-case method;
/// when batch C changes the use-case signature it changes only this body.
pub(crate) async fn get_object(
usecase: &DefaultObjectUsecase,
req: S3Request<GetObjectInput>,
) -> S3Result<S3Response<GetObjectOutput>> {
use crate::app::object_usecase::GetObjectFields;
use crate::app::{Answered, RequestEnvelope};
rustfs_io_metrics::record_s3_op(rustfs_s3_ops::S3Operation::GetObject);
let envelope = RequestEnvelope::from_s3s(&req);
let Answered { output, status, headers } = get_object_fields(usecase, envelope, GetObjectFields::from_s3s(req.input)).await?;
let mut response = S3Response::new(output.into_s3s().map_err(crate::app::dto_values::seam_error)?);
response.status = status;
response.headers = headers;
Ok(response)
}
/// [`get_object`] for a fixture that sets nothing but `GET /`.
///
/// `build_request` leaves the URI, headers, and extensions empty, so this envelope matches that request.
#[cfg(test)]
pub(crate) async fn get_object_method_only(
usecase: &DefaultObjectUsecase,
input: GetObjectInput,
) -> S3Result<S3Response<GetObjectOutput>> {
use crate::app::object_usecase::GetObjectFields;
use crate::app::{Answered, RequestEnvelope};
rustfs_io_metrics::record_s3_op(rustfs_s3_ops::S3Operation::GetObject);
let envelope = RequestEnvelope::from_parts(
crate::app::RequestHead { crate::app::RequestHead {
method: http::Method::GET, method: http::Method::GET,
uri: http::Uri::from_static("/"), uri: http::Uri::from_static("/"),
headers: http::HeaderMap::new(), headers,
credentials: None, credentials: None,
region: None, region: None,
service: None, service: None,
}, },
http::Extensions::new(), extensions,
); )
let Answered { output, status, headers } = get_object_fields(usecase, envelope, GetObjectFields::from_s3s(input)).await?; }
let mut response = S3Response::new(output.into_s3s().map_err(crate::app::dto_values::seam_error)?);
response.status = status; pub(crate) fn get_object_input(bucket: &str, key: &str, version_id: Option<String>) -> rustfs_gateway_types::dto::GetObjectInput {
response.headers = headers; rustfs_gateway_types::dto::GetObjectInput {
Ok(response) bucket: rustfs_gateway_types::BucketName::new(bucket).expect("test bucket name"),
key: rustfs_gateway_types::ObjectKey::new(key).expect("test object key"),
version_id,
..Default::default()
}
}
pub(crate) async fn get_object_gateway(
usecase: &DefaultObjectUsecase,
envelope: crate::app::RequestEnvelope,
input: rustfs_gateway_types::dto::GetObjectInput,
) -> rustfs_s3_types::S3Result<crate::app::Answered<crate::app::object_usecase::GetObjectOutputFacts>> {
rustfs_io_metrics::record_s3_op(rustfs_s3_ops::S3Operation::GetObject);
get_object_fields(usecase, envelope, input.into()).await
}
pub(crate) fn get_http_body(body: GetObjectBody) -> rustfs_gateway_stream::Body {
use rustfs_gateway_stream::Body;
match body {
GetObjectBody::Bytes(bytes) => Body::from_bytes(bytes),
GetObjectBody::Stream(stream) => Body::from_stream(stream).expect("valid GET stream"),
}
}
/// Reads a successful GET body to completion where the caller verifies its bytes.
pub(crate) async fn read_get_body(body: GetObjectBody) -> bytes::Bytes {
use http_body_util::BodyExt;
let collected = get_http_body(body).collect().await.expect("GET body must be readable");
assert!(collected.trailers().is_none(), "unexpected GET response trailers");
collected.to_bytes()
} }
/// Calls `DefaultObjectUsecase::execute_get_object_fields` with owned inputs. /// Calls `DefaultObjectUsecase::execute_get_object_fields` with owned inputs.
+3 -3
View File
@@ -23,9 +23,9 @@ mod head_object;
mod list_objects_v2; mod list_objects_v2;
mod put_object; mod put_object;
#[cfg(test)] pub(crate) use get_object::{
pub(crate) use get_object::get_object_method_only; get_envelope, get_http_body, get_object_fields, get_object_gateway, get_object_input, read_get_body,
pub(crate) use get_object::{get_object, get_object_fields}; };
pub(crate) use head_object::{head_envelope, head_object_fields, head_object_gateway, head_object_input}; pub(crate) use head_object::{head_envelope, head_object_fields, head_object_gateway, head_object_input};
#[cfg(test)] #[cfg(test)]
pub(crate) use list_objects_v2::list_objects_v2_method_only; pub(crate) use list_objects_v2::list_objects_v2_method_only;
+99 -117
View File
@@ -25,6 +25,7 @@ use rustfs_iam::sys::{
}; };
use rustfs_policy::policy::action::Action; use rustfs_policy::policy::action::Action;
use rustfs_policy::policy::{ClaimLookup, get_claim_case_insensitive}; use rustfs_policy::policy::{ClaimLookup, get_claim_case_insensitive};
use rustfs_s3_types::{S3Result as OwnedResult, s3_error as owned_error};
use rustfs_trusted_proxies::ClientInfo; use rustfs_trusted_proxies::ClientInfo;
use rustfs_utils::MaskedAccessKey; use rustfs_utils::MaskedAccessKey;
use rustfs_utils::http::metadata_compat::starts_with_ignore_ascii_case; use rustfs_utils::http::metadata_compat::starts_with_ignore_ascii_case;
@@ -33,7 +34,6 @@ use s3s::S3ErrorCode;
use s3s::S3Result; use s3s::S3Result;
use s3s::auth::S3Auth; use s3s::auth::S3Auth;
use s3s::auth::SecretKey; use s3s::auth::SecretKey;
use s3s::auth::SimpleAuth;
use s3s::s3_error; use s3s::s3_error;
use serde_json::Value; use serde_json::Value;
use std::collections::HashMap; use std::collections::HashMap;
@@ -131,33 +131,18 @@ pub enum AuthType {
StreamingUnsignedTrailer, StreamingUnsignedTrailer,
} }
#[derive(Clone)]
pub struct IAMAuth { pub struct IAMAuth {
simple_auth: SimpleAuth,
access_key: String, access_key: String,
secret_key: SecretKey, secret_key: SecretKey,
server_ctx: Option<std::sync::Arc<ServerContextSlot>>, server_ctx: Option<std::sync::Arc<ServerContextSlot>>,
} }
impl Clone for IAMAuth {
fn clone(&self) -> Self {
Self {
simple_auth: SimpleAuth::from_single(self.access_key.clone(), self.secret_key.clone()),
access_key: self.access_key.clone(),
secret_key: self.secret_key.clone(),
server_ctx: self.server_ctx.clone(),
}
}
}
impl IAMAuth { impl IAMAuth {
pub fn new(ak: impl Into<String>, sk: impl Into<SecretKey>) -> Self { pub fn new(ak: impl Into<String>, sk: impl Into<SecretKey>) -> Self {
let access_key = ak.into();
let secret_key = sk.into();
let simple_auth = SimpleAuth::from_single(access_key.clone(), secret_key.clone());
Self { Self {
simple_auth, access_key: ak.into(),
access_key, secret_key: sk.into(),
secret_key,
server_ctx: None, server_ctx: None,
} }
} }
@@ -206,10 +191,6 @@ impl S3Auth for IAMAuth {
return Ok(self.secret_key.clone()); return Ok(self.secret_key.clone());
} }
if let Ok(key) = self.simple_auth.get_secret_key(access_key).await {
return Ok(key);
}
let iam_store = match &self.server_ctx { let iam_store = match &self.server_ctx {
Some(server_ctx) => server_ctx Some(server_ctx) => server_ctx
.installed_app_context() .installed_app_context()
@@ -1014,8 +995,8 @@ const SIGV4_UNSIGNED_ENVELOPE_HEADERS: &[&str] = &[
/// ///
/// Every signed-header list the request carries must cover every `x-amz-*` /// Every signed-header list the request carries must cover every `x-amz-*`
/// header, so an `Authorization` header can never widen a presigned URL and a /// header, so an `Authorization` header can never widen a presigned URL and a
/// query can never widen a header signature. The header is parsed with the /// query can never widen a header signature. The gateway reads the verifier's
/// verifier's own parser so both sides read the same `SignedHeaders` list, and /// header grammar so both sides see the same `SignedHeaders` list, and
/// the algorithm token is pinned because the verifier accepts any token there. /// the algorithm token is pinned because the verifier accepts any token there.
/// A header the parser rejects never authenticates as SigV4 upstream, but one /// A header the parser rejects never authenticates as SigV4 upstream, but one
/// that claims the SigV4 algorithm still fails closed here. SigV2 signs every /// that claims the SigV4 algorithm still fails closed here. SigV2 signs every
@@ -1027,17 +1008,17 @@ pub(crate) fn reject_unsigned_amz_headers_on_sigv4_request(header: &HeaderMap, q
let Ok(value) = value.to_str() else { let Ok(value) = value.to_str() else {
continue; continue;
}; };
let authorization = match s3s_sigv4::AuthorizationV4::parse(value) { let authorization = match rustfs_gateway::sig::SigV4HeaderCoverage::parse(value) {
Ok(authorization) => authorization, Some(authorization) => authorization,
Err(_) if value.starts_with(SIGN_V4_ALGORITHM) => { None if value.starts_with(SIGN_V4_ALGORITHM) => {
return Err(S3Error::with_message( return Err(S3Error::with_message(
S3ErrorCode::AccessDenied, S3ErrorCode::AccessDenied,
"Invalid SigV4 authorization header".to_owned(), "Invalid SigV4 authorization header".to_owned(),
)); ));
} }
Err(_) => continue, None => continue,
}; };
if authorization.algorithm != SIGN_V4_ALGORITHM { if authorization.algorithm() != SIGN_V4_ALGORITHM {
warn!( warn!(
event = EVENT_SIGV4_UNSUPPORTED_ALGORITHM, event = EVENT_SIGV4_UNSUPPORTED_ALGORITHM,
component = LOG_COMPONENT_AUTH, component = LOG_COMPONENT_AUTH,
@@ -1057,10 +1038,7 @@ pub(crate) fn reject_unsigned_amz_headers_on_sigv4_request(header: &HeaderMap, q
if !name.starts_with("x-amz-") if !name.starts_with("x-amz-")
|| SIGV4_UNSIGNED_ENVELOPE_HEADERS.contains(&name) || SIGV4_UNSIGNED_ENVELOPE_HEADERS.contains(&name)
|| PRESIGNED_UNSIGNED_AMZ_HEADER_ALLOWLIST.contains(&name) || PRESIGNED_UNSIGNED_AMZ_HEADER_ALLOWLIST.contains(&name)
|| authorization || authorization.covers_header(name)
.signed_headers
.iter()
.any(|signed_name| signed_name.eq_ignore_ascii_case(name))
{ {
continue; continue;
} }
@@ -1207,7 +1185,7 @@ pub(crate) fn parse_presigned_put_max_content_length(
header: &HeaderMap, header: &HeaderMap,
query: Option<&str>, query: Option<&str>,
verified_presigned: bool, verified_presigned: bool,
) -> S3Result<Option<u64>> { ) -> OwnedResult<Option<u64>> {
let Some(query) = query else { let Some(query) = query else {
return Ok(None); return Ok(None);
}; };
@@ -1218,16 +1196,13 @@ pub(crate) fn parse_presigned_put_max_content_length(
decoded_query.push((name.to_string(), candidate.to_string())); decoded_query.push((name.to_string(), candidate.to_string()));
if name == RUSTFS_MAX_CONTENT_LENGTH_QUERY { if name == RUSTFS_MAX_CONTENT_LENGTH_QUERY {
if value.is_some() { if value.is_some() {
return Err(S3Error::with_message( return Err(owned_error!(InvalidRequest, "{RUSTFS_MAX_CONTENT_LENGTH_QUERY} must appear exactly once"));
S3ErrorCode::InvalidRequest,
format!("{RUSTFS_MAX_CONTENT_LENGTH_QUERY} must appear exactly once"),
));
} }
value = Some(candidate.into_owned()); value = Some(candidate.into_owned());
} else if name.eq_ignore_ascii_case(RUSTFS_MAX_CONTENT_LENGTH_QUERY) { } else if name.eq_ignore_ascii_case(RUSTFS_MAX_CONTENT_LENGTH_QUERY) {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("query parameter name must be exactly {RUSTFS_MAX_CONTENT_LENGTH_QUERY}"), "query parameter name must be exactly {RUSTFS_MAX_CONTENT_LENGTH_QUERY}"
)); ));
} }
} }
@@ -1258,18 +1233,15 @@ pub(crate) fn parse_presigned_put_max_content_length(
|| !is_complete_sigv4_query || !is_complete_sigv4_query
|| !matches!(get_request_auth_type_with_query(header, Some(query)), AuthType::Presigned) || !matches!(get_request_auth_type_with_query(header, Some(query)), AuthType::Presigned)
{ {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("{RUSTFS_MAX_CONTENT_LENGTH_QUERY} requires a SigV4 presigned request"), "{RUSTFS_MAX_CONTENT_LENGTH_QUERY} requires a SigV4 presigned request"
)); ));
} }
let limit = value.parse::<u64>().map_err(|_| { let limit = value
S3Error::with_message( .parse::<u64>()
S3ErrorCode::InvalidRequest, .map_err(|_| owned_error!(InvalidRequest, "{RUSTFS_MAX_CONTENT_LENGTH_QUERY} must be a non-negative 64-bit integer"))?;
format!("{RUSTFS_MAX_CONTENT_LENGTH_QUERY} must be a non-negative 64-bit integer"),
)
})?;
Ok(Some(limit)) Ok(Some(limit))
} }
@@ -1280,11 +1252,11 @@ pub(crate) fn reject_presigned_put_max_content_length_for_other_operation(
header: &HeaderMap, header: &HeaderMap,
query: Option<&str>, query: Option<&str>,
verified_presigned: bool, verified_presigned: bool,
) -> S3Result<()> { ) -> OwnedResult<()> {
if parse_presigned_put_max_content_length(header, query, verified_presigned)?.is_some() { if parse_presigned_put_max_content_length(header, query, verified_presigned)?.is_some() {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("{RUSTFS_MAX_CONTENT_LENGTH_QUERY} is only supported for presigned PutObject"), "{RUSTFS_MAX_CONTENT_LENGTH_QUERY} is only supported for presigned PutObject"
)); ));
} }
Ok(()) Ok(())
@@ -1298,7 +1270,7 @@ pub(crate) fn parse_presigned_multipart_max_total_object_size(
header: &HeaderMap, header: &HeaderMap,
query: Option<&str>, query: Option<&str>,
verified_sigv4: bool, verified_sigv4: bool,
) -> S3Result<Option<u64>> { ) -> OwnedResult<Option<u64>> {
let Some(query) = query else { let Some(query) = query else {
return Ok(None); return Ok(None);
}; };
@@ -1309,16 +1281,16 @@ pub(crate) fn parse_presigned_multipart_max_total_object_size(
decoded_query.push((name.to_string(), candidate.to_string())); decoded_query.push((name.to_string(), candidate.to_string()));
if name == RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY { if name == RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY {
if value.is_some() { if value.is_some() {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} must appear exactly once"), "{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} must appear exactly once"
)); ));
} }
value = Some(candidate.into_owned()); value = Some(candidate.into_owned());
} else if name.eq_ignore_ascii_case(RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY) { } else if name.eq_ignore_ascii_case(RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY) {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("query parameter name must be exactly {RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY}"), "query parameter name must be exactly {RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY}"
)); ));
} }
} }
@@ -1348,16 +1320,16 @@ pub(crate) fn parse_presigned_multipart_max_total_object_size(
let authenticated = verified_sigv4 && (is_header_signed || (is_presigned && complete_presigned_query)); let authenticated = verified_sigv4 && (is_header_signed || (is_presigned && complete_presigned_query));
if !authenticated { if !authenticated {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} requires a verified SigV4 request"), "{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} requires a verified SigV4 request"
)); ));
} }
value.parse::<u64>().map(Some).map_err(|_| { value.parse::<u64>().map(Some).map_err(|_| {
S3Error::with_message( owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} must be a non-negative 64-bit integer"), "{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} must be a non-negative 64-bit integer"
) )
}) })
} }
@@ -1366,11 +1338,11 @@ pub(crate) fn reject_presigned_multipart_max_total_object_size_for_other_operati
header: &HeaderMap, header: &HeaderMap,
query: Option<&str>, query: Option<&str>,
verified_sigv4: bool, verified_sigv4: bool,
) -> S3Result<()> { ) -> OwnedResult<()> {
if parse_presigned_multipart_max_total_object_size(header, query, verified_sigv4)?.is_some() { if parse_presigned_multipart_max_total_object_size(header, query, verified_sigv4)?.is_some() {
return Err(S3Error::with_message( return Err(owned_error!(
S3ErrorCode::InvalidRequest, InvalidRequest,
format!("{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} is only supported for CreateMultipartUpload"), "{RUSTFS_MAX_TOTAL_OBJECT_SIZE_QUERY} is only supported for CreateMultipartUpload"
)); ));
} }
Ok(()) Ok(())
@@ -1544,8 +1516,8 @@ mod tests {
let iam_auth = IAMAuth::new("test-ak", SecretKey::from("test-sk")); let iam_auth = IAMAuth::new("test-ak", SecretKey::from("test-sk"));
let cloned = iam_auth.clone(); let cloned = iam_auth.clone();
let secret = cloned.get_secret_key("test-ak").await; let secret = cloned.get_secret_key("test-ak").await.expect("cloned root credentials");
assert!(secret.is_ok()); assert_eq!(secret.expose(), "test-sk");
} }
#[tokio::test] #[tokio::test]
@@ -2446,6 +2418,12 @@ mod tests {
assert_eq!(result, Some("value=with=equals")); assert_eq!(result, Some("value=with=equals"));
} }
fn assert_invalid_capability(error: rustfs_s3_types::S3Error, message: &str) {
assert_eq!(error.code(), &rustfs_s3_types::S3ErrorCode::InvalidRequest);
assert_eq!(error.status_code(), Some(http::StatusCode::BAD_REQUEST));
assert_eq!(error.message(), Some(message));
}
#[test] #[test]
fn presigned_put_max_content_length_requires_exactly_one_signed_query_value() { fn presigned_put_max_content_length_requires_exactly_one_signed_query_value() {
let headers = HeaderMap::new(); let headers = HeaderMap::new();
@@ -2464,26 +2442,25 @@ mod tests {
); );
let duplicate = format!("{query}&x-rustfs-max-content-length=1"); let duplicate = format!("{query}&x-rustfs-max-content-length=1");
assert_eq!( assert_invalid_capability(
parse_presigned_put_max_content_length(&headers, Some(&duplicate), true) parse_presigned_put_max_content_length(&headers, Some(&duplicate), true).unwrap_err(),
.unwrap_err() "x-rustfs-max-content-length must appear exactly once",
.code(),
&S3ErrorCode::InvalidRequest
); );
let wrong_case = format!("{signed_prefix}&X-RustFS-Max-Content-Length=1"); let wrong_case = format!("{signed_prefix}&X-RustFS-Max-Content-Length=1");
assert_eq!( assert_invalid_capability(
parse_presigned_put_max_content_length(&headers, Some(&wrong_case), true) parse_presigned_put_max_content_length(&headers, Some(&wrong_case), true).unwrap_err(),
.unwrap_err() "query parameter name must be exactly x-rustfs-max-content-length",
.code(),
&S3ErrorCode::InvalidRequest
); );
assert_eq!( assert_invalid_capability(
reject_presigned_put_max_content_length_for_other_operation(&headers, Some(&query), true) reject_presigned_put_max_content_length_for_other_operation(&headers, Some(&query), true).unwrap_err(),
.unwrap_err() "x-rustfs-max-content-length is only supported for presigned PutObject",
.code(), );
&S3ErrorCode::InvalidRequest let overflow = format!("{signed_prefix}&x-rustfs-max-content-length=18446744073709551616");
assert_invalid_capability(
parse_presigned_put_max_content_length(&headers, Some(&overflow), true).unwrap_err(),
"x-rustfs-max-content-length must be a non-negative 64-bit integer",
); );
} }
@@ -2752,11 +2729,9 @@ mod tests {
fn presigned_put_max_content_length_rejects_unsigned_or_invalid_values() { fn presigned_put_max_content_length_rejects_unsigned_or_invalid_values() {
let headers = HeaderMap::new(); let headers = HeaderMap::new();
let forged = "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=test/credential&X-Amz-Signature=fake&x-rustfs-max-content-length=1"; let forged = "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=test/credential&X-Amz-Signature=fake&x-rustfs-max-content-length=1";
assert_eq!( assert_invalid_capability(
parse_presigned_put_max_content_length(&headers, Some(forged), false) parse_presigned_put_max_content_length(&headers, Some(forged), false).unwrap_err(),
.unwrap_err() "x-rustfs-max-content-length requires a SigV4 presigned request",
.code(),
&S3ErrorCode::InvalidRequest
); );
for query in [ for query in [
"x-rustfs-max-content-length=1", "x-rustfs-max-content-length=1",
@@ -2764,7 +2739,7 @@ mod tests {
"X-Amz-Credential=test/credential&x-rustfs-max-content-length=18446744073709551616", "X-Amz-Credential=test/credential&x-rustfs-max-content-length=18446744073709551616",
] { ] {
let error = parse_presigned_put_max_content_length(&headers, Some(query), true).unwrap_err(); let error = parse_presigned_put_max_content_length(&headers, Some(query), true).unwrap_err();
assert_eq!(error.code(), &S3ErrorCode::InvalidRequest); assert_invalid_capability(error, "x-rustfs-max-content-length requires a SigV4 presigned request");
} }
} }
@@ -2778,11 +2753,14 @@ mod tests {
parse_presigned_multipart_max_total_object_size(&headers, Some(&query), true).unwrap(), parse_presigned_multipart_max_total_object_size(&headers, Some(&query), true).unwrap(),
Some(104_857_600) Some(104_857_600)
); );
assert_eq!( assert_invalid_capability(
reject_presigned_multipart_max_total_object_size_for_other_operation(&headers, Some(&query), true) reject_presigned_multipart_max_total_object_size_for_other_operation(&headers, Some(&query), true).unwrap_err(),
.unwrap_err() "x-rustfs-max-total-object-size is only supported for CreateMultipartUpload",
.code(), );
&S3ErrorCode::InvalidRequest let overflow = format!("{signed_prefix}&x-rustfs-max-total-object-size=18446744073709551616");
assert_invalid_capability(
parse_presigned_multipart_max_total_object_size(&headers, Some(&overflow), true).unwrap_err(),
"x-rustfs-max-total-object-size must be a non-negative 64-bit integer",
); );
} }
@@ -2790,27 +2768,31 @@ mod tests {
fn multipart_max_total_object_size_rejects_tampering_and_invalid_values() { fn multipart_max_total_object_size_rejects_tampering_and_invalid_values() {
let headers = HeaderMap::new(); let headers = HeaderMap::new();
let signed_prefix = "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=test/20260827/us-east-1/s3/aws4_request&X-Amz-Signature=signature"; let signed_prefix = "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=test/20260827/us-east-1/s3/aws4_request&X-Amz-Signature=signature";
for query in [ let auth_message = "x-rustfs-max-total-object-size requires a verified SigV4 request";
"x-rustfs-max-total-object-size=1", for (query, message) in [
"X-RustFS-Max-Total-Object-Size=1", ("x-rustfs-max-total-object-size=1", auth_message),
"X-Amz-Algorithm=AWS4-HMAC-SHA256&x-rustfs-max-total-object-size=1&x-rustfs-max-total-object-size=2", (
"X-Amz-Algorithm=AWS4-HMAC-SHA256&x-rustfs-max-total-object-size=-1", "X-RustFS-Max-Total-Object-Size=1",
"X-Amz-Algorithm=AWS4-HMAC-SHA256&x-rustfs-max-total-object-size=18446744073709551616", "query parameter name must be exactly x-rustfs-max-total-object-size",
),
(
"X-Amz-Algorithm=AWS4-HMAC-SHA256&x-rustfs-max-total-object-size=1&x-rustfs-max-total-object-size=2",
"x-rustfs-max-total-object-size must appear exactly once",
),
("X-Amz-Algorithm=AWS4-HMAC-SHA256&x-rustfs-max-total-object-size=-1", auth_message),
(
"X-Amz-Algorithm=AWS4-HMAC-SHA256&x-rustfs-max-total-object-size=18446744073709551616",
auth_message,
),
] { ] {
assert_eq!( let error = parse_presigned_multipart_max_total_object_size(&headers, Some(query), true).unwrap_err();
parse_presigned_multipart_max_total_object_size(&headers, Some(query), true) assert_invalid_capability(error, message);
.unwrap_err()
.code(),
&S3ErrorCode::InvalidRequest
);
} }
let forged = format!("{signed_prefix}&x-rustfs-max-total-object-size=1"); let forged = format!("{signed_prefix}&x-rustfs-max-total-object-size=1");
assert_eq!( assert_invalid_capability(
parse_presigned_multipart_max_total_object_size(&headers, Some(&forged), false) parse_presigned_multipart_max_total_object_size(&headers, Some(&forged), false).unwrap_err(),
.unwrap_err() "x-rustfs-max-total-object-size requires a verified SigV4 request",
.code(),
&S3ErrorCode::InvalidRequest
); );
} }
+72 -13
View File
@@ -18,7 +18,6 @@ use http::StatusCode;
use rustfs_kms::KmsUnavailableError; use rustfs_kms::KmsUnavailableError;
use rustfs_lock::LockError; use rustfs_lock::LockError;
use rustfs_s3_types::S3ErrorCode; use rustfs_s3_types::S3ErrorCode;
use rustfs_sse::{SseError, data_plane_kms_error};
use s3s::S3Error as LegacyS3Error; use s3s::S3Error as LegacyS3Error;
use s3s::stream::{aws_chunked_stream::AwsChunkedStreamError, upload_stream::UploadStreamError}; use s3s::stream::{aws_chunked_stream::AwsChunkedStreamError, upload_stream::UploadStreamError};
@@ -52,7 +51,7 @@ pub(crate) fn rpc_replay_admission_exhausted_status() -> tonic::Status {
const UNSUPPORTED_PARTICIPANT_MESSAGE: &str = "A storage participant does not support this operation's protocol version. If the cluster is being upgraded, finish upgrading every node and retry."; 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. /// S3 error code for a request that names a KMS key the KMS does not hold.
pub use rustfs_sse::KMS_KEY_NOT_FOUND_ERROR_CODE; pub const KMS_KEY_NOT_FOUND_ERROR_CODE: &str = "KMS.NotFoundException";
fn lock_resource_class(resource: Option<&str>) -> &'static str { fn lock_resource_class(resource: Option<&str>) -> &'static str {
let Some(resource) = resource else { let Some(resource) = resource else {
@@ -123,6 +122,77 @@ fn record_s3_lock_failure(err: &StorageError) {
} }
} }
/// Map a KMS failure that surfaced on the S3 data path to its S3 error code.
///
/// The contract deliberately differs from the admin lifecycle handlers
/// (`kms_key_lifecycle::lifecycle_error_status`): there a key id is the
/// resource being addressed, so a missing key is `404`. Here the key id
/// arrives inside a request header or a bucket default, so a key that is
/// missing, disabled, or otherwise unusable is configuration the caller has to
/// correct — AWS answers `400`, and reporting `500` instead both misfiles the
/// failure as a server fault and makes SDKs back off and retry a request that
/// cannot succeed.
///
/// `None` keeps the caller's fallthrough, which is the `500` that integrity
/// faults — damaged, unreadable, or unknown-format key material — must keep.
///
/// Messages either name what the caller asked for or stay generic; detail that
/// belongs to the deployment rather than the request stays in `source`, which
/// the caller attaches and the logs retain.
fn data_plane_kms_error(error: &rustfs_kms::KmsError) -> Option<(S3ErrorCode, String)> {
use rustfs_kms::KmsError as Kms;
let generic = |code: S3ErrorCode| {
let message = ApiError::error_code_to_message(&code);
Some((code, message))
};
match error {
Kms::KeyNotFound { key_id } => Some((
S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into()),
format!("KMS key not found: {key_id}"),
)),
Kms::KeyVersionNotFound { key_id, version } => Some((
S3ErrorCode::Custom(KMS_KEY_NOT_FOUND_ERROR_CODE.into()),
format!("KMS key version {version} not found for key {key_id}"),
)),
// The key exists but its state forbids the operation (disabled,
// pending deletion). AWS treats an invalid key state as a request
// error, not a server fault.
Kms::InvalidOperation { .. } => Some((S3ErrorCode::InvalidRequest, error.to_string())),
// A policy decision needs a human, so it must be distinguishable from
// the transient classes an SDK retries.
Kms::AccessDenied { .. } => generic(S3ErrorCode::AccessDenied),
// Request-side faults: what was asked for cannot be served as asked.
Kms::ContextMismatch { .. }
| Kms::InvalidKey { .. }
| Kms::ValidationError { .. }
| Kms::UnsupportedAlgorithm { .. }
| Kms::InvalidKeySize { .. } => Some((S3ErrorCode::InvalidRequest, error.to_string())),
// A deployment whose KMS configuration cannot serve the request (for
// example no key named and no default). Actionable, but the detail
// describes the deployment, so it stays out of the response body.
Kms::ConfigurationError { .. } => {
Some((S3ErrorCode::InvalidRequest, "The KMS configuration cannot serve this request".to_string()))
}
// Transient: worth retrying, and must be counted against availability
// rather than against the caller. `IoError` belongs here because it is
// how a backend reports that its key store itself was unreachable —
// rustfs/rustfs#7470 separated that from a missing key precisely so the
// two stop looking alike, and leaving it on the 500 fallthrough would
// erase that distinction again at the S3 boundary.
Kms::BackendError { .. }
| Kms::IoError { .. }
| Kms::OperationTimedOut { .. }
| Kms::OperationCancelled { .. }
| Kms::CredentialsUnavailable { .. }
| Kms::CacheError { .. } => generic(S3ErrorCode::ServiceUnavailable),
// A permanent gap in the configured backend, never a missing resource.
Kms::UnsupportedCapability { .. } => Some((S3ErrorCode::NotImplemented, error.to_string())),
_ => None,
}
}
/// HTTP status of the error codes s3s cannot derive on its own. /// HTTP status of the error codes s3s cannot derive on its own.
/// ///
/// s3s answers `None` for every `Custom` code, which the response layer turns /// s3s answers `None` for every `Custom` code, which the response layer turns
@@ -697,17 +767,6 @@ impl From<crate::table_catalog::TableCatalogStoreError> for ApiError {
} }
} }
/// An SSE failure arrives already classified for the S3 data path; carry it over as is.
impl From<SseError> for ApiError {
fn from(err: SseError) -> Self {
ApiError {
code: err.code,
message: err.message,
source: err.source,
}
}
}
impl From<StorageError> for ApiError { impl From<StorageError> for ApiError {
fn from(err: StorageError) -> Self { fn from(err: StorageError) -> Self {
record_s3_lock_failure(&err); record_s3_lock_failure(&err);
+2 -4
View File
@@ -25,7 +25,7 @@ use crate::storage_api::startup::init::{
use crate::storage_api::startup::services::ECStore; use crate::storage_api::startup::services::ECStore;
#[cfg(any(feature = "ftps", feature = "webdav", feature = "sftp"))] #[cfg(any(feature = "ftps", feature = "webdav", feature = "sftp"))]
use crate::storage_api::startup::services::ServerContextSlot; use crate::storage_api::startup::services::ServerContextSlot;
use crate::storage_api::startup::sse::init_sse_startup; use crate::storage_api::startup::sse::log_sse_kms_key_policy_mode;
use crate::{admin, config, startup_runtime_sources, version}; use crate::{admin, config, startup_runtime_sources, version};
use rustfs_config::{ use rustfs_config::{
DEFAULT_BUFFER_MAX_SIZE, DEFAULT_BUFFER_MIN_SIZE, DEFAULT_BUFFER_PROFILE, DEFAULT_BUFFER_UNKNOWN_SIZE, DEFAULT_UPDATE_CHECK, DEFAULT_BUFFER_MAX_SIZE, DEFAULT_BUFFER_MIN_SIZE, DEFAULT_BUFFER_PROFILE, DEFAULT_BUFFER_UNKNOWN_SIZE, DEFAULT_UPDATE_CHECK,
@@ -539,9 +539,7 @@ pub async fn init_kms_system(config: &config::Config, store: Arc<ECStore>) -> st
// Initialize global KMS service manager (starts in NotConfigured state) // Initialize global KMS service manager (starts in NotConfigured state)
let service_manager = startup_runtime_sources::init_kms_service_manager(); let service_manager = startup_runtime_sources::init_kms_service_manager();
// Settles what SSE reads from the environment. Idempotent, so a second log_sse_kms_key_policy_mode();
// embedded server in this process reports nothing new.
init_sse_startup();
// A key referenced by any bucket's encryption configuration must never be // A key referenced by any bucket's encryption configuration must never be
// deleted. Register the gate before the service can start so every // deleted. Register the gate before the service can start so every
+33 -7
View File
@@ -1609,6 +1609,8 @@ mod tests {
#[test] #[test]
fn protocol_mainflow_retention_timestamp_matches_legacy_precision() { fn protocol_mainflow_retention_timestamp_matches_legacy_precision() {
use crate::app::object_usecase::{GetObjectOutputFacts, HeadObjectOutputFacts}; use crate::app::object_usecase::{GetObjectOutputFacts, HeadObjectOutputFacts};
use gateway_s3s_compat::generated::ops::{get_object, head_object};
let instant = rustfs_gateway_types::Timestamp::from_secs_nanos(1_700_000_000, 123_456_789).expect("test timestamp"); let instant = rustfs_gateway_types::Timestamp::from_secs_nanos(1_700_000_000, 123_456_789).expect("test timestamp");
let get = || GetObjectOutputFacts { let get = || GetObjectOutputFacts {
dto: gateway_dto::GetObjectOutput { dto: gateway_dto::GetObjectOutput {
@@ -1624,12 +1626,10 @@ mod tests {
}, },
etag: None, etag: None,
}; };
let old_get = let old_get = get_object::output_to_s3s(get().dto).expect("old GET projection");
gateway_s3s_compat::generated::ops::get_object::output_from_s3s(get().into_s3s().expect("old GET projection")) let old_get = get_object::output_from_s3s(old_get).expect("old GET output");
.expect("old GET output"); let old_head = head_object::output_to_s3s(head().dto).expect("old HEAD projection");
let old_head = let old_head = head_object::output_from_s3s(old_head).expect("old HEAD output");
gateway_s3s_compat::generated::ops::head_object::output_from_s3s(head().into_s3s().expect("old HEAD projection"))
.expect("old HEAD output");
let old = (old_get.object_lock_retain_until_date, old_head.object_lock_retain_until_date); let old = (old_get.object_lock_retain_until_date, old_head.object_lock_retain_until_date);
let expected = let expected =
Some(rustfs_gateway_types::Timestamp::from_secs_nanos(1_700_000_000, 123_000_000).expect("millisecond timestamp")); Some(rustfs_gateway_types::Timestamp::from_secs_nanos(1_700_000_000, 123_000_000).expect("millisecond timestamp"));
@@ -2732,6 +2732,32 @@ mod listing_tests {
); );
assert_eq!(current.buckets[0].creation_date.subsec_nanos(), 123000000); assert_eq!(current.buckets[0].creation_date.subsec_nanos(), 123000000);
} }
/// Same facts `RequestEnvelope::from_s3s` copies: method, URI, headers, extensions, region, service, and credentials.
#[cfg(any(feature = "webdav", feature = "sftp"))]
fn envelope_from_legacy_listing_request<T>(req: &S3Request<T>) -> crate::app::RequestEnvelope {
let credentials = req.credentials.as_ref().map(|credentials| {
let session_token = crate::auth::get_session_token(&req.uri, &req.headers).map(str::to_owned);
crate::app::RequestCredentials::new(
credentials.access_key.clone(),
credentials.secret_key.expose().to_owned(),
session_token.clone(),
)
.unwrap_or_else(|_| crate::app::RequestCredentials::without_secret_key(credentials.access_key.clone(), session_token))
});
crate::app::RequestEnvelope::from_parts(
crate::app::RequestHead {
method: req.method.clone(),
uri: req.uri.clone(),
headers: req.headers.clone(),
credentials,
region: req.region.as_ref().map(|region| region.as_str().to_owned()),
service: req.service.clone(),
},
req.extensions.clone(),
)
}
#[cfg(any(feature = "webdav", feature = "sftp"))] #[cfg(any(feature = "webdav", feature = "sftp"))]
#[test] #[test]
fn protocol_listing_session_credential_projection_matches_legacy() { fn protocol_listing_session_credential_projection_matches_legacy() {
@@ -2767,7 +2793,7 @@ mod listing_tests {
) )
.expect("legacy request"); .expect("legacy request");
legacy.headers = headers.clone(); legacy.headers = headers.clone();
let legacy = crate::app::RequestEnvelope::from_s3s(&legacy); let legacy = envelope_from_legacy_listing_request(&legacy);
let current = let current =
session_list_buckets_envelope(ServerContextSlot::new(), &session, &headers, true, credentials, false); session_list_buckets_envelope(ServerContextSlot::new(), &session, &headers, true, credentials, false);
let legacy = legacy.credentials().expect("legacy credentials"); let legacy = legacy.credentials().expect("legacy credentials");
+39 -48
View File
@@ -325,47 +325,9 @@ fn copy_output_facts(tag: Option<&str>) -> CopyObjectWriteOutput {
} }
} }
/// Same facts `RequestEnvelope::from_s3s` copies: method, URI, headers, extensions, region, service, and credentials.
fn envelope_from_legacy_copy_request(req: &s3s::S3Request<()>) -> crate::app::RequestEnvelope {
let credentials = req.credentials.as_ref().map(|credentials| {
let session_token = crate::auth::get_session_token(&req.uri, &req.headers).map(str::to_owned);
crate::app::RequestCredentials::new(
credentials.access_key.clone(),
credentials.secret_key.expose().to_owned(),
session_token.clone(),
)
.unwrap_or_else(|_| crate::app::RequestCredentials::without_secret_key(credentials.access_key.clone(), session_token))
});
crate::app::RequestEnvelope::from_parts(
crate::app::RequestHead {
method: req.method.clone(),
uri: req.uri.clone(),
headers: req.headers.clone(),
credentials,
region: req.region.as_ref().map(|region| region.as_str().to_owned()),
service: req.service.clone(),
},
req.extensions.clone(),
)
}
#[test] #[test]
fn protocol_copy_request_head_matches_legacy() { fn protocol_copy_request_head_matches_legacy() {
fn facts(envelope: &crate::app::RequestEnvelope) -> serde_json::Value { for (secret, expected_head_secret) in [("copy-secret", Some("copy-secret")), ("", None)] {
let info = envelope.req_info().expect("request info");
let credentials = envelope.credentials().expect("request credentials");
let identity = info.cred.as_ref().expect("request identity");
serde_json::json!({
"method":envelope.method().as_str(),"uri":envelope.uri().to_string(),"headers":format!("{:?}",envelope.headers()),
"credentials":[credentials.access_key(),credentials.secret_key(),credentials.session_token()],
"identity":[identity.access_key,identity.secret_key,identity.session_token],
"bucket":info.bucket,"object":info.object,"version":info.version_id,"owner":info.is_owner,
"keystone":info.keystone_session_present,"replication":info.replication_request_authorized,"region":info.region,
"request_context":info.request_context.is_some(),"suppress_log":info.suppress_denial_log,"suppress_audit":info.suppress_denial_audit,
"head_region":envelope.region(),"service":envelope.service(),"server":envelope.server_context().is_some(),"presigned":envelope.verified_presigned().is_some(),
})
}
for secret in ["copy-secret", ""] {
let credentials = rustfs_credentials::Credentials { let credentials = rustfs_credentials::Credentials {
access_key: "copy-identity".into(), access_key: "copy-identity".into(),
secret_key: secret.into(), secret_key: secret.into(),
@@ -374,15 +336,44 @@ fn protocol_copy_request_head_matches_legacy() {
..Default::default() ..Default::default()
}; };
let uri = build_object_uri("copy-target", "a ?&/%é", &[]).expect("request URI"); let uri = build_object_uri("copy-target", "a ?&/%é", &[]).expect("request URI");
let params = || RequestParams { let envelope = ProtocolStorageClient::create_envelope(
bucket: Some("copy-target".to_owned()), Method::PUT,
object: Some("a ?&/%é".to_owned()), uri,
credentials: &credentials, RequestParams {
}; bucket: Some("copy-target".to_owned()),
let old = ProtocolStorageClient::create_request((), Method::PUT, uri.clone(), params()).expect("legacy request"); object: Some("a ?&/%é".to_owned()),
let old = envelope_from_legacy_copy_request(&old); credentials: &credentials,
let current = ProtocolStorageClient::create_envelope(Method::PUT, uri, params()); },
assert_eq!(facts(&current), facts(&old)); );
assert_eq!(envelope.method(), &Method::PUT);
assert_eq!(envelope.uri().to_string(), "/copy-target/a%20%3F&/%25%C3%A9");
assert!(envelope.headers().is_empty());
assert!(envelope.region().is_none());
assert!(envelope.service().is_none());
assert!(envelope.server_context().is_none());
assert!(envelope.verified_presigned().is_none());
let head_credentials = envelope.credentials().expect("request credentials");
assert_eq!(head_credentials.access_key(), "copy-identity");
assert_eq!(head_credentials.secret_key(), expected_head_secret);
assert!(head_credentials.session_token().is_none());
let info = envelope.req_info().expect("request info");
let identity = info.cred.as_ref().expect("request identity");
assert_eq!(identity.access_key, "copy-identity");
assert_eq!(identity.secret_key, secret);
assert_eq!(identity.session_token, "identity-token");
assert_eq!(info.bucket.as_deref(), Some("copy-target"));
assert_eq!(info.object.as_deref(), Some("a ?&/%é"));
assert!(info.version_id.is_none());
assert!(!info.is_owner);
assert!(info.keystone_session_present.is_none());
assert!(!info.replication_request_authorized);
assert!(info.region.is_none());
assert!(info.request_context.is_some());
assert!(!info.suppress_denial_log);
assert!(!info.suppress_denial_audit);
} }
} }
+4 -4
View File
@@ -156,10 +156,10 @@ pub(super) fn complete_multipart_output(
] { ] {
if let Some(value) = value { if let Some(value) = value {
http::HeaderValue::from_str(&value).map_err(|_| { http::HeaderValue::from_str(&value).map_err(|_| {
crate::app::dto_values::seam_error(rustfs_gateway_types::compat::ConversionError { S3Error::with_message(
field, S3ErrorCode::InternalError,
reason: "not a header value", format!("failed to convert through the gateway compatibility seam: {field}: not a header value"),
}) )
})?; })?;
} }
} }
+59 -31
View File
@@ -187,19 +187,20 @@ fn multipart_complete_projection_matches_original_parts_and_conditions() {
#[test] #[test]
fn multipart_completion_projection_preserves_original_escaped_tags() { fn multipart_completion_projection_preserves_original_escaped_tags() {
for (opaque, weak) in [("abc", false), ("a&b<c", false), ("a\"b", true)] { for (opaque, weak, expected) in [
("abc", false, "abc"),
("a&b<c", false, "a&amp;b&lt;c"),
("a\"b", true, "a&quot;b"),
] {
let input = dto::CompleteMultipartUploadOutput { let input = dto::CompleteMultipartUploadOutput {
e_tag: Some(if weak { ETag::new_weak(opaque) } else { ETag::new(opaque) }.expect("tag")), e_tag: Some(if weak { ETag::new_weak(opaque) } else { ETag::new(opaque) }.expect("tag")),
..Default::default() ..Default::default()
}; };
let mut legacy = let tag = complete_multipart_output(input)
compat::generated::ops::complete_multipart_upload::output_to_s3s(input.clone()).expect("original output"); .expect("completion output")
let stored = if weak { format!("W/\"{opaque}\"") } else { opaque.to_owned() }; .e_tag
legacy.e_tag = Some(crate::app::storage_api::object_utils::to_s3s_xml_etag(&stored)); .expect("ETag");
let expected = compat::generated::ops::complete_multipart_upload::output_from_s3s(legacy).expect("original answer"); assert_eq!((tag.opaque_tag(), tag.is_weak()), (expected, weak));
let actual = complete_multipart_output(input).expect("owned answer");
let tag = |value: Option<ETag>| value.map(|value| (value.opaque_tag().to_owned(), value.is_weak()));
assert_eq!(tag(actual.e_tag), tag(expected.e_tag));
} }
} }
@@ -255,28 +256,55 @@ fn multipart_refusals_match_original_client_errors() {
#[test] #[test]
fn multipart_completion_projection_preserves_header_only_field_behavior() { fn multipart_completion_projection_preserves_header_only_field_behavior() {
let output = dto::CompleteMultipartUploadOutput { let headers = [
checksum_header_xxhash3: Some("AAAAAAAAAAA=".into()), "x-amz-checksum-md5",
sse_customer_algorithm: Some("AES256".into()), "x-amz-checksum-sha512",
sse_customer_key_md5: Some("digest".into()), "x-amz-checksum-xxhash3",
..Default::default() "x-amz-checksum-xxhash64",
}; "x-amz-checksum-xxhash128",
let output = complete_multipart_output(output).expect("header fields remain valid"); "x-amz-server-side-encryption-customer-algorithm",
assert!(output.checksum_header_xxhash3.is_none()); "x-amz-server-side-encryption-customer-key-md5",
assert!(output.sse_customer_algorithm.is_none()); ];
assert!(output.sse_customer_key_md5.is_none()); for first_invalid in 0..=headers.len() {
let error = complete_multipart_output(dto::CompleteMultipartUploadOutput { let valid = ["md5", "sha512", "AAAAAAAAAAA=", "xxhash64", "xxhash128", "AES256", "digest"];
sse_customer_algorithm: Some("bad\nvalue".into()), let value = |index: usize| Some(if index < first_invalid { valid[index] } else { "bad\nvalue" }.to_owned());
..Default::default() let output = dto::CompleteMultipartUploadOutput {
}) checksum_header_md5: value(0),
.expect_err("invalid original response header"); checksum_header_sha512: value(1),
assert_eq!(error.code(), &S3ErrorCode::InternalError); checksum_header_xxhash3: value(2),
assert!( checksum_header_xxhash64: value(3),
error checksum_header_xxhash128: value(4),
.message() sse_customer_algorithm: value(5),
.expect("message") sse_customer_key_md5: value(6),
.contains("x-amz-server-side-encryption-customer-algorithm: not a header value") ..Default::default()
); };
let result = complete_multipart_output(output);
if let Some(header) = headers.get(first_invalid) {
let error = result.expect_err("invalid response header");
assert_eq!(error.code(), &S3ErrorCode::InternalError);
assert_eq!(
error.message(),
Some(format!("failed to convert through the gateway compatibility seam: {header}: not a header value").as_str())
);
assert_eq!(error.status_code(), Some(http::StatusCode::INTERNAL_SERVER_ERROR));
assert!(error.headers().is_none());
assert!(std::error::Error::source(&error).is_none());
} else {
let output = result.expect("valid response headers");
assert_eq!(
[
output.checksum_header_md5,
output.checksum_header_sha512,
output.checksum_header_xxhash3,
output.checksum_header_xxhash64,
output.checksum_header_xxhash128,
output.sse_customer_algorithm,
output.sse_customer_key_md5
],
[const { None }; 7]
);
}
}
} }
#[test] #[test]
+91 -69
View File
@@ -17,7 +17,6 @@
use super::*; use super::*;
use crate::app::multipart_usecase::{DefaultMultipartUsecase, UploadPartCopyWriteInput, UploadPartCopyWriteOutput}; use crate::app::multipart_usecase::{DefaultMultipartUsecase, UploadPartCopyWriteInput, UploadPartCopyWriteOutput};
use crate::app::storage_api::s3::S3Response;
use rustfs_gateway_types::{CopySourceValue, UploadIdClaim, dto}; use rustfs_gateway_types::{CopySourceValue, UploadIdClaim, dto};
use rustfs_protocols::common::client::s3::StorageBackend; use rustfs_protocols::common::client::s3::StorageBackend;
use rustfs_s3_types::S3Error; use rustfs_s3_types::S3Error;
@@ -594,42 +593,70 @@ fn output_facts(raw: Option<&str>) -> crate::app::multipart_usecase::UploadPartC
#[test] #[test]
fn protocol_upload_copy_output_matches_original_composed_codec() { fn protocol_upload_copy_output_matches_original_composed_codec() {
for raw in [ let missing = "failed to convert UploadPartCopy output through the gateway compatibility seam: e_tag: the gateway shape requires this member";
None, let invalid = "failed to convert UploadPartCopy output through the gateway compatibility seam: e_tag: not an entity tag the gateway can write";
Some("abc"), for (raw, expected) in [
Some("\"abc\""), (None, Err(missing)),
Some("W/\"abc\""), (Some("abc"), Ok(("abc", false))),
Some("a&\"b"), (Some("\"abc\""), Ok(("abc", false))),
Some(""), (Some("W/\"abc\""), Ok(("abc", true))),
Some("\"\""), (Some("a&\"b"), Ok(("a&amp;&quot;b", false))),
Some("a\0b"), (Some(""), Err(invalid)),
(Some("\"\""), Err(invalid)),
(Some("a\0b"), Err(invalid)),
] { ] {
let fields = output_facts(raw); let result = multipart::upload_part_copy_output(output_facts(raw));
let legacy = UploadPartCopyOutput { match expected {
copy_part_result: Some(CopyPartResult { Err(message) => {
e_tag: raw.map(crate::app::storage_api::multipart_usecase::object_utils::to_s3s_xml_etag), let error = result.expect_err("unrepresentable stored ETag");
last_modified: fields.last_modified.map(Timestamp::from), assert!(std::error::Error::source(&error).is_none());
checksum_crc32: fields.checksum_crc32, assert_eq!(
checksum_crc32c: fields.checksum_crc32c, error_facts(error),
checksum_sha1: fields.checksum_sha1, (
checksum_sha256: fields.checksum_sha256, "InternalError".to_owned(),
checksum_crc64nvme: fields.checksum_crc64nvme, Some(message.to_owned()),
..Default::default() Some(http::StatusCode::INTERNAL_SERVER_ERROR),
}), None
copy_source_version_id: fields.copy_source_version_id, ),
server_side_encryption: fields.server_side_encryption.map(ServerSideEncryption::from), "{raw:?}"
ssekms_key_id: fields.ssekms_key_id, );
sse_customer_algorithm: fields.sse_customer_algorithm, }
sse_customer_key_md5: fields.sse_customer_key_md5, Ok((opaque, weak)) => {
..Default::default() let output = result.expect("copy output");
}; let expected = dto::UploadPartCopyOutput {
let expected = gateway_s3s_compat::generated::ops::upload_part_copy::output_from_s3s(legacy) e_tag: if weak {
.map(|output| format!("{output:?}")) rustfs_gateway_types::ETag::new_weak(opaque)
.map_err(|error| conversion_error("UploadPartCopy output", error).to_string()); } else {
let actual = multipart::upload_part_copy_output(output_facts(raw)) rustfs_gateway_types::ETag::new(opaque)
.map(|output| format!("{output:?}")) }
.map_err(|error| error.to_string()); .expect("ETag"),
assert_eq!(actual, expected, "stored tag {raw:?}"); last_modified: Some(
rustfs_gateway_types::Timestamp::from_secs_nanos(1_700_000_000, 123_000_000)
.expect("millisecond timestamp"),
),
copy_source_version_id: Some("null".into()),
server_side_encryption: Some(dto::ServerSideEncryption::custom("aws:kms")),
ssekms_key_id: Some("kms-id".into()),
sse_customer_algorithm: Some("AES256".into()),
sse_customer_key_md5: Some("digest".into()),
checksum_crc32: Some("crc32".into()),
checksum_crc32c: Some("crc32c".into()),
checksum_crc64nvme: Some("crc64nvme".into()),
checksum_sha1: Some("sha1".into()),
checksum_sha256: Some("sha256".into()),
bucket_key_enabled: None,
request_charged: None,
checksum_sha512: None,
checksum_md5: None,
checksum_xxhash64: None,
checksum_xxhash3: None,
checksum_xxhash128: None,
};
assert_eq!(format!("{output:?}"), format!("{expected:?}"), "{raw:?}");
assert_eq!(output.ssekms_key_id, expected.ssekms_key_id);
assert_eq!(output.sse_customer_key_md5, expected.sse_customer_key_md5);
}
}
} }
} }
@@ -659,14 +686,6 @@ fn protocol_upload_copy_error_keeps_explicit_message_headers_and_storage_cause()
} }
// Keep construction of the large use-case futures outside the test's async frame. // Keep construction of the large use-case futures outside the test's async frame.
#[inline(never)]
fn legacy_copy_future(
usecase: &DefaultMultipartUsecase,
request: S3Request<UploadPartCopyInput>,
) -> impl std::future::Future<Output = S3Result<S3Response<UploadPartCopyOutput>>> + '_ {
Box::pin(usecase.execute_upload_part_copy(request))
}
#[inline(never)] #[inline(never)]
fn owned_copy_future( fn owned_copy_future(
usecase: &DefaultMultipartUsecase, usecase: &DefaultMultipartUsecase,
@@ -701,40 +720,43 @@ async fn protocol_upload_copy_capabilities_precede_part_validation() {
"x-rustfs-max-total-object-size is only supported for CreateMultipartUpload", "x-rustfs-max-total-object-size is only supported for CreateMultipartUpload",
), ),
] { ] {
let make = || { let uri: http::Uri = format!("/bucket/copy-target?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=fixture/20260827/us-east-1/s3/aws4_request&X-Amz-Signature=fixture{query}").parse().expect("URI");
let mut request = input("bucket", "upload"); let request = ProtocolStorageClient::create_envelope(
request.part_number = 0;
request
};
let source = legacy_copy_source(make().copy_source).expect("source");
let legacy = gateway_s3s_compat::generated::ops::upload_part_copy::input_to_s3s(make(), source).expect("legacy input");
let uri = format!("/bucket/copy-target?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260827T000000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Credential=fixture/20260827/us-east-1/s3/aws4_request&X-Amz-Signature=fixture{query}").parse().expect("URI");
let mut request = ProtocolStorageClient::create_request(
legacy,
Method::PUT, Method::PUT,
uri, uri.clone(),
RequestParams { RequestParams {
bucket: Some("bucket".into()), bucket: Some("bucket".into()),
object: Some("copy-target".into()), object: Some("copy-target".into()),
credentials: &credentials, credentials: &credentials,
}, },
) );
.expect("request"); let mut extensions = http::Extensions::new();
request.extensions.insert(crate::auth::VerifiedSigV4Request); extensions.insert(request.req_info().expect("request identity").clone());
request.extensions.insert(crate::auth::VerifiedPresignedRequest); extensions.insert(crate::auth::VerifiedSigV4Request);
let envelope = crate::app::RequestEnvelope::from_s3s(&request); extensions.insert(crate::auth::VerifiedPresignedRequest);
let usecase = crate::app::multipart_usecase::DefaultMultipartUsecase::without_context(); let envelope = crate::app::RequestEnvelope::from_parts(
let expected = legacy_copy_future(&usecase, request) crate::app::RequestHead {
.await method: Method::PUT,
.err() uri,
.map(S3Error::from) headers: HeaderMap::new(),
.expect("legacy refusal"); credentials: request.credentials().cloned(),
let (_, input) = multipart::prepare_upload_part_copy(make()).expect("owned input"); region: None,
service: None,
},
extensions,
);
let usecase = DefaultMultipartUsecase::without_context();
let mut request = input("bucket", "upload");
request.part_number = 0;
let (_, input) = multipart::prepare_upload_part_copy(request).expect("owned input");
let actual = owned_copy_future(&usecase, envelope, input) let actual = owned_copy_future(&usecase, envelope, input)
.await .await
.err() .err()
.expect("owned refusal"); .expect("owned refusal");
assert_eq!((actual.code().as_str(), actual.message()), (code, Some(message))); assert!(std::error::Error::source(&actual).is_none());
assert_eq!(error_facts(actual), error_facts(expected)); assert_eq!(
error_facts(actual),
(code.to_owned(), Some(message.to_owned()), Some(http::StatusCode::BAD_REQUEST), None)
);
} }
} }
+87 -29
View File
@@ -69,6 +69,7 @@ use rustfs_common::{
GlobalReadiness, GlobalReadiness,
trace_bus::{TelemetryTraceEvent, TelemetryTraceOperation, TelemetryTraceStatus, telemetry_trace_emit}, trace_bus::{TelemetryTraceEvent, TelemetryTraceOperation, TelemetryTraceStatus, telemetry_trace_emit},
}; };
use rustfs_gateway::{LegacyDomainError, LegacyRustfsVirtualHosts};
use rustfs_io_metrics::internode_metrics::{ use rustfs_io_metrics::internode_metrics::{
INTERNODE_OPERATION_GRPC_COMPARE_AND_UPDATE_FILE, INTERNODE_OPERATION_GRPC_OTHER, INTERNODE_OPERATION_GRPC_READ_ALL, INTERNODE_OPERATION_GRPC_COMPARE_AND_UPDATE_FILE, INTERNODE_OPERATION_GRPC_OTHER, INTERNODE_OPERATION_GRPC_READ_ALL,
INTERNODE_OPERATION_GRPC_READ_MULTIPLE, INTERNODE_OPERATION_GRPC_WRITE_ALL, INTERNODE_TRANSPORT_BACKEND_GRPC, INTERNODE_OPERATION_GRPC_READ_MULTIPLE, INTERNODE_OPERATION_GRPC_WRITE_ALL, INTERNODE_TRANSPORT_BACKEND_GRPC,
@@ -83,6 +84,7 @@ use rustfs_protos::proto_gen::node_service::{
}; };
use rustfs_trusted_proxies::ClientInfo; use rustfs_trusted_proxies::ClientInfo;
use rustfs_utils::net::parse_and_resolve_address; use rustfs_utils::net::parse_and_resolve_address;
#[cfg(test)]
use s3s::host::MultiDomain; use s3s::host::MultiDomain;
use socket2::{SockRef, TcpKeepalive}; use socket2::{SockRef, TcpKeepalive};
use std::io::{Error, Result}; use std::io::{Error, Result};
@@ -183,23 +185,23 @@ static HTTP_STATUS_CLASS_METRICS: std::sync::LazyLock<[HttpStatusClassMetrics; 6
static HTTP_TRANSPORT_FAILURES_COUNTER: std::sync::LazyLock<metrics::Counter> = static HTTP_TRANSPORT_FAILURES_COUNTER: std::sync::LazyLock<metrics::Counter> =
std::sync::LazyLock::new(|| counter!(METRIC_HTTP_SERVER_FAILURES_TOTAL, LABEL_HTTP_STATUS_CLASS => "transport")); std::sync::LazyLock::new(|| counter!(METRIC_HTTP_SERVER_FAILURES_TOTAL, LABEL_HTTP_STATUS_CLASS => "transport"));
fn validated_domains(variable: &str, domains: &[String]) -> Result<LegacyRustfsVirtualHosts> {
LegacyRustfsVirtualHosts::new(domains).map_err(|err| {
let reason = match err {
LegacyDomainError::NotADomain => "The domain is invalid",
LegacyDomainError::Overlapping => "Some subdomains overlap with each other",
};
Error::other(format!("invalid {variable} {domains:?}: {reason}"))
})
}
fn s3_host_domains(config: &config::Config) -> Result<Option<Vec<String>>> { fn s3_host_domains(config: &config::Config) -> Result<Option<Vec<String>>> {
if config.server_domains.is_empty() || config.console_enable { if config.server_domains.is_empty() || config.console_enable {
return Ok(None); return Ok(None);
} }
let mut domains = Vec::with_capacity(config.server_domains.len()); let hosts = validated_domains("RUSTFS_SERVER_DOMAINS", &config.server_domains)?;
let mut seen = std::collections::HashSet::with_capacity(config.server_domains.len()); Ok(Some(hosts.domains().map(str::to_owned).collect()))
for domain in &config.server_domains {
if seen.insert(strip_valid_port_suffix(domain).to_string()) {
domains.push(domain.clone());
}
}
MultiDomain::new(&domains)
.map_err(|err| Error::other(format!("invalid RUSTFS_SERVER_DOMAINS {:?}: {err}", config.server_domains)))?;
Ok(Some(domains))
} }
fn website_host_domains(config: &config::Config) -> Result<Option<Vec<String>>> { fn website_host_domains(config: &config::Config) -> Result<Option<Vec<String>>> {
@@ -230,7 +232,7 @@ fn website_host_domains(config: &config::Config) -> Result<Option<Vec<String>>>
if domains.is_empty() { if domains.is_empty() {
Ok(None) Ok(None)
} else { } else {
MultiDomain::new(&domains).map_err(|err| Error::other(format!("invalid RUSTFS_WEBSITE_DOMAINS {:?}: {err}", domains)))?; validated_domains("RUSTFS_WEBSITE_DOMAINS", &domains)?;
Ok(Some(domains)) Ok(Some(domains))
} }
} }
@@ -1693,7 +1695,7 @@ struct ControlBodyDigestService<S> {
idle_timeout: Duration, idle_timeout: Duration,
total_timeout: Duration, total_timeout: Duration,
max_body_size: usize, max_body_size: usize,
virtual_host: Option<Arc<MultiDomain>>, virtual_host: Option<Arc<LegacyRustfsVirtualHosts>>,
} }
/// The largest control-plane XML body read for digest validation: 20 MiB, the XML body limit /// The largest control-plane XML body read for digest validation: 20 MiB, the XML body limit
@@ -1720,13 +1722,15 @@ impl<S> ControlBodyDigestService<S> {
fn with_virtual_host_domains(mut self, domains: Arc<[String]>) -> Self { fn with_virtual_host_domains(mut self, domains: Arc<[String]>) -> Self {
if !domains.is_empty() { if !domains.is_empty() {
// Startup already validated this same domain set for S3Service. // Startup already validated this same domain set for S3Service.
self.virtual_host = Some(Arc::new(MultiDomain::new(domains.iter()).expect("validated S3 host domains"))); self.virtual_host = Some(Arc::new(
LegacyRustfsVirtualHosts::new(domains.iter()).expect("validated S3 host domains"),
));
} }
self self
} }
} }
fn control_body_digest_required<B>(request: &HttpRequest<B>, virtual_host: Option<&MultiDomain>) -> Option<bool> { fn control_body_digest_required<B>(request: &HttpRequest<B>, virtual_host: Option<&LegacyRustfsVirtualHosts>) -> Option<bool> {
let query = url::form_urlencoded::parse(request.uri().query().unwrap_or_default().as_bytes()); let query = url::form_urlencoded::parse(request.uri().query().unwrap_or_default().as_bytes());
// Match s3s' multipart POST precedence, including its unique-header rule. // Match s3s' multipart POST precedence, including its unique-header rule.
if request.method() == Method::POST if request.method() == Method::POST
@@ -1748,9 +1752,8 @@ fn control_body_digest_required<B>(request: &HttpRequest<B>, virtual_host: Optio
} }
if request.method() == Method::POST { if request.method() == Method::POST {
let decoded_path = urlencoding::decode(request.uri().path()).ok()?; let decoded_path = urlencoding::decode(request.uri().path()).ok()?;
use s3s::host::S3Host; use rustfs_gateway_types::{LegacyRustfsNameValidator, NameValidator};
// Use s3s' host parser, including CNAME fallback, and its Host-first // This middleware selects Host first, with an authority fallback on HTTP/2 and HTTP/3.
// precedence. A rate-limit host hint is intentionally only best-effort.
let mut host_values = request.headers().get_all("host").iter(); let mut host_values = request.headers().get_all("host").iter();
let host = host_values.next().and_then(|value| value.to_str().ok()).or_else(|| { let host = host_values.next().and_then(|value| value.to_str().ok()).or_else(|| {
matches!(request.version(), Version::HTTP_2 | Version::HTTP_3) matches!(request.version(), Version::HTTP_2 | Version::HTTP_3)
@@ -1760,14 +1763,19 @@ fn control_body_digest_required<B>(request: &HttpRequest<B>, virtual_host: Optio
if host_values.next().is_some() { if host_values.next().is_some() {
return None; return None;
} }
let host = match (virtual_host, host) { let virtual_bucket = match (virtual_host, host) {
(Some(parser), Some(host)) if host.parse::<SocketAddr>().is_err() && host.parse::<IpAddr>().is_err() => { (Some(parser), Some(host)) => parser.bucket_for_host_header(host).ok()?,
Some(parser.parse_host_header(host).ok()?)
}
_ => None, _ => None,
}; };
let path = s3s::path::parse_virtual_hosted_style(host.as_ref().and_then(|host| host.bucket()), &decoded_path).ok()?; let path = decoded_path.strip_prefix('/')?;
if !matches!(path, s3s::path::S3Path::Bucket { .. }) { let is_bucket = if virtual_bucket.is_some() {
path.is_empty()
} else {
// A path-style bucket can end in one slash. Any remaining slash denotes an object.
let bucket = path.strip_suffix('/').unwrap_or(path);
LegacyRustfsNameValidator.check_bucket(bucket).into_result().is_ok()
};
if !is_bucket {
return None; return None;
} }
let delete_objects = match operation_id.as_deref() { let delete_objects = match operation_id.as_deref() {
@@ -8064,10 +8072,60 @@ mod tests {
let err = s3_host_domains(&config).expect_err("real subdomain overlap must stay rejected"); let err = s3_host_domains(&config).expect_err("real subdomain overlap must stay rejected");
let message = err.to_string(); assert_eq!(
assert!(message.contains("RUSTFS_SERVER_DOMAINS"), "{message}"); err.to_string(),
assert!(message.contains("example.com"), "{message}"); r#"invalid RUSTFS_SERVER_DOMAINS ["example.com", "s3.example.com"]: Some subdomains overlap with each other"#
assert!(message.contains("s3.example.com"), "{message}"); );
}
#[test]
fn s3_host_domains_reports_invalid_entries_before_later_overlaps() {
let config = test_config_with_domains(&["example.com:9000", "example.com", "bad_name", "s3.example.com"]);
assert_eq!(
s3_host_domains(&config).unwrap_err().to_string(),
r#"invalid RUSTFS_SERVER_DOMAINS ["example.com:9000", "example.com", "bad_name", "s3.example.com"]: The domain is invalid"#
);
}
#[test]
fn website_host_domains_preserves_startup_errors_and_normalization() {
let config = test_config_with_domains(&["s3.example:9000"]);
for (value, message) in [
(
"Site.Example, BAD_NAME",
r#"invalid RUSTFS_WEBSITE_DOMAINS ["site.example", "bad_name"]: The domain is invalid"#,
),
(
"SITE.example,k.site.example",
r#"invalid RUSTFS_WEBSITE_DOMAINS ["site.example", "k.site.example"]: Some subdomains overlap with each other"#,
),
("site.example, SITE.example", "duplicate RUSTFS_WEBSITE_DOMAINS entry: SITE.example"),
("website.s3.example", "website domain overlaps RUSTFS_SERVER_DOMAINS: website.s3.example"),
("site.example:9000", "invalid RUSTFS_WEBSITE_DOMAINS entry: site.example:9000"),
("site.example.", "invalid RUSTFS_WEBSITE_DOMAINS entry: site.example."),
] {
temp_env::with_var("RUSTFS_WEBSITE_DOMAINS", Some(value), || {
assert_eq!(website_host_domains(&config).unwrap_err().to_string(), message);
});
}
temp_env::with_var("RUSTFS_WEBSITE_DOMAINS", Some("Z.Example, ,A.Example"), || {
assert_eq!(website_host_domains(&config).unwrap().unwrap(), ["z.example", "a.example"]);
});
}
#[test]
fn startup_host_domains_skip_empty_lists_and_console_configuration() {
let mut config = test_config_with_domains(&[]);
assert_eq!(s3_host_domains(&config).unwrap(), None);
temp_env::with_var("RUSTFS_WEBSITE_DOMAINS", Some(", ,"), || {
assert_eq!(website_host_domains(&config).unwrap(), None);
});
config.server_domains.push("bad_name".to_owned());
config.console_enable = true;
temp_env::with_var("RUSTFS_WEBSITE_DOMAINS", Some("bad_name"), || {
assert_eq!(s3_host_domains(&config).unwrap(), None);
assert_eq!(website_host_domains(&config).unwrap(), None);
});
} }
#[test] #[test]
-2
View File
@@ -12,9 +12,7 @@ Applies to `rustfs/src/storage/`.
- Never log plaintext customer keys, decrypted key material, or sensitive SSE request payloads. - Never log plaintext customer keys, decrypted key material, or sensitive SSE request payloads.
- Keep SSE behavior aligned with KMS and admin handler integrations. - 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: - Coordinate related changes with:
- `crates/sse/`
- `crates/kms/` - `crates/kms/`
- `rustfs/src/admin/handlers/kms*.rs` - `rustfs/src/admin/handlers/kms*.rs`
- `crates/ecstore/` - `crates/ecstore/`
+3 -1
View File
@@ -20,6 +20,8 @@ pub mod deadlock_detector;
pub(crate) mod denial_audit; pub(crate) mod denial_audit;
pub(crate) mod helper; pub(crate) mod helper;
pub mod options; pub mod options;
#[cfg(test)]
mod replication_config_tests;
pub(crate) mod req_info; pub(crate) mod req_info;
pub mod request_context; pub mod request_context;
pub(crate) mod request_markers; pub(crate) mod request_markers;
@@ -76,7 +78,7 @@ pub(crate) use storage_api::{
helper_consumer, init_background_replication, init_bucket_metadata_sys, init_ecstore_config, helper_consumer, init_background_replication, init_bucket_metadata_sys, init_ecstore_config,
init_local_disks_with_instance_ctx, init_lock_clients, is_err_bucket_not_found, is_err_object_not_found, init_local_disks_with_instance_ctx, init_lock_clients, is_err_bucket_not_found, is_err_object_not_found,
is_err_version_not_found, is_valid_storage_class, options_consumer, prewarm_local_disk_id_map_with_instance_ctx, read_config, is_err_version_not_found, is_valid_storage_class, options_consumer, prewarm_local_disk_id_map_with_instance_ctx, read_config,
record_replication_proxy, rpc_consumer, runtime_sources_consumer, s3_api_consumer, table_catalog_path_hash, to_s3s_etag, record_replication_proxy, rpc_consumer, runtime_sources_consumer, s3_api_consumer, table_catalog_path_hash,
topology_snapshot_from_endpoint_pools_with_capabilities, try_migrate_bucket_metadata, try_migrate_iam_config, topology_snapshot_from_endpoint_pools_with_capabilities, try_migrate_bucket_metadata, try_migrate_iam_config,
try_migrate_server_config, update_bucket_metadata_config, update_bucket_metadata_config_if_incarnation, try_migrate_server_config, update_bucket_metadata_config, update_bucket_metadata_config_if_incarnation,
validate_website_configuration, verify_rpc_signature, wrap_reader, validate_website_configuration, verify_rpc_signature, wrap_reader,
@@ -0,0 +1,263 @@
// 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.
//! Replication fixtures written by the historical S3 codec at 5761ddfe.
//! The XML lives in bucket metadata. The scanner keeps compact MessagePack.
use super::storage_api::ecstore_bucket::{replication::ReplicationConfig, utils::BucketConfigXml};
use rustfs_gateway_types::persistence::{
PersistedAccessControlTranslation, PersistedEncryptionConfiguration, PersistedOptionalReplicationStatus,
PersistedReplicationAnd, PersistedReplicationConfiguration, PersistedReplicationDestination, PersistedReplicationFilter,
PersistedReplicationMetrics, PersistedReplicationRule, PersistedReplicationStatus, PersistedReplicationTag,
PersistedReplicationTime, PersistedReplicationTimeValue, PersistedSourceSelectionCriteria,
};
const ALL_XML: &[u8] = b"<ReplicationConfiguration><Role>arn:aws:iam::123456789012:role/replication</Role><Rule>\
<DeleteMarkerReplication><Status>FutureDeleteMarker</Status></DeleteMarkerReplication>\
<DeleteReplication><Status>FutureDelete</Status></DeleteReplication><Destination>\
<AccessControlTranslation><Owner>FutureOwner</Owner></AccessControlTranslation>\
<Account>123456789012</Account><Bucket>arn:aws:s3:::backup</Bucket><EncryptionConfiguration>\
<ReplicaKmsKeyID>kms-key</ReplicaKmsKeyID></EncryptionConfiguration><Metrics><EventThreshold>\
<Minutes>15</Minutes></EventThreshold><Status>FutureMetrics</Status></Metrics><ReplicationTime>\
<Status>FutureRtc</Status><Time><Minutes>30</Minutes></Time></ReplicationTime>\
<StorageClass>FutureClass</StorageClass></Destination><ExistingObjectReplication>\
<Status>FutureExisting</Status></ExistingObjectReplication><Filter><And><Prefix>docs/</Prefix><Tag>\
<Key>team</Key><Value>storage</Value></Tag><Tag><Key>tier</Key><Value>gold</Value></Tag></And>\
<Prefix>filter/</Prefix><Tag><Key>env</Key><Value>prod</Value></Tag></Filter><ID>every-member</ID>\
<Prefix>legacy/</Prefix><Priority>7</Priority><SourceSelectionCriteria><ReplicaModifications>\
<Status>FutureReplica</Status></ReplicaModifications><SseKmsEncryptedObjects><Status>FutureKms</Status>\
</SseKmsEncryptedObjects></SourceSelectionCriteria><Status>FutureRule</Status></Rule><Rule>\
<Destination><Bucket>arn:aws:s3:::second</Bucket></Destination><Status>Disabled</Status></Rule>\
</ReplicationConfiguration>";
const KEYLESS_XML: &[u8] = b"<ReplicationConfiguration><Role></Role><Rule><Destination><Bucket>arn:aws:s3:::backup</Bucket>\
</Destination><Filter><Tag></Tag></Filter><Status>Enabled</Status></Rule></ReplicationConfiguration>";
const EMPTY_KEY_XML: &[u8] = b"<ReplicationConfiguration><Role></Role><Rule><Destination><Bucket>arn:aws:s3:::backup</Bucket>\
</Destination><Filter><Tag><Key></Key><Value></Value></Tag></Filter><Status>Enabled</Status></Rule>\
</ReplicationConfiguration>";
const LOWERCASE_XML: &[u8] = b"<ReplicationConfiguration><Role></Role><Rule><Destination><Bucket>arn:aws:s3:::backup</Bucket>\
</Destination><Filter></Filter><Status>enabled</Status></Rule></ReplicationConfiguration>";
const MARKER_XML: &[u8] = b"<ReplicationConfiguration><Role></Role><Rule><DeleteMarkerReplication></DeleteMarkerReplication>\
<Destination><Bucket>arn:aws:s3:::backup</Bucket></Destination><Filter></Filter>\
<Status>Enabled</Status></Rule></ReplicationConfiguration>";
const MINIMAL_XML: &[u8] = b"<ReplicationConfiguration><Role></Role><Rule><Destination><Bucket>arn:aws:s3:::backup</Bucket>\
</Destination><Filter></Filter><Status>Enabled</Status></Rule></ReplicationConfiguration>";
const ALL_CACHE: &str = "9292d92a61726e3a6177733a69616d3a3a3132333435363738393031323a726f6c652f7265706c69636174696f6e929a\
91b246757475726544656c6574654d61726b657291ac46757475726544656c6574659791ab4675747572654f776e6572\
ac313233343536373839303132b361726e3a6177733a73333a3a3a6261636b757091a76b6d732d6b657992910fad4675\
747572654d65747269637392a9467574757265527463911eab467574757265436c61737391ae46757475726545786973\
74696e679492a5646f63732f9292a47465616da773746f7261676592a474696572a4676f6c6480a766696c7465722f92\
a3656e76a470726f64ac65766572792d6d656d626572a76c65676163792f079291ad4675747572655265706c69636191\
a94675747572654b6d73aa46757475726552756c659ac0c097c0c0b361726e3a6177733a73333a3a3a7365636f6e64c0\
c0c0c0c0c0c0c0c0c0a844697361626c6564c0";
const EMPTY_TAGS_CACHE: &str = "9292a0919ac0c097c0c0b361726e3a6177733a73333a3a3a6261636b7570c0c0c0c0c09492c09080c0c0c0c0c0c0a745\
6e61626c6564c0";
const ABSENT_TAGS_CACHE: &str = "9292a0919ac0c097c0c0b361726e3a6177733a73333a3a3a6261636b7570c0c0c0c0c09492c0c080c0c0c0c0c0c0a745\
6e61626c6564c0";
fn status(value: &str) -> PersistedReplicationStatus {
PersistedReplicationStatus {
status: value.to_owned(),
}
}
fn tag(key: &str, value: &str) -> PersistedReplicationTag {
PersistedReplicationTag {
key: Some(key.to_owned()),
value: Some(value.to_owned()),
}
}
fn every_member() -> PersistedReplicationConfiguration {
PersistedReplicationConfiguration {
role: "arn:aws:iam::123456789012:role/replication".to_owned(),
rules: vec![
PersistedReplicationRule {
delete_marker_replication: Some(PersistedOptionalReplicationStatus {
status: Some("FutureDeleteMarker".to_owned()),
}),
delete_replication: Some(status("FutureDelete")),
destination: PersistedReplicationDestination {
account: Some("123456789012".to_owned()),
access_control_translation: Some(PersistedAccessControlTranslation {
owner: "FutureOwner".to_owned(),
}),
bucket: "arn:aws:s3:::backup".to_owned(),
encryption_configuration: Some(PersistedEncryptionConfiguration {
replica_kms_key_id: Some("kms-key".to_owned()),
}),
metrics: Some(PersistedReplicationMetrics {
event_threshold: Some(PersistedReplicationTimeValue { minutes: Some(15) }),
status: "FutureMetrics".to_owned(),
}),
replication_time: Some(PersistedReplicationTime {
status: "FutureRtc".to_owned(),
time: PersistedReplicationTimeValue { minutes: Some(30) },
}),
storage_class: Some("FutureClass".to_owned()),
},
existing_object_replication: Some(status("FutureExisting")),
filter: Some(PersistedReplicationFilter {
and: Some(PersistedReplicationAnd {
prefix: Some("docs/".to_owned()),
tags: Some(vec![tag("team", "storage"), tag("tier", "gold")]),
}),
prefix: Some("filter/".to_owned()),
tag: Some(tag("env", "prod")),
}),
id: Some("every-member".to_owned()),
prefix: Some("legacy/".to_owned()),
priority: Some(7),
source_selection_criteria: Some(PersistedSourceSelectionCriteria {
replica_modifications: Some(status("FutureReplica")),
sse_kms_encrypted_objects: Some(status("FutureKms")),
}),
status: "FutureRule".to_owned(),
},
PersistedReplicationRule {
delete_marker_replication: None,
delete_replication: None,
destination: PersistedReplicationDestination {
bucket: "arn:aws:s3:::second".to_owned(),
..Default::default()
},
existing_object_replication: None,
filter: None,
id: None,
prefix: None,
priority: None,
source_selection_criteria: None,
status: "Disabled".to_owned(),
},
],
}
}
fn read_xml(input: &[u8]) -> PersistedReplicationConfiguration {
PersistedReplicationConfiguration::decode_config_xml(input).unwrap()
}
fn read_cache(hex: &str) -> PersistedReplicationConfiguration {
let bytes = hex_simd::decode_to_vec(hex).unwrap();
let cache: ReplicationConfig = rmp_serde::from_slice(&bytes).unwrap();
assert!(cache.remotes.is_none());
assert_eq!(rmp_serde::to_vec(&cache).unwrap(), bytes);
cache.config.unwrap()
}
#[test]
fn full_scanner_cache_keeps_every_member() {
let config = every_member();
assert_eq!(read_cache(ALL_CACHE), config);
let cache = ReplicationConfig::new(Some(config), None);
assert_eq!(rmp_serde::to_vec(&cache).unwrap(), hex_simd::decode_to_vec(ALL_CACHE).unwrap());
}
#[test]
fn bucket_metadata_writes_the_historical_xml_bytes() {
assert_eq!(every_member().encode_config_xml().unwrap(), ALL_XML);
}
#[test]
fn bucket_metadata_reads_every_member_of_the_historical_xml() {
assert_eq!(read_xml(ALL_XML), every_member());
}
#[test]
fn a_tag_without_key_or_value_survives() {
let config = read_xml(KEYLESS_XML);
let tag = config.rules[0].filter.as_ref().unwrap().tag.as_ref().unwrap();
assert_eq!(tag.key, None);
assert_eq!(tag.value, None);
assert_eq!(config.encode_config_xml().unwrap(), KEYLESS_XML);
}
#[test]
fn empty_tag_key_and_value_survive() {
let config = read_xml(EMPTY_KEY_XML);
let tag = config.rules[0].filter.as_ref().unwrap().tag.as_ref().unwrap();
assert_eq!(tag.key.as_deref(), Some(""));
assert_eq!(tag.value.as_deref(), Some(""));
assert_eq!(config.encode_config_xml().unwrap(), EMPTY_KEY_XML);
}
#[test]
fn the_scanner_cache_distinguishes_empty_and_absent_tag_lists() {
for (bytes, expected) in [(EMPTY_TAGS_CACHE, Some(Vec::new())), (ABSENT_TAGS_CACHE, None)] {
let config = read_cache(bytes);
let and = config.rules[0].filter.as_ref().unwrap().and.as_ref().unwrap();
assert_eq!(and.tags, expected);
}
}
#[test]
fn unknown_rule_status_keeps_its_spelling() {
let config = read_xml(LOWERCASE_XML);
assert_eq!(config.rules[0].status, "enabled");
assert_eq!(config.encode_config_xml().unwrap(), LOWERCASE_XML);
}
#[test]
fn a_delete_marker_wrapper_can_lack_status() {
let config = read_xml(MARKER_XML);
assert_eq!(
config.rules[0].delete_marker_replication,
Some(PersistedOptionalReplicationStatus { status: None })
);
assert_eq!(config.encode_config_xml().unwrap(), MARKER_XML);
}
#[test]
fn absent_storage_class_survives() {
let config = read_xml(MINIMAL_XML);
assert_eq!(config.rules[0].destination.storage_class, None);
assert_eq!(config.encode_config_xml().unwrap(), MINIMAL_XML);
}
#[test]
fn bucket_metadata_refuses_historically_invalid_documents() {
let refused: [&[u8]; 7] = [
b"<ReplicationConfiguration><Role></Role><Rule><Future>x</Future><Status>Enabled</Status><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Status>Enabled</Status><Destination><Bucket>b</Bucket><Future>x</Future></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Status>Enabled</Status><Filter><Tag><Key>k</Key><Future>x</Future></Tag></Filter><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Status>Enabled</Status><Priority>high</Priority><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>",
b"<ReplicationConfiguration><Role></Role><Rule><Status>Enabled</Status></Rule></ReplicationConfiguration>",
b"<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>",
];
for input in refused {
assert!(
PersistedReplicationConfiguration::decode_config_xml(input).is_err(),
"{}",
String::from_utf8_lossy(input)
);
}
}
#[test]
fn an_unknown_root_child_is_skipped() {
let input = b"<ReplicationConfiguration><Role></Role><FutureTopLevel>x</FutureTopLevel><Rule><Status>Enabled</Status><Destination><Bucket>b</Bucket></Destination></Rule></ReplicationConfiguration>";
let config = read_xml(input);
assert_eq!(config.rules.len(), 1);
assert_eq!(config.rules[0].destination.bucket, "b");
assert_eq!(config.rules[0].status, "Enabled");
}
-176
View File
@@ -1,176 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The historical GetBucketLifecycleConfiguration output projection used by the XML parity test.
use rustfs_gateway_types::persistence::{PersistedLifecycleConfiguration, PersistedLifecycleRule, PersistedLifecycleTag};
use s3s::dto;
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
#[cfg(test)]
fn date_to_s3s(value: Option<String>) -> std::io::Result<Option<dto::Timestamp>> {
value
.map(|value| {
OffsetDateTime::parse(&value, &Rfc3339)
.map(dto::Timestamp::from)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
})
.transpose()
}
#[cfg(test)]
pub(crate) fn lifecycle_configuration_to_s3s(
value: PersistedLifecycleConfiguration,
) -> std::io::Result<dto::BucketLifecycleConfiguration> {
Ok(dto::BucketLifecycleConfiguration {
expiry_updated_at: date_to_s3s(value.expiry_updated_at)?,
rules: value.rules.into_iter().map(rule_to_s3s).collect::<std::io::Result<_>>()?,
})
}
#[cfg(test)]
fn rule_to_s3s(value: PersistedLifecycleRule) -> std::io::Result<dto::LifecycleRule> {
Ok(dto::LifecycleRule {
abort_incomplete_multipart_upload: value
.abort_incomplete_multipart_upload
.map(|v| dto::AbortIncompleteMultipartUpload {
days_after_initiation: v.days_after_initiation,
}),
del_marker_expiration: value.del_marker_expiration.map(|v| dto::DelMarkerExpiration { days: v.days }),
expiration: value
.expiration
.map(|v| -> std::io::Result<dto::LifecycleExpiration> {
Ok(dto::LifecycleExpiration {
date: date_to_s3s(v.date)?,
days: v.days,
expired_object_all_versions: v.expired_object_all_versions,
expired_object_delete_marker: v.expired_object_delete_marker,
})
})
.transpose()?,
filter: value.filter.map(|v| dto::LifecycleRuleFilter {
and: v.and.map(|v| dto::LifecycleRuleAndOperator {
object_size_greater_than: v.object_size_greater_than,
object_size_less_than: v.object_size_less_than,
prefix: v.prefix,
tags: v.tags.map(|tags| tags.into_iter().map(tag_to_s3s).collect()),
}),
object_size_greater_than: v.object_size_greater_than,
object_size_less_than: v.object_size_less_than,
prefix: v.prefix,
tag: v.tag.map(tag_to_s3s),
cached_tags: Default::default(),
}),
id: value.id,
noncurrent_version_expiration: value.noncurrent_version_expiration.map(|v| dto::NoncurrentVersionExpiration {
newer_noncurrent_versions: v.newer_noncurrent_versions,
noncurrent_days: v.noncurrent_days,
}),
noncurrent_version_transitions: value.noncurrent_version_transitions.map(|values| {
values
.into_iter()
.map(|v| dto::NoncurrentVersionTransition {
newer_noncurrent_versions: v.newer_noncurrent_versions,
noncurrent_days: v.noncurrent_days,
storage_class: v.storage_class.map(Into::into),
})
.collect()
}),
prefix: value.prefix,
status: value.status.into(),
transitions: value
.transitions
.map(|values| {
values
.into_iter()
.map(|v| -> std::io::Result<dto::Transition> {
Ok(dto::Transition {
date: date_to_s3s(v.date)?,
days: v.days,
storage_class: v.storage_class.map(Into::into),
})
})
.collect::<std::io::Result<_>>()
})
.transpose()?,
})
}
#[cfg(test)]
fn tag_to_s3s(value: PersistedLifecycleTag) -> dto::Tag {
dto::Tag {
key: value.key,
value: value.value,
}
}
#[cfg(test)]
mod tests {
use super::lifecycle_configuration_to_s3s;
use crate::app::dto_values::stored_config;
use crate::storage::storage_api::ecstore_bucket::utils::BucketConfigXml;
use rustfs_gateway_types::compat::s3s_5761ddfe::generated::ops::get_bucket_lifecycle_configuration::output_to_s3s;
use rustfs_gateway_types::dto as gateway_dto;
use rustfs_gateway_types::persistence::{PersistedLifecycleConfiguration, parse_lifecycle_dto};
use s3s::{dto, xml};
/// Every member the legacy answer carries, the MinIO ones and dates with an offset included.
const STORED: &[u8] = b"<LifecycleConfiguration><Rule><DelMarkerExpiration><Days>7</Days></DelMarkerExpiration>\
<Expiration><Days>30</Days><ExpiredObjectAllVersions>true</ExpiredObjectAllVersions></Expiration><Filter><And><Prefix>logs/\
</Prefix><Tag><Key>tier</Key><Value>cold</Value></Tag><ObjectSizeGreaterThan>1</ObjectSizeGreaterThan></And></Filter>\
<ID>members</ID><NoncurrentVersionExpiration><NoncurrentDays>7</NoncurrentDays><NewerNoncurrentVersions>2\
</NewerNoncurrentVersions></NoncurrentVersionExpiration><NoncurrentVersionTransition><NoncurrentDays>3</NoncurrentDays>\
<StorageClass>WARM</StorageClass></NoncurrentVersionTransition><Status>Enabled</Status><Transition><Days>10</Days>\
<StorageClass>WARM</StorageClass></Transition></Rule><Rule><AbortIncompleteMultipartUpload><DaysAfterInitiation>3\
</DaysAfterInitiation></AbortIncompleteMultipartUpload><Expiration><Date>2099-01-01T00:00:00Z</Date></Expiration><ID>dated\
</ID><Prefix>archive/</Prefix><Status>Disabled</Status><Transition><Date>2098-06-01T08:00:00+08:00</Date><StorageClass>WARM\
</StorageClass></Transition></Rule></LifecycleConfiguration>";
fn s3s_bytes(value: &dto::GetBucketLifecycleConfigurationOutput) -> String {
let mut buf = Vec::new();
xml::Serialize::serialize(value, &mut xml::Serializer::new(&mut buf)).expect("the s3s encoder writes the answer");
String::from_utf8(buf).expect("the s3s encoder writes UTF-8")
}
/// The legacy stack answers a stored configuration through the gateway seam with the bytes it
/// answered through this module's reverse direction.
#[test]
fn the_legacy_answer_through_the_seam_is_the_answer_of_the_reverse_direction() {
let stored = PersistedLifecycleConfiguration::decode_config_xml(STORED).expect("the fixture is a stored document");
let before = dto::GetBucketLifecycleConfigurationOutput {
rules: Some(
lifecycle_configuration_to_s3s(stored.clone())
.expect("reverse direction")
.rules,
),
..Default::default()
};
let answer = gateway_dto::GetBucketLifecycleConfigurationOutput {
rules: stored_config(&stored, parse_lifecycle_dto).expect("gateway answer").rules,
..Default::default()
};
let after = s3s_bytes(&output_to_s3s(answer).expect("seam"));
assert_eq!(after, s3s_bytes(&before));
for member in [
"<DelMarkerExpiration>",
"<ExpiredObjectAllVersions>",
"<Transition>",
"<Date>2098-06-01T",
] {
assert!(after.contains(member), "{member} is missing from {after}");
}
}
}

Some files were not shown because too many files have changed in this diff Show More