diff --git a/.github/workflows/kms-script-tests.yml b/.github/workflows/kms-script-tests.yml index 60b5820..f0f71fc 100644 --- a/.github/workflows/kms-script-tests.yml +++ b/.github/workflows/kms-script-tests.yml @@ -5,6 +5,8 @@ on: paths: - rustfs-kms-test.sh - test_rustfs_kms_presign.py + - scripts/sse_contract_cases.py + - test_sse_contract_cases.py - test_validation_kms.sh - .github/workflows/kms-script-tests.yml push: @@ -12,6 +14,8 @@ on: paths: - rustfs-kms-test.sh - test_rustfs_kms_presign.py + - scripts/sse_contract_cases.py + - test_sse_contract_cases.py - test_validation_kms.sh - .github/workflows/kms-script-tests.yml @@ -30,5 +34,7 @@ jobs: run: bash -n rustfs-kms-test.sh - name: Test presigned KMS case without a server run: python3 -m unittest test_rustfs_kms_presign.py + - name: Test strict SSE contract cases without a server + run: python3 -B -m unittest test_sse_contract_cases.py - name: Test canonical KMS round trip without a server run: bash test_validation_kms.sh diff --git a/.github/workflows/s3-script-tests.yml b/.github/workflows/s3-script-tests.yml index bbf967f..3e77a6d 100644 --- a/.github/workflows/s3-script-tests.yml +++ b/.github/workflows/s3-script-tests.yml @@ -23,6 +23,8 @@ on: - test_s3_bulk_delete_regressions.py - test_s3_bulk_delete_keys.py - test_s3_bulk_delete_observations.py + - scripts/sse_contract_cases.py + - test_sse_contract_cases.py - test_rustfs_worm_object_lock.py - test_validation_s3_basic.sh - .github/workflows/s3-script-tests.yml @@ -49,6 +51,8 @@ on: - test_s3_bulk_delete_regressions.py - test_s3_bulk_delete_keys.py - test_s3_bulk_delete_observations.py + - scripts/sse_contract_cases.py + - test_sse_contract_cases.py - test_rustfs_worm_object_lock.py - test_validation_s3_basic.sh - .github/workflows/s3-script-tests.yml @@ -69,7 +73,7 @@ jobs: - name: Install independent SigV4 verifier run: python3 -m pip install botocore==1.43.19 'boto3>=1.43.19,<1.43.20' - name: Test S3 cases and signatures without a cluster - run: python3 -B -m unittest test_rustfs_s3_usage.py test_rustfs_s3_signing.py test_rustfs_s3_regressions.py test_rustfs_worm_object_lock.py test_s3_bulk_delete_regressions.py test_s3_bulk_delete_keys.py test_s3_bulk_delete_observations.py + run: python3 -B -m unittest test_rustfs_s3_usage.py test_rustfs_s3_signing.py test_rustfs_s3_regressions.py test_rustfs_worm_object_lock.py test_s3_bulk_delete_regressions.py test_s3_bulk_delete_keys.py test_s3_bulk_delete_observations.py test_sse_contract_cases.py - name: Test standalone S3 probe oracles run: python3 -B -m unittest test_mrf_long_root_refresh.py test_s3_request_id_parity.py test_s3_upload_part_timeout.py test_s3_veeam_sosapi_capacity.py - name: Test validation S3 round trip without a cluster diff --git a/README.md b/README.md index 4af4ece..be40682 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,21 @@ The S3 script tests run the same live case when `RUSTFS_BIN` points to a candida Run `python3 scripts/mrf_long_root_refresh.py --rustfs-bin /absolute/path/to/rustfs` with Python 3.10+ and boto3. The `admin.mrf-long-root-refresh` case starts a four-disk instance with a 257-byte root access key, seeds a committed unbound MRF snapshot, verifies that `POST /rustfs/admin/v4/heal/mrf/responsibilities/actions` `refresh` returns 200 `refreshed`, and checks that `acceptUnverifiedRisk` still caps persisted operator identities at 256 bytes. +## Strict SSE contract cases + +`ENC-201` to `ENC-210` in `rustfs-s3-compat-test.sh` and `KMS-601` to `KMS-609` in `rustfs-kms-test.sh` state what a client must observe from server-side encryption, exactly: a response carries the SSE headers of its scheme and no other SSE header, a refusal has the expected HTTP status and S3 error code, and a HEAD after a refused write answers 404. The older `S3C-90x`, `ENC-1xx` and `KMS-3xx` cases mostly accept a successful command with matching bytes and match a refusal against a loose pattern; they stay as they are. + +Both suites run the cases through `scripts/sse_contract_cases.py`, which needs Python 3.8 or newer and no third-party package, talks only to the suite's endpoint, and deploys nothing. The `ENC-2xx` cases rely on the S3 compatibility suite's server having `RUSTFS_SSE_S3_MASTER_KEY` and no KMS; the `KMS-6xx` cases rely on the KMS suite's default key and create the keys `sse-contract-key-1` and `sse-contract-key-2` through the admin API. The helper can also be pointed at any existing endpoint: + +```bash +RUSTFS_ACCESS_KEY=... RUSTFS_SECRET_KEY=... \ + python3 scripts/sse_contract_cases.py --endpoint http://node:9000 --case ENC-204 +``` + +It exits 0 when the case holds and 1 when it does not, an unreachable endpoint included; a wrong command line exits 64, never 2, which the suites read as UNSUPPORTED. See [the case contracts](docs/sse-contract-cases.md) ([中文](docs/sse-contract-cases.zh-CN.md)). + +`python3 -B -m unittest -v test_sse_contract_cases.py` runs every case against an in-memory S3 that behaves as required, then again with one behavior wrong at a time and requires the matching case to fail. This validates the oracles and the suite wiring, not RustFS. + ## Bulk-delete regressions The complete S3 topology suite includes bulk-delete regressions `S3C-213`, `S3C-214`, `S3C-1306` and `S3C-1307`. They cover batch boundaries, duplicate keys, immutable GET load and finite same-key PUT contention in off/on/suspended versioning modes. Python boto3 is required. Each subcase retains JSON, phase/request timing, HTTP 503 and per-object error counts, version/marker cleanup receipts and a Chinese Markdown summary under `--bulk-delete-results-dir`. The standalone runner accepts existing endpoints and does not deploy nodes; its caller must hold the environment lock. S3C-213 and S3C-1306 distinguish per-key S3 results from the historical ten-second client timeout and can compare short and long keys at controlled depths. See [the case contracts and usage](docs/s3-bulk-delete-regressions.zh-CN.md). diff --git a/docs/source-test-migration-inventory.md b/docs/source-test-migration-inventory.md index 2a42635..e9ba5ba 100644 --- a/docs/source-test-migration-inventory.md +++ b/docs/source-test-migration-inventory.md @@ -814,7 +814,7 @@ The source audit lists the following function entries. Names are preserved as au - Tests: `TestKeyString`, `TestParseKey` ## Scope interpretation -The target collection absorbs source test content and testing ideas. Observable behavior, negative branches, boundary values, state transitions, cleanup rules, and assertion oracles are represented in the 158 canonical scenarios and 261 local procedures. Source-native implementation mechanics and generated serialization helpers remain in this inventory for traceability and are not copied one-to-one. +The target collection absorbs source test content and testing ideas. Observable behavior, negative branches, boundary values, state transitions, cleanup rules, and assertion oracles are represented in the 158 canonical scenarios and 282 local procedures. Source-native implementation mechanics and generated serialization helpers remain in this inventory for traceability and are not copied one-to-one. Benchmarks remain performance references. Build, lint, security-scan, and repository workflows remain automation references. They do not create duplicate behavior cases in the target collection. diff --git a/docs/sse-contract-cases.md b/docs/sse-contract-cases.md new file mode 100644 index 0000000..3d35cb9 --- /dev/null +++ b/docs/sse-contract-cases.md @@ -0,0 +1,78 @@ +# Strict SSE contract cases + +[中文](sse-contract-cases.zh-CN.md) + +`scripts/sse_contract_cases.py` holds nineteen cases that state what a client must observe from server-side encryption. The cluster suites register them next to their older encryption cases and report them through the same `[PASS]`, `[FAIL]` and case-table lines. + +## What "strict" means + +- **Exact SSE headers.** A response is reduced to its headers starting with `x-amz-server-side-encryption`, and that set must equal the expected one: nothing missing and nothing extra. SSE-S3 is `{AES256}`, SSE-KMS is `aws:kms` plus the key id the request resolved to, SSE-C is the customer algorithm plus the key MD5, and a plaintext object has none. +- **Exact refusals.** A refusal must carry the expected HTTP status and S3 error code. A pattern such as `400|InvalidArgument` is not used. +- **No residue.** A refused write is followed by a HEAD of the same key, which must answer 404. +- **Bytes.** Data read back is compared by SHA-256 and by `Content-Length`. +- **No vacuous pass.** A case that evaluated no expectation fails. + +A table-driven case names each input row in its failure lines, and a row that breaks does not stop the next row. + +## Cases in `rustfs-s3-compat-test.sh` + +The server of this suite has `RUSTFS_SSE_S3_MASTER_KEY` and no KMS. `ENC-204` depends on that: with KMS running, SSE-KMS is accepted and the case fails. + +| Case | Name | Holds when | +| --- | --- | --- | +| `ENC-201` | SseS3ExactHeaders | SSE-S3 objects of 0, 1 and 71680 bytes answer PUT, GET and HEAD with exactly x-amz-server-side-encryption: AES256, read back byte-identical, and are listed with their plaintext size. | +| `ENC-202` | SseCExactHeaders | SSE-C objects of 0, 1 and 71680 bytes answer PUT, GET and HEAD with exactly the customer algorithm and key-MD5 headers, and a GET without the customer key is refused with 400 InvalidRequest. | +| `ENC-203` | BucketDefaultExact | A bucket default of AES256 encrypts a PUT that names no scheme, leaves an SSE-C PUT as SSE-C, and after its removal new objects carry no SSE header while earlier ones still read back as SSE-S3. | +| `ENC-204` | SseKmsNotDowngraded | Without KMS an SSE-KMS PUT is refused with 400 InvalidRequest and stores nothing, while SSE-S3 under the master key still round-trips. | +| `ENC-205` | SseCTripleNegatives | Seven incomplete or inconsistent SSE-C header triples are each refused with 400 InvalidRequest, and a HEAD of each key answers 404. | +| `ENC-206` | SseCCopySourceKey | CopyObject from an SSE-C source without or with a wrong source key is refused with an explicit 400 and stores nothing; with the right key the destination opens only with its own key. | +| `ENC-207` | SseCMultipartExact | An SSE-C multipart upload answers CreateMultipartUpload and CompleteMultipartUpload with exactly the customer headers, reads back byte-identical with the key, and is refused without it. | +| `ENC-208` | SseCPartKeyMismatch | UploadPart without the key, with another key, or with a key on a plaintext upload is refused with 400 InvalidRequest, and the SSE-C upload still completes afterwards. | +| `ENC-209` | SseReadHeaderMismatch | Six GET requests whose SSE headers do not match how the object was stored are refused with the exact error code and return no object bytes. | +| `ENC-210` | ListingEtagNotPlaintextMd5 | ListObjectsV2, ListObjects and ListObjectVersions never report the MD5 of the plaintext as the ETag of an SSE-S3 or SSE-C object, with a plaintext object as the control. | + +## Cases in `rustfs-kms-test.sh` + +The server of this suite runs KMS with the default key `kms-default` on the Local or Vault KV2 backend. The helper receives the default key id through `--kms-default-key` and creates `sse-contract-key-1` and `sse-contract-key-2` through the admin API before a case starts; a key that already exists is reused. The cases run after `KMS-318` and before the per-key authorization and fault cases. + +| Case | Name | Holds when | +| --- | --- | --- | +| `KMS-601` | SseS3KeyNotNamed | SSE-S3 under KMS round-trips with exactly AES256, and no response of eight operations carries a KMS key id header or names the default key. | +| `KMS-602` | SseKmsKeyResolutionExact | SSE-KMS without a key id answers with the default key id, and with an explicit non-default key answers with that key id on PUT, GET and HEAD for 0, 1 and 71680 bytes. | +| `KMS-603` | SseKmsRangeExact | Four range reads of an SSE-KMS object answer 206 with the exact Content-Range, the plaintext slice and the exact SSE-KMS headers. | +| `KMS-604` | BucketDefaultKmsExact | A bucket default of aws:kms without a key id pins the default key, leaves SSE-C as SSE-C, and an explicit AES256 PUT does not inherit the bucket's KMS key. | +| `KMS-605` | CopySchemeMatrix | Six CopyObject combinations across plaintext, SSE-S3, SSE-KMS and SSE-C produce exactly the destination scheme's headers on GET and HEAD and byte-identical data. | +| `KMS-606` | MultipartSseKmsExact | A three-part SSE-KMS upload answers create, complete, GET and HEAD with exactly the SSE-KMS headers of its key, the full length and a three-part ETag. | +| `KMS-607` | SsePutHeaderNegatives | Ten malformed SSE header combinations are refused with 400 InvalidArgument and a missing KMS key with 400 KMS.NotFoundException; a HEAD of each key answers 404. | +| `KMS-608` | SseReadHeaderMismatch | Seven GET requests whose SSE headers do not match how the object was stored, an SSE-KMS object included, are refused with the exact error code and return no object bytes. | +| `KMS-609` | ContextAndEtagNotEchoed | PUT, GET and HEAD of an object written with an encryption context do not repeat the context, and no listing reports the plaintext MD5 as the ETag of an encrypted object. | + +## Running one case + +```bash +./rustfs-s3-compat-test.sh --topology single-single -y --cases ENC-204 --package-url +./rustfs-kms-test.sh --topology single-single --backends local -y --cases KMS-605 --package-url + +RUSTFS_ACCESS_KEY=... RUSTFS_SECRET_KEY=... \ + python3 scripts/sse_contract_cases.py --endpoint http://node:9000 --case KMS-605 --kms-default-key kms-default +``` + +The helper needs Python 3.8 or newer and the standard library only. It connects to the endpoint directly and ignores proxy variables. Each case works in buckets named `sse--` and removes them afterwards on a best-effort basis. Exit status: 0 the case holds, 1 it does not (an unreachable endpoint included), 64 the command line is wrong. Status 2 is never used, because `run_test` reads it as UNSUPPORTED. + +The catalog ids are `s3.compatibility.enc-2xx` and `source-procedure.kms.kms-6xx`, so `--validation-case` selects a single case in the same way as for the older ones. + +## What has been verified + +- Every case holds against a local single-process server started with the environment the respective suite writes: master key only for `ENC-2xx`; Local and Vault KV2 KMS for `KMS-6xx`, also with `RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY=true` and `RUSTFS_ENCRYPTION_FRAME_V2=true`. +- The suites' own `run_all_tests` ran the cases against those servers and printed the expected `[PASS]` lines; against a server without a master key `ENC-201` and `ENC-204` printed `[FAIL]` with the refusal they saw. +- `test_sse_contract_cases.py` runs every case against an in-memory S3 that behaves as required, and again with one behavior wrong at a time; the matching case must fail and name what it saw. + +The cases have not run on the fleet yet. Multi-node topologies and the packaged binary are covered only once the scheduled suites pick the cases up. + +## Server versions + +The cases describe the behavior of current `main`. `ENC-207` fails against a server built before rustfs/rustfs#9575: such a server answers CreateMultipartUpload and CompleteMultipartUpload of an SSE-C upload with an extra `x-amz-server-side-encryption: AES256`, and the case reports exactly that header set. A run against an older release tag should read this failure as the known defect of that release. + +## What is deliberately not here + +The cases were taken from a suite that drives a bare server binary. Parts of it need things a deployed cluster cannot give and were left out: starting the server with other key sources (none at all, an invalid master key, Vault Transit, the Static backend), comparing two binaries, checking the stored form of objects on the drives, and searching whole runs for key material. Per-key authorization with separate identities is covered loosely by `KMS-401` and `KMS-402` and is not tightened here. diff --git a/docs/sse-contract-cases.zh-CN.md b/docs/sse-contract-cases.zh-CN.md new file mode 100644 index 0000000..21277ca --- /dev/null +++ b/docs/sse-contract-cases.zh-CN.md @@ -0,0 +1,78 @@ +# 严格的 SSE 契约用例 + +[English](sse-contract-cases.md) + +`scripts/sse_contract_cases.py` 里有十九条用例,陈述客户端在服务端加密上必须观察到什么。集群套件把它们登记在原有加密用例旁边,结果走同一套 `[PASS]`、`[FAIL]` 行和用例表。 + +## “严格”指什么 + +- **响应头恰好相符。** 把响应归约为以 `x-amz-server-side-encryption` 开头的那些头,这个集合必须与期望完全相等:不能少,也不能多。SSE-S3 是 `{AES256}`,SSE-KMS 是 `aws:kms` 加上请求解析到的密钥 ID,SSE-C 是客户算法加密钥 MD5,明文对象一个都没有。 +- **拒绝必须确切。** 拒绝必须是期望的 HTTP 状态码和 S3 错误码,不使用 `400|InvalidArgument` 这类模式匹配。 +- **不留残余。** 被拒绝的写之后,对同一个键做 HEAD,必须返回 404。 +- **字节。** 读回的数据按 SHA-256 和 `Content-Length` 比较。 +- **不允许空过。** 一条没有评估任何期望的用例判为失败。 + +表驱动用例会在失败行里写出是哪一个输入行;某一行出错不会让后面的行不执行。 + +## `rustfs-s3-compat-test.sh` 里的用例 + +这个套件的服务端设置了 `RUSTFS_SSE_S3_MASTER_KEY`,没有 KMS。`ENC-204` 依赖这一点:KMS 在运行时 SSE-KMS 会被接受,这条用例就会失败。 + +| 用例 | 名称 | 成立条件 | +| --- | --- | --- | +| `ENC-201` | SseS3ExactHeaders | 0、1、71680 字节的 SSE-S3 对象,PUT、GET、HEAD 的响应恰好只带 `x-amz-server-side-encryption: AES256`,读回字节一致,列举结果给出明文大小。 | +| `ENC-202` | SseCExactHeaders | 0、1、71680 字节的 SSE-C 对象,PUT、GET、HEAD 的响应恰好只带客户算法头与密钥 MD5 头;不带客户密钥的 GET 以 400 InvalidRequest 拒绝。 | +| `ENC-203` | BucketDefaultExact | 桶默认 AES256 会加密未指明方案的 PUT,SSE-C 的 PUT 仍是 SSE-C;删除默认配置后新对象不带任何 SSE 头,之前的对象仍按 SSE-S3 读回。 | +| `ENC-204` | SseKmsNotDowngraded | 没有 KMS 时,SSE-KMS 的 PUT 以 400 InvalidRequest 拒绝且不落盘,主密钥下的 SSE-S3 仍能往返。 | +| `ENC-205` | SseCTripleNegatives | 七种不完整或自相矛盾的 SSE-C 三元组,各自以 400 InvalidRequest 拒绝,随后对该键的 HEAD 返回 404。 | +| `ENC-206` | SseCCopySourceKey | 从 SSE-C 源复制时,不带或带错源密钥都以明确的 400 拒绝且不落盘;带对源密钥时,目标对象只能用它自己的密钥打开。 | +| `ENC-207` | SseCMultipartExact | SSE-C 多段上传的 CreateMultipartUpload 与 CompleteMultipartUpload 响应恰好只带客户头,带密钥读回字节一致,不带密钥被拒绝。 | +| `ENC-208` | SseCPartKeyMismatch | UploadPart 不带密钥、带另一把密钥、或对明文上传带密钥,均以 400 InvalidRequest 拒绝;之后这次 SSE-C 上传仍能完成。 | +| `ENC-209` | SseReadHeaderMismatch | 六种读请求头与对象落盘方式不符的 GET,各以确切的错误码拒绝,且不返回对象字节。 | +| `ENC-210` | ListingEtagNotPlaintextMd5 | ListObjectsV2、ListObjects、ListObjectVersions 都不会把明文的 MD5 作为 SSE-S3 或 SSE-C 对象的 ETag,以一个明文对象作对照。 | + +## `rustfs-kms-test.sh` 里的用例 + +这个套件的服务端运行 KMS,默认密钥为 `kms-default`,后端是 Local 或 Vault KV2。辅助脚本通过 `--kms-default-key` 得到默认密钥 ID,并在用例开始前经 admin 接口创建 `sse-contract-key-1` 与 `sse-contract-key-2`;已存在的密钥直接复用。这些用例排在 `KMS-318` 之后、按密钥授权与故障类用例之前。 + +| 用例 | 名称 | 成立条件 | +| --- | --- | --- | +| `KMS-601` | SseS3KeyNotNamed | KMS 下的 SSE-S3 恰好只带 AES256 并能往返;八种操作的响应都不带 KMS 密钥 ID 头,也不出现默认密钥的名字。 | +| `KMS-602` | SseKmsKeyResolutionExact | 不带密钥 ID 的 SSE-KMS 响应给出默认密钥 ID;显式指定非默认密钥时,0、1、71680 字节对象的 PUT、GET、HEAD 都给出该密钥 ID。 | +| `KMS-603` | SseKmsRangeExact | SSE-KMS 对象的四种范围读返回 206、确切的 Content-Range、对应的明文片段,以及恰好的 SSE-KMS 响应头。 | +| `KMS-604` | BucketDefaultKmsExact | 桶默认 aws:kms 且不带密钥 ID 时固定为默认密钥,SSE-C 仍是 SSE-C;显式 AES256 的 PUT 不继承桶的 KMS 密钥。 | +| `KMS-605` | CopySchemeMatrix | 明文、SSE-S3、SSE-KMS、SSE-C 之间的六种 CopyObject 组合,目标对象的 GET 与 HEAD 恰好是目标方案的响应头,数据字节一致。 | +| `KMS-606` | MultipartSseKmsExact | 三段的 SSE-KMS 上传在创建、完成、GET、HEAD 上恰好带该密钥的 SSE-KMS 响应头,长度完整,ETag 为三段形式。 | +| `KMS-607` | SsePutHeaderNegatives | 十种畸形的 SSE 请求头组合以 400 InvalidArgument 拒绝,不存在的 KMS 密钥以 400 KMS.NotFoundException 拒绝;每个键的 HEAD 返回 404。 | +| `KMS-608` | SseReadHeaderMismatch | 七种读请求头与对象落盘方式不符的 GET(含一个 SSE-KMS 对象),各以确切的错误码拒绝,且不返回对象字节。 | +| `KMS-609` | ContextAndEtagNotEchoed | 带加密上下文写入的对象,其 PUT、GET、HEAD 响应不回显上下文;任何列举都不把明文 MD5 作为加密对象的 ETag。 | + +## 单独运行一条 + +```bash +./rustfs-s3-compat-test.sh --topology single-single -y --cases ENC-204 --package-url +./rustfs-kms-test.sh --topology single-single --backends local -y --cases KMS-605 --package-url + +RUSTFS_ACCESS_KEY=... RUSTFS_SECRET_KEY=... \ + python3 scripts/sse_contract_cases.py --endpoint http://node:9000 --case KMS-605 --kms-default-key kms-default +``` + +辅助脚本需要 Python 3.8 或更新版本,只用标准库。它直接连接 endpoint,不理会代理环境变量。每条用例在名为 `sse-<用例编号>-<随机串>` 的桶里工作,结束后尽力清理。退出码:0 表示用例成立,1 表示不成立(endpoint 连不上也算),64 表示命令行有误。从不使用 2,因为 `run_test` 把它读作 UNSUPPORTED。 + +目录里的编号是 `s3.compatibility.enc-2xx` 和 `source-procedure.kms.kms-6xx`,所以 `--validation-case` 选单条用例的方式与原有用例相同。 + +## 已经验证了什么 + +- 每条用例都在本机单进程服务端上成立,服务端用对应套件写入的环境变量启动:`ENC-2xx` 是仅主密钥;`KMS-6xx` 是 Local 与 Vault KV2 两种 KMS,并另外加上 `RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY=true` 与 `RUSTFS_ENCRYPTION_FRAME_V2=true` 跑过。 +- 用两个套件自己的 `run_all_tests` 对这些服务端跑过这些用例,输出了预期的 `[PASS]` 行;对没有主密钥的服务端,`ENC-201` 与 `ENC-204` 输出 `[FAIL]` 并写出它们看到的拒绝。 +- `test_sse_contract_cases.py` 让每条用例对一个行为符合要求的内存版 S3 跑一遍,再每次改错一个行为跑一遍;对应的用例必须失败并指出它看到了什么。 + +这些用例还没有在机群上跑过。多节点拓扑和打包后的二进制,要等定时套件带上这些用例之后才算覆盖。 + +## 服务端版本 + +这些用例描述的是当前 `main` 的行为。在 rustfs/rustfs#9575 之前构建的服务端上 `ENC-207` 会失败:这样的服务端对 SSE-C 上传的 CreateMultipartUpload 与 CompleteMultipartUpload 多回一个 `x-amz-server-side-encryption: AES256`,用例报告的正是这组响应头。对旧发布版本运行时,应把这条失败看作该版本的已知缺陷。 + +## 有意没有搬过来的部分 + +这些用例取自一个驱动裸服务端二进制的套件。其中有些内容需要已部署集群给不了的条件,因此没有搬:用别的密钥来源启动服务端(完全没有、非法主密钥、Vault Transit、Static 后端)、两个二进制的比较、检查对象在盘上的落盘形态、在整次运行里查找密钥材料。使用不同身份的按密钥授权目前由 `KMS-401`、`KMS-402` 宽松覆盖,这里没有收紧。 diff --git a/docs/validation-migration-map.md b/docs/validation-migration-map.md index 837fbea..b52f7ac 100644 --- a/docs/validation-migration-map.md +++ b/docs/validation-migration-map.md @@ -446,8 +446,11 @@ The table-catalog suite contributes 7 additional `source-procedure.table.*` entries, and the upgrade suite contributes 18 `source-procedure.upgrade.*` entries. Both suites select one existing procedure in dry-run mode and retain the original case-level assertions and -diagnostics. The local catalog therefore contains 261 executable procedure -entries in addition to the 158 canonical source scenarios. +diagnostics. The strict SSE contract cases add 10 `s3.compatibility.enc-2xx` +and 9 `source-procedure.kms.kms-6xx` entries, executed by +`scripts/sse_contract_cases.py` through the same two suites. The local catalog +therefore contains 282 executable procedure entries in addition to the 158 +canonical source scenarios. The complete source-audit crosswalk is recorded in `docs/source-test-migration-inventory.md`. It enumerates all 18 workflows, 17 diff --git a/rustfs-kms-test.sh b/rustfs-kms-test.sh index 649b482..a6d6b7e 100755 --- a/rustfs-kms-test.sh +++ b/rustfs-kms-test.sh @@ -905,6 +905,15 @@ run_all_tests() { run_test KMS-316 "S3SelectCross" test_kms316 run_test KMS-317 "PresignedUrl" test_kms317 run_test KMS-318 "FrameCompat" test_kms318 + run_test KMS-601 "SseS3KeyNotNamed" test_kms601 + run_test KMS-602 "SseKmsKeyResolutionExact" test_kms602 + run_test KMS-603 "SseKmsRangeExact" test_kms603 + run_test KMS-604 "BucketDefaultKmsExact" test_kms604 + run_test KMS-605 "CopySchemeMatrix" test_kms605 + run_test KMS-606 "MultipartSseKmsExact" test_kms606 + run_test KMS-607 "SsePutHeaderNegatives" test_kms607 + run_test KMS-608 "SseReadHeaderMismatch" test_kms608 + run_test KMS-609 "ContextAndEtagNotEchoed" test_kms609 run_test KMS-401 "PerKeySseAuthz" test_kms401 run_test KMS-402 "AnonymousEnforcement" test_kms402 run_test KMS-403 "AdminActionAuthz" test_kms403 @@ -918,6 +927,27 @@ run_all_tests() { fi } +# Strict SSE contract: exact SSE response headers, exact refusal codes, and no +# object left behind by a refused write. The helper talks to the endpoint only +# and creates the keys sse-contract-key-1/2 through the admin API. The cases run +# before the per-key authorization and fault cases, while the default key and +# the KMS service are as the environment setup left them. +sse_contract_case() { + RUSTFS_ACCESS_KEY="${ACCESS_KEY}" RUSTFS_SECRET_KEY="${SECRET_KEY}" \ + python3 "${SCRIPT_DIR}/scripts/sse_contract_cases.py" --endpoint "${ENDPOINT}" --case "$1" \ + --kms-default-key "${KMS_DEFAULT_KEY_ID}" +} + +test_kms601() { sse_contract_case KMS-601; } +test_kms602() { sse_contract_case KMS-602; } +test_kms603() { sse_contract_case KMS-603; } +test_kms604() { sse_contract_case KMS-604; } +test_kms605() { sse_contract_case KMS-605; } +test_kms606() { sse_contract_case KMS-606; } +test_kms607() { sse_contract_case KMS-607; } +test_kms608() { sse_contract_case KMS-608; } +test_kms609() { sse_contract_case KMS-609; } + test_kms101() { rc_run admin kms status local --json assert_rc_ok || return 1 @@ -2352,7 +2382,8 @@ main() { need_cmd jq "JSON processor" need_cmd curl "HTTP client" need_cmd openssl "OpenSSL (SigV4)" - if [ -n "${VALIDATION_CASE}" ]; then need_cmd python3 "validation result writer"; fi + need_cmd python3 "Python 3 (SSE contract cases, validation result writer)" + [ -f "${SCRIPT_DIR}/scripts/sse_contract_cases.py" ] || die "missing scripts/sse_contract_cases.py" log "nodes: ${NODES[*]} package: $(resolve_package_url)" log "backends: ${BACKENDS[*]} topologies: ${SELECTED_TOPOLOGIES[*]}" diff --git a/rustfs-s3-compat-test.sh b/rustfs-s3-compat-test.sh index 5a6fc87..4fe264a 100755 --- a/rustfs-s3-compat-test.sh +++ b/rustfs-s3-compat-test.sh @@ -914,6 +914,26 @@ bulk_delete_regression() { "${S3_BULK_PYTHON}" "${SCRIPT_DIR}/scripts/s3_bulk_delete_regressions.py" "${args[@]}" } +# Strict SSE contract: exact SSE response headers, exact refusal codes, and no +# object left behind by a refused write. The helper talks to the endpoint only; +# this suite's server has RUSTFS_SSE_S3_MASTER_KEY and no KMS, which ENC-204 +# relies on. +sse_contract_case() { + RUSTFS_ACCESS_KEY="${ACCESS_KEY}" RUSTFS_SECRET_KEY="${SECRET_KEY}" \ + python3 "${SCRIPT_DIR}/scripts/sse_contract_cases.py" --endpoint "${ENDPOINT}" --case "$1" +} + +test_enc201() { sse_contract_case ENC-201; } +test_enc202() { sse_contract_case ENC-202; } +test_enc203() { sse_contract_case ENC-203; } +test_enc204() { sse_contract_case ENC-204; } +test_enc205() { sse_contract_case ENC-205; } +test_enc206() { sse_contract_case ENC-206; } +test_enc207() { sse_contract_case ENC-207; } +test_enc208() { sse_contract_case ENC-208; } +test_enc209() { sse_contract_case ENC-209; } +test_enc210() { sse_contract_case ENC-210; } + test_s3c213() { bulk_delete_regression S3C-213; } test_s3c214() { bulk_delete_regression S3C-214; } test_s3c1306() { bulk_delete_regression S3C-1306; } @@ -980,6 +1000,16 @@ run_all_tests() { run_test ENC-111 "SseChecksum" test_enc111 run_test ENC-114 "PresignedUrlSseS3" test_enc114 run_test ENC-117 "SnowballSse" test_enc117 + run_test ENC-201 "SseS3ExactHeaders" test_enc201 + run_test ENC-202 "SseCExactHeaders" test_enc202 + run_test ENC-203 "BucketDefaultExact" test_enc203 + run_test ENC-204 "SseKmsNotDowngraded" test_enc204 + run_test ENC-205 "SseCTripleNegatives" test_enc205 + run_test ENC-206 "SseCCopySourceKey" test_enc206 + run_test ENC-207 "SseCMultipartExact" test_enc207 + run_test ENC-208 "SseCPartKeyMismatch" test_enc208 + run_test ENC-209 "SseReadHeaderMismatch" test_enc209 + run_test ENC-210 "ListingEtagNotPlaintextMd5" test_enc210 run_test S3C-1001 "SigV4Basics" test_s3c1001 run_test S3C-1002 "SigV2Compatibility" test_s3c1002 run_test S3C-1003 "PresignedUrl" test_s3c1003 @@ -3491,6 +3521,7 @@ main() { need_cmd curl "HTTP client" need_cmd openssl "OpenSSL (SigV4)" need_cmd python3 "Python 3 (archive fixtures)" + [ -f "${SCRIPT_DIR}/scripts/sse_contract_cases.py" ] || die "missing scripts/sse_contract_cases.py" need_cmd tar "tar archive tool" if [ "${DRY_RUN}" -eq 0 ] && [ -z "${VALIDATION_CASE}" ]; then case ",${SELECTED_CASES}," in diff --git a/scripts/sse_contract_cases.py b/scripts/sse_contract_cases.py new file mode 100755 index 0000000..1106e6e --- /dev/null +++ b/scripts/sse_contract_cases.py @@ -0,0 +1,872 @@ +#!/usr/bin/env python3 +"""Strict server-side-encryption contract cases against an existing endpoint. + +The cluster suites call one case at a time and take the exit status as its verdict: + + RUSTFS_ACCESS_KEY=... RUSTFS_SECRET_KEY=... \ + python3 scripts/sse_contract_cases.py --endpoint http://node:9000 --case ENC-201 + +A case states what a client must observe, exactly: + +- a response carries the SSE headers of its scheme and no other SSE header; +- a refusal has the expected HTTP status and S3 error code; +- a refused write is followed by a HEAD that must answer 404, so nothing was stored; +- bytes read back are compared by SHA-256 and by Content-Length. + +The `ENC-2xx` cases need a server with `RUSTFS_SSE_S3_MASTER_KEY` and no KMS (the S3 compatibility suite). The +`KMS-6xx` cases need a running KMS with a default key (the KMS suite); they create two more keys through the admin +API. Nothing is deployed, restarted or reconfigured. Standard library only. + +Exit status: 0 the case holds, 1 it does not (an unreachable endpoint included), 64 the command line is wrong. +Status 2 is never used: the suites read it as "unsupported". +""" + +from __future__ import annotations + +import argparse +import base64 +import contextlib +import datetime +import hashlib +import hmac +import http.client +import json +import os +import secrets +import sys +import time +import urllib.parse +import xml.etree.ElementTree as ET + +ADMIN_PREFIX = "/rustfs/admin/v3" +REGION = "us-east-1" +SERVICE = "s3" +UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD" +REQUEST_TIMEOUT = 120.0 +EXIT_USAGE = 64 + +KIB = 1024 +MIB = 1024 * 1024 +SIZE = 70 * KIB +PART = 5 * MIB + +SSE = "x-amz-server-side-encryption" +SSE_KEY_ID = SSE + "-aws-kms-key-id" +SSE_CONTEXT = SSE + "-context" +SSEC = SSE + "-customer-" +COPY_SSEC = "x-amz-copy-source-server-side-encryption-customer-" + +# Keys the KMS cases create next to the suite's default key. Two, so a copy between keys cannot pass by reuse. +KEY_1 = "sse-contract-key-1" +KEY_2 = "sse-contract-key-2" +MISSING_KEY = "sse-contract-key-that-was-never-created" + + +class CaseFailed(Exception): + """An expectation later steps depend on does not hold; the case ends here.""" + + +class NoResponse(CaseFailed): + """The endpoint did not answer. The suites have no verdict for that, so it fails the case.""" + + +# --------------------------------------------------------------------------- +# Deterministic test data +# --------------------------------------------------------------------------- + +def plain(seed, size): + """Incompressible bytes fully determined by `seed`.""" + out = bytearray() + counter = 0 + while len(out) < size: + out += hashlib.sha256(f"sse-contract plaintext {seed} {counter}".encode()).digest() + counter += 1 + return bytes(out[:size]) + + +def derived_key(label, size=32): + """SSE-C key material derived at run time; the repository carries no key literal.""" + return hashlib.sha256(f"sse-contract key {label}".encode()).digest()[:size] + + +def sha256_hex(data): + return hashlib.sha256(data).hexdigest() + + +KEY_A = derived_key("ssec a") +KEY_B = derived_key("ssec b") + + +# --------------------------------------------------------------------------- +# SigV4 client +# --------------------------------------------------------------------------- + +def _hmac(key, message): + return hmac.new(key, message.encode(), hashlib.sha256).digest() + + +def _uri_encode(value, encode_slash): + return urllib.parse.quote(value, safe="-._~" + ("" if encode_slash else "/")) + + +def _canonical_query(query): + pairs = urllib.parse.parse_qsl(query, keep_blank_values=True) + return "&".join(f"{k}={v}" for k, v in sorted((_uri_encode(k, True), _uri_encode(v, True)) for k, v in pairs)) + + +def sign(method, host, path, query, headers, access_key, secret_key, now): + """Header-signed SigV4 with an unsigned payload: the complete request headers, lower-cased.""" + amz_date = now.strftime("%Y%m%dT%H%M%SZ") + date_stamp = now.strftime("%Y%m%d") + signed = {"host": host, "x-amz-content-sha256": UNSIGNED_PAYLOAD, "x-amz-date": amz_date} + signed.update({name.lower(): value for name, value in (headers or {}).items()}) + names = ";".join(sorted(signed)) + canonical = "\n".join([method, _uri_encode(path, False), _canonical_query(query), + "".join(f"{name}:{' '.join(signed[name].split())}\n" for name in sorted(signed)), names, UNSIGNED_PAYLOAD]) + scope = f"{date_stamp}/{REGION}/{SERVICE}/aws4_request" + to_sign = "\n".join(["AWS4-HMAC-SHA256", amz_date, scope, sha256_hex(canonical.encode())]) + key = _hmac(_hmac(_hmac(_hmac(f"AWS4{secret_key}".encode(), date_stamp), REGION), SERVICE), "aws4_request") + signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest() + signed["authorization"] = f"AWS4-HMAC-SHA256 Credential={access_key}/{scope}, SignedHeaders={names}, Signature={signature}" + return signed + + +class Client: + """One endpoint and one identity. `request` returns (status, lower-cased headers, body) for every HTTP answer.""" + + def __init__(self, endpoint, access_key, secret_key): + parts = urllib.parse.urlsplit(endpoint) + if parts.scheme not in ("http", "https") or not parts.netloc or parts.path not in ("", "/"): + raise ValueError(f"endpoint must be http(s)://host[:port], got {endpoint!r}") + self.scheme, self.netloc = parts.scheme, parts.netloc + self.access_key, self.secret_key = access_key, secret_key + + def request(self, method, path, query="", body=None, headers=None): + now = datetime.datetime.now(datetime.timezone.utc) # noqa: UP017 - the runner may have Python 3.8 + signed = sign(method, self.netloc, path, query, headers, self.access_key, self.secret_key, now) + url = urllib.parse.quote(path, safe="/-._~") + (f"?{query}" if query else "") + connection_type = http.client.HTTPSConnection if self.scheme == "https" else http.client.HTTPConnection + # A direct connection: the endpoint is a cluster node, and a proxy from the environment must not answer for it. + connection = connection_type(self.netloc, timeout=REQUEST_TIMEOUT) + try: + connection.request(method, url, body=body, headers={k: v for k, v in signed.items() if k != "host"}) + response = connection.getresponse() + response_headers = {name.lower(): value for name, value in response.getheaders()} + try: + return response.status, response_headers, response.read() + except http.client.IncompleteRead as err: + raise CaseFailed(f"{method} {path}: HTTP {response.status}, then the body ended after {len(err.partial)} " + f"of {response_headers.get('content-length')} bytes") from err + except (OSError, http.client.HTTPException) as err: + raise NoResponse(f"{method} {path}: no HTTP response from {self.netloc} ({err})") from err + finally: + connection.close() + + def admin(self, method, subpath, query="", payload=None): + body = json.dumps(payload).encode() if payload is not None else None + headers = {"content-type": "application/json"} if body is not None else None + status, _, raw = self.request(method, f"{ADMIN_PREFIX}/{subpath}", query, body, headers) + try: + return status, json.loads(raw) if raw else None + except ValueError: + return status, raw.decode(errors="replace") + + +def s3_error(body): + """(Code, Message) of an S3 XML error document; ('', '') when the body is not one.""" + try: + root = ET.fromstring(body) + except ET.ParseError: + return "", "" + return root.findtext("{*}Code") or root.findtext("Code") or "", root.findtext("{*}Message") or root.findtext("Message") or "" + + +# --------------------------------------------------------------------------- +# SSE request headers and the response headers each scheme must produce +# --------------------------------------------------------------------------- + +def sse_s3(): + return {SSE: "AES256"} + + +def sse_kms(key_id=None, context=None): + headers = {SSE: "aws:kms"} + if key_id: + headers[SSE_KEY_ID] = key_id + if context is not None: + headers[SSE_CONTEXT] = base64.b64encode(json.dumps(context, separators=(",", ":")).encode()).decode() + return headers + + +def key_md5(key): + return base64.b64encode(hashlib.md5(key).digest()).decode() + + +def ssec(key, prefix=SSEC): + """The SSE-C triple; `COPY_SSEC` as the prefix gives the copy-source variant.""" + return {prefix + "algorithm": "AES256", prefix + "key": base64.b64encode(key).decode(), prefix + "key-md5": key_md5(key)} + + +def projection(headers): + """The SSE headers actually present in a response.""" + return {name: value for name, value in headers.items() if name.startswith(SSE)} + + +def projection_s3(): + return {SSE: "AES256"} + + +def projection_kms(key_id): + return {SSE: "aws:kms", SSE_KEY_ID: key_id} + + +def projection_c(key): + return {SSEC + "algorithm": "AES256", SSEC + "key-md5": key_md5(key)} + + +# --------------------------------------------------------------------------- +# S3 operations +# --------------------------------------------------------------------------- + +def put(c, bucket, key, data, headers=None): + return c.request("PUT", f"/{bucket}/{key}", body=data, headers={"content-type": "application/octet-stream", **(headers or {})}) + + +def get(c, bucket, key, headers=None, range_=None): + request_headers = dict(headers or {}) + if range_: + request_headers["range"] = range_ + return c.request("GET", f"/{bucket}/{key}", headers=request_headers or None) + + +def head(c, bucket, key, headers=None): + status, response_headers, _ = c.request("HEAD", f"/{bucket}/{key}", headers=headers) + return status, response_headers + + +def copy(c, bucket, key, source_bucket, source_key, headers=None): + """CopyObject; `headers` carries the destination SSE headers and the copy-source SSE-C triple.""" + return c.request("PUT", f"/{bucket}/{key}", + headers={"x-amz-copy-source": f"/{source_bucket}/{urllib.parse.quote(source_key)}", **(headers or {})}) + + +def create_multipart(c, bucket, key, headers=None): + status, response_headers, body = c.request("POST", f"/{bucket}/{key}", query="uploads=", headers=headers) + upload_id = None + if status == 200: + with contextlib.suppress(ET.ParseError): + upload_id = ET.fromstring(body).findtext("{*}UploadId") + return status, response_headers, upload_id, body + + +def upload_part(c, bucket, key, upload_id, number, data, headers=None): + return c.request("PUT", f"/{bucket}/{key}", query=f"partNumber={number}&uploadId={_uri_encode(upload_id, True)}", + body=data, headers=headers) + + +def complete_multipart(c, bucket, key, upload_id, parts, headers=None): + parts_xml = "".join(f"{number}{etag}" for number, etag in parts) + return c.request("POST", f"/{bucket}/{key}", query=f"uploadId={_uri_encode(upload_id, True)}", + body=f"{parts_xml}".encode(), + headers={"content-type": "application/xml", **(headers or {})}) + + +def list_parts(c, bucket, key, upload_id): + return c.request("GET", f"/{bucket}/{key}", query=f"uploadId={_uri_encode(upload_id, True)}") + + +def listing(c, bucket, query, entry): + """{key: (size, ETag without quotes)} from one page of a listing; None when the listing is refused.""" + status, _, body = c.request("GET", f"/{bucket}", query=query) + if status != 200: + return None + return {item.findtext("{*}Key"): (int(item.findtext("{*}Size") or -1), (item.findtext("{*}ETag") or "").strip('"')) + for item in ET.fromstring(body).findall("{*}" + entry)} + + +def put_bucket_encryption(c, bucket, algorithm, kms_key_id=None): + key_xml = f"{kms_key_id}" if kms_key_id else "" + payload = ('' + f"{algorithm}{key_xml}" + "").encode() + return c.request("PUT", f"/{bucket}", query="encryption=", body=payload, headers={"content-type": "application/xml"}) + + +def get_bucket_encryption(c, bucket): + """(status, {'algorithm', 'kms_key_id'}).""" + status, _, body = c.request("GET", f"/{bucket}", query="encryption=") + config = {} + if status == 200: + root = ET.fromstring(body) + config = {"algorithm": root.findtext(".//{*}SSEAlgorithm"), "kms_key_id": root.findtext(".//{*}KMSMasterKeyID")} + return status, config + + +def delete_bucket_encryption(c, bucket): + return c.request("DELETE", f"/{bucket}", query="encryption=") + + +def ensure_kms_key(c, name): + """The named KMS key exists afterwards, or the case cannot start.""" + quoted = urllib.parse.quote(name, safe="") + if c.admin("GET", f"kms/keys/{quoted}")[0] == 200: + return + created, response = c.admin("POST", "kms/keys", payload={"tags": {"name": name}}) + if c.admin("GET", f"kms/keys/{quoted}")[0] != 200: + raise CaseFailed(f"KMS key {name} could not be created: HTTP {created} {str(response)[:200]}") + + +# --------------------------------------------------------------------------- +# Expectations +# --------------------------------------------------------------------------- + +class Ctx: + """One case: the client, the failures found so far, and how many expectations were evaluated.""" + + def __init__(self, client, case_id, default_key=""): + self.client = client + self.case_id = case_id + self.default_key = default_key + self.failures = [] + self.evaluated = 0 + self.buckets = [] + self._row = "" + + def check(self, condition, message): + self.evaluated += 1 + if not condition: + self.failures.append(f"[{self._row}] {message}" if self._row else message) + return bool(condition) + + def need(self, condition, message): + self.evaluated += 1 + if not condition: + raise CaseFailed(message) + + @contextlib.contextmanager + def row(self, name): + """One input of a table-driven case: a broken row is reported and the next one still runs.""" + self._row = name + try: + yield + except NoResponse: + raise + except CaseFailed as err: + self.failures.append(f"[{name}] {err}") + finally: + self._row = "" + + def ok(self, response, what, want=200): + """The exchange answered `want`; anything else ends the case or the row, since later steps depend on it.""" + status, headers, body = response + code, message = s3_error(body) + self.need(status == want, f"{what}: HTTP {status} {code} {message[:200]!r}, expected {want}") + return headers, body + + def refused(self, response, status, code, what): + """An explicit refusal: the exact status and the exact S3 error code.""" + got_status, _, body = response + got_code, got_message = s3_error(body) + return self.check(got_status == status and got_code == code, + f"{what}: HTTP {got_status} {got_code!r} {got_message[:200]!r}, expected {status} {code!r}") + + def projection(self, headers, want, what): + """The SSE headers present are exactly `want`: nothing missing and nothing extra.""" + got = projection(headers) + self.check(got == want, f"{what}: SSE headers {got}, expected exactly {want}") + + def bytes_equal(self, headers, body, data, what): + self.check(sha256_hex(body) == sha256_hex(data), + f"{what}: body sha256 {sha256_hex(body)[:16]} len {len(body)}, expected {sha256_hex(data)[:16]} len {len(data)}") + self.check(headers.get("content-length") == str(len(data)), + f"{what}: Content-Length {headers.get('content-length')}, expected {len(data)}") + + def absent(self, bucket, key, what, headers=None): + """A refused write left nothing behind.""" + status, _ = head(self.client, bucket, key, headers) + self.check(status == 404, f"{what}: HEAD after the refused write is {status}, expected 404 (nothing may be stored)") + + def bucket(self): + """A bucket of this run only, so a rerun on a kept environment starts from nothing.""" + name = f"sse-{self.case_id.lower()}-{secrets.token_hex(4)}" + deadline = time.monotonic() + 30.0 + while True: + status, _, body = self.client.request("PUT", f"/{name}") + if status < 500 or time.monotonic() > deadline: + break + time.sleep(0.5) + self.need(status == 200, f"CreateBucket {name}: HTTP {status} {s3_error(body)}") + self.buckets.append(name) + return name + + def roundtrip(self, bucket, key, data, write_headers, read_headers, want, what): + """PUT, GET and HEAD one object: the SSE headers hold on all three and the bytes come back unchanged.""" + put_headers, _ = self.ok(put(self.client, bucket, key, data, write_headers), f"{what} PUT") + self.projection(put_headers, want, f"{what} PUT") + self.read_back(bucket, key, data, read_headers, want, what) + status, head_headers = head(self.client, bucket, key, read_headers) + if self.check(status == 200, f"{what} HEAD: HTTP {status}, expected 200"): + self.projection(head_headers, want, f"{what} HEAD") + self.check(head_headers.get("content-length") == str(len(data)), + f"{what} HEAD: Content-Length {head_headers.get('content-length')}, expected {len(data)}") + + def read_back(self, bucket, key, data, read_headers, want, what): + get_headers, body = self.ok(get(self.client, bucket, key, read_headers), f"{what} GET") + self.projection(get_headers, want, f"{what} GET") + self.bytes_equal(get_headers, body, data, f"{what} GET") + + def upload(self, bucket, key, parts, create_headers, part_headers, complete_headers): + """A full multipart upload; returns the CreateMultipartUpload and CompleteMultipartUpload response headers.""" + status, create_response, upload_id, body = create_multipart(self.client, bucket, key, create_headers) + self.need(status == 200 and upload_id, f"CreateMultipartUpload: HTTP {status} {s3_error(body)}") + etags = [] + for number, data in enumerate(parts, start=1): + part_response, _ = self.ok(upload_part(self.client, bucket, key, upload_id, number, data, part_headers), + f"UploadPart {number}") + etags.append((number, part_response.get("etag", ""))) + complete_response, _ = self.ok(complete_multipart(self.client, bucket, key, upload_id, etags, complete_headers), + "CompleteMultipartUpload") + return create_response, complete_response + + def cleanup(self): + """Best effort: the verdict is already decided, and the suites remove the data directories afterwards.""" + for bucket in self.buckets: + with contextlib.suppress(Exception): + for key in listing(self.client, bucket, "list-type=2", "Contents") or {}: + self.client.request("DELETE", f"/{bucket}/{key}") + self.client.request("DELETE", f"/{bucket}") + + +# --------------------------------------------------------------------------- +# Cases for a server with a local master key and no KMS +# --------------------------------------------------------------------------- + +def _sizes(c, bucket, schemes, seed): + """Sizes 0, 1 and 70 KiB under each scheme, and the listing reports the plaintext sizes.""" + expected = {} + for name, write_headers, read_headers, want in schemes: + for size in (0, 1, SIZE): + key = f"{name}-{size}" + with c.row(key): + c.roundtrip(bucket, key, plain(f"{seed} {key}", size), write_headers, read_headers, want, key) + expected[key] = size + listed = listing(c.client, bucket, "list-type=2", "Contents") + c.need(listed is not None, "ListObjectsV2 was refused") + for key, size in expected.items(): + c.check(listed.get(key, (None, ""))[0] == size, + f"ListObjectsV2 reports size {listed.get(key, (None, ''))[0]} for {key}, expected the plaintext size {size}") + + +def enc_201(c): + bucket = c.bucket() + _sizes(c, bucket, [("sse-s3", sse_s3(), None, projection_s3())], "enc-201") + + +def enc_202(c): + bucket = c.bucket() + _sizes(c, bucket, [("sse-c", ssec(KEY_A), ssec(KEY_A), projection_c(KEY_A))], "enc-202") + c.refused(get(c.client, bucket, f"sse-c-{SIZE}"), 400, "InvalidRequest", "GET without the customer key") + + +def enc_203(c): + bucket = c.bucket() + before, after = plain("enc-203 before", SIZE), plain("enc-203 after", SIZE) + c.ok(put_bucket_encryption(c.client, bucket, "AES256"), "PutBucketEncryption") + with c.row("default-applies"): + c.roundtrip(bucket, "before", before, None, None, projection_s3(), "PUT that names no scheme") + with c.row("sse-c-stays-sse-c"): + c.roundtrip(bucket, "customer", plain("enc-203 customer", SIZE), ssec(KEY_A), ssec(KEY_A), projection_c(KEY_A), "SSE-C") + c.refused(get(c.client, bucket, "customer"), 400, "InvalidRequest", "GET without the customer key") + c.ok(delete_bucket_encryption(c.client, bucket), "DeleteBucketEncryption", want=204) + with c.row("default-removed"): + c.roundtrip(bucket, "after", after, None, None, {}, "PUT after the default was removed") + c.read_back(bucket, "before", before, None, projection_s3(), "object written under the default, read afterwards") + + +def enc_204(c): + bucket = c.bucket() + c.roundtrip(bucket, "sse-s3", plain("enc-204 s3", SIZE), sse_s3(), None, projection_s3(), "SSE-S3") + # An object that says aws:kms while only the local master key protects it would be a silent downgrade. + c.refused(put(c.client, bucket, "sse-kms", plain("enc-204 kms", SIZE), sse_kms()), 400, "InvalidRequest", "SSE-KMS PUT") + c.absent(bucket, "sse-kms", "SSE-KMS PUT") + + +def enc_205(c): + bucket = c.bucket() + data = plain("enc-205", KIB) + triple = ssec(KEY_A) + algorithm, key, md5 = SSEC + "algorithm", SSEC + "key", SSEC + "key-md5" + rows = { + "algorithm-only": {algorithm: "AES256"}, + "key-only": {key: triple[key]}, + "md5-missing": {algorithm: "AES256", key: triple[key]}, + "key-not-base64": {**triple, key: "!!! not base64 !!!"}, + "key-16-bytes": ssec(derived_key("short", 16)), + "md5-of-another-key": {**triple, md5: key_md5(KEY_B)}, + "algorithm-aes128": {**triple, algorithm: "AES128"}, + } + for name, headers in rows.items(): + with c.row(name): + # A partial triple that is treated as "no SSE-C" would store the object in plaintext. + c.refused(put(c.client, bucket, name, data, headers), 400, "InvalidRequest", "PUT") + c.absent(bucket, name, "PUT") + + +def enc_206(c): + bucket = c.bucket() + c.ok(put(c.client, bucket, "src", plain("enc-206", SIZE), ssec(KEY_A)), "source PUT") + for name, copy_source in (("no-source-key", {}), ("wrong-source-key", ssec(KEY_B, COPY_SSEC))): + with c.row(name): + status, _, body = copy(c.client, bucket, f"dst-{name}", bucket, "src", copy_source) + code, message = s3_error(body) + c.check(status == 400 and code != "", f"CopyObject: HTTP {status} {code!r} {message[:160]!r}, expected an explicit 400") + c.absent(bucket, f"dst-{name}", "CopyObject") + with c.row("right-source-key"): + data = plain("enc-206", SIZE) + c.ok(copy(c.client, bucket, "dst-ok", bucket, "src", {**ssec(KEY_A, COPY_SSEC), **ssec(KEY_B)}), "CopyObject") + c.read_back(bucket, "dst-ok", data, ssec(KEY_B), projection_c(KEY_B), "destination") + # The data was re-encrypted, not relabelled: the source key no longer opens the destination. + c.refused(get(c.client, bucket, "dst-ok", ssec(KEY_A)), 400, "InvalidRequest", "destination GET with the source key") + + +def enc_207(c): + bucket = c.bucket() + parts = [plain("enc-207 part 1", PART), plain("enc-207 part 2", MIB + 17)] + triple, want = ssec(KEY_A), projection_c(KEY_A) + create_response, complete_response = c.upload(bucket, "object", parts, triple, triple, triple) + # An SSE-C upload answers with its customer-key headers only: `x-amz-server-side-encryption` names a managed algorithm. + c.projection(create_response, want, "CreateMultipartUpload") + c.projection(complete_response, want, "CompleteMultipartUpload") + c.read_back(bucket, "object", b"".join(parts), triple, want, "completed object") + c.refused(get(c.client, bucket, "object"), 400, "InvalidRequest", "GET without the customer key") + + +def enc_208(c): + bucket = c.bucket() + triple = ssec(KEY_A) + part_1, part_2 = plain("enc-208 part 1", PART), plain("enc-208 part 2", KIB) + status, _, upload_id, body = create_multipart(c.client, bucket, "ssec", triple) + c.need(status == 200 and upload_id, f"CreateMultipartUpload (SSE-C): HTTP {status} {s3_error(body)}") + with c.row("part-without-key"): + c.refused(upload_part(c.client, bucket, "ssec", upload_id, 1, part_1), 400, "InvalidRequest", "UploadPart") + with c.row("part-with-another-key"): + c.refused(upload_part(c.client, bucket, "ssec", upload_id, 1, part_1, ssec(KEY_B)), 400, "InvalidRequest", "UploadPart") + status, _, plain_upload, body = create_multipart(c.client, bucket, "plain") + c.need(status == 200 and plain_upload, f"CreateMultipartUpload (plaintext): HTTP {status} {s3_error(body)}") + with c.row("key-on-plaintext-upload"): + c.refused(upload_part(c.client, bucket, "plain", plain_upload, 1, part_1, triple), 400, "InvalidRequest", "UploadPart") + with c.row("upload-still-usable"): + etags = [] + for number, data in ((1, part_1), (2, part_2)): + response, _ = c.ok(upload_part(c.client, bucket, "ssec", upload_id, number, data, triple), f"UploadPart {number}") + etags.append((number, response.get("etag", ""))) + c.ok(complete_multipart(c.client, bucket, "ssec", upload_id, etags, triple), "CompleteMultipartUpload") + c.read_back(bucket, "ssec", part_1 + part_2, triple, projection_c(KEY_A), "completed object") + + +def _read_mismatches(c, bucket, objects, rows): + """GET with read headers that do not match how the object was stored: refused, and no object bytes returned.""" + data = {name: plain(f"{c.case_id} {name}", SIZE) for name in objects} + for name, headers in objects.items(): + c.ok(put(c.client, bucket, name, data[name], headers), f"{name} PUT") + for name, (target, headers, code) in rows.items(): + with c.row(name): + response = get(c.client, bucket, target, headers) + c.refused(response, 400, code, "GET") + c.check(data[target][:64] not in response[2], "the refused GET returned object bytes") + + +def _ssec_read_rows(): + md5_only_matches = {**ssec(KEY_B), SSEC + "key-md5": key_md5(KEY_A)} + return { + "ssec-without-key": ("ssec", None, "InvalidRequest"), + "ssec-with-another-key": ("ssec", ssec(KEY_B), "InvalidRequest"), + "ssec-right-md5-wrong-key": ("ssec", md5_only_matches, "InvalidRequest"), + "plain-with-ssec": ("plain", ssec(KEY_A), "InvalidRequest"), + "plain-with-aes256": ("plain", sse_s3(), "InvalidArgument"), + # No customer key came with the request, and that is what the refusal reports; the aws:kms header is not reached. + "ssec-with-aws-kms": ("ssec", sse_kms(), "InvalidRequest"), + } + + +def enc_209(c): + _read_mismatches(c, c.bucket(), {"ssec": ssec(KEY_A), "plain": None}, _ssec_read_rows()) + + +def _listed_etags(c, bucket, schemes): + """No listing shows the MD5 of an encrypted object's plaintext as its ETag.""" + md5 = {} + for name, headers in schemes.items(): + data = plain(f"{c.case_id} etag {name}", SIZE) + md5[name] = hashlib.md5(data).hexdigest() + c.ok(put(c.client, bucket, name, data, headers), f"{name} PUT") + listings = {"list-objects-v2": ("list-type=2", "Contents"), "list-objects-v1": ("", "Contents"), + "list-object-versions": ("versions=", "Version")} + for name, (query, entry) in listings.items(): + with c.row(name): + listed = listing(c.client, bucket, query, entry) + c.need(listed is not None, "the listing was refused") + etags = {key: etag for key, (_, etag) in listed.items()} + c.check(sorted(etags) == sorted(schemes), f"the listing names {sorted(etags)}, expected {sorted(schemes)}") + # The plaintext object is the control: its ETag is its MD5, which is what a leak would look like. + c.check(etags.get("plain") == md5["plain"], + f"plaintext object: listed ETag {etags.get('plain')!r} is not its MD5, so the comparison proves nothing") + for scheme in schemes: + if scheme != "plain": + c.check(etags.get(scheme) not in (None, "", md5[scheme]), + f"{scheme} object: the listed ETag {etags.get(scheme)!r} is missing or is the MD5 of the plaintext") + + +def enc_210(c): + _listed_etags(c, c.bucket(), {"plain": None, "sse-s3": sse_s3(), "sse-c": ssec(KEY_A)}) + + +# --------------------------------------------------------------------------- +# Cases for a server with a running KMS and a default key +# --------------------------------------------------------------------------- + +def kms_601(c): + bucket = c.bucket() + data, part = plain("kms-601", SIZE), plain("kms-601 part", PART) + c.roundtrip(bucket, "object", data, sse_s3(), None, projection_s3(), "SSE-S3") + # SSE-S3 is "a key the service manages": no response may say which KMS key wraps the data key. + responses = {"PutObject": put(c.client, bucket, "named", data, sse_s3()), "GetObject": get(c.client, bucket, "named")} + status, head_headers = head(c.client, bucket, "named") + responses["HeadObject"] = (status, head_headers, b"") + responses["CopyObject"] = copy(c.client, bucket, "copy", bucket, "named", sse_s3()) + status, create_headers, upload_id, body = create_multipart(c.client, bucket, "multipart", sse_s3()) + responses["CreateMultipartUpload"] = (status, create_headers, body) + c.need(status == 200 and upload_id, f"CreateMultipartUpload: HTTP {status} {s3_error(body)}") + responses["UploadPart"] = upload_part(c.client, bucket, "multipart", upload_id, 1, part) + responses["ListParts"] = list_parts(c.client, bucket, "multipart", upload_id) + etag = responses["UploadPart"][1].get("etag", "") + responses["CompleteMultipartUpload"] = complete_multipart(c.client, bucket, "multipart", upload_id, [(1, etag)]) + for name, (status, headers, body) in responses.items(): + with c.row(name): + c.check(status == 200, f"HTTP {status}, expected 200") + c.check(SSE_KEY_ID not in headers, f"the response carries {SSE_KEY_ID}: {headers.get(SSE_KEY_ID)!r}") + if name != "GetObject": + c.check(c.default_key.encode() not in body, f"the response body names the default key {c.default_key}") + for header, value in headers.items(): + c.check(c.default_key not in value, f"header {header} names the default key {c.default_key}") + + +def kms_602(c): + bucket = c.bucket() + status, body = c.client.admin("GET", "kms/status") + c.check(status == 200 and c.default_key in json.dumps(body), + f"KMS status does not report the default key {c.default_key}: HTTP {status} {str(body)[:200]}") + with c.row("no-key-id"): + c.roundtrip(bucket, "default", plain("kms-602 default", SIZE), sse_kms(), None, projection_kms(c.default_key), "SSE-KMS") + # KEY_1 differs from the default key, so a response naming the wrong key cannot pass. + _sizes(c, bucket, [("sse-kms", sse_kms(KEY_1), None, projection_kms(KEY_1))], "kms-602") + + +def kms_603(c): + bucket = c.bucket() + data = plain("kms-603", SIZE) + c.ok(put(c.client, bucket, "object", data, sse_kms(KEY_1)), "PUT") + last = SIZE - 1 + ranges = {"first-byte": ("bytes=0-0", 0, 0), "last-byte": (f"bytes={last}-{last}", last, last), + "suffix-100": ("bytes=-100", SIZE - 100, last), "across-8k": ("bytes=8000-8500", 8000, 8500)} + for name, (spec, first, end) in ranges.items(): + with c.row(name): + status, headers, body = get(c.client, bucket, "object", range_=spec) + c.check(status == 206, f"Range {spec}: HTTP {status}, expected 206") + c.check(headers.get("content-range") == f"bytes {first}-{end}/{SIZE}", + f"Range {spec}: Content-Range {headers.get('content-range')!r}, expected 'bytes {first}-{end}/{SIZE}'") + c.check(body == data[first:end + 1], f"Range {spec}: body sha256 {sha256_hex(body)[:16]} len {len(body)} is not the plaintext slice") + c.projection(headers, projection_kms(KEY_1), f"Range {spec}") + + +def kms_604(c): + with c.row("default-without-key-id"): + bucket = c.bucket() + c.ok(put_bucket_encryption(c.client, bucket, "aws:kms"), "PutBucketEncryption") + status, config = get_bucket_encryption(c.client, bucket) + c.check(status == 200 and config.get("algorithm") == "aws:kms" and config.get("kms_key_id") == c.default_key, + f"GetBucketEncryption: HTTP {status} {config}, expected aws:kms with KMSMasterKeyID {c.default_key}") + c.roundtrip(bucket, "object", plain("kms-604 default", SIZE), None, None, projection_kms(c.default_key), "PUT that names no scheme") + c.roundtrip(bucket, "customer", plain("kms-604 customer", SIZE), ssec(KEY_A), ssec(KEY_A), projection_c(KEY_A), "SSE-C") + c.refused(get(c.client, bucket, "customer"), 400, "InvalidRequest", "GET without the customer key") + with c.row("explicit-aes256-wins"): + bucket = c.bucket() + c.ok(put_bucket_encryption(c.client, bucket, "aws:kms", KEY_1), "PutBucketEncryption") + # No key id in the expected headers: the request did not inherit the bucket's KMS key. + c.roundtrip(bucket, "object", plain("kms-604 explicit", SIZE), sse_s3(), None, projection_s3(), "explicit AES256") + + +def kms_605(c): + bucket = c.bucket() + # name: (source write headers, copy-source headers, destination headers, destination read headers, expected headers) + combos = { + "plain-to-kms": (None, {}, sse_kms(KEY_2), None, projection_kms(KEY_2)), + "kms-to-ssec": (sse_kms(KEY_1), {}, ssec(KEY_B), ssec(KEY_B), projection_c(KEY_B)), + "ssec-to-s3": (ssec(KEY_A), ssec(KEY_A, COPY_SSEC), sse_s3(), None, projection_s3()), + "ssec-to-ssec": (ssec(KEY_A), ssec(KEY_A, COPY_SSEC), ssec(KEY_B), ssec(KEY_B), projection_c(KEY_B)), + "s3-to-none": (sse_s3(), {}, {}, None, {}), + "kms-to-kms": (sse_kms(KEY_1), {}, sse_kms(KEY_2), None, projection_kms(KEY_2)), + } + for name, (source_headers, copy_source, destination, read_headers, want) in combos.items(): + with c.row(name): + data = plain(f"kms-605 {name}", SIZE) + c.ok(put(c.client, bucket, f"{name}-src", data, source_headers), "source PUT") + c.ok(copy(c.client, bucket, f"{name}-dst", bucket, f"{name}-src", {**copy_source, **destination}), "CopyObject") + c.read_back(bucket, f"{name}-dst", data, read_headers, want, "destination") + status, head_headers = head(c.client, bucket, f"{name}-dst", read_headers) + if c.check(status == 200, f"destination HEAD: HTTP {status}, expected 200"): + c.projection(head_headers, want, "destination HEAD") + if name == "ssec-to-ssec": + c.refused(get(c.client, bucket, f"{name}-dst", ssec(KEY_A)), 400, "InvalidRequest", "destination GET with the source key") + + +def kms_606(c): + bucket = c.bucket() + parts = [plain("kms-606 part 1", PART), plain("kms-606 part 2", PART), plain("kms-606 part 3", MIB + 17)] + data = b"".join(parts) + want = projection_kms(KEY_1) + create_response, complete_response = c.upload(bucket, "object", parts, sse_kms(KEY_1), None, None) + c.projection(create_response, want, "CreateMultipartUpload") + c.projection(complete_response, want, "CompleteMultipartUpload") + c.read_back(bucket, "object", data, None, want, "completed object") + status, head_headers = head(c.client, bucket, "object") + if c.check(status == 200, f"HEAD: HTTP {status}, expected 200"): + c.projection(head_headers, want, "HEAD") + c.check(head_headers.get("content-length") == str(len(data)), + f"HEAD: Content-Length {head_headers.get('content-length')}, expected {len(data)}") + etag = head_headers.get("etag", "").strip('"') + c.check(len(etag) == 34 and etag.endswith("-3"), f"HEAD: ETag {etag!r}, expected 32 hex digits followed by -3") + + +def _b64(text): + return base64.b64encode(text.encode()).decode() + + +def kms_607(c): + bucket = c.bucket() + data = plain("kms-607", KIB) + rows = { + "algorithm-aes128": ({SSE: "AES128"}, "InvalidArgument"), + "algorithm-lowercase": ({SSE: "aes256"}, "InvalidArgument"), + "ssec-with-aes256": ({**ssec(KEY_A), SSE: "AES256"}, "InvalidArgument"), + "ssec-with-key-id": ({**ssec(KEY_A), SSE_KEY_ID: KEY_1}, "InvalidArgument"), + "key-id-without-algorithm": ({SSE_KEY_ID: KEY_1}, "InvalidArgument"), + "aes256-with-key-id": ({SSE: "AES256", SSE_KEY_ID: KEY_1}, "InvalidArgument"), + "context-without-algorithm": ({SSE_CONTEXT: _b64('{"dept":"a"}')}, "InvalidArgument"), + "context-not-base64": ({SSE: "aws:kms", SSE_CONTEXT: "!!! not base64 !!!"}, "InvalidArgument"), + "context-json-array": ({SSE: "aws:kms", SSE_CONTEXT: _b64('["dept","a"]')}, "InvalidArgument"), + "context-key-equals-bucket": ({SSE: "aws:kms", SSE_CONTEXT: _b64(json.dumps({bucket: "elsewhere"}))}, "InvalidArgument"), + "key-that-does-not-exist": (sse_kms(MISSING_KEY), "KMS.NotFoundException"), + } + for name, (headers, code) in rows.items(): + with c.row(name): + c.refused(put(c.client, bucket, name, data, headers), 400, code, "PUT") + c.absent(bucket, name, "PUT") + + +def kms_608(c): + rows = {**_ssec_read_rows(), "kms-with-ssec": ("kms", ssec(KEY_A), "InvalidArgument")} + _read_mismatches(c, c.bucket(), {"ssec": ssec(KEY_A), "kms": sse_kms(KEY_1), "plain": None}, rows) + + +def kms_609(c): + bucket = c.bucket() + # One pair only: the server stores the context as a map and writes it back in no particular order. + write_headers = sse_kms(KEY_1, {"department": "finance"}) + encoded = write_headers[SSE_CONTEXT] + data = plain("kms-609", SIZE) + want = projection_kms(KEY_1) + put_headers, _ = c.ok(put(c.client, bucket, "context", data, write_headers), "PUT with an encryption context") + get_headers, body = c.ok(get(c.client, bucket, "context"), "GET") + c.bytes_equal(get_headers, body, data, "GET") + status, head_headers = head(c.client, bucket, "context") + c.need(status == 200, f"HEAD: HTTP {status}, expected 200") + for what, headers in (("PUT", put_headers), ("GET", get_headers), ("HEAD", head_headers)): + with c.row(what.lower()): + c.projection(headers, want, what) + for name, value in headers.items(): + c.check(encoded not in value and "finance" not in value, f"{what}: header {name} repeats the encryption context") + _listed_etags(c, c.bucket(), {"plain": None, "sse-s3": sse_s3(), "sse-kms": sse_kms(KEY_1), "sse-c": ssec(KEY_A)}) + + +# id: (name, needs KMS, function) +CASES = { + "ENC-201": ("SseS3ExactHeaders", False, enc_201), + "ENC-202": ("SseCExactHeaders", False, enc_202), + "ENC-203": ("BucketDefaultExact", False, enc_203), + "ENC-204": ("SseKmsNotDowngraded", False, enc_204), + "ENC-205": ("SseCTripleNegatives", False, enc_205), + "ENC-206": ("SseCCopySourceKey", False, enc_206), + "ENC-207": ("SseCMultipartExact", False, enc_207), + "ENC-208": ("SseCPartKeyMismatch", False, enc_208), + "ENC-209": ("SseReadHeaderMismatch", False, enc_209), + "ENC-210": ("ListingEtagNotPlaintextMd5", False, enc_210), + "KMS-601": ("SseS3KeyNotNamed", True, kms_601), + "KMS-602": ("SseKmsKeyResolutionExact", True, kms_602), + "KMS-603": ("SseKmsRangeExact", True, kms_603), + "KMS-604": ("BucketDefaultKmsExact", True, kms_604), + "KMS-605": ("CopySchemeMatrix", True, kms_605), + "KMS-606": ("MultipartSseKmsExact", True, kms_606), + "KMS-607": ("SsePutHeaderNegatives", True, kms_607), + "KMS-608": ("SseReadHeaderMismatch", True, kms_608), + "KMS-609": ("ContextAndEtagNotEchoed", True, kms_609), +} + + +def run_case(client, case_id, default_key=""): + """(failures, expectations evaluated) for one case.""" + _, needs_kms, function = CASES[case_id] + ctx = Ctx(client, case_id, default_key) + try: + if needs_kms: + for name in (KEY_1, KEY_2): + ensure_kms_key(client, name) + function(ctx) + except CaseFailed as err: + ctx.failures.append(str(err)) + finally: + with contextlib.suppress(Exception): + ctx.cleanup() + if not ctx.failures and ctx.evaluated == 0: + ctx.failures.append("the case evaluated no expectation") + return ctx.failures, ctx.evaluated + + +class _Parser(argparse.ArgumentParser): + def error(self, message): + self.print_usage(sys.stderr) + self.exit(EXIT_USAGE, f"{self.prog}: error: {message}\n") + + +def main(argv=None): + parser = _Parser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--endpoint", help="http(s)://host[:port] of one node") + parser.add_argument("--case", choices=sorted(CASES), help="the case to run") + parser.add_argument("--kms-default-key", default="", help="the KMS default key id of the server; required by KMS-6xx") + parser.add_argument("--list", action="store_true", help="print the case ids and names, then exit") + args = parser.parse_args(argv) + if args.list: + for case_id, (name, _, _) in CASES.items(): + print(f"{case_id} {name}") + return 0 + if not args.endpoint or not args.case: + parser.error("--endpoint and --case are required") + name, needs_kms, _ = CASES[args.case] + if needs_kms and not args.kms_default_key: + parser.error(f"{args.case} requires --kms-default-key") + access_key, secret_key = os.environ.get("RUSTFS_ACCESS_KEY"), os.environ.get("RUSTFS_SECRET_KEY") + if not access_key or not secret_key: + parser.error("RUSTFS_ACCESS_KEY and RUSTFS_SECRET_KEY must be set") + try: + client = Client(args.endpoint, access_key, secret_key) + except ValueError as err: + parser.error(str(err)) + failures, evaluated = run_case(client, args.case, args.kms_default_key) + for failure in failures: + print(f"{args.case} {name}: {failure}") + print(f"{args.case} {name}: {evaluated} expectations evaluated, {len(failures)} failed") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test_sse_contract_cases.py b/test_sse_contract_cases.py new file mode 100644 index 0000000..1a066e6 --- /dev/null +++ b/test_sse_contract_cases.py @@ -0,0 +1,457 @@ +"""Offline checks of scripts/sse_contract_cases.py. + +A small in-memory S3 stands in for the server. Left alone it behaves the way the cases require, so every case must +hold on it; with one behavior changed, the case written for that behavior must fail and say why. This validates the +oracles and the wiring into the suites, not RustFS. +""" + +import base64 +import datetime +import hashlib +import importlib.util +import io +import json +import re +import unittest +import urllib.parse +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +_spec = importlib.util.spec_from_file_location("sse_contract_cases", ROOT / "scripts" / "sse_contract_cases.py") +cc = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(cc) + +DEFAULT_KEY = "kms-default" +XMLNS = 'xmlns="http://s3.amazonaws.com/doc/2006-03-01/"' + + +def _error(status, code, message="refused"): + return status, {"content-type": "application/xml"}, f"{code}{message}".encode() + + +class FakeS3: + """The subset of S3 and of the KMS admin API the cases use. `mutations` names behaviors to get wrong.""" + + admin = cc.Client.admin + + def __init__(self, master_key=False, kms=False, mutations=()): + self.master_key, self.kms = master_key, kms + self.mutations = set(mutations) + self.buckets = {} # name -> {"objects": {key: object}, "default": (algorithm, key id) | None} + self.uploads = {} # upload id -> {"scheme": ..., "parts": {number: bytes}} + self.keys = {DEFAULT_KEY} if kms else set() + + # -- request parsing ---------------------------------------------------- + + @staticmethod + def _customer_key(headers, prefix=cc.SSEC): + """(key bytes, error) for an SSE-C triple; (None, None) when the request carries none of it.""" + triple = {name[len(prefix):]: value for name, value in headers.items() if name.startswith(prefix)} + if not triple: + return None, None + try: + key = base64.b64decode(triple.get("key", ""), validate=True) + except ValueError: + return None, "InvalidRequest" + complete = triple.get("algorithm") == "AES256" and len(key) == 32 and triple.get("key-md5") == cc.key_md5(key) + return (key, None) if complete else (None, "InvalidRequest") + + def _write_scheme(self, bucket, headers): + """The scheme a write resolves to, as (scheme dict, error response).""" + algorithm, key_id, context = headers.get(cc.SSE), headers.get(cc.SSE_KEY_ID), headers.get(cc.SSE_CONTEXT) + key, key_error = self._customer_key(headers) + has_customer = any(name.startswith(cc.SSEC) for name in headers) + if has_customer and (algorithm or key_id): + return None, _error(400, "InvalidArgument") + if key_error: + code = "InvalidArgument" if "refusal-wrong-code" in self.mutations else key_error + return None, _error(400, code) + if key: + return {"scheme": "sse-c", "customer_md5": cc.key_md5(key)}, None + if algorithm not in (None, "AES256", "aws:kms") or (algorithm != "aws:kms" and (key_id or context)): + return None, _error(400, "InvalidArgument") + if context is not None: + try: + parsed = json.loads(base64.b64decode(context, validate=True)) + except ValueError: + return None, _error(400, "InvalidArgument") + if not isinstance(parsed, dict) or bucket in parsed: + return None, _error(400, "InvalidArgument") + if algorithm is None and self.buckets[bucket]["default"]: + algorithm, key_id = self.buckets[bucket]["default"] + if "bucket-default-ignored" in self.mutations: + algorithm = None + if algorithm == "aws:kms": + if not self.kms: + if "downgrade-kms-to-s3" in self.mutations: + return {"scheme": "sse-s3"}, None + return None, _error(400, "InvalidRequest") + key_id = key_id or DEFAULT_KEY + if key_id not in self.keys: + return None, _error(400, "KMS.NotFoundException") + return {"scheme": "sse-kms", "key_id": key_id, "context": context}, None + if algorithm == "AES256": + if not (self.kms or self.master_key): + return None, _error(400, "InvalidRequest") + return {"scheme": "sse-s3"}, None + return {"scheme": "plain"}, None + + def _sse_headers(self, stored, operation=""): + scheme = stored["scheme"] + if scheme == "sse-c": + return {cc.SSEC + "algorithm": "AES256", cc.SSEC + "key-md5": stored["customer_md5"]} + if scheme == "sse-kms": + key_id = DEFAULT_KEY if "wrong-kms-key-in-response" in self.mutations else stored["key_id"] + headers = {cc.SSE: "aws:kms", cc.SSE_KEY_ID: key_id} + if "context-echoed" in self.mutations and stored.get("context"): + headers[cc.SSE_CONTEXT] = stored["context"] + return headers + if scheme == "sse-s3": + if operation == "HEAD" and "head-drops-sse" in self.mutations: + return {} + headers = {cc.SSE: "AES256"} + if operation == "GET" and "extra-sse-header-on-get" in self.mutations: + headers[cc.SSE_KEY_ID] = DEFAULT_KEY + return headers + return {} + + def _etag(self, data, scheme): + plaintext_md5 = hashlib.md5(data).hexdigest() + if scheme == "plain" or "etag-is-plaintext-md5" in self.mutations: + return plaintext_md5 + return hashlib.md5(b"ciphertext of " + data).hexdigest() + + def _store(self, bucket, key, data, scheme, etag=None): + stored = {**scheme, "data": data, "etag": etag or self._etag(data, scheme["scheme"])} + self.buckets[bucket]["objects"][key] = stored + return stored + + def _read_refusal(self, stored, headers, prefix=cc.SSEC): + """Why a read with these headers must be refused, or None.""" + key, key_error = self._customer_key(headers, prefix) + has_customer = any(name.startswith(prefix) for name in headers) + if stored["scheme"] == "sse-c": + if key is None or key_error or cc.key_md5(key) != stored["customer_md5"]: + relabelled = "copy-relabels" in self.mutations and stored.get("copied") and key is not None + return None if relabelled else "InvalidRequest" + return None + if has_customer: + return "InvalidRequest" if stored["scheme"] == "plain" else "InvalidArgument" + if prefix == cc.SSEC and cc.SSE in headers: + return "InvalidArgument" + return None + + # -- the endpoint -------------------------------------------------------- + + def request(self, method, path, query="", body=None, headers=None): + headers = {name.lower(): value for name, value in (headers or {}).items()} + params = dict(urllib.parse.parse_qsl(query, keep_blank_values=True)) + if path.startswith(cc.ADMIN_PREFIX + "/"): + return self._admin(method, path[len(cc.ADMIN_PREFIX) + 1:], body) + bucket, _, key = path.lstrip("/").partition("/") + if not key: + return self._bucket(method, bucket, params, body) + if bucket not in self.buckets: + return _error(404, "NoSuchBucket") + if "uploads" in params or "uploadId" in params: + return self._multipart(method, bucket, key, params, body, headers) + if method == "PUT" and "x-amz-copy-source" in headers: + return self._copy(bucket, key, headers) + if method == "PUT": + scheme, refusal = self._write_scheme(bucket, headers) + if refusal: + if "store-refused-write" in self.mutations: + self._store(bucket, key, body or b"", {"scheme": "plain"}) + return refusal + stored = self._store(bucket, key, body or b"", scheme) + return 200, {"etag": f'"{stored["etag"]}"', **self._sse_headers(stored, "PUT")}, b"" + stored = self.buckets[bucket]["objects"].get(key) + if method == "DELETE": + self.buckets[bucket]["objects"].pop(key, None) + return 204, {}, b"" + if stored is None: + return _error(404, "NoSuchKey") + refusal = self._read_refusal(stored, headers) + if refusal: + if method == "GET" and "refused-get-serves-bytes" in self.mutations: + return 400, {}, _error(400, refusal)[2] + stored["data"] + return _error(400, refusal) if method == "GET" else (400, {}, b"") + data = stored["data"] + response = {"etag": f'"{stored["etag"]}"', "content-length": str(len(data)), **self._sse_headers(stored, method)} + if method == "HEAD": + return 200, response, b"" + if "range" in headers: + first, _, last = headers["range"][len("bytes="):].partition("-") + start = len(data) - int(last) if first == "" else int(first) + end = len(data) - 1 if first == "" or last == "" else int(last) + part = data[start:end + 1] + return 206, {**response, "content-length": str(len(part)), "content-range": f"bytes {start}-{end}/{len(data)}"}, part + return 200, response, data + + def _bucket(self, method, bucket, params, body): + if "encryption" in params: + if method == "PUT": + text = (body or b"").decode() + algorithm = re.search(r"(.*?)", text).group(1) + key_id = re.search(r"(.*?)", text) + self.buckets[bucket]["default"] = (algorithm, key_id.group(1) if key_id else + (DEFAULT_KEY if algorithm == "aws:kms" else None)) + return 200, {}, b"" + if method == "DELETE": + self.buckets[bucket]["default"] = None + return 204, {}, b"" + algorithm, key_id = self.buckets[bucket]["default"] + key_xml = f"{key_id}" if key_id else "" + return 200, {}, (f"" + f"{algorithm}{key_xml}" + "").encode() + if method == "PUT": + self.buckets[bucket] = {"objects": {}, "default": None} + return 200, {}, b"" + if method == "DELETE": + self.buckets.pop(bucket, None) + return 204, {}, b"" + entry = "Version" if "versions" in params else "Contents" + items = [] + for key, stored in sorted(self.buckets[bucket]["objects"].items()): + size = len(stored["data"]) + (32 if "listing-ciphertext-size" in self.mutations and stored["scheme"] != "plain" else 0) + items.append(f'<{entry}>{key}{size}"{stored["etag"]}"') + return 200, {}, f"{''.join(items)}".encode() + + def _copy(self, bucket, key, headers): + source_bucket, _, source_key = urllib.parse.unquote(headers["x-amz-copy-source"]).lstrip("/").partition("/") + source = self.buckets[source_bucket]["objects"].get(source_key) + if source is None: + return _error(404, "NoSuchKey") + if self._read_refusal(source, headers, cc.COPY_SSEC): + return _error(400, "InvalidRequest") + destination = {name: value for name, value in headers.items() if not name.startswith(cc.COPY_SSEC)} + scheme, refusal = self._write_scheme(bucket, destination) + if refusal: + return refusal + stored = self._store(bucket, key, source["data"], {**scheme, "copied": True}) + return 200, self._sse_headers(stored, "PUT"), f"{stored['etag']}".encode() + + def _multipart(self, method, bucket, key, params, body, headers): + if "uploads" in params: + scheme, refusal = self._write_scheme(bucket, headers) + if refusal: + return refusal + upload_id = f"upload-{len(self.uploads) + 1}" + self.uploads[upload_id] = {"scheme": scheme, "parts": {}} + return 200, self._sse_headers(scheme), (f"{upload_id}" + "").encode() + upload = self.uploads[params["uploadId"]] + scheme = upload["scheme"] + if method == "GET": + return 200, {}, f"{params['uploadId']}".encode() + customer_key, key_error = self._customer_key(headers) + has_customer = any(name.startswith(cc.SSEC) for name in headers) + matches = customer_key is not None and not key_error and cc.key_md5(customer_key) == scheme.get("customer_md5") + if (scheme["scheme"] == "sse-c") != has_customer or (has_customer and not matches): + return _error(400, "InvalidRequest") + if method == "PUT": + upload["parts"][int(params["partNumber"])] = body or b"" + return 200, {"etag": f'"{hashlib.md5(body or b"").hexdigest()}"', **self._sse_headers(scheme)}, b"" + data = b"".join(part for _, part in sorted(upload["parts"].items())) + stored = self._store(bucket, key, data, scheme, etag=f"{hashlib.md5(data).hexdigest()}-{len(upload['parts'])}") + return 200, self._sse_headers(stored), f"{key}".encode() + + def _admin(self, method, subpath, body): + if not self.kms: + return 503, {}, json.dumps({"success": False, "message": "kms service is not running"}).encode() + if subpath == "kms/status": + return 200, {}, json.dumps({"backend_status": "healthy", "default_key_id": DEFAULT_KEY}).encode() + if subpath == "kms/keys" and method == "POST": + self.keys.add(json.loads(body)["tags"]["name"]) + return 200, {}, json.dumps({"success": True}).encode() + name = urllib.parse.unquote(subpath[len("kms/keys/"):]) + return (200 if name in self.keys else 404), {}, b"{}" + + +def run(case_id, **server): + kms = cc.CASES[case_id][1] + fake = FakeS3(master_key=not kms, kms=kms, **server) + return cc.run_case(fake, case_id, DEFAULT_KEY if kms else "") + + +class ConformingServerTest(unittest.TestCase): + def test_every_case_holds(self): + for case_id in cc.CASES: + with self.subTest(case=case_id): + failures, evaluated = run(case_id) + self.assertEqual(failures, []) + self.assertGreater(evaluated, 5) + + def test_cases_do_not_hold_without_their_key_source(self): + """ENC-201 needs the master key and KMS-602 needs KMS: on a server with neither they must not pass.""" + for case_id in ("ENC-201", "ENC-203", "ENC-204", "ENC-210", "KMS-602"): + with self.subTest(case=case_id): + failures, _ = cc.run_case(FakeS3(), case_id, DEFAULT_KEY) + self.assertNotEqual(failures, []) + + +class MutatedServerTest(unittest.TestCase): + """One wrong behavior at a time: the named case fails, and its message names what it saw.""" + + EXPECTED = ( + ("extra-sse-header-on-get", "ENC-201", "expected exactly"), + ("extra-sse-header-on-get", "KMS-601", "the response carries " + cc.SSE_KEY_ID), + ("head-drops-sse", "ENC-201", "HEAD: SSE headers {}"), + ("listing-ciphertext-size", "ENC-201", "expected the plaintext size"), + ("refused-get-serves-bytes", "ENC-209", "the refused GET returned object bytes"), + ("bucket-default-ignored", "ENC-203", "[default-applies]"), + ("downgrade-kms-to-s3", "ENC-204", "SSE-KMS PUT: HTTP 200"), + ("downgrade-kms-to-s3", "ENC-204", "nothing may be stored"), + ("refusal-wrong-code", "ENC-205", "expected 400 'InvalidRequest'"), + ("store-refused-write", "ENC-205", "nothing may be stored"), + ("store-refused-write", "KMS-607", "nothing may be stored"), + ("copy-relabels", "ENC-206", "destination GET with the source key"), + ("copy-relabels", "KMS-605", "[ssec-to-ssec]"), + ("etag-is-plaintext-md5", "ENC-210", "is the MD5 of the plaintext"), + ("etag-is-plaintext-md5", "KMS-609", "is the MD5 of the plaintext"), + ("wrong-kms-key-in-response", "KMS-602", "expected exactly"), + ("wrong-kms-key-in-response", "KMS-603", "expected exactly"), + ("wrong-kms-key-in-response", "KMS-606", "expected exactly"), + ("context-echoed", "KMS-609", "repeats the encryption context"), + ) + + def test_each_mutation_is_caught(self): + for mutation, case_id, evidence in self.EXPECTED: + with self.subTest(mutation=mutation, case=case_id): + failures, _ = run(case_id, mutations=[mutation]) + self.assertTrue(any(evidence in failure for failure in failures), + f"{case_id} did not report {evidence!r} under {mutation}: {failures}") + + def test_every_mutation_the_fake_knows_is_exercised(self): + known = set(re.findall(r'"([a-z0-9-]+)" in self\.mutations', Path(__file__).read_text())) + self.assertEqual(known, {mutation for mutation, _, _ in self.EXPECTED}) + + +class OracleTest(unittest.TestCase): + def test_a_case_without_expectations_does_not_pass(self): + cc.CASES["ENC-299"] = ("Vacuous", False, lambda c: None) + try: + failures, evaluated = cc.run_case(FakeS3(master_key=True), "ENC-299") + finally: + del cc.CASES["ENC-299"] + self.assertEqual((failures, evaluated), (["the case evaluated no expectation"], 0)) + + def test_a_broken_row_does_not_hide_the_next_one(self): + ctx = cc.Ctx(FakeS3(master_key=True), "ENC-000") + with ctx.row("first"): + ctx.need(False, "stops this row") + with ctx.row("second"): + ctx.check(False, "still evaluated") + self.assertEqual(ctx.failures, ["[first] stops this row", "[second] still evaluated"]) + + def test_no_response_ends_the_case_as_a_failure(self): + class Down(FakeS3): + def request(self, method, path, query="", body=None, headers=None): + raise cc.NoResponse(f"{method} {path}: no HTTP response") + + failures, _ = cc.run_case(Down(master_key=True), "ENC-205") + self.assertEqual(len(failures), 1) + self.assertIn("no HTTP response", failures[0]) + + +class CommandLineTest(unittest.TestCase): + def invoke(self, *argv, env=None): + saved = {name: cc.os.environ.get(name) for name in ("RUSTFS_ACCESS_KEY", "RUSTFS_SECRET_KEY")} + cc.os.environ.update(env if env is not None else {"RUSTFS_ACCESS_KEY": "ak", "RUSTFS_SECRET_KEY": "sk"}) + out, err = io.StringIO(), io.StringIO() + try: + with redirect_stdout(out), redirect_stderr(err): + try: + status = cc.main(list(argv)) + except SystemExit as exit_: + status = exit_.code + finally: + for name, value in saved.items(): + if value is None: + cc.os.environ.pop(name, None) + else: + cc.os.environ[name] = value + return status, out.getvalue(), err.getvalue() + + def test_usage_errors_are_not_read_as_unsupported(self): + """The suites take exit status 2 for UNSUPPORTED; a wrong command line must be a failure instead.""" + for argv in (["--case", "ENC-201"], ["--endpoint", "http://node:9000", "--case", "ENC-999"], + ["--endpoint", "http://node:9000", "--case", "KMS-601"], + ["--endpoint", "node:9000", "--case", "ENC-201"]): + with self.subTest(argv=argv): + status, _, err = self.invoke(*argv) + self.assertEqual(status, cc.EXIT_USAGE, err) + + def test_missing_credentials_are_a_usage_error(self): + saved = {name: cc.os.environ.pop(name, None) for name in ("RUSTFS_ACCESS_KEY", "RUSTFS_SECRET_KEY")} + try: + status, _, err = self.invoke("--endpoint", "http://node:9000", "--case", "ENC-201", env={}) + finally: + cc.os.environ.update({name: value for name, value in saved.items() if value is not None}) + self.assertEqual(status, cc.EXIT_USAGE) + self.assertIn("RUSTFS_ACCESS_KEY", err) + + def test_unreachable_endpoint_fails_the_case(self): + status, out, _ = self.invoke("--endpoint", "http://127.0.0.1:1", "--case", "ENC-205") + self.assertEqual(status, 1) + self.assertIn("no HTTP response", out) + + def test_list_names_every_case(self): + status, out, _ = self.invoke("--list") + self.assertEqual(status, 0) + self.assertEqual([line.split()[0] for line in out.splitlines()], list(cc.CASES)) + + +class SuiteWiringTest(unittest.TestCase): + """Every case is registered in the suite that starts the server it needs, under the helper's own name.""" + + def registered(self, script): + text = (ROOT / script).read_text() + rows = re.findall(r'^\s*run_test (\S+)\s+"([^"]+)"\s+(\S+)$', text, re.MULTILINE) + functions = dict(re.findall(r"^(test_\w+)\(\) \{ sse_contract_case (\S+); \}$", text, re.MULTILINE)) + return {case_id: (name, functions.get(function)) for case_id, name, function in rows}, text + + def test_registration_matches_the_helper(self): + for script, needs_kms in (("rustfs-s3-compat-test.sh", False), ("rustfs-kms-test.sh", True)): + registered, text = self.registered(script) + for case_id, (name, kms, _) in cc.CASES.items(): + with self.subTest(script=script, case=case_id): + if kms == needs_kms: + self.assertEqual(registered.get(case_id), (name, case_id)) + else: + self.assertNotIn(case_id, registered) + self.assertIn('[ -f "${SCRIPT_DIR}/scripts/sse_contract_cases.py" ]', text) + + def test_kms_suite_passes_its_default_key(self): + text = (ROOT / "rustfs-kms-test.sh").read_text() + self.assertIn('--kms-default-key "${KMS_DEFAULT_KEY_ID}"', text) + + +class SignatureTest(unittest.TestCase): + def test_signature_matches_an_independent_signer(self): + try: + from botocore.auth import S3SigV4Auth + from botocore.awsrequest import AWSRequest + from botocore.credentials import Credentials + except ImportError: + self.skipTest("botocore is not installed") + now = datetime.datetime(2026, 1, 2, 3, 4, 5, tzinfo=datetime.timezone.utc) # noqa: UP017 - Python 3.8 has no datetime.UTC + path, query = "/bucket/a key/with+plus", "partNumber=1&uploadId=" + urllib.parse.quote("a/b+c=", safe="") + headers = {cc.SSE: "aws:kms", cc.SSE_KEY_ID: "key with two spaces", "content-type": "application/octet-stream"} + signed = cc.sign("PUT", "node:9000", path, query, headers, "ak@id", "sk", now) + authorization = signed.pop("authorization") + self.assertEqual(sorted(signed), authorization.split("SignedHeaders=")[1].split(",")[0].split(";")) + + url = "http://node:9000" + urllib.parse.quote(path, safe="/-._~") + "?" + query + request = AWSRequest(method="PUT", url=url, headers=signed) + request.context["timestamp"] = signed["x-amz-date"] + request.context["payload_signing_enabled"] = False + verifier = S3SigV4Auth(Credentials("ak@id", "sk"), cc.SERVICE, cc.REGION) + expected = verifier.signature(verifier.string_to_sign(request, verifier.canonical_request(request)), request) + self.assertEqual(authorization.split("Signature=")[1], expected) + + +if __name__ == "__main__": + unittest.main() diff --git a/validation-cases.json b/validation-cases.json index fe1da14..38be0f3 100644 --- a/validation-cases.json +++ b/validation-cases.json @@ -6447,6 +6447,266 @@ ] } }, + { + "id": "s3.compatibility.enc-201", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api" + ], + "assertions": [ + "SseS3ExactHeaders: SSE-S3 objects of 0, 1 and 71680 bytes answer PUT, GET and HEAD with exactly x-amz-server-side-encryption: AES256, read back byte-identical, and are listed with their plaintext size.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "ENC-201", + "executionMode": "configured-endpoint", + "runner": "rustfs-s3-compat-test.sh", + "topology": "single-1disk" + }, + "reuse_candidates": { + "suites": [ + "rustfs-s3-compat-test.sh" + ], + "case_ids": [ + "ENC-201" + ] + } + }, + { + "id": "s3.compatibility.enc-202", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api" + ], + "assertions": [ + "SseCExactHeaders: SSE-C objects of 0, 1 and 71680 bytes answer PUT, GET and HEAD with exactly the customer algorithm and key-MD5 headers, and a GET without the customer key is refused with 400 InvalidRequest.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "ENC-202", + "executionMode": "configured-endpoint", + "runner": "rustfs-s3-compat-test.sh", + "topology": "single-1disk" + }, + "reuse_candidates": { + "suites": [ + "rustfs-s3-compat-test.sh" + ], + "case_ids": [ + "ENC-202" + ] + } + }, + { + "id": "s3.compatibility.enc-203", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api" + ], + "assertions": [ + "BucketDefaultExact: A bucket default of AES256 encrypts a PUT that names no scheme, leaves an SSE-C PUT as SSE-C, and after its removal new objects carry no SSE header while earlier ones still read back as SSE-S3.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "ENC-203", + "executionMode": "configured-endpoint", + "runner": "rustfs-s3-compat-test.sh", + "topology": "single-1disk" + }, + "reuse_candidates": { + "suites": [ + "rustfs-s3-compat-test.sh" + ], + "case_ids": [ + "ENC-203" + ] + } + }, + { + "id": "s3.compatibility.enc-204", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api" + ], + "assertions": [ + "SseKmsNotDowngraded: Without KMS an SSE-KMS PUT is refused with 400 InvalidRequest and stores nothing, while SSE-S3 under the master key still round-trips.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "ENC-204", + "executionMode": "configured-endpoint", + "runner": "rustfs-s3-compat-test.sh", + "topology": "single-1disk" + }, + "reuse_candidates": { + "suites": [ + "rustfs-s3-compat-test.sh" + ], + "case_ids": [ + "ENC-204" + ] + } + }, + { + "id": "s3.compatibility.enc-205", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api" + ], + "assertions": [ + "SseCTripleNegatives: Seven incomplete or inconsistent SSE-C header triples are each refused with 400 InvalidRequest, and a HEAD of each key answers 404.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "ENC-205", + "executionMode": "configured-endpoint", + "runner": "rustfs-s3-compat-test.sh", + "topology": "single-1disk" + }, + "reuse_candidates": { + "suites": [ + "rustfs-s3-compat-test.sh" + ], + "case_ids": [ + "ENC-205" + ] + } + }, + { + "id": "s3.compatibility.enc-206", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api" + ], + "assertions": [ + "SseCCopySourceKey: CopyObject from an SSE-C source without or with a wrong source key is refused with an explicit 400 and stores nothing; with the right key the destination opens only with its own key.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "ENC-206", + "executionMode": "configured-endpoint", + "runner": "rustfs-s3-compat-test.sh", + "topology": "single-1disk" + }, + "reuse_candidates": { + "suites": [ + "rustfs-s3-compat-test.sh" + ], + "case_ids": [ + "ENC-206" + ] + } + }, + { + "id": "s3.compatibility.enc-207", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api" + ], + "assertions": [ + "SseCMultipartExact: An SSE-C multipart upload answers CreateMultipartUpload and CompleteMultipartUpload with exactly the customer headers, reads back byte-identical with the key, and is refused without it.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "ENC-207", + "executionMode": "configured-endpoint", + "runner": "rustfs-s3-compat-test.sh", + "topology": "single-1disk" + }, + "reuse_candidates": { + "suites": [ + "rustfs-s3-compat-test.sh" + ], + "case_ids": [ + "ENC-207" + ] + } + }, + { + "id": "s3.compatibility.enc-208", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api" + ], + "assertions": [ + "SseCPartKeyMismatch: UploadPart without the key, with another key, or with a key on a plaintext upload is refused with 400 InvalidRequest, and the SSE-C upload still completes afterwards.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "ENC-208", + "executionMode": "configured-endpoint", + "runner": "rustfs-s3-compat-test.sh", + "topology": "single-1disk" + }, + "reuse_candidates": { + "suites": [ + "rustfs-s3-compat-test.sh" + ], + "case_ids": [ + "ENC-208" + ] + } + }, + { + "id": "s3.compatibility.enc-209", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api" + ], + "assertions": [ + "SseReadHeaderMismatch: Six GET requests whose SSE headers do not match how the object was stored are refused with the exact error code and return no object bytes.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "ENC-209", + "executionMode": "configured-endpoint", + "runner": "rustfs-s3-compat-test.sh", + "topology": "single-1disk" + }, + "reuse_candidates": { + "suites": [ + "rustfs-s3-compat-test.sh" + ], + "case_ids": [ + "ENC-209" + ] + } + }, + { + "id": "s3.compatibility.enc-210", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api" + ], + "assertions": [ + "ListingEtagNotPlaintextMd5: ListObjectsV2, ListObjects and ListObjectVersions never report the MD5 of the plaintext as the ETag of an SSE-S3 or SSE-C object, with a plaintext object as the control.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "ENC-210", + "executionMode": "configured-endpoint", + "runner": "rustfs-s3-compat-test.sh", + "topology": "single-1disk" + }, + "reuse_candidates": { + "suites": [ + "rustfs-s3-compat-test.sh" + ], + "case_ids": [ + "ENC-210" + ] + } + }, { "id": "s3.compatibility.s3c-1001", "source_status": "procedure-ready", @@ -10333,6 +10593,249 @@ ] } }, + { + "id": "source-procedure.kms.kms-601", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api", + "admin-api" + ], + "assertions": [ + "SseS3KeyNotNamed: SSE-S3 under KMS round-trips with exactly AES256, and no response of eight operations carries a KMS key id header or names the default key.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "KMS-601", + "executionMode": "configured-endpoint", + "runner": "rustfs-kms-test.sh", + "topology": "configured-suite" + }, + "reuse_candidates": { + "suites": [ + "rustfs-kms-test.sh" + ], + "case_ids": [ + "KMS-601" + ] + } + }, + { + "id": "source-procedure.kms.kms-602", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api", + "admin-api" + ], + "assertions": [ + "SseKmsKeyResolutionExact: SSE-KMS without a key id answers with the default key id, and with an explicit non-default key answers with that key id on PUT, GET and HEAD for 0, 1 and 71680 bytes.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "KMS-602", + "executionMode": "configured-endpoint", + "runner": "rustfs-kms-test.sh", + "topology": "configured-suite" + }, + "reuse_candidates": { + "suites": [ + "rustfs-kms-test.sh" + ], + "case_ids": [ + "KMS-602" + ] + } + }, + { + "id": "source-procedure.kms.kms-603", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api", + "admin-api" + ], + "assertions": [ + "SseKmsRangeExact: Four range reads of an SSE-KMS object answer 206 with the exact Content-Range, the plaintext slice and the exact SSE-KMS headers.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "KMS-603", + "executionMode": "configured-endpoint", + "runner": "rustfs-kms-test.sh", + "topology": "configured-suite" + }, + "reuse_candidates": { + "suites": [ + "rustfs-kms-test.sh" + ], + "case_ids": [ + "KMS-603" + ] + } + }, + { + "id": "source-procedure.kms.kms-604", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api", + "admin-api" + ], + "assertions": [ + "BucketDefaultKmsExact: A bucket default of aws:kms without a key id pins the default key, leaves SSE-C as SSE-C, and an explicit AES256 PUT does not inherit the bucket's KMS key.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "KMS-604", + "executionMode": "configured-endpoint", + "runner": "rustfs-kms-test.sh", + "topology": "configured-suite" + }, + "reuse_candidates": { + "suites": [ + "rustfs-kms-test.sh" + ], + "case_ids": [ + "KMS-604" + ] + } + }, + { + "id": "source-procedure.kms.kms-605", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api", + "admin-api" + ], + "assertions": [ + "CopySchemeMatrix: Six CopyObject combinations across plaintext, SSE-S3, SSE-KMS and SSE-C produce exactly the destination scheme's headers on GET and HEAD and byte-identical data.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "KMS-605", + "executionMode": "configured-endpoint", + "runner": "rustfs-kms-test.sh", + "topology": "configured-suite" + }, + "reuse_candidates": { + "suites": [ + "rustfs-kms-test.sh" + ], + "case_ids": [ + "KMS-605" + ] + } + }, + { + "id": "source-procedure.kms.kms-606", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api", + "admin-api" + ], + "assertions": [ + "MultipartSseKmsExact: A three-part SSE-KMS upload answers create, complete, GET and HEAD with exactly the SSE-KMS headers of its key, the full length and a three-part ETag.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "KMS-606", + "executionMode": "configured-endpoint", + "runner": "rustfs-kms-test.sh", + "topology": "configured-suite" + }, + "reuse_candidates": { + "suites": [ + "rustfs-kms-test.sh" + ], + "case_ids": [ + "KMS-606" + ] + } + }, + { + "id": "source-procedure.kms.kms-607", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api", + "admin-api" + ], + "assertions": [ + "SsePutHeaderNegatives: Ten malformed SSE header combinations are refused with 400 InvalidArgument and a missing KMS key with 400 KMS.NotFoundException; a HEAD of each key answers 404.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "KMS-607", + "executionMode": "configured-endpoint", + "runner": "rustfs-kms-test.sh", + "topology": "configured-suite" + }, + "reuse_candidates": { + "suites": [ + "rustfs-kms-test.sh" + ], + "case_ids": [ + "KMS-607" + ] + } + }, + { + "id": "source-procedure.kms.kms-608", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api", + "admin-api" + ], + "assertions": [ + "SseReadHeaderMismatch: Seven GET requests whose SSE headers do not match how the object was stored, an SSE-KMS object included, are refused with the exact error code and return no object bytes.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "KMS-608", + "executionMode": "configured-endpoint", + "runner": "rustfs-kms-test.sh", + "topology": "configured-suite" + }, + "reuse_candidates": { + "suites": [ + "rustfs-kms-test.sh" + ], + "case_ids": [ + "KMS-608" + ] + } + }, + { + "id": "source-procedure.kms.kms-609", + "source_status": "procedure-ready", + "priority": "P1", + "channels": [ + "s3-api", + "admin-api" + ], + "assertions": [ + "ContextAndEtagNotEchoed: PUT, GET and HEAD of an object written with an encryption context do not repeat the context, and no listing reports the plaintext MD5 as the ETag of an encrypted object.", + "The helper scripts/sse_contract_cases.py reports every expectation that does not hold; exact SSE header sets, exact error codes and residue checks fail the case." + ], + "probes": { + "sourceCase": "KMS-609", + "executionMode": "configured-endpoint", + "runner": "rustfs-kms-test.sh", + "topology": "configured-suite" + }, + "reuse_candidates": { + "suites": [ + "rustfs-kms-test.sh" + ], + "case_ids": [ + "KMS-609" + ] + } + }, { "id": "source-procedure.kms.kms-401", "source_status": "procedure-ready", diff --git a/validation-migration-review.json b/validation-migration-review.json index 5a9508f..e8d8768 100644 --- a/validation-migration-review.json +++ b/validation-migration-review.json @@ -5,7 +5,7 @@ "source_sha256": "463fdd02dee43e42fef4f3aacf7506709ce87af535e1a53d91c521bc2e361cad", "reviewed_testing_commit": "5e76033d7ccad414aad1f7edb9867de6462eee43", "scope": "Test implementation migration and candidate live acceptance are independent. This review does not rewrite original results, change migration_status semantics or relax the canonical gate. Environment procedures remain disabled by default under the accepted delivery scope.", - "evidence_basis": "20261026-canonical-migration-ledger-7094.json plus later G01/G02 attempts and source review on 2026-10-28; historical result bytes and audit reports remain in the separate evidence store. 2026-11-10: a scoped re-review of the Rebalance activity fixture, capacity admission, Started non-zero progress, and the early-completion diagnosis; this local regression adds no product live acceptance. 2026-11-22: reviewed the replication inventory pagination, Heal census completeness, expected-manifest comparison, ILM control survival, and exact marker oracles after automated review findings. Reviewed the 10-version NewerNoncurrentVersions retention procedure and source/target version-purge convergence evidence for this change. 2026-11-22: indexed the source-audit inventory and added individually dispatchable local compatibility and source-suite procedure entries with selector and candidate-admission checks. 2026-11-22: added table-catalog and upgrade procedure selectors with shared validation artifact wiring; dry-run selectors cover all 25 newly indexed procedures. 2026-11-22: clarified that source-native tests are used as assertion and boundary-value references; one-to-one native ports are outside the migration scope. 2026-11-24: re-reviewed the ILM scanner-readiness preflight after a 4-node VM run (auto-testing 644b935, RustFS 2d90297) blocked all 14 ILM cases because followers report effective_interval_available=false with a zero effective interval by design; the effective-interval comparison now runs only on the leader. This is a test-oracle correction and adds no product live acceptance. 2026-11-24: refreshed the reviewed digest for rustfs-s3-compat-test.sh to match current main (a3a9e83 and 6feeeec changed that script without updating this ledger); this PR does not modify the script, and the same digest mismatch reproduces on a clean origin/main checkout. 2026-11-24: refreshed the reviewed digest again for rustfs-s3-compat-test.sh after 90b4fe1 changed that script without updating this ledger; the main push of ba6051d failed the contract-tests job. This follow-up does not modify the script. 2026-11-24: accepted the product last_cycle_partial_reason=unknown sentinel in the ILM scanner-readiness preflight after a healthy leader was still blocked; this is a test-oracle correction and adds no product live acceptance. 2026-11-24: reviewed the new STOR-135 DeepKeyListingResilience case in rustfs-storage-test.sh (backlog#3293): a 301-segment key PUT followed by a recursive ListObjectsV2 must either return the key or fail with a controlled error while the server stays alive, and GET must return the same bytes. This is a test-oracle addition guarding the scan_dir recursion-depth fix; it adds no product live acceptance. 2026-11-25: fixed the S3C-206 fixture to send the single encoded metadata value it expects; the previous fixture sent two encoded words and the product preserved them exactly, so the case falsely failed.", + "evidence_basis": "20261026-canonical-migration-ledger-7094.json plus later G01/G02 attempts and source review on 2026-10-28; historical result bytes and audit reports remain in the separate evidence store. 2026-11-10: a scoped re-review of the Rebalance activity fixture, capacity admission, Started non-zero progress, and the early-completion diagnosis; this local regression adds no product live acceptance. 2026-11-22: reviewed the replication inventory pagination, Heal census completeness, expected-manifest comparison, ILM control survival, and exact marker oracles after automated review findings. Reviewed the 10-version NewerNoncurrentVersions retention procedure and source/target version-purge convergence evidence for this change. 2026-11-22: indexed the source-audit inventory and added individually dispatchable local compatibility and source-suite procedure entries with selector and candidate-admission checks. 2026-11-22: added table-catalog and upgrade procedure selectors with shared validation artifact wiring; dry-run selectors cover all 25 newly indexed procedures. 2026-11-22: clarified that source-native tests are used as assertion and boundary-value references; one-to-one native ports are outside the migration scope. 2026-11-24: re-reviewed the ILM scanner-readiness preflight after a 4-node VM run (auto-testing 644b935, RustFS 2d90297) blocked all 14 ILM cases because followers report effective_interval_available=false with a zero effective interval by design; the effective-interval comparison now runs only on the leader. This is a test-oracle correction and adds no product live acceptance. 2026-11-24: refreshed the reviewed digest for rustfs-s3-compat-test.sh to match current main (a3a9e83 and 6feeeec changed that script without updating this ledger); this PR does not modify the script, and the same digest mismatch reproduces on a clean origin/main checkout. 2026-11-24: refreshed the reviewed digest again for rustfs-s3-compat-test.sh after 90b4fe1 changed that script without updating this ledger; the main push of ba6051d failed the contract-tests job. This follow-up does not modify the script. 2026-11-24: accepted the product last_cycle_partial_reason=unknown sentinel in the ILM scanner-readiness preflight after a healthy leader was still blocked; this is a test-oracle correction and adds no product live acceptance. 2026-11-24: reviewed the new STOR-135 DeepKeyListingResilience case in rustfs-storage-test.sh (backlog#3293): a 301-segment key PUT followed by a recursive ListObjectsV2 must either return the key or fail with a controlled error while the server stays alive, and GET must return the same bytes. This is a test-oracle addition guarding the scan_dir recursion-depth fix; it adds no product live acceptance. 2026-11-25: fixed the S3C-206 fixture to send the single encoded metadata value it expects; the previous fixture sent two encoded words and the product preserved them exactly, so the case falsely failed. 2026-11-23: added strict SSE contract procedures ENC-201..ENC-210 (S3 compatibility suite) and KMS-601..KMS-609 (KMS suite), executed by scripts/sse_contract_cases.py and individually dispatchable; they were exercised against local single-process servers started with each suite's environment, which is no fleet live acceptance.", "reviewed_files": { "scripts/run_validation_case.sh": "58e0eb2fb007b28fb16b0fd4a25ac2f997cc9f01a4a3700c01fe7c9a6dd1a683", "scripts/validation_heal/authority.py": "8f2225f184427674de1f45aff4c4976c812f9d70fd4bc927ce460726a4ff74a0", @@ -121,14 +121,14 @@ "test_validation_ilm.py": "f4d361850f278a5be965f05ff8950d91347907be2253bfa31a1864ae5b2a730c", "test_validation_replication.py": "83e1b532e8a6a352c5e38de48799356157e1fad4f1f314ea8ad256fdecf942c5", "test_validation_scanner_usage.py": "cd5cb785184586cf90824c347bf584642545acffdf6302ad361de39773d4732e", - "rustfs-s3-compat-test.sh": "8182128d5b58ed5d6b59b4db6680c3a197eeeb1ba66709976ce773e07230de7a", + "rustfs-s3-compat-test.sh": "31f986f574484da43f36fcc1ee74b0a088d83574202a91945a3473b49cab82aa", "rustfs-security-test.sh": "02cddd15636df1e74210c172ee898dba9b3adf83943da45d874d6c827583d9d2", "rustfs-tier-test.sh": "3b37a6b26a4af862d7f2d178872900f314c8328ffd3db6a3e769928a5d1b3964", "rustfs-storage-test.sh": "197ffa9b8349d12db10678897a87209801e3c3d52ef08ec060801bd553762ab3", - "rustfs-kms-test.sh": "8054b46fa6e5de305b484c6db18a5e0f6819f4dcc98cefb330977274df2d4b53", - "validation-cases.json": "8fa9aaf17f3f0e2c0a38b627703741cfe6e9e419c266f32960c0a22e531359d9", - "docs/validation-migration-map.md": "b9e2d86a6d46ee8597c2d5b25faa718fff1e7127e18fea8be5abe3b447d7955d", - "docs/source-test-migration-inventory.md": "e2fb6ff49835f61e0e38ed327f41f50eac07587ce2b7beb8e31fddc1751ad53d", + "rustfs-kms-test.sh": "4a20d95a04287fa4d84d1ce58e074725cd0507163eaeb6e27e0ea7fc098c3bb0", + "validation-cases.json": "fe5946970206e59c1bb91cc414b183fdbbb0fbf3069a5c19c0720041db1ad81a", + "docs/validation-migration-map.md": "b8dd536df1f1e14324f27bbe61cb3ea796aeb3f7220876c36a828e9d80a9dffc", + "docs/source-test-migration-inventory.md": "ac434d583c69f9c2a1128e4a84eb52d9bf46395f3fe22383b2a2d5ce9a0bddd5", "test_source_test_migration_inventory.py": "5c0122c6940ea224e7bde57fa1159536ab9ef132cf9d34517fe27c053a56b972", "test_source_procedure_catalog.py": "ed50ad0e8a0aeef2e947b9f090ffcfd00420fe5f1ef85157b4fc8deb2280e5c7", "test_validation_s3_compatibility.py": "c1978bc5eaec91c07d65ebc2460644b81f73c48b63fe382d79508d45a5b573bb",