Compare commits

...

1 Commits

Author SHA1 Message Date
Chris An fbe7471ba6 docs(security,kms): add KMS version policy and close doc/compat gaps (#9661) 2026-11-27 17:29:38 +08:00
14 changed files with 621 additions and 22 deletions
+1
View File
@@ -65,6 +65,7 @@ script-tests: ## Run shell script tests
./scripts/test_fuzz_runner.sh
./scripts/test_python_bin.sh
$(RUSTFS_PYTHON_BIN) ./scripts/test_check_doc_paths.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_check_kms_format_versions.py
./scripts/check_embedded_secrets.sh --self-test
./scripts/check_s3s_footprint.sh --self-test
./scripts/test_check_test_count_ratchet.sh
+1
View File
@@ -271,6 +271,7 @@ pub const ENV_RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE: &str = "RUSTFS_ENCRYPTI
///
/// Default value: false
/// Environment variable: RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE
// RUSTFS_COMPAT_TODO(backlog-2703-multipart-segment-nonce): keep 0x03 multipart segment-nonce writes off by default during rolling upgrades while older nodes or ciphertext-passthrough targets lack 0x03 read support. Remove after the minimum supported release (and warm/replication passthrough targets) reads 0x03 frames and the default flips to true.
pub const DEFAULT_RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE: bool = false;
/// Environment variable for server KMS backend.
+1
View File
@@ -134,6 +134,7 @@ pub fn desired_context_binding(existing: Option<u8>) -> Option<u8> {
/// opened by a node that predates it (the unwrap fails authentication), so the
/// switch must only be enabled once every node in the cluster runs a release
/// that understands `context_binding`. Reading bound envelopes needs no switch.
// RUSTFS_COMPAT_TODO(backlog-1667-kms-envelope-aad): keep Local and Vault KV2 DEK envelope AAD writes off by default during rolling upgrades while older nodes lack context_binding support. Remove after the minimum supported release understands CONTEXT_BINDING_AAD_V1 and the default flips to true.
pub fn envelope_aad_write_enabled() -> bool {
use crate::config::ENV_KMS_ENVELOPE_AAD;
use rustfs_utils::get_env_bool;
+1
View File
@@ -56,6 +56,7 @@ Required headings and strings in these files are asserted by `scripts/check_arch
| [plugin-delegation.md](plugin-delegation.md) | changing original-user plugin delegation, attempt credentials, or Runner task APIs |
| [admin-route-action-snapshot.md](admin-route-action-snapshot.md) | adding, moving, or re-authorizing an admin route and needing to know where the route → handler → `AdminAction` contract is enforced |
| [kms-bulk-rekey-contract.md](kms-bulk-rekey-contract.md) | changing the bulk envelope re-wrap sweep, its admin endpoints, the re-wrap primitive, or which objects a rekey may touch |
| [kms-format-version-policy.md](kms-format-version-policy.md) | adding, evolving, or deprecating a persisted KMS/SSE record format, an object ciphertext stream frame type, or a `/rustfs/admin/v3/kms/*` request/response schema, or before bumping any KMS format version constant |
| [remote-credential-sealing-adr.md](remote-credential-sealing-adr.md) | adding, reading, or persisting a stored remote credential (replication target, remote tier, on-demand migration source), or needing the sealed-envelope format, the mixed-version rules, or the reason this is worth doing in one deployment and not in another |
| [tier-stats-contract.md](tier-stats-contract.md) | changing what `GET /rustfs/admin/v3/tier-stats` returns, adding a tier accounting source, or wiring a metric to a remote tier request |
| [s3-over-rdma-llm-serving.md](s3-over-rdma-llm-serving.md) | you change the RDMA or NIXL data path, the large-PUT path, or a per-bucket ETag setting, or you build or run a client that loads model weights or offloads KV cache to RustFS over RDMA, such as the SGLang weight loader and HiCache backend |
@@ -67,6 +67,8 @@
- `backlog-2097-tier-delete-journal-v6` tier-delete sole-owner recovery: v6 distinguishes transactions that may replace the xl.meta free-version owner and therefore require the all-pool live-source proof. v5-and-older readers reject and retain v6 records during rolling upgrades instead of performing an unsafe remote delete. Keep v1-v5 readers for upgrade recovery and keep the downgrade prohibition while any v6 record exists; retire the fence only after every supported rollback release understands and enforces v6 proof semantics.
- `multipart-compression-default-off-window` staged multipart disk-compression rollout: releases before the resumable legacy decompressor fail transient reads of compressed objects under mid-payload suspension, so multipart uploads advertise the compression marker only when RUSTFS_COMPRESSION_MULTIPART_ENABLED is set in addition to RUSTFS_COMPRESSION_ENABLED, keeping rolling upgrades from creating new compressed multipart objects while pre-fix nodes may still serve reads. Flip the default to enabled (and retire the extra switch) after the minimum supported direct-upgrade release ships the resumable decompressor.
- `listing-cursor-legacy-tag` ListObjects cursor compatibility: releases up to 1.0.x appended a metacache tag ([rustfs_cache:v2,id:...,src:walker,gen:live]) to continuation markers. V2 tokens continue to accept that legacy form, and cache-shaped literal keys retain an outer tag in newly issued V2 cursors. V1 markers, V2 StartAfter, and ListObjectVersions markers are literal keys. Clients must restart old version-listing chains and V1 chains holding escaped markers after upgrading. Remove the V2 tag stripping after every supported direct-upgrade release has issued plain key markers for a full release, so no client can still hold a tagged cursor.
- `backlog-2703-multipart-segment-nonce` staged multipart segment-nonce rollout: RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE (DEFAULT_RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE in crates/config/src/constants/app.rs) defaults to false because nodes predating 0x03 frame read support reject authenticated 37-byte segment-nonce frames (FRAME_TYPE_SEGMENT_NONCE in crates/rio/src/encrypt_reader.rs), and encrypted ciphertext travels verbatim through transition, decommission, heal, and SSE-C replication passthrough. Reading 0x03 segments is unconditional without any switch. Flip the default to true once every supported cluster release and every RustFS warm or replication target receiving raw ciphertext supports reading 0x03 frames, and remove the default-off compatibility window after the default-on release has been live across a full rolling-upgrade window.
- `backlog-1667-kms-envelope-aad` staged DEK envelope context-binding AAD rollout: RUSTFS_KMS_ENVELOPE_AAD (envelope_aad_write_enabled in crates/kms/src/encryption/dek.rs) defaults to false because Local and Vault KV2 nodes predating DataKeyEnvelope::context_binding fail AES-GCM unwrap when an envelope is sealed with canonical encryption_context AAD (CONTEXT_BINDING_AAD_V1). Reading bound envelopes is unconditional, unknown context_binding versions fail closed, and rewrap never downgrades an already-bound envelope. Flip the default to true after every supported direct-upgrade and rollback release understands context_binding, and remove the default-off compatibility window one release after that while keeping legacy unbound envelope reads until migration rewrites all pre-AAD envelopes.
## Review Checklist
@@ -0,0 +1,116 @@
# KMS Format Version and Deprecation Policy
**Use this when:** adding, evolving, or deprecating a persisted KMS/SSE record format, an object ciphertext stream frame type, or a `/rustfs/admin/v3/kms/*` request/response schema, or before bumping any KMS format version constant.
**Source of truth:** `crates/kms/src/backup/manifest.rs`, `crates/kms/src/backup/local_restore.rs`, `crates/kms/src/backup/vault_restore.rs`, `crates/kms/src/backup/drill.rs`, `crates/kms/src/backends/local.rs`, `crates/kms/src/backends/vault.rs`, `crates/kms/src/backends/vault_transit.rs`, `crates/kms/src/encryption/dek.rs`, `crates/kms/src/config.rs`, `crates/kms/src/persisted_observability.rs`, `crates/kms/src/api_types.rs`, `crates/sse/src/kms/local.rs`, `crates/utils/src/http/object_encryption_keys.rs`, `crates/rio/src/encrypt_reader.rs`, and `scripts/check_kms_format_versions.py`.
This document defines the architectural persistence and API evolution contract for RustFS KMS and SSE. Operator rolling-upgrade procedures and deployment matrices live in [kms-backend-security.md](../operations/kms-backend-security.md); bulk envelope re-wrap contracts live in [kms-bulk-rekey-contract.md](kms-bulk-rekey-contract.md); MinIO on-disk SSE interoperability lives in [minio-file-format-compat.md](minio-file-format-compat.md).
## Persisted Format Inventory and Version Commitments
Every persisted KMS and SSE format in RustFS declares three concrete commitments: whether mixed-version reads are supported, what an older build does when it encounters a newer write, and what cluster upgrade order a format change requires. Adding a numeric `format_version` field is deliberate, not uniform: formats whose on-disk bytes or interoperability contract forbid a wrapper header (`.master-key.salt` and object SSE metadata keys) stay intentionally unversioned.
| Format | Code anchor | Version / discriminator | Unknown fields & unknown versions | Mixed-version read | Old reader on newer write | Upgrade requirement on bump |
| --- | --- | --- | --- | --- | --- | --- |
| Backup manifest | `BackupManifest` (`crates/kms/src/backup/manifest.rs`) | `format_version: u32` (`BackupManifest::FORMAT_VERSION`) plus `ReservedSlot` (`key_versions`, `capability_discovery`) | `deny_unknown_fields`; `ManifestProbe` checks exact equality (`!=` returns `BackupError::UnknownVersion { found, supported }`); populated `ReservedSlot` fails closed | No (offline bundle) | Fails closed with `UnknownVersion` before full schema decode or digest check | Upgrade the restore binary before restoring a bundle written at a higher format version |
| Local restore commit marker (`.restore-commit.json`) | `RestoreCommitMarker` (`crates/kms/src/backup/local_restore.rs`), filename `LOCAL_RESTORE_COMMIT_MARKER_FILE` (`crates/kms/src/backends/local.rs`) | `format_version: u32` (`RESTORE_MARKER_FORMAT_VERSION`) | `deny_unknown_fields`; exact equality (`!=` fails closed with `BackupError::corrupted`) | No (transient cutover marker) | Fails closed on startup, roll-forward, and abort | Finish or abort any in-progress Local restore before upgrading or downgrading across a marker version bump |
| Vault restore commit marker | `VaultRestoreCommitMarker` (`crates/kms/src/backup/vault_restore.rs`) | `format_version: u32` (`VAULT_RESTORE_MARKER_FORMAT_VERSION`) | `deny_unknown_fields`; exact equality (`!=` fails closed with `BackupError::corrupted`) | No (transient cutover marker) | Fails closed on roll-forward and abort | Finish or abort any in-progress Vault restore before upgrading or downgrading across a marker version bump |
| DR drill evidence | `DrillEvidence` (`crates/kms/src/backup/drill.rs`) | `format_version: u32` (`DRILL_EVIDENCE_FORMAT_VERSION`) | `deny_unknown_fields`; archived evidence record inspected by consumers against `format_version` | No (offline evidence artifact) | Consumer rejects unknown fields or unsupported `format_version` | Upgrade evidence consumers alongside any schema bump |
| Local SSE DEK envelope | `LocalSseDekEnvelope` (`crates/sse/src/kms/local.rs`) | `version: u8` (`LOCAL_SSE_DEK_FORMAT_VERSION`) | `deny_unknown_fields`; exact equality (`!=` returns `SseError::internal`); read-only legacy colon-delimited fallback (`RUSTFS_COMPAT_TODO(sse-local-dek-json-v1)`) | Only legacy colon-delimited -> v1 JSON; newer JSON versions fail closed | Fails closed (`Unsupported encrypted DEK format version`) | Upgrade every cluster node to read the new version before enabling writes via a staged write switch |
| Local KMS master key record (`<key_id>.key`) | `StoredMasterKey`, `StoredKeyProtection` (`crates/kms/src/backends/local.rs`) | `format_version: u32` (`STORED_MASTER_KEY_FORMAT_VERSION`, `serde(default)` -> 1) and `at_rest_protection` enum probed via `has_unknown_protection_marker` | Tolerates unknown fields via hand-written `Deserialize` with sampled field-name-only `warn` and `rustfs_kms_persisted_unknown_fields_total{record_kind="local-key-record"}`; `format_version > STORED_MASTER_KEY_FORMAT_VERSION` or unknown `at_rest_protection` fails closed as `KmsError::UnsupportedFormatVersion` across `decode_stored_key`, `ensure_missing_salt_can_be_generated`, `list_keys`, `crates/kms/src/backup/local_export.rs`, and `crates/kms/src/backup/local_restore.rs` | Newer builds read `<=` versions and pre-field records (defaulting to 1); older builds reject newer versions/markers | Fails closed as `UnsupportedFormatVersion` (and blocks missing-salt regeneration); never misclassified as corruption | Local backend is single-node only; never roll back past a written `format_version` or new `at_rest_protection` variant |
| Local KMS master key salt (`.master-key.salt`) | `LOCAL_KMS_MASTER_KEY_SALT_FILE`, `LOCAL_KMS_MASTER_KEY_SALT_LEN`, `LOCAL_KMS_ARGON2_*` (`crates/kms/src/backends/local.rs`) | None (intentionally unversioned raw 16-byte salt; Argon2id m/t/p are compile-time constants) | Rejects any byte length other than 16; missing salt with unreadable or encrypted `.key` files fails closed in `ensure_missing_salt_can_be_generated` | Yes while Argon2id parameters remain unchanged | Changing KDF constants without explicit migration makes existing encrypted key files undecryptable | Do not add a header to `.master-key.salt`; KDF parameter persistence belongs to Local durability (`rustfs/backlog#1568`) |
| DEK envelope (`DataKeyEnvelope`) | `DataKeyEnvelope`, `is_data_key_envelope`, `envelope_wrap_aad` (`crates/kms/src/encryption/dek.rs`) | No top-level schema version (`master_key_version` is KEK rotation version); opt-in `context_binding: Option<u8>` (`CONTEXT_BINDING_AAD_V1`) | Tolerates unknown fields via hand-written `Deserialize` with sampled field-name-only `warn` and `rustfs_kms_persisted_unknown_fields_total{record_kind="data-key-envelope"}`; unrecognized `context_binding` fails closed in `envelope_wrap_aad` | Additive optional fields work; `context_binding: 1` and post-rotation `master_key_version` require upgraded readers | Older nodes ignore unknown fields; for `context_binding: 1`, pre-AAD nodes fail AES-GCM unwrap; for rotated keys, pre-versioning nodes unwrap against current material | Upgrade every node before rotating keys or enabling `RUSTFS_KMS_ENVELOPE_AAD=true` (`RUSTFS_COMPAT_TODO(backlog-1667-kms-envelope-aad)`); update `is_data_key_envelope` (`DataKeyEnvelopeMarker`) in the same change if any breaking v2 shape retains the seven base fields |
| Object SSE metadata key set | `crates/utils/src/http/object_encryption_keys.rs`, `crates/sse/src/core/keying/direct.rs`, `crates/sse/src/core/keying/object.rs` | None (intentionally unversioned to preserve MinIO metadata compatibility); encrypted ETag listing uses `SUFFIX_OPAQUE_ENCRYPTED_ETAG` (`"v1"`) | Missing `INTERNAL_ENCRYPTION_ALGORITHM_HEADER` defaults to `"AES256"`; unknown MinIO seal algorithms return `Ok(None)` in `parse_minio_managed_sealed_key`; additive keys only | Yes for additive keys when old slots are preserved or neutralized on rewrite | Older nodes ignore unknown metadata keys and may take stale MinIO branches unless superseded slots are neutralized | Deploy readers across every cluster node and replication/tier target before writers emit new metadata keys |
| Vault KV2 key record | `VaultKeyData` (`crates/kms/src/backends/vault.rs`) | None (`version: u32` is KEK rotation version; `baseline_version: Option<u32>` uses `serde(default)`) | Tolerates unknown fields via hand-written `Deserialize` with sampled field-name-only `warn` and `rustfs_kms_persisted_unknown_fields_total{record_kind="vault-kv2-key"}` | Bidirectional reads work | Older nodes read safely, but **drop unknown fields (`baseline_version`, `wrap_budget_reserved`) on write-back** and write blind without CAS | Freeze KMS admin writes and upgrade every cluster node before first key rotation or before relying on new fields |
| Vault Transit key metadata | `TransitKeyMetadataPersisted`, `TransitKeyMetadata::synthesized` (`crates/kms/src/backends/vault_transit.rs`) | None (`current_version: u32` is Vault Transit key version); missing metadata synthesizes `KeyState::Enabled` | Tolerates unknown fields via hand-written `Deserialize` with sampled field-name-only `warn` and `rustfs_kms_persisted_unknown_fields_total{record_kind="vault-transit-key-metadata"}` | Bidirectional reads work | Older nodes drop unknown fields on write-back and retain unbounded metadata caches | Freeze KMS admin writes and upgrade every cluster node before relying on new metadata fields or CAS lifecycle writes |
| Persisted KMS configuration (`config/kms_config.json`) | `KmsConfig`, `kms_config_from_persisted_json` (`crates/kms/src/config.rs`), `KMS_CONFIG_PATH` (`rustfs/src/admin/handlers/kms_dynamic.rs`) | None (deliberately tolerant of unknown fields for rolling upgrades, pinned by `persisted_config_unknown_fields_remain_readable_and_are_observed`) | Loaded through `serde_ignored`, emitting sampled field-path-only `warn` and incrementing `rustfs_kms_persisted_unknown_fields_total{record_kind="kms-config"}`; never logs field values; retains pre-beta.9 Local config fallback (`RUSTFS_COMPAT_TODO(rustfs-5063)`) | Yes for additive optional fields with defaults | Older nodes ignore unknown fields and reject reload broadcasts predating KMS reload support | Confirm `cluster_config.consistent` after reconfiguration; never tighten `KmsConfig` to `deny_unknown_fields` |
## Object Ciphertext Stream Framing
Object payload encryption framing in `crates/rio/src/encrypt_reader.rs` evolves through explicit leading frame-type bytes rather than a file header so single-part and multipart segments can transition independently:
| Frame type | Constant | Value | Semantics and mixed-version rule |
| --- | --- | --- | --- |
| v1 data frame | `FRAME_TYPE_V1` | `0x00` | Default write layout; header and `0xFF` end marker sit outside AEAD. Legacy pre-`1.0.0-alpha.91` segment-nonce fallback is gated by `RUSTFS_ENCRYPTION_LEGACY_NONCE_FALLBACK` (`RUSTFS_COMPAT_TODO(backlog-2369-legacy-nonce-fallback)`). |
| v2 non-final data frame | `FRAME_TYPE_V2` | `0x01` | Fixed 8 KiB plaintext blocks with 8-byte header and frame index bound as AEAD AAD; read unconditionally, written only when `RUSTFS_ENCRYPTION_FRAME_V2=true` (off by default). |
| v2 final data frame | `FRAME_TYPE_V2_FINAL` | `0x02` | Authenticated final frame of a v2 segment, detecting trailing truncation; read unconditionally, written only when `RUSTFS_ENCRYPTION_FRAME_V2=true`. |
| Multipart segment-nonce frame | `FRAME_TYPE_SEGMENT_NONCE` | `0x03` | Authenticated 37-byte opening frame carrying a random 96-bit per-upload segment nonce for v1 or v2 multipart parts; read unconditionally, written only when `RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE=true` (`RUSTFS_COMPAT_TODO(backlog-2703-multipart-segment-nonce)`). Older nodes and ciphertext-passthrough targets without `0x03` read support reject it. |
| Segment end marker | `FRAME_TYPE_END` | `0xFF` | Delimits the end of an encrypted stream or multipart part segment. |
## Version Anchors
`scripts/check_kms_format_versions.py` parses the table below directly and asserts that every listed constant matches its Rust source definition and that no numeric format-version or context-binding constant under `crates/kms/src/` or `crates/sse/src/kms/` escapes documentation. Update this table in the same change before bumping or adding any constant.
| Format | File | Constant | Value | Enforcement |
| --- | --- | --- | --- | --- |
| Backup manifest | `crates/kms/src/backup/manifest.rs` | `BackupManifest::FORMAT_VERSION` | `1` | Exact equality (`!=` -> `BackupError::UnknownVersion`) |
| Local restore commit marker | `crates/kms/src/backup/local_restore.rs` | `RESTORE_MARKER_FORMAT_VERSION` | `1` | Exact equality (`!=` -> `BackupError::corrupted`) |
| Vault restore commit marker | `crates/kms/src/backup/vault_restore.rs` | `VAULT_RESTORE_MARKER_FORMAT_VERSION` | `1` | Exact equality (`!=` -> `BackupError::corrupted`) |
| DR drill evidence | `crates/kms/src/backup/drill.rs` | `DRILL_EVIDENCE_FORMAT_VERSION` | `1` | Explicit schema tag with `deny_unknown_fields` |
| Local KMS master key record | `crates/kms/src/backends/local.rs` | `STORED_MASTER_KEY_FORMAT_VERSION` | `1` | Upper bound (`>` -> `KmsError::UnsupportedFormatVersion`, missing defaults to `1`) |
| DEK envelope context binding | `crates/kms/src/encryption/dek.rs` | `CONTEXT_BINDING_AAD_V1` | `1` | Opt-in write switch (`RUSTFS_KMS_ENVELOPE_AAD`); unrecognized values fail closed |
| Local SSE DEK envelope | `crates/sse/src/kms/local.rs` | `LOCAL_SSE_DEK_FORMAT_VERSION` | `1` | Exact equality (`!=` -> `SseError::internal`, with `deny_unknown_fields`) |
| Ciphertext stream v1 frame | `crates/rio/src/encrypt_reader.rs` | `FRAME_TYPE_V1` | `0x00` | Default write layout; always read |
| Ciphertext stream v2 frame | `crates/rio/src/encrypt_reader.rs` | `FRAME_TYPE_V2` | `0x01` | Opt-in write (`RUSTFS_ENCRYPTION_FRAME_V2`); always read |
| Ciphertext stream v2 final frame | `crates/rio/src/encrypt_reader.rs` | `FRAME_TYPE_V2_FINAL` | `0x02` | Opt-in write (`RUSTFS_ENCRYPTION_FRAME_V2`); always read |
| Ciphertext stream segment-nonce frame | `crates/rio/src/encrypt_reader.rs` | `FRAME_TYPE_SEGMENT_NONCE` | `0x03` | Opt-in write (`RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE`); always read |
| Ciphertext stream end marker | `crates/rio/src/encrypt_reader.rs` | `FRAME_TYPE_END` | `0xFF` | Segment terminator; always read |
## Reference Evolution Pattern
New strictly versioned formats should copy the `BackupManifest` pattern in `crates/kms/src/backup/manifest.rs` rather than inventing ad-hoc parsers:
1. **Probe before full decode.** Decode a minimal version/marker probe first so a record written by a newer build reports `UnknownVersion` or `UnsupportedFormatVersion` instead of generic corruption, which prevents operators from starting disaster recovery during a version mismatch.
2. **Enforce deterministic decode ordering.** Follow the manifest sequence: malformed framing -> version probe -> completeness/lifecycle marker -> schema decode -> raw-bytes integrity digest -> semantic validation. Verify integrity digests over the stored bytes as read, never by re-serializing parsed structs.
3. **Reserve future slots explicitly.** Use `ReservedSlot` (hard-rejecting non-null data in the current version) when a field name is reserved for a known upcoming contract so older builds never silently accept unimplemented semantics.
4. **Choose exact equality vs `<=` intentionally.** Use exact equality for offline bundles and transient cutover markers (`BackupManifest`, restore markers). Use `<=` with `serde(default)` for live stores that need backward-compatible reads (`StoredMasterKey`). Use an opt-in, default-off write switch with unconditional reads for cluster-shared formats that cannot tolerate an uncoordinated cutover (`DataKeyEnvelope::context_binding`, `FRAME_TYPE_V2`, `FRAME_TYPE_SEGMENT_NONCE`).
5. **Make tolerant formats observable without leaking secrets.** Formats that must stay tolerant of unknown fields during rolling upgrades (`KmsConfig`, `DataKeyEnvelope`, `StoredMasterKey`, `VaultKeyData`, `TransitKeyMetadataPersisted`) must never use silent `serde` ignores: they record bounded field names only (never field values) via `UnknownFieldSummary` in `crates/kms/src/persisted_observability.rs`, emitting power-of-two sampled `warn` logs and incrementing `rustfs_kms_persisted_unknown_fields_total{record_kind=...}`.
## Format Version Bump Checklist
Complete every step below before merging a change that bumps any KMS/SSE format version or adds a new persisted discriminator:
1. Update this policy document first — including the inventory table, `## Version Anchors`, mixed-version read rules, downgrade behavior, and the one-time upgrade path if existing records must be rewritten.
2. Keep existing persisted records readable during upgrades: any new field added to an existing tolerant record (`StoredMasterKey`, `VaultKeyData`, `TransitKeyMetadataPersisted`, `DataKeyEnvelope`, `KmsConfig`) must carry `serde(default)` so pre-existing records do not fail to deserialize.
3. Audit every format probe and classifier (`ManifestProbe`, `stored_master_key_format_version`, `has_unknown_protection_marker`, `is_data_key_envelope`, `is_local_sse_dek`, `parse_minio_managed_sealed_key`) so a future version is never misclassified as v1 or collapsed into generic corruption.
4. For cluster-shared formats, ship read support first with the write path behind a default-off switch, register that switch in [compat-cleanup-register.md](compat-cleanup-register.md) with a matching `RUSTFS_COMPAT_TODO(<id>)` source marker and explicit removal condition, and flip the default only in a later release after full fleet convergence.
5. Add negative regression tests proving an unknown version or unknown discriminator fails closed with the expected error classification, plus downgrade/legacy read tests proving existing records remain readable.
6. Run `python3 scripts/check_kms_format_versions.py` and `python3 scripts/test_check_kms_format_versions.py` (alongside `./scripts/check_architecture_migration_rules.sh`) to verify documentation-to-code parity.
## API Surface Stability and Deprecation Policy
The KMS administrative API is versioned in the URL path (`/rustfs/admin/v3/kms/*`) rather than inside JSON request/response bodies (`crates/kms/src/api_types.rs`, `rustfs/src/admin/handlers/kms*.rs`):
- **Request strictness policy.** Admin request structs reject unknown fields with `#[serde(deny_unknown_fields)]` so typos or unsupported security options fail closed with HTTP 400 rather than being silently ignored. The configure and start requests in `crates/kms/src/api_types.rs` and the handler-local request types in `rustfs/src/admin/handlers/kms_keys.rs` and `rustfs/src/admin/handlers/kms_backup.rs` already enforce this; `UpdateKeyDescriptionRequest`, `TagKeyRequest`, and `UntagKeyRequest` in `crates/kms/src/api_types.rs` remain open for strictness convergence under `rustfs/backlog#1641` once client compatibility is confirmed.
- **Response compatibility policy.** Response structs omit `deny_unknown_fields` so older clients can ignore additive fields, and their wire JSON shapes are pinned by `insta` snapshots under `crates/kms/src/snapshots/`.
- **Deprecation workflow.** Removing or renaming an accepted field follows four mandatory steps:
1. Keep the deprecated field accepted on deserialization (never rely on `deny_unknown_fields` to silently break existing callers).
2. Add a dedicated deserialization regression guard test verifying both presence and omission of the deprecated field, and register it in `### Active Deprecation Guards` below. The canonical example is `test_deserialize_vault_kv2_configure_request_mount_path_optional_but_accepted` in `crates/kms/src/api_types.rs` for the deprecated Vault `mount_path` field.
3. When a temporary compatibility branch is slated for deletion, mark the source with `RUSTFS_COMPAT_TODO(<task-id>)` and record the exact removal condition in [compat-cleanup-register.md](compat-cleanup-register.md).
4. Delete the deprecated field only in a dedicated cleanup change once its documented removal condition is satisfied.
### Active Deprecation Guards
`scripts/check_kms_format_versions.py` verifies that every test named below exists in its cited file so a deprecated-but-accepted field cannot lose its regression guard silently.
| Surface | Field | Test file | Regression guard |
| --- | --- | --- | --- |
| `ConfigureVaultKmsRequest` / `ConfigureKmsRequest` | `mount_path` | `crates/kms/src/api_types.rs` | `test_deserialize_vault_kv2_configure_request_mount_path_optional_but_accepted` |
## Why No Standalone Migration Framework Is Built
RustFS intentionally does **not** build a generic KMS format migration framework today (`rustfs/backlog#1641`):
- **Zero v1-to-v2 transitions exist yet.** Every explicitly versioned KMS format (`BackupManifest`, `RestoreCommitMarker`, `VaultRestoreCommitMarker`, `DrillEvidence`, `StoredMasterKey`, `LocalSseDekEnvelope`) is still at version 1, so a generic framework would have no real input and would freeze speculative abstractions before the first migration's real constraints are known.
- **Backup and restore already serve as the cross-version transport.** KMS backup export and restore (`crates/kms/src/backup/local_export.rs`, `crates/kms/src/backup/local_restore.rs`, `crates/kms/src/backup/vault_restore.rs`) already serialize KMS state into a self-describing, versioned, integrity-verified bundle and validate target compatibility before cutover.
- **Explicit trigger condition.** Instead of a pre-built framework, every format version bump must specify its downgrade behavior and concrete one-time upgrade path under the [Format Version Bump Checklist](#format-version-bump-checklist); a dedicated migration utility will be built alongside the first actual v1-to-v2 bump if backup/restore or online rewrite (such as `POST /rustfs/admin/v3/kms/keys/rekey`) cannot serve it directly.
## Verification
Run the drift guard and its negative-case unit tests whenever editing this document or any listed KMS/SSE/encryption format constant:
```bash
python3 scripts/check_kms_format_versions.py
python3 scripts/test_check_kms_format_versions.py
./scripts/check_architecture_migration_rules.sh
./scripts/check_doc_paths.sh
```
+1 -1
View File
@@ -31,7 +31,7 @@ Every provider key can be set as `RUSTFS_IDENTITY_OPENID_<KEY>` in the process e
| `issuer` | `RUSTFS_IDENTITY_OPENID_ISSUER` | Expected `iss` when it differs from `config_url` (internal discovery URL, public token issuer). |
| `client_id`, `client_secret` | `RUSTFS_IDENTITY_OPENID_CLIENT_ID`, `RUSTFS_IDENTITY_OPENID_CLIENT_SECRET` | Confidential client credentials. |
| `scopes` | `RUSTFS_IDENTITY_OPENID_SCOPES` | Comma-separated; `openid` is required. |
| `other_audiences` | `RUSTFS_IDENTITY_OPENID_OTHER_AUDIENCES` | Additional accepted `aud` values. |
| `other_audiences` | `RUSTFS_IDENTITY_OPENID_OTHER_AUDIENCES` | Additional `aud` values allowed alongside `client_id` in multi-audience tokens (`client_id` is still required). |
| `redirect_uri` | `RUSTFS_IDENTITY_OPENID_REDIRECT_URI` | Callback URL sent to the IdP; must equal the URL registered there. |
| `redirect_uri_dynamic` | `RUSTFS_IDENTITY_OPENID_REDIRECT_URI_DYNAMIC` | `on` derives the callback from request headers. Keep `off` behind proxies. |
| `claim_name`, `claim_prefix` | `RUSTFS_IDENTITY_OPENID_CLAIM_NAME`, `RUSTFS_IDENTITY_OPENID_CLAIM_PREFIX` | Policy claim name and a fixed string prepended to each value. `claim_prefix` is not a mapping table. |
@@ -17,7 +17,7 @@ The table below describes Console login. For endpoint-free STS issuers, use the
| 4 | Authorization-code flow with PKCE (S256) | The authorization request carries `response_type=code`, `scope`, `redirect_uri`, `state`, `nonce`, `code_challenge`, `code_challenge_method=S256`; the token request carries the `code_verifier`. Providers that ignore or reject PKCE, `state`, or `nonce` are not supported. | `crates/iam/src/oidc/runtime.rs` `PkceCodeChallenge::new_random_sha256`; `crates/iam/src/oidc/state.rs` `pkce_verifier` |
| 5 | Scopes | Default `openid,profile,email` (`OIDC_DEFAULT_SCOPES`); override with `RUSTFS_IDENTITY_OPENID_SCOPES` (comma-separated). The provider must accept every configured scope. | `crates/config/src/constants/oidc.rs` `OIDC_DEFAULT_SCOPES`; `crates/iam/src/oidc/config.rs` `OidcProviderConfig::scopes` |
| 6 | Callback returns `state` | The callback must carry both `code` and the original `state`; `state` locates the in-flight session that holds the nonce and PKCE verifier. A callback with only `code` fails. | `rustfs/src/admin/handlers/oidc.rs` `OIDC_CALLBACK_SUFFIX`; `crates/iam/src/oidc/state.rs` |
| 7 | ID token claims | `iss`, `aud`, `exp`, and `nonce` are verified; `sub` identifies the user. `aud` must contain the client id or one of `RUSTFS_IDENTITY_OPENID_OTHER_AUDIENCES`. | `crates/iam/src/oidc/runtime.rs` `trusted_aud`, `OidcClaims` |
| 7 | ID token claims | `iss`, `aud`, `exp`, and `nonce` are verified; `sub` identifies the user. `aud` must contain the configured `client_id` (`RUSTFS_IDENTITY_OPENID_CLIENT_ID`); `RUSTFS_IDENTITY_OPENID_OTHER_AUDIENCES` only allows additional audience values present alongside `client_id` in a multi-audience token and does not substitute for `client_id`. | `crates/iam/src/oidc/runtime.rs` `trusted_aud`, `OidcClaims`; `crates/iam/src/oidc/provider.rs` `ProviderMetadata::verifier` |
| 8 | Authorization claims in the ID token | Policy mapping reads the claim named by `RUSTFS_IDENTITY_OPENID_CLAIM_NAME` (default `groups`, `OIDC_DEFAULT_CLAIM_NAME`) together with `RUSTFS_IDENTITY_OPENID_GROUPS_CLAIM` and the optional `RUSTFS_IDENTITY_OPENID_ROLES_CLAIM`, as a string or array of strings, optionally prefixed by `RUSTFS_IDENTITY_OPENID_CLAIM_PREFIX`. Values must equal RustFS policy names (for example `consoleAdmin`, `readwrite`, `readonly`) made only of `[A-Za-z0-9_:.-]`. Groups-claim and roles-claim values with no policy of that name, such as the Active Directory group `DOMAIN\Domain Users` or Keycloak's `offline_access` role, are ignored once storage confirms that no such policy exists. Login is rejected when a policy lookup fails, when no value resolves, when a value names an existing policy whose name is outside that character set (dropping it could remove a Deny), or when a name from `RUSTFS_IDENTITY_OPENID_ROLE_POLICY`, a separate `RUSTFS_IDENTITY_OPENID_CLAIM_NAME` claim, or an explicit IAM policy mapping does not exist. Email and username come from `RUSTFS_IDENTITY_OPENID_EMAIL_CLAIM` (default `email`) and `RUSTFS_IDENTITY_OPENID_USERNAME_CLAIM` (default `preferred_username`). A provider that returns only a user id can authenticate but cannot express RustFS authorization. | `crates/iam/src/oidc/runtime.rs` `map_claims_to_policies`, `extract_canonical_group_values`, `OidcSys::group_claim_policy_names`; `rustfs/src/admin/service/federated_identity.rs` `select_oidc_policies` |
| 9 | Registered redirect URI | The provider must accept the callback `{public-origin}/rustfs/admin/v3/oidc/callback/{provider_id}`. RustFS picks the origin in this order: the provider's `redirect_uri` (`RUSTFS_IDENTITY_OPENID_REDIRECT_URI`), then `RUSTFS_BROWSER_REDIRECT_URL`, then the request's own scheme and host — the last only when `RUSTFS_IDENTITY_OPENID_REDIRECT_URI_DYNAMIC` is enabled. | `rustfs/src/admin/handlers/oidc.rs` `derive_callback_uri_with_provider_config`, `browser_redirect_url` |
| 10 | Logout endpoint (optional) | When discovery advertises `end_session_endpoint`, RustFS builds an RP-initiated logout URL with `id_token_hint`, `client_id`, and `post_logout_redirect_uri`. Without it, logout falls back to the console login page. | `crates/iam/src/oidc/runtime.rs` `build_logout_url` (reads `end_session_endpoint` from `ProviderMetadataWithLogout`) |
+19 -20
View File
@@ -118,37 +118,36 @@ Functional-chain health runs on a hosted runner independently of the lab fleet.
## Release validation
Post-merge and tag-driven; not a substitute for a PR gate. Every public publication exit consumes the release certification described here; this certification path is separate from the reusable CI artifact contract in [verification plans](ci-verification-pipeline.md), whose archives expire after one day and are never used as release certification.
Post-merge and dispatch-driven; not a substitute for a PR gate. Every public publication exit consumes the release certification described here; this certification path is separate from the reusable CI artifact contract in [verification plans](ci-verification-pipeline.md), whose archives expire after one day and are never used as release certification.
The versioned plan is `.config/release-validation-plan.json` (`schema_version=1`): release types, target OS/arch/ABI, supported features, a fixed harness SHA per lane, required case IDs, environment capabilities, timeouts, applicability conditions, and an explicit `upgrade_sources` list carrying the real artifact digests of the supported N-1/N-2 sources plus a stated rollback basis — compatibility and rollback are never invented or defaulted. `scripts/release/release_gate.py validate` expands and freezes `plan_sha256` and the required case set before reading results, then binds that plan, a `candidate.json` (product 40-character SHA, version, release profile, features, immutable deliverable locations with SHA256 and wrapped-binary SHA256, image digest) and the shared G01 evidence-envelope set (rustfs/backlog#2658) of one parent candidate batch, and writes machine JSON, JUnit and a summary. Within a batch the unique key is `(lane, platform{os,arch,abi}, case_id)`; the top-level run/attempt is the parent batch and the nested workflow run/attempt is the child workflow identity, and both are validated separately (workflow SHA and product build SHA are bound independently and need not be equal). Missing, duplicate or extra cases, stale attempts, wrong digests, wrong platforms, wrong harness SHAs, zero tests, cancellation, timeout, untrusted sources and any non-PASS required item block with classified errors; only a complete legal success returns 0. `verify-promotion` re-checks the exact bytes about to be published against the passed list and fails on a swapped package or an edited plan after verification. preview, prerelease and stable all require an explicit plan; preview may use the plan's smaller pre-declared set but never bypasses artifact identity and startup checks. development artifacts are explicitly uncertified and never touch official or latest channels.
The versioned plan is `.config/release-validation-plan.json` (`schema_version=1`): release types (`preview`, `prerelease`, `stable`), the six shipped OS/arch/ABI targets, supported features (`pyroscope` on Linux gnu and macOS), the trusted workflow allowlist (`rustfs/rustfs` `release-candidate.yml` and `release-complete.yml`), per-lane harness identity pinned to `candidate.workflow_sha`, required case IDs (`identity` on all platforms for every release type; `upgrade` on `linux-x86_64-gnu` for `prerelease` and `stable`), environment capabilities, timeouts, and an explicit `upgrade_sources` list carrying the pinned previous-release digests from `.github/workflows/e2e-upgrade.yml` — compatibility and rollback are never invented or defaulted. `scripts/release/release_gate.py validate` expands and freezes `plan_sha256` and the required case set before reading results, then binds that plan, a `candidate.json` (product 40-character SHA, version, release profile, features, immutable deliverable locations with SHA256 and wrapped-binary SHA256, image digest), and the shared G01 evidence-envelope set (`rustfs/backlog#2658`) of one parent candidate batch, and writes machine JSON, JUnit, and a summary. Within a batch the unique key is `(lane, platform{os,arch,abi}, case_id)`; the top-level run/attempt is the parent batch and the nested workflow run/attempt is the child workflow identity, and both are validated separately (workflow SHA and product build SHA are bound independently and need not be equal). Missing, duplicate, or extra cases, stale attempts, wrong digests, wrong platforms, wrong harness SHAs, zero tests, cancellation, timeout, untrusted sources, and any non-PASS required item block with classified errors; only a complete legal success returns 0, and Linux-only certification always keeps `publish_allowed=false`. Preview, prerelease, and stable all require an explicit plan; preview may use the plan's smaller pre-declared set (`identity` lane only) but never bypasses artifact identity and startup checks. Development artifacts are explicitly uncertified and never touch official or latest channels.
Public release writes live exclusively in `.github/workflows/release-publish.yml`. The build and packaging workflows (`build.yml`, `docker.yml`, `package.yml`, `helm-package.yml`) run with read-only `contents: read` / `actions: read` permissions when called by the three-stage immutable-candidate chain (`release-candidate.yml` -> `release-complete.yml` -> `release-publish.yml`), staging workflow artifacts only and never pushing public tags or releases directly.
| Trigger | Workflow / job | Result |
|---|---|---|
| Nightly Linux schedule, weekly desktop schedule, or dispatch | `build.yml` `build-rustfs` (development build of that schedule's platform subset, or the dispatch platform list) | build artifacts and the uncertified dev download channel; no release publication |
| Valid release or preview tag | `build.yml` `build-rustfs`, `release-certification`, `create-release`, `upload-release-assets`, `publish-release`, `promote-release-artifacts` | staged binaries, draft release, checksummed assets, then certified publish and promotion of the same bytes |
| Successful non-preview release-tag build (`workflow_run`) | `docker.yml` `release-certification`, `build-docker`, `scan-docker-image` | multi-architecture images staged, verified against the certification and promoted, plus vulnerability report |
| Successful release-tag build (`workflow_run`) | `package.yml` `release-certification`, `package`, `promote-packages` | DEB/RPM packages with wrapped-binary verification, staged then promoted with checksums |
| Successful non-preview release-tag build (`workflow_run`) | `helm-package.yml` `release-certification`, `build-helm-package`, `publish-helm-package` | versioned chart and repository index, only over a certified image promotion record |
| Final tag's release published | `build.yml` `cleanup-preview-releases` | deletes every `<target>-preview.<N>` Release for that target; the tags are kept |
| --- | --- | --- |
| Nightly Linux schedule, weekly desktop schedule, or manual `workflow_dispatch` | `build.yml` `build-check`, `build-rustfs` (platform subset for that schedule or dispatch list; optional `publish=true` for dev channel only) | Uncertified development build artifacts and optional dev download channel; never publishes a release |
| Manual `workflow_dispatch` on `main` (`version`, `source_sha`) | `release-candidate.yml` `freeze`, reusable `build.yml` (`linux`), `upgrade`, `seal-linux` | Verifies exact-source CI (`Quick Checks`, `Test and Lint`, `End-to-End Tests (full merge gate)` including merge-group-proven pushes), freezes `inputs.json`, builds the four Linux binaries, runs previous-release upgrade verification, runs `linux`-scope `release_gate` (`publish_allowed=false`), and uploads the sealed `release-linux` artifact (`linux-manifest.json`) for backlog acceptance |
| Manual `workflow_dispatch` on `main` (`candidate_run_id`, `linux_manifest_sha256`, `acceptance_report`) | `release-complete.yml` `acceptance` (environment `release-linux-acceptance`), reusable `build.yml` (`desktop`), `package.yml` (`package`), `docker.yml` (`build-docker`), `helm-package.yml` (`package`), `seal` | Re-verifies the accepted Linux manifest, recipe digest, and backlog report URL; builds read-only desktop archives, Linux DEB/RPM packages, multi-arch `musl`/`gnu` OCI tar archives (with binary + startup smoke and report-only Trivy SARIF scans), and the tested Helm chart; runs full-scope `release_gate` (`publish_allowed=true`), bundles `release-evidence.zip`, CycloneDX SBOM, SLSA provenance, `SHA256SUMS`/`SHA512SUMS`, and uploads the approved `release-seal` artifact (`release-manifest.json`) |
| Manual `workflow_dispatch` on `main` (`complete_run_id`, `manifest_sha256`) | `release-publish.yml` `verify`, `version` (environment `release-publication`), `channels` | Never compiles or packages; re-verifies the sealed manifest, files, recipe, deliveries, and full certification (`scripts/release/publish.py verify`), promotes immutable versioned exits, then promotes the Helm catalog and monotonic stable channel pointers |
Publication exits and their gate:
| Exit | Writer | Certification consumed |
|---|---|---|
| GitHub Release draft → public | `build.yml` `publish-release` | `release-certification` success and per-asset `verify-promotion` |
| Official R2 binary path `artifacts/rustfs/release/` | `build.yml` `promote-release-artifacts` | `release-certification` plus `verify-promotion`; the build job itself only writes `artifacts/rustfs/staging/<run>/<attempt>/` |
| `latest.json` version pointer | `build.yml` `update-latest-version` | transitively through `publish-release` |
| Image channels (Docker Hub, GHCR, Quay tags) | `docker.yml` `build-docker` promotion step | certified input digests, staged image binary identity and `verify-promotion`, then promotion of the same digest with `imagetools create` |
| Official R2 package paths `packages/release` and `packages/latest` | `package.yml` `promote-packages` | `release-certification` and wrapped-binary `verify-promotion`; the package job only stages |
| GitHub release package assets | `package.yml` `package` | `release-certification` and wrapped-binary `verify-promotion` before upload |
| Helm chart repository (`rustfs/helm` push) | `helm-package.yml` `publish-helm-package` | `release-certification` plus the Docker workflow's image-promotion record bound to the same candidate |
| Exit | Writer | Certification and approval consumed |
| --- | --- | --- |
| Annotated Git tag `<version>` and GitHub Release (draft -> public with checksummed archives, DEB/RPM, chart, SBOM, provenance, `release-manifest.json`, `release-evidence.zip`, and `latest` aliases) | `release-publish.yml` `version` (`scripts/release/publish.py version`) | `verify` job (`manifest_sha256` match, full `release_gate` `publish_allowed=true`, `verify_seal_files`, `verify_deliveries`, backlog acceptance URL) plus `release-publication` environment gate; draft turns public only after every versioned destination verifies |
| Versioned R2 release assets (`artifacts/rustfs/release/` and `artifacts/rustfs/release/<version>/`) | `release-publish.yml` `version` (`scripts/release/publish.py version`) | Same `verify` and `release-publication` gate; conditional non-overwriting uploads with read-back SHA-256 check |
| Versioned OCI image tags (`<version>` and `<version>-glibc` on Docker Hub, GHCR, Quay) and Trivy SARIF uploads | `release-publish.yml` `version` (`scripts/release/publish.py version` + `github/codeql-action/upload-sarif`) | Same `verify` and `release-publication` gate; verbatim `skopeo copy --all --preserve-digests` from the sealed OCI tar archives with post-copy manifest digest verification |
| Helm chart repository (`rustfs/helm` chart `.tgz` and `index.yaml` push) | `release-publish.yml` `channels` (`scripts/release/publish.py channels`) | `verify` + `version` completion, re-verification of all immutable versioned destinations, and `chart.json` SHA-256 check |
| Mutable stable channels (GitHub Release `make_latest=true`, `:latest` / `:latest-glibc` OCI tags on Docker Hub/GHCR/Quay, R2 `artifacts/rustfs/release/rustfs-<target>-latest.zip`, Alibaba Cloud OSS `oss://rustfs-version/latest.json`) | `release-publish.yml` `channels` (`scripts/release/publish.py channels`, serialized under `rustfs-release-channels`) | Same `verify` + `version` gate; skipped for prereleases and skipped if a newer stable release already owns the channels |
Downstream workflows fail closed when the trusted certification is absent: a manual dispatch without certification fails and pushes no official tag. Only results from the trusted verification sources listed in the plan (currently the `rustfs/s3chaos` `release-gate.yml` envelope runs) carry release authority; a PR-uploaded JSON set cannot certify a release. Retries reuse the same candidate, only the staged bytes are promoted (no rebuild-after-verify), and no downstream step re-resolves a mutable `latest`.
All three release workflows fail closed when called off `rustfs/rustfs` `refs/heads/main`, when a manifest digest does not match the downloaded seal, when the release recipe or validation plan changed after freezing, or when any receipt was not produced by the exact downloaded `release-candidate.yml` or `release-complete.yml` run. A PR-uploaded JSON set cannot certify a release. Retries reuse already-verified artifacts for the same frozen candidate (never rebuilding after verification), versioned destinations refuse to overwrite differing bytes, and no downstream step re-resolves a mutable `latest`.
Use an exact preview tag for an end-to-end release rehearsal. Manual dispatches are backfill/debug paths and do not prove the automatic `workflow_run` chain. The committed fixtures under `testdata/release-gate/` and the commands below are contract rehearsals of this orchestration; they are explicitly not product release evidence and not live verifier results.
The committed fixtures under `testdata/release-gate/` and the commands below are contract rehearsals of this orchestration (`scripts/security/check_preview_release_workflow.sh` runs `WorkflowContractTests` in `scripts/release/test_pipeline.py`); they are explicitly not product release evidence and not live verifier results.
```bash
python3 -m unittest discover -s scripts/release -p 'test_release_gate.py'
python3 scripts/release/test_pipeline.py
python3 scripts/release/release_gate.py validate --plan testdata/release-gate/plan.json --candidate testdata/release-gate/candidate.json --results testdata/release-gate/pass --output target/release-gate-check
bash scripts/security/check_preview_release_workflow.sh
```
+14
View File
@@ -21,6 +21,19 @@ Every fixed RustFS GitHub Security Advisory maps to at least one named regressio
| GHSA-xm99-m3gq-83g8 | A header-signed SigV4 request must reject `x-amz-*` headers missing from its `SignedHeaders` (an unsigned `x-amz-copy-source` turned a replayed PutObject into a cross-bucket CopyObject), and a non-`AWS4-HMAC-SHA256` algorithm token must not route around that check | this fix | `ghsa_xm99_header_sigv4_rejects_unsigned_x_amz_headers`, `ghsa_xm99_header_sigv4_accepts_signed_or_exempt_x_amz_headers`, `ghsa_xm99_header_sigv4_rejects_unsupported_algorithm_token`, `ghsa_xm99_header_and_query_signatures_cannot_widen_each_other`, `ghsa_xm99_check_ignores_sigv2_jwt_and_anonymous_requests` (`rustfs/src/auth.rs`); `ghsa_xm99_check_access_rejects_unsigned_amz_header_on_header_signed_custom_route` for routes that bypass `S3Access::check` (`rustfs/src/admin/router.rs`); `ghsa_xm99_header_sigv4_rejects_unsigned_copy_source`, which also asserts the destination bytes survive, plus the signed-copy control `ghsa_xm99_header_sigv4_accepts_signed_copy_source` (`crates/e2e_test/src/negative_sigv4_test.rs`) | unit; e2e (`e2e-smoke`) |
| [GHSA-g3vq-vv42-f647](https://github.com/rustfs/rustfs/security/advisories/GHSA-g3vq-vv42-f647) | FTPS `MKD` must clear the `s3:CreateBucket` authorization boundary before reaching the backend | fixed, GHSA private-fork merge | `ghsa_g3vq_mkd_denied_before_reaching_backend` (`crates/protocols/src/ftps/driver.rs`); primes `create_bucket` to succeed so the assertion distinguishes "denied at authorization" from "backend refused" | unit (`ftps` feature) |
## Closed advisory dispositions
Historical advisories closed without a `ghsa_*`-prefixed test name are audited here so every closed GHSA has a verifiable disposition (fixed, duplicate, or by-design) tied to current code and tests (`rustfs/backlog#1506`). Still-open issues and tracked rolling-upgrade compatibilities are not listed as fixed here.
| Advisory | Disposition | Class | Verified code and test anchors | Layer |
| --- | --- | --- | --- | --- |
| [GHSA-8r6f-hmq2-28rg](https://github.com/rustfs/rustfs/security/advisories/GHSA-8r6f-hmq2-28rg) | Fixed | Object-key path traversal rejected during key validation | `has_bad_path_component`, `is_valid_object_name`, `test_is_valid_object_name`, `valid_object_names_preserve_name_invariants` (`crates/ecstore/src/bucket/utils.rs`) | unit |
| [GHSA-jqmc-mg33-v45g](https://github.com/rustfs/rustfs/security/advisories/GHSA-jqmc-mg33-v45g) | Fixed | Profiling endpoints (`/profile/cpu`, `/profile/memory`) require authenticated high-risk admin authorization | Route policy entries in `rustfs/src/admin/route_policy.rs`; `an_anonymous_admin_request_is_refused_under_both_prefixes_and_every_method` (`rustfs/src/admin/router/admission_tests.rs`); `every_control_plane_class_answers_as_legacy_and_never_reaches_it` (`rustfs/src/server/http/tests/native_admin_tests/control_plane_tests.rs`) | unit |
| [GHSA-xrrf-67jm-3c2r](https://github.com/rustfs/rustfs/security/advisories/GHSA-xrrf-67jm-3c2r) | Fixed | SSE write path persists ciphertext rather than plaintext on disk | `sse_encryption` (`crates/sse/src/core/write.rs`); `assert_storage_encrypted`, `test_multipart_upload_writes_encrypted_data` (`crates/e2e_test/src/kms/encryption_metadata_test.rs`) | e2e |
| [GHSA-68cw-96m3-h2cf](https://github.com/rustfs/rustfs/security/advisories/GHSA-68cw-96m3-h2cf), [GHSA-75fx-qg6f-8rm7](https://github.com/rustfs/rustfs/security/advisories/GHSA-75fx-qg6f-8rm7) | Fixed (paired with `GHSA-r5qv-rc46-hv8q`, rustfs/rustfs#4402, rustfs/rustfs#5248) | Internode RPC authentication refuses default-credential secret fallback and distributed startup fails fast without a resolved RPC secret | `ghsa_r5qv_resolve_shared_secret_rejects_default_fallback` (`crates/ecstore/src/cluster/rpc/http_auth.rs`); `preflight_startup_rpc_secret_with`, `test_rpc_secret_preflight_aborts_for_remote_endpoints_without_secret` (`crates/ecstore/src/store/init.rs`) | unit |
| [GHSA-m479-9x88-94w6](https://github.com/rustfs/rustfs/security/advisories/GHSA-m479-9x88-94w6), [GHSA-frwq-mfqx-83p8](https://github.com/rustfs/rustfs/security/advisories/GHSA-frwq-mfqx-83p8), [GHSA-q9q8-rf9r-fg9f](https://github.com/rustfs/rustfs/security/advisories/GHSA-q9q8-rf9r-fg9f), [GHSA-j5c2-hhf7-6gf5](https://github.com/rustfs/rustfs/security/advisories/GHSA-j5c2-hhf7-6gf5) | Fixed (four duplicate reports) | OIDC discovery and config validation re-check resolved IPs at connection time and disable redirects to block DNS-rebinding SSRF | `OutboundPolicy::resolver_for`, `outbound_dns_resolver_filters_rebinding_and_mixed_answers`, `reqwest_rechecks_dns_policy_for_each_new_connection` (`crates/utils/src/egress.rs`); wired in `crates/iam/src/oidc/transport.rs`; `oidc_reqwest_dns_policy_rejection_stays_typed`, `oidc_explicit_issuer_preserves_dns_policy_rejection` (`crates/iam/src/oidc/provider_tests.rs`) | unit |
| [GHSA-3473-5353-xhwh](https://github.com/rustfs/rustfs/security/advisories/GHSA-3473-5353-xhwh), [GHSA-5qfg-mf7r-jp3w](https://github.com/rustfs/rustfs/security/advisories/GHSA-5qfg-mf7r-jp3w), [GHSA-jxrr-r6pv-h958](https://github.com/rustfs/rustfs/security/advisories/GHSA-jxrr-r6pv-h958) | Closed as by-design (hardened in rustfs/rustfs#9163 and rustfs/rustfs#9641) | Unauthenticated `POST /` `AssumeRoleWithWebIdentity` matches AWS STS (the verified OIDC JWT is the credential), while `AssumeRole` requires SigV4 (`check_key_valid`) and other actions return `InvalidArgument`; follow-on hardening added single-flight JWKS refresh with failure cooldown and sanitized public verification errors | `handle_assume_role`, `sanitize_web_identity_verification_error`, `web_identity_errors_preserve_existing_s3_semantics` (`rustfs/src/admin/handlers/sts.rs`); `jwks_refresh_is_single_flight_and_survives_request_cancellation`, `jwks_refresh_cools_down_failures_and_recovers_after_the_interval` (`crates/iam/src/oidc/provider_tests.rs`) | unit |
## Where these run
| Layer | Command | Lane | Guard |
@@ -41,3 +54,4 @@ Notes:
2. Name the test (or the helper/assertion) `ghsa_<id>_*`, or attach a `GHSA-<id>` doc comment with the advisory URL.
3. Add a row to the table above.
4. Land it where it runs (table above): a unit guard needs nothing extra; an S3 e2e guard joins the `e2e-smoke` filter in `.config/nextest.toml` with its digest updated, and a negative-auth module also bumps `.config/security-smoke-floor.txt`; a fixed-port protocol guard goes into the protocols suite (nightly lane).
5. When closing an advisory without a new `ghsa_*`-named fix test (duplicate, by-design, or historical fix), record a one-line disposition and evidence anchor under `## Closed advisory dispositions` (or `## Advisory -> test map` when pinned by a named test) so every closed advisory remains auditable.
+2
View File
@@ -28,6 +28,8 @@ their issue closes.
| `check_architecture_migration_rules.sh` | ci-gate | Architecture-boundary anti-regression guard | ci.yml Quick Checks; `make pre-commit` |
| `check_body_cache_whitelist.sh` | ci-gate | Keeps the app-layer body-cache eligibility gate fail-closed | ci.yml Quick Checks |
| `check_doc_paths.sh` | ci-gate | Fails when instruction/architecture docs reference repo paths that no longer exist | `make pre-commit` / `pre-pr` |
| `check_kms_format_versions.py` | ci-gate | Verifies KMS/SSE/encryption format version constants and active deprecation guard tests against `docs/architecture/kms-format-version-policy.md` | `check_architecture_migration_rules.sh`; `test_check_kms_format_versions.py` (`make script-tests`) |
| `test_check_kms_format_versions.py` | ci-gate | Contract tests (valid repo, tampered decimal/hex constants, undocumented constants, missing deprecation guards) for `check_kms_format_versions.py` | `make script-tests` |
| `check_embedded_secrets.sh` | ci-gate | Repo-wide scan blocking committed private key material and provider credential literals | ci.yml Quick Checks; `make pre-commit` / `pre-pr` |
| `check_extension_schema_boundaries.sh` | ci-gate | Extension-schema crate boundary guard | ci.yml Quick Checks; `make pre-commit` |
| `check_layer_dependencies.sh` | ci-gate | Crate-layering DAG guard (reads `layer-dependency-baseline.txt`) | ci.yml Quick Checks |
@@ -5592,6 +5592,10 @@ if ! bash "${ROOT_DIR}/scripts/check_oidc_architecture_boundaries.sh"; then
report_failure "OIDC architecture boundary check"
fi
if ! "${ROOT_DIR}/scripts/python_bin.sh" "${ROOT_DIR}/scripts/check_kms_format_versions.py"; then
report_failure "KMS format version policy check"
fi
if (( FAILURES > 0 )); then
exit 1
fi
+313
View File
@@ -0,0 +1,313 @@
#!/usr/bin/env python3
# Copyright 2026 RustFS Team
# SPDX-License-Identifier: Apache-2.0
"""Verify KMS/SSE format version constants and deprecation guards against policy docs.
Checks:
1. Every row in `## Version Anchors` of `docs/architecture/kms-format-version-policy.md`
matches the exact constant value in the cited Rust source file.
2. Every numeric `*FORMAT_VERSION` and `CONTEXT_BINDING_*` constant declared under
`crates/kms/src/` or `crates/sse/src/kms/` is registered in `## Version Anchors`.
3. Every row in `### Active Deprecation Guards` names a test function present in its
cited Rust source file.
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass
from pathlib import Path
import re
import sys
ROOT = Path(__file__).resolve().parents[1]
POLICY_REL_PATH = Path("docs/architecture/kms-format-version-policy.md")
VERSION_SECTION_HEADING = "## Version Anchors"
DEPRECATION_SECTION_HEADING = "### Active Deprecation Guards"
# Matches Rust integer constants such as:
# pub const FORMAT_VERSION: u32 = 1;
# pub(crate) const LOCAL_SSE_DEK_FORMAT_VERSION: u8 = 1;
# const FRAME_TYPE_SEGMENT_NONCE: u8 = 0x03;
CONST_DECL_RE = re.compile(
r"^\s*(?:pub(?:\s*\([^)]*\))?\s+)?const\s+([A-Z][A-Z0-9_]*)\s*:\s*"
r"(?:u8|u16|u32|u64|usize|i8|i16|i32|i64)\s*=\s*([0-9A-Fa-fxX_]+)\s*;",
re.MULTILINE,
)
# Matches an `impl [Type]` block header for associated constants (e.g. BackupManifest::FORMAT_VERSION).
IMPL_HEADER_RE = re.compile(r"^\s*impl(?:<[^>]*>)?\s+([A-Za-z_][A-Za-z0-9_]*)\b")
# Tracks constants under crates/kms/src/ and crates/sse/src/kms/ that must stay documented.
TRACKED_CONST_NAME_RE = re.compile(r"^(?:[A-Z0-9_]*FORMAT_VERSION|CONTEXT_BINDING_[A-Z0-9_]+)$")
TRACKED_SCAN_DIRS = (Path("crates/kms/src"), Path("crates/sse/src/kms"))
TEST_FN_RE_TEMPLATE = r"^\s*(?:pub(?:\s*\([^)]*\))?\s+)?(?:async\s+)?fn\s+{name}\s*\("
@dataclass(frozen=True)
class VersionAnchor:
fmt: str
rel_file: str
symbol: str
value_raw: str
@dataclass(frozen=True)
class DeprecationGuard:
surface: str
field: str
rel_file: str
test_fn: str
def strip_code_ticks(cell: str) -> str:
text = cell.strip()
if len(text) >= 2 and text.startswith("`") and text.endswith("`"):
return text[1:-1].strip()
return text
def parse_markdown_table(text: str, heading: str) -> list[list[str]]:
lines = text.splitlines()
in_section = False
heading_level = len(heading) - len(heading.lstrip("#"))
rows: list[list[str]] = []
saw_header = False
saw_separator = False
for line in lines:
stripped = line.strip()
if not in_section:
if stripped == heading:
in_section = True
continue
if stripped.startswith("#"):
level = len(stripped) - len(stripped.lstrip("#"))
if level <= heading_level:
break
if not stripped.startswith("|"):
if saw_separator:
break
continue
cells = [part.strip() for part in stripped.strip("|").split("|")]
if not saw_header:
saw_header = True
continue
if not saw_separator:
if all(re.fullmatch(r":?-{3,}:?", cell) for cell in cells):
saw_separator = True
continue
break
rows.append(cells)
return rows
def parse_version_anchors(policy_text: str) -> tuple[list[VersionAnchor], list[str]]:
rows = parse_markdown_table(policy_text, VERSION_SECTION_HEADING)
errors: list[str] = []
anchors: list[VersionAnchor] = []
if not rows:
errors.append(f"{POLICY_REL_PATH}: missing or empty '{VERSION_SECTION_HEADING}' table")
return anchors, errors
seen: set[tuple[str, str]] = set()
for index, cells in enumerate(rows, 1):
if len(cells) < 4:
errors.append(f"{POLICY_REL_PATH}: '{VERSION_SECTION_HEADING}' row {index} has fewer than 4 columns")
continue
fmt = cells[0].strip()
rel_file = strip_code_ticks(cells[1])
symbol = strip_code_ticks(cells[2])
value_raw = strip_code_ticks(cells[3])
if not rel_file or not symbol or not value_raw:
errors.append(f"{POLICY_REL_PATH}: '{VERSION_SECTION_HEADING}' row {index} has empty required fields")
continue
key = (rel_file, symbol)
if key in seen:
errors.append(f"{POLICY_REL_PATH}: duplicate Version Anchor entry for {rel_file}::{symbol}")
continue
seen.add(key)
anchors.append(VersionAnchor(fmt=fmt, rel_file=rel_file, symbol=symbol, value_raw=value_raw))
return anchors, errors
def parse_deprecation_guards(policy_text: str) -> tuple[list[DeprecationGuard], list[str]]:
rows = parse_markdown_table(policy_text, DEPRECATION_SECTION_HEADING)
errors: list[str] = []
guards: list[DeprecationGuard] = []
if not rows:
errors.append(f"{POLICY_REL_PATH}: missing or empty '{DEPRECATION_SECTION_HEADING}' table")
return guards, errors
for index, cells in enumerate(rows, 1):
if len(cells) < 4:
errors.append(f"{POLICY_REL_PATH}: '{DEPRECATION_SECTION_HEADING}' row {index} has fewer than 4 columns")
continue
surface = strip_code_ticks(cells[0])
field = strip_code_ticks(cells[1])
rel_file = strip_code_ticks(cells[2])
test_fn = strip_code_ticks(cells[3])
if not rel_file or not test_fn:
errors.append(f"{POLICY_REL_PATH}: '{DEPRECATION_SECTION_HEADING}' row {index} has empty file or test name")
continue
guards.append(DeprecationGuard(surface=surface, field=field, rel_file=rel_file, test_fn=test_fn))
return guards, errors
def parse_rust_int(raw: str) -> int:
return int(raw.replace("_", ""), 0)
def extract_constants(rust_source: str) -> dict[str, list[str]]:
"""Return mapping of symbol name (both bare `CONST` and `Type::CONST` inside impl) -> raw values."""
found: dict[str, list[str]] = {}
current_impl: str | None = None
impl_brace_depth = 0
brace_depth = 0
for line in rust_source.splitlines():
code_part = line.split("//", 1)[0]
if current_impl is None:
impl_match = IMPL_HEADER_RE.match(code_part)
if impl_match:
current_impl = impl_match.group(1)
impl_brace_depth = brace_depth
const_match = CONST_DECL_RE.match(code_part)
if const_match:
name, value = const_match.group(1), const_match.group(2)
found.setdefault(name, []).append(value)
if current_impl is not None and brace_depth > impl_brace_depth:
found.setdefault(f"{current_impl}::{name}", []).append(value)
brace_depth += code_part.count("{") - code_part.count("}")
if current_impl is not None and brace_depth <= impl_brace_depth and "{" in code_part:
# Single-line impl block ended on the same line.
current_impl = None
elif current_impl is not None and brace_depth <= impl_brace_depth and "}" in code_part:
current_impl = None
return found
def check_repo(root: Path) -> list[str]:
failures: list[str] = []
policy_path = root / POLICY_REL_PATH
if not policy_path.is_file():
return [f"missing KMS format version policy document: {POLICY_REL_PATH}"]
policy_text = policy_path.read_text(encoding="utf-8")
anchors, anchor_errors = parse_version_anchors(policy_text)
guards, guard_errors = parse_deprecation_guards(policy_text)
failures.extend(anchor_errors)
failures.extend(guard_errors)
file_cache: dict[str, str] = {}
const_cache: dict[str, dict[str, list[str]]] = {}
documented_const_keys: set[tuple[str, str]] = set()
for anchor in anchors:
src_path = root / anchor.rel_file
if not src_path.is_file():
failures.append(f"Version Anchor {anchor.symbol} cites missing file: {anchor.rel_file}")
continue
if anchor.rel_file not in file_cache:
file_cache[anchor.rel_file] = src_path.read_text(encoding="utf-8")
const_cache[anchor.rel_file] = extract_constants(file_cache[anchor.rel_file])
try:
expected_int = parse_rust_int(anchor.value_raw)
except ValueError:
failures.append(
f"Version Anchor {anchor.rel_file}::{anchor.symbol} has non-integer documented value {anchor.value_raw!r}"
)
continue
matches = const_cache[anchor.rel_file].get(anchor.symbol, [])
if not matches:
failures.append(f"Version Anchor constant {anchor.symbol} not found in {anchor.rel_file}")
continue
if len(matches) > 1:
failures.append(
f"Version Anchor constant {anchor.symbol} is declared {len(matches)} times in {anchor.rel_file}"
)
continue
actual_raw = matches[0]
actual_int = parse_rust_int(actual_raw)
if actual_int != expected_int:
failures.append(
f"Version Anchor mismatch for {anchor.rel_file}::{anchor.symbol}: "
f"policy documents {anchor.value_raw} ({expected_int}), source defines {actual_raw} ({actual_int})"
)
bare_name = anchor.symbol.split("::")[-1]
documented_const_keys.add((anchor.rel_file, anchor.symbol))
documented_const_keys.add((anchor.rel_file, bare_name))
# Reverse check: any tracked KMS/SSE format version constant in source must be documented.
for scan_dir_rel in TRACKED_SCAN_DIRS:
scan_dir = root / scan_dir_rel
if not scan_dir.is_dir():
continue
for rs_file in sorted(scan_dir.rglob("*.rs")):
rel_posix = rs_file.relative_to(root).as_posix()
if rel_posix not in file_cache:
file_cache[rel_posix] = rs_file.read_text(encoding="utf-8")
const_cache[rel_posix] = extract_constants(file_cache[rel_posix])
for symbol in sorted(const_cache[rel_posix]):
if "::" in symbol:
continue
if TRACKED_CONST_NAME_RE.match(symbol) and (rel_posix, symbol) not in documented_const_keys:
failures.append(
f"undocumented KMS/SSE format version constant {symbol} in {rel_posix}; "
f"register it in {POLICY_REL_PATH} under '{VERSION_SECTION_HEADING}'"
)
# Check every active deprecation guard test exists in source.
for guard in guards:
src_path = root / guard.rel_file
if not src_path.is_file():
failures.append(f"Deprecation guard {guard.test_fn} cites missing file: {guard.rel_file}")
continue
if guard.rel_file not in file_cache:
file_cache[guard.rel_file] = src_path.read_text(encoding="utf-8")
pattern = re.compile(TEST_FN_RE_TEMPLATE.format(name=re.escape(guard.test_fn)), re.MULTILINE)
if not pattern.search(file_cache[guard.rel_file]):
failures.append(
f"Deprecation guard test '{guard.test_fn}' for field '{guard.field}' not found in {guard.rel_file}"
)
return failures
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--root",
type=Path,
default=ROOT,
help="Repository root directory (defaults to this script's repository root).",
)
args = parser.parse_args(argv)
failures = check_repo(args.root)
if failures:
for failure in failures:
print(f"KMS format version policy check failed: {failure}", file=sys.stderr)
return 1
print("KMS format version policy check passed.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env python3
# Copyright 2026 RustFS Team
# SPDX-License-Identifier: Apache-2.0
"""Unit tests for scripts/check_kms_format_versions.py."""
from __future__ import annotations
from pathlib import Path
import sys
import tempfile
import unittest
SCRIPT_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPT_DIR.parent
sys.path.insert(0, str(SCRIPT_DIR))
import check_kms_format_versions as guard # noqa: E402
SAMPLE_POLICY = """# KMS Format Version and Deprecation Policy
## Version Anchors
| Format | File | Constant | Value | Enforcement |
| --- | --- | --- | --- | --- |
| Backup manifest | `crates/kms/src/backup/manifest.rs` | `BackupManifest::FORMAT_VERSION` | `1` | Exact equality |
| Local KMS master key | `crates/kms/src/backends/local.rs` | `STORED_MASTER_KEY_FORMAT_VERSION` | `1` | Upper bound |
| DEK context binding | `crates/kms/src/encryption/dek.rs` | `CONTEXT_BINDING_AAD_V1` | `1` | Opt-in write |
| Local SSE DEK envelope | `crates/sse/src/kms/local.rs` | `LOCAL_SSE_DEK_FORMAT_VERSION` | `1` | Exact equality |
| Ciphertext segment nonce | `crates/rio/src/encrypt_reader.rs` | `FRAME_TYPE_SEGMENT_NONCE` | `0x03` | Opt-in write |
### Active Deprecation Guards
| Surface | Field | Test file | Regression guard |
| --- | --- | --- | --- |
| `ConfigureVaultKmsRequest` | `mount_path` | `crates/kms/src/api_types.rs` | `test_mount_path_accepted` |
"""
def write_fixture(root: Path, *, policy: str = SAMPLE_POLICY, manifest_ver: str = "1", seg_nonce: str = "0x03") -> None:
files = {
"docs/architecture/kms-format-version-policy.md": policy,
"crates/kms/src/backup/manifest.rs": (
f"pub struct BackupManifest;\nimpl BackupManifest {{\n pub const FORMAT_VERSION: u32 = {manifest_ver};\n}}\n"
),
"crates/kms/src/backends/local.rs": "pub(crate) const STORED_MASTER_KEY_FORMAT_VERSION: u32 = 1;\n",
"crates/kms/src/encryption/dek.rs": "pub const CONTEXT_BINDING_AAD_V1: u8 = 1;\n",
"crates/sse/src/kms/local.rs": "pub(crate) const LOCAL_SSE_DEK_FORMAT_VERSION: u8 = 1;\n",
"crates/rio/src/encrypt_reader.rs": f"const FRAME_TYPE_SEGMENT_NONCE: u8 = {seg_nonce};\n",
"crates/kms/src/api_types.rs": "#[test]\nfn test_mount_path_accepted() {}\n",
}
for rel, content in files.items():
path = root / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
class CheckKmsFormatVersionsTests(unittest.TestCase):
def test_live_repository_passes(self) -> None:
self.assertEqual(guard.check_repo(REPO_ROOT), [])
def test_valid_fixture_passes(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root)
self.assertEqual(guard.check_repo(root), [])
def test_tampered_rust_constant_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root, manifest_ver="2")
failures = guard.check_repo(root)
self.assertTrue(
any("BackupManifest::FORMAT_VERSION" in f and "2" in f for f in failures),
f"expected version mismatch failure, got: {failures}",
)
def test_tampered_hex_constant_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root, seg_nonce="0x04")
failures = guard.check_repo(root)
self.assertTrue(
any("FRAME_TYPE_SEGMENT_NONCE" in f and "0x04" in f for f in failures),
f"expected hex mismatch failure, got: {failures}",
)
def test_tampered_policy_value_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
tampered_policy = SAMPLE_POLICY.replace("| `LOCAL_SSE_DEK_FORMAT_VERSION` | `1` |", "| `LOCAL_SSE_DEK_FORMAT_VERSION` | `2` |")
write_fixture(root, policy=tampered_policy)
failures = guard.check_repo(root)
self.assertTrue(
any("LOCAL_SSE_DEK_FORMAT_VERSION" in f for f in failures),
f"expected policy value mismatch failure, got: {failures}",
)
def test_missing_constant_in_source_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root)
(root / "crates/kms/src/encryption/dek.rs").write_text("// removed\n", encoding="utf-8")
failures = guard.check_repo(root)
self.assertTrue(
any("CONTEXT_BINDING_AAD_V1" in f and "not found" in f for f in failures),
f"expected missing constant failure, got: {failures}",
)
def test_undocumented_kms_format_version_constant_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root)
extra = root / "crates/kms/src/backends/new_format.rs"
extra.write_text("pub const NEW_RECORD_FORMAT_VERSION: u32 = 1;\n", encoding="utf-8")
failures = guard.check_repo(root)
self.assertTrue(
any("NEW_RECORD_FORMAT_VERSION" in f and "undocumented" in f for f in failures),
f"expected undocumented constant failure, got: {failures}",
)
def test_missing_deprecation_guard_test_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root)
(root / "crates/kms/src/api_types.rs").write_text("// guard deleted\n", encoding="utf-8")
failures = guard.check_repo(root)
self.assertTrue(
any("test_mount_path_accepted" in f and "not found" in f for f in failures),
f"expected missing deprecation guard failure, got: {failures}",
)
def test_missing_version_table_fails(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
write_fixture(root, policy="# Empty policy\n")
failures = guard.check_repo(root)
self.assertTrue(
any("## Version Anchors" in f for f in failures),
f"expected missing table failure, got: {failures}",
)
if __name__ == "__main__":
unittest.main()