Compare commits

...

35 Commits

Author SHA1 Message Date
overtrue f5d6ea1623 test(ecstore): check replica lock ordering during publication 2026-12-02 02:53:05 +00:00
overtrue 5619b880b1 test(s3): verify the tag lookup after a versioned read 2026-12-02 09:18:25 +08:00
overtrue 17a4feb685 fix(snowball): keep SSE-C settings independent across archive members 2026-12-02 08:44:55 +08:00
overtrue dfc05048cf test(snowball): pass owned PAX budget fixtures directly 2026-12-02 08:02:17 +08:00
overtrue b388fae57a fix(s3): preserve validation of reserved archive metadata 2026-12-02 07:47:27 +08:00
overtrue 39bfa6ccf6 test(s3): compare tagged object expiry against UTC 2026-12-02 07:31:47 +08:00
overtrue 744ec5fb1d fix(s3): return the permitted tag count on local GET requests 2026-12-02 07:31:47 +08:00
overtrue e043b00d74 fix(snowball): ignore opaque file attributes during extraction 2026-12-02 07:31:47 +08:00
overtrue a14bc4029b chore(ci): retain the current regression branch test configuration
# Conflicts:
#	.config/nextest.toml
2026-12-02 07:10:39 +08:00
overtrue af3b0c5bfc fix(ecstore): bound readahead on cold shard window reads 2026-12-02 07:10:00 +08:00
overtrue 4014e284da fix(replication): replay user credentials separately from policy grants 2026-12-02 07:10:00 +08:00
overtrue 8dc8b52dcc fix(sse): preserve content MD5 for SSE-S3 writes and parts 2026-12-02 07:10:00 +08:00
overtrue e237b6dd54 chore(ci): merge main and align nextest and fuzz lockfile 2026-12-02 01:28:01 +08:00
overtrue b8602068e7 chore: pin main for the local gateway acceptance run 2026-12-02 00:16:34 +08:00
overtrue 13236a2cfc chore: merge main for the local regression run 2026-12-02 00:14:34 +08:00
overtrue 3a06e82e33 test(ci): isolate pinned erasure reconstruction fixtures
Use the two scoped nextest reservations from 1846c1c8e1 for the 12-drive GET fixtures. Both retain their 30-second deadline and byte-level reconstruction checks.

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-12-01 19:38:06 +08:00
overtrue 20c9263169 fix(scanner): integrate signed progress across local epochs 2026-12-01 17:09:08 +08:00
Hauser Zhi c62ed4edfe test(ecstore): verify post-quorum timeouts on paused disks
Apply the fixture changes from 1846c1c8e1.
Check one dispatch per disk, three readable responses, and a typed timeout
for the held disk after read quorum.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 14:59:24 +08:00
Hauser Zhi 3882240e11 test(ci): give deep storage regressions a 4 MiB stack
Use the existing nextest stack setup for the eight real-store tests
reported to overflow Linux libtest threads. Match each test exactly
in the local and CI profiles.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-01 14:59:24 +08:00
overtrue a3040b9252 fix(s3): report unconditional public object grants in policy status 2026-12-01 12:16:41 +08:00
overtrue 009cd1bb0f Move duplicate-destination fixtures into their final test run 2026-12-01 12:03:08 +08:00
overtrue 1584b0e767 Distinguish replication buckets sharing the same remote endpoint 2026-12-01 11:48:40 +08:00
overtrue 8f63f76af2 Verify scanner publication across pool changes and decommission 2026-12-01 11:37:15 +08:00
overtrue b8c32fb9d1 Measure retained pages and memory across wide scanner rounds 2026-12-01 11:04:02 +08:00
overtrue 4effd4b63a Verify workers without bucket watches reject stale cross-cycle coverage 2026-12-01 10:49:29 +08:00
overtrue f65b9be7a4 Exercise cold ranges under active writes and wide on-disk scanner checkpoints 2026-12-01 10:17:54 +08:00
overtrue 8c1d9ee7f1 Exercise scanner acceptance on physical cache and admission boundaries 2026-12-01 09:59:15 +08:00
overtrue f1042c2413 Account for scanner checks and durable site resync admission 2026-12-01 09:32:57 +08:00
overtrue a2753868f5 fix(lock): order object PUT votes before contention splits quorum 2026-12-01 09:15:24 +08:00
overtrue c0977b4862 fix(lock): order contended writer retries before collecting quorum votes 2026-12-01 08:24:05 +08:00
overtrue 321790b42d chore(deps): align the fuzz workspace with the accepted SHA-2 patch 2026-12-01 07:56:38 +08:00
Hauser Zhi 7bbf1e14b1 chore(deps): update sha2 to 0.11.3
Replace the yanked 0.11.2 resolution while preserving the existing
0.10 dependency line and the rest of the locked dependency graph.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
(cherry picked from commit 0961259974)
2026-12-01 07:54:58 +08:00
overtrue 3a18bacc48 fix(gateway): pin the SigV2 HTTP date compatibility fix 2026-12-01 07:34:10 +08:00
overtrue 30d25b7ca3 fix(replication): validate user destinations separately from site rules 2026-12-01 07:34:10 +08:00
overtrue 6ca2376ad6 fix(ecstore): persist every reported versioned batch delete marker 2026-12-01 07:34:09 +08:00
57 changed files with 1768 additions and 304 deletions
Generated
+11 -11
View File
@@ -12054,7 +12054,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway"
version = "0.70.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"arc-swap",
"bytes",
@@ -12101,7 +12101,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-core"
version = "0.67.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bytes",
"futures-core",
@@ -12122,7 +12122,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-corpus"
version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"serde",
"serde_json",
@@ -12132,7 +12132,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-corpus-recorder"
version = "0.1.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bytes",
"http 1.5.0",
@@ -12147,7 +12147,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-dialect-rustfs-admin"
version = "0.15.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bytes",
"form_urlencoded",
@@ -12161,7 +12161,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-http"
version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"hmac 0.13.0",
"http 1.5.0",
@@ -12180,7 +12180,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-macros"
version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"proc-macro2",
"quote",
@@ -12190,7 +12190,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-sig"
version = "0.18.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"hmac 0.13.0",
"http 1.5.0",
@@ -12206,7 +12206,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-stream"
version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bitflags 2.13.2",
"bytes",
@@ -12217,7 +12217,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-types"
version = "0.44.0+aws.2026-10-02"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bytes",
"crc-fast",
@@ -12239,7 +12239,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-xml"
version = "0.4.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"quick-xml 0.41.0",
]
+7 -7
View File
@@ -161,17 +161,17 @@ rustfs-dst-runtime = { path = "vendor/rustfs-dst-runtime", default-features = fa
rustfs-dst-faults = { path = "vendor/rustfs-dst-faults", default-features = false }
# Pin the gateway and its protocol crates to the same revision.
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.44.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.2.0", default-features = false }
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.44.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.2.0", default-features = false }
# The gateway framework itself, consumed for its extension traits by the ring-2
# adapter. `default-features = false` keeps the `server` feature, and with it the
# server crate, out of the build.
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.70.0", default-features = false }
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.70.0", default-features = false }
# Test-only: builds the `EffectiveHost` a host-resolution test queries with.
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.67.0", default-features = false }
rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.1.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.15.0", default-features = false }
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.67.0", default-features = false }
rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.1.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.15.0", default-features = false }
# Async Runtime and Networking
async-channel = "2.5.0"
@@ -148,6 +148,14 @@ mod tests {
.await
.expect("HEAD should succeed after tag replacement");
assert_eq!(replace_head.tag_count(), Some(2));
let replaced = client
.get_object()
.bucket(bucket)
.key("replace.txt")
.send()
.await
.expect("GET should return the replacement tags' count");
assert_eq!(replaced.tag_count(), Some(2));
client
.copy_object()
@@ -167,6 +175,14 @@ mod tests {
.await
.expect("HEAD should succeed after empty tag replacement");
assert_eq!(empty_head.tag_count(), None);
let empty = client
.get_object()
.bucket(bucket)
.key("empty-replace.txt")
.send()
.await
.expect("GET should succeed after clearing the tags");
assert_eq!(empty.tag_count(), None);
client
.copy_object()
@@ -360,6 +376,14 @@ mod tests {
.send()
.await?;
let read = local_http_client()
.get(format!("{}/{source_bucket}/source.txt", env.url))
.send()
.await?;
assert_eq!(read.status(), reqwest::StatusCode::OK);
assert!(!read.headers().contains_key("x-amz-tagging-count"));
assert_eq!(read.bytes().await?.as_ref(), b"source");
let destination_policy = serde_json::json!({
"Version": "2012-10-17",
"Statement": [
+25 -24
View File
@@ -4444,8 +4444,7 @@ async fn test_signed_put_object_extract_preserves_sse_c() -> Result<(), Box<dyn
let bucket = "extract-sse-c";
let archive_key = "bundle.tar";
let extracted_key = "nested/file.txt";
let expected_body = b"extract-sse-c-body".to_vec();
let members: [(&str, &[u8]); 2] = [("nested/file.txt", b"extract-sse-c-body"), ("second.txt", b"another member")];
let customer_key = "01234567890123456789012345678901";
let customer_key_b64 = base64_simd::STANDARD.encode_to_string(customer_key);
let customer_key_md5 = sse_customer_key_md5_base64(customer_key);
@@ -4453,7 +4452,7 @@ async fn test_signed_put_object_extract_preserves_sse_c() -> Result<(), Box<dyn
let client = env.create_s3_client();
client.create_bucket().bucket(bucket).send().await?;
let archive = make_tar(&[(extracted_key, expected_body.as_slice())], &[]).await;
let archive = make_tar(&members, &[]).await;
client
.put_object()
@@ -4473,28 +4472,30 @@ async fn test_signed_put_object_extract_preserves_sse_c() -> Result<(), Box<dyn
.send()
.await?;
let extracted = client
.head_object()
.bucket(bucket)
.key("extract-root/nested/file.txt")
.sse_customer_algorithm("AES256")
.sse_customer_key(customer_key_b64.clone())
.sse_customer_key_md5(customer_key_md5.clone())
.send()
.await?;
assert_eq!(extracted.sse_customer_algorithm(), Some("AES256"));
for (key, expected) in members {
let object = format!("extract-root/{key}");
let extracted = client
.head_object()
.bucket(bucket)
.key(&object)
.sse_customer_algorithm("AES256")
.sse_customer_key(customer_key_b64.clone())
.sse_customer_key_md5(customer_key_md5.clone())
.send()
.await?;
assert_eq!(extracted.sse_customer_algorithm(), Some("AES256"));
let fetched = client
.get_object()
.bucket(bucket)
.key("extract-root/nested/file.txt")
.sse_customer_algorithm("AES256")
.sse_customer_key(customer_key_b64)
.sse_customer_key_md5(customer_key_md5)
.send()
.await?;
let actual_body = fetched.body.collect().await?.into_bytes().to_vec();
assert_eq!(actual_body, expected_body);
let fetched = client
.get_object()
.bucket(bucket)
.key(&object)
.sse_customer_algorithm("AES256")
.sse_customer_key(customer_key_b64.clone())
.sse_customer_key_md5(customer_key_md5.clone())
.send()
.await?;
assert_eq!(fetched.body.collect().await?.into_bytes().as_ref(), expected);
}
Ok(())
}
@@ -135,14 +135,14 @@ enum ObjectShape {
/// Single-part object uploaded with `x-amz-checksum-sha256`; the replica
/// must carry the same header (rustfs/backlog#2340).
Checksummed,
/// Single-part SSE-S3 object. Its ETag is a keyed fingerprint, not the
/// plaintext MD5 (docs/operations/encrypted-etags.md), while the replica
/// travels as plaintext under `x-amz-server-side-encryption: AES256`.
/// Single-part SSE-S3 with a content MD5.
SseS3,
/// Single-part SSE-KMS with an opaque ETag on the source.
SseKms,
}
impl ObjectShape {
const ALL: [ObjectShape; 9] = [
const ALL: [ObjectShape; 10] = [
ObjectShape::Empty,
ObjectShape::Plain,
ObjectShape::Retention,
@@ -152,6 +152,7 @@ impl ObjectShape {
ObjectShape::OdmPreservedMd5Multipart,
ObjectShape::Checksummed,
ObjectShape::SseS3,
ObjectShape::SseKms,
];
fn key(self) -> &'static str {
@@ -165,6 +166,7 @@ impl ObjectShape {
ObjectShape::OdmPreservedMd5Multipart => "matrix/odm-preserved-md5.bin",
ObjectShape::Checksummed => "matrix/checksummed.bin",
ObjectShape::SseS3 => "matrix/sse-s3.bin",
ObjectShape::SseKms => "matrix/sse-kms.bin",
}
}
@@ -248,22 +250,24 @@ impl ObjectShape {
.await?;
Ok(body)
}
ObjectShape::SseS3 => {
ObjectShape::SseS3 | ObjectShape::SseKms => {
let body = payload(56 * 1024, 0x77);
let algorithm = if self == ObjectShape::SseS3 {
ServerSideEncryption::Aes256
} else {
ServerSideEncryption::AwsKms
};
let put = client
.put_object()
.bucket(bucket)
.key(key)
.body(ByteStream::from(body.clone()))
.server_side_encryption(ServerSideEncryption::Aes256)
.server_side_encryption(algorithm)
.send()
.await?;
// The cell only proves something while the source ETag is
// not the content MD5 a generic target reports back.
let plaintext_md5 = hex_simd::encode_to_string(Md5::digest(&body), hex_simd::AsciiCase::Lower);
if put.e_tag().map(|etag| etag.trim_matches('"')) == Some(plaintext_md5.as_str()) {
return Err("SSE-S3 source ETag is the plaintext MD5; the cell no longer exercises encrypted ETags".into());
}
let source_etag = put.e_tag().ok_or("managed-SSE write returned no ETag")?.trim_matches('"');
assert_eq!(source_etag == plaintext_md5, self == ObjectShape::SseS3, "{self:?}");
Ok(body)
}
}
@@ -311,7 +315,7 @@ async fn matrix_mint_own_version_ids_redrive_does_not_duplicate() -> TestResult
run_redrive_does_not_duplicate(RedriveObjects::Plaintext).await
}
/// The same re-drives for SSE-S3 objects against a target that also computes
/// The same re-drives for SSE-KMS objects against a target that also computes
/// its own ETags (AWS S3). The source ETag is a keyed fingerprint
/// (docs/operations/encrypted-etags.md) while the replica reports the MD5 of
/// the plaintext it received, so no exact-ETag lookup can ever find the
@@ -319,18 +323,18 @@ async fn matrix_mint_own_version_ids_redrive_does_not_duplicate() -> TestResult
/// without comparing ETags.
#[tokio::test]
async fn matrix_mint_own_version_ids_encrypted_redrive_does_not_duplicate() -> TestResult {
run_redrive_does_not_duplicate(RedriveObjects::SseS3OnEtagComputingTarget).await
run_redrive_does_not_duplicate(RedriveObjects::SseKmsOnEtagComputingTarget).await
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RedriveObjects {
Plaintext,
SseS3OnEtagComputingTarget,
SseKmsOnEtagComputingTarget,
}
async fn run_redrive_does_not_duplicate(objects: RedriveObjects) -> TestResult {
init_logging();
let encrypted = objects == RedriveObjects::SseS3OnEtagComputingTarget;
let encrypted = objects == RedriveObjects::SseKmsOnEtagComputingTarget;
let target = FakeS3Target::start().await?;
let target_bucket = "matrix-mint-own-redrive-dst".to_string();
@@ -388,7 +392,7 @@ async fn run_redrive_does_not_duplicate(objects: RedriveObjects) -> TestResult {
.key(key)
.body(ByteStream::from(payload(len, fill)));
let request = if encrypted {
request.server_side_encryption(ServerSideEncryption::Aes256)
request.server_side_encryption(ServerSideEncryption::AwsKms)
} else {
request
};
@@ -1004,7 +1008,7 @@ async fn run_row(mode: TargetMode) -> TestResult {
env_vars.extend_from_slice(&[("NO_PROXY", "127.0.0.1,localhost"), ("HTTP_PROXY", ""), ("HTTPS_PROXY", "")]);
let env = OdmTestEnv::start_with(OdmEnvOptions {
env: env_vars,
// The SseS3 shape needs a KMS for SSE-S3.
// Both managed-SSE shapes use the local KMS.
local_kms: true,
..OdmEnvOptions::default()
})
@@ -839,8 +839,10 @@ async fn test_bucket_tags_opa_contract() -> TestResult {
.version_id(version)
.send()
.await?;
assert_eq!(read.tag_count(), Some(1));
assert_eq!(read.body.collect().await?.into_bytes().as_ref(), b"report");
opa.expect_bucket_tags("s3:GetObjectVersion", source, Some("finance")).await?;
opa.expect_versioned_tag_permission(source, "report", version).await?;
let head = client
.head_object()
.bucket(source)
@@ -1070,6 +1072,7 @@ async fn test_bucket_tags_opa_contract() -> TestResult {
.await?;
assert_eq!(read.body.collect().await?.into_bytes().as_ref(), b"report");
opa.expect_bucket_tags("s3:GetObjectVersion", source, Some("finance")).await?;
opa.expect_versioned_tag_permission(source, "report", version).await?;
let error = client
.get_object()
+69 -21
View File
@@ -925,29 +925,24 @@ impl BucketTargetSys {
target: &BucketTarget,
update: bool,
) -> Result<(), BucketTargetError> {
let mut found = false;
for (idx, existing_target) in bucket_targets.iter().enumerate() {
if existing_target.target_type.to_string() == target.target_type.to_string() {
if existing_target.arn == target.arn {
if !update {
return Err(BucketTargetError::BucketRemoteAlreadyExists {
bucket: existing_target.target_bucket.clone(),
});
}
bucket_targets[idx] = target.clone();
found = true;
break;
}
if existing_target.endpoint == target.endpoint {
return Err(BucketTargetError::BucketRemoteAlreadyExists {
bucket: existing_target.target_bucket.clone(),
});
}
let mut replace_index = None;
for (index, existing) in bucket_targets.iter().enumerate() {
if existing.target_type != target.target_type {
continue;
}
if update && existing.arn == target.arn {
replace_index.get_or_insert(index);
} else if existing.arn == target.arn
|| (existing.endpoint == target.endpoint && existing.target_bucket == target.target_bucket)
{
return Err(BucketTargetError::BucketRemoteAlreadyExists {
bucket: existing.target_bucket.clone(),
});
}
}
if !found && !update {
if let Some(index) = replace_index {
bucket_targets[index] = target.clone();
} else if !update {
bucket_targets.push(target.clone());
}
@@ -5567,6 +5562,59 @@ mod tests {
}
}
#[test]
fn site_and_bucket_replication_can_register_distinct_destinations_on_one_peer() {
let site = BucketTarget {
target_bucket: "source".into(),
..repair_target("source", "site")
};
let operator = repair_target("source", "archive");
for (first, second) in [(&site, &operator), (&operator, &site)] {
let mut targets = vec![first.clone()];
BucketTargetSys::upsert_target_entry(&mut targets, second, false).expect("register the other destination");
let mut edited = second.clone();
edited.bandwidth_limit = 4096;
BucketTargetSys::upsert_target_entry(&mut targets, &edited, true).expect("update only the selected ARN");
assert_eq!(targets.len(), 2);
assert_eq!(targets[0].arn, first.arn);
assert_eq!(targets[0].bandwidth_limit, first.bandwidth_limit);
assert_eq!(targets[1].arn, second.arn);
assert_eq!(targets[1].target_bucket, second.target_bucket);
assert_eq!(targets[1].bandwidth_limit, 4096);
let duplicate = BucketTarget {
arn: "another-arn".into(),
..second.clone()
};
assert!(matches!(
BucketTargetSys::upsert_target_entry(&mut targets, &duplicate, false),
Err(BucketTargetError::BucketRemoteAlreadyExists { .. })
));
assert!(BucketTargetSys::upsert_target_entry(&mut targets, first, false).is_err());
assert_eq!(targets.len(), 2);
}
}
#[test]
fn retargeting_to_an_existing_destination_preserves_both_entries_in_either_order() {
let first = repair_target("source", "first");
let old = BucketTarget {
endpoint: "second.example.com".into(),
..repair_target("source", "second")
};
let edit = BucketTarget {
endpoint: first.endpoint.clone(),
..old.clone()
};
for mut targets in [vec![first.clone(), old.clone()], vec![old, first]] {
let before = serde_json::to_vec(&targets).unwrap();
assert!(matches!(
BucketTargetSys::upsert_target_entry(&mut targets, &edit, true),
Err(BucketTargetError::BucketRemoteAlreadyExists { .. })
));
assert_eq!(serde_json::to_vec(&targets).unwrap(), before);
}
}
#[tokio::test]
async fn an_unreadable_target_set_refuses_cached_writes() {
let sys = BucketTargetSys::default();
@@ -25,6 +25,7 @@ use tracing::error;
use super::replication_config_boundary::{
ObjectOpts, ReplicationConfigurationExt as _, ReplicationRuleExt as _, invalid_replication_config_status_field,
site_replication_rule_deployment_id,
};
use super::replication_error_boundary::Result;
use super::replication_filemeta_boundary::{
@@ -153,7 +154,9 @@ fn validate_delete_replication_config(
"enabled replication rule has no destination ARN",
));
}
if !role.is_empty() && !destination.is_empty() {
// The reconciler appends a rule per site while preserving the operator's role.
// Its peer ID and destination ARN identify it independently of the operator rules.
if !role.is_empty() && !destination.is_empty() && site_replication_rule_deployment_id(rule).is_none() {
match role_destination {
Some(existing) if existing != destination => {
return Err(super::replication_error_boundary::Error::other(
@@ -755,6 +758,31 @@ mod tests {
assert!(validate_delete_replication_config(&VersioningConfiguration::default(), Some(&config)).is_err());
}
#[test]
fn delete_snapshot_accepts_an_operator_role_alongside_a_reconciled_site_rule() {
let mut operator = replication_rule();
operator.destination.bucket = "arn:rustfs:replication::operator:archive".to_owned();
let mut site = replication_rule();
site.id = Some("site-repl-peer".to_owned());
site.destination.bucket = "arn:rustfs:replication::peer:photos".to_owned();
let mut metadata = BucketMetadata::new("photos");
metadata.versioning_config = Some(VersioningConfiguration {
status: Some("Enabled".to_owned()),
..Default::default()
});
metadata.replication_config = Some(PersistedReplicationConfiguration {
role: operator.destination.bucket.clone(),
rules: vec![operator, site],
});
let snapshot = delete_request_snapshot_from_metadata(Arc::new(metadata.clone()))
.expect("a site rule coexists with bucket replication");
assert_eq!(snapshot.replication_config().expect("active rules").rules.len(), 2);
// An operator can choose any rule ID. Its prefix alone cannot establish site ownership.
metadata.replication_config.as_mut().unwrap().rules[1].id = Some("site-repl-other".to_owned());
assert!(delete_request_snapshot_from_metadata(Arc::new(metadata)).is_err());
}
#[test]
fn delete_snapshot_rejects_unknown_status_values() {
let invalid_versioning = VersioningConfiguration {
@@ -354,9 +354,8 @@ fn replica_etag_verification_enabled() -> bool {
/// mismatch fails the replication instead. Encrypted sources are exempt: an
/// SSE-C ciphertext passthrough sends ciphertext while the source ETag is the
/// plaintext MD5 (that path has its own HEAD-back audit), and a managed-SSE
/// (SSE-S3 / SSE-KMS) source stores a keyed fingerprint, or a legacy plaintext
/// MD5, that the ETag of the target's re-encrypted replica can neither confirm
/// nor refute. A managed-SSE source forwards no checksum either
/// source can carry either a content MD5 or an opaque fingerprint depending
/// on its scheme and writer version. A target can assign its own ETag. A managed-SSE source forwards no checksum either
/// (`replication_put_object_options`), so its replica has no post-PUT
/// content audit.
fn verify_single_part_replica(
@@ -236,7 +236,7 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
future
}
let (_dirs, store) = isolated_store_over_temp_disks().await;
let (dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let blocked = "usage-blocked-identity";
let healthy = "usage-healthy-identity";
@@ -260,6 +260,10 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
canonical.usage_snapshot_pending_bucket_count = 2;
canonical.buckets_count = 2;
canonical.calculate_totals();
let completed_at = canonical.usage_snapshot_bucket_observations[healthy].completed_at;
let certificate = canonical.buckets_usage[healthy]
.usage_certification
.expect("persisted certificate");
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
@@ -276,6 +280,8 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
)
.await
.expect("hold the real bucket metadata writer lock");
let collected_at = SystemTime::now();
assert!(collected_at > completed_at && completed_at > certificate.certified_at);
let response = tokio::time::timeout(
ADMIN_USAGE_INCARNATION_TIMEOUT + Duration::from_secs(3),
assert_send(load_admin_data_usage_from_backend_cached(store.clone())),
@@ -288,6 +294,9 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
"an unavailable current identity cannot bind the canonical value"
);
assert!(!response.bucket_sizes.contains_key(blocked));
assert!(!response.usage_snapshot_bucket_observations.contains_key(blocked));
assert_eq!(response.usage_snapshot_bucket_observations[healthy].completed_at, completed_at);
assert!(response.buckets_usage[healthy].usage_certification.is_none());
assert_eq!(response.buckets_usage[healthy].size, 250);
assert_eq!(response.buckets_usage[healthy].usage_value_state, Some(BucketUsageValueState::Observed));
assert!(response.usage_snapshot_admin_projection);
@@ -307,11 +316,32 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
"unavailable identity can recover on a cache hit"
);
assert_eq!(recovered.buckets_usage[healthy].size, 250);
for bucket in [blocked, healthy] {
assert_eq!(recovered.usage_snapshot_bucket_observations[bucket].completed_at, completed_at);
assert!(recovered.buckets_usage[bucket].usage_certification.is_none());
}
let quota = load_data_usage_from_backend_cached(store)
.await
.expect("separate canonical quota read");
assert_eq!(quota.buckets_usage[blocked].size, 100);
assert_eq!(quota.buckets_usage[healthy].size, 100);
for bucket in [blocked, healthy] {
assert_eq!(quota.buckets_usage[bucket].usage_certification, Some(certificate));
}
let evidence = serde_json::json!({
"collection_started_at": collected_at, "persisted_observation_at": completed_at,
"retained_certificate_at": certificate.certified_at, "blocked_bucket_unknown": true,
});
let paths: Vec<_> = dirs.iter().map(|dir| dir.path().to_path_buf()).collect();
for dir in dirs {
dir.close().expect("remove collector timeout fixture");
}
assert!(paths.iter().all(|path| !path.exists()));
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-18","assertion_id":"USAGE-18-A02","status":"PASS","evidence":evidence})
);
println!("usage_cleanup: {}", serde_json::json!({"case_id":"USAGE-18","status":"PASS"}));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+47 -26
View File
@@ -10304,7 +10304,14 @@ impl LocalDisk {
if fi.deleted && force_del_marker {
return self
.write_missing_delete_marker(volume, path, fi, file_path.as_path(), &opts, namespace_owner.clone())
.write_missing_delete_markers(
volume,
path,
std::slice::from_ref(&fi),
file_path.as_path(),
&opts,
namespace_owner.clone(),
)
.await;
}
@@ -11953,11 +11960,11 @@ impl LocalDisk {
Ok((bytes, modtime))
}
async fn write_missing_delete_marker(
async fn write_missing_delete_markers(
&self,
volume: &str,
path: &str,
fi: FileInfo,
markers: &[FileInfo],
object_dir: &Path,
opts: &DeleteOptions,
namespace_owner: Option<Arc<dyn Send + Sync>>,
@@ -11973,6 +11980,9 @@ impl LocalDisk {
Err(err) if err.kind() == ErrorKind::NotFound => {}
Err(err) => return Err(to_file_error(err).into()),
}
for marker in markers {
marker.validate_for_metadata_read()?;
}
let mut recovery_target = None;
if let Some(rollback_dir) = rollback_dir {
if opts.recoverable_delete {
@@ -11981,7 +11991,7 @@ impl LocalDisk {
volume,
path,
None,
std::slice::from_ref(&fi),
markers,
None,
delete_recovery::DeletePreparationContext {
transaction: rollback_dir,
@@ -12003,23 +12013,32 @@ impl LocalDisk {
.await?;
}
}
let committed = if let Some(target) = recovery_target {
async {
fi.validate_for_metadata_read()?;
self.write_all_meta_with_namespace_owner(
volume,
&format!("{path}/{STORAGE_FORMAT_FILE}"),
target.into(),
true,
namespace_owner.clone(),
)
.await
}
let committed = async {
let target = match (recovery_target, markers) {
(Some(target), _) => target,
(None, [marker]) => {
return self
.write_metadata_with_namespace_owner(volume, path, marker.clone(), namespace_owner.clone())
.await;
}
(None, _) => {
let mut meta = FileMeta::new();
for marker in markers {
meta.add_version(marker.clone())?;
}
meta.marshal_msg()?
}
};
self.write_all_meta_with_namespace_owner(
volume,
&format!("{path}/{STORAGE_FORMAT_FILE}"),
target.into(),
true,
namespace_owner.clone(),
)
.await
} else {
self.write_metadata_with_namespace_owner(volume, path, fi, namespace_owner.clone())
.await
};
}
.await;
if let Err(err) = committed {
if let Some(rollback_dir) = rollback_dir
&& let Err(restore_err) = restore_delete_rollback_with_namespace_owner(
@@ -12138,11 +12157,12 @@ impl LocalDisk {
.await;
// `deleted` alone can be an explicit marker purge; only
// `mark_deleted` may create metadata that was not present.
let Some(delete_marker) = fis.iter().find(|fi| fi.deleted && fi.mark_deleted).cloned() else {
let markers: Vec<_> = fis.iter().filter(|fi| fi.deleted && fi.mark_deleted).cloned().collect();
if markers.is_empty() {
return Err(DiskError::FileNotFound);
};
}
return self
.write_missing_delete_marker(volume, path, delete_marker, object_dir, opts, namespace_owner.clone())
.write_missing_delete_markers(volume, path, &markers, object_dir, opts, namespace_owner.clone())
.await;
}
Err(err) => return Err(err),
@@ -15253,11 +15273,12 @@ async fn batch_shard_pread_blocking(requests: Vec<PermittedShardPreadRequest>) -
metrics.as_deref(),
LocalBatchReadStage::Read,
|| {
// Preload the requested window before reading it. Kernel
// readahead is advisory and may still extend past the
// window, so the tail is reclaimed after the read below.
// Preload just this window. Disable automatic readahead
// on this descriptor so pread does not start a second
// read past the window while the explicit hint is in flight.
#[cfg(target_os = "linux")]
if let (Ok(start), Ok(len)) = (u64::try_from(offset), u64::try_from(length)) {
let _ = rustix::fs::fadvise(&file, 0, None, rustix::fs::Advice::Random);
let _ = rustix::fs::fadvise(
&file,
start,
+77 -15
View File
@@ -31,6 +31,7 @@ use native as variant;
pub use variant::*;
use rustfs_utils::CompressionAlgorithm;
use rustfs_utils::http::object_encryption_keys::SSEType;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadCompressionBackend {
@@ -61,6 +62,7 @@ pub enum ReadEncryptionBackend {
pub struct WriteEncryption {
key_bytes: [u8; 32],
mode: WriteEncryptionMode,
s3_content_etag: bool,
}
#[derive(Debug, Clone, Copy)]
@@ -83,6 +85,7 @@ impl WriteEncryption {
Self {
key_bytes: object_key,
mode: WriteEncryptionMode::SinglepartObjectKey,
s3_content_etag: false,
}
}
@@ -90,6 +93,7 @@ impl WriteEncryption {
Self {
key_bytes,
mode: WriteEncryptionMode::Singlepart { base_nonce },
s3_content_etag: false,
}
}
@@ -100,6 +104,7 @@ impl WriteEncryption {
base_nonce,
multipart_part_number,
},
s3_content_etag: false,
}
}
@@ -107,8 +112,31 @@ impl WriteEncryption {
Self {
key_bytes: object_key,
mode: WriteEncryptionMode::MultipartObjectKey { multipart_part_number },
s3_content_etag: false,
}
}
/// SSE-S3 clients verify a single PUT or upload part against the MD5 of the original bytes.
pub const fn for_sse_type(mut self, scheme: SSEType) -> Self {
self.s3_content_etag = matches!(scheme, SSEType::SseS3);
self
}
fn encrypt(self, reader: impl rustfs_rio::Reader + 'static, actual_size: i64) -> std::io::Result<HashReader> {
let key = self.key_bytes;
let encrypted = match self.mode {
WriteEncryptionMode::SinglepartObjectKey => variant::encrypt_under_object_key(reader, key),
WriteEncryptionMode::Singlepart { base_nonce } => variant::encrypt_singlepart(reader, key, base_nonce),
WriteEncryptionMode::MultipartLegacy {
base_nonce,
multipart_part_number,
} => variant::encrypt_part(reader, key, base_nonce, multipart_part_number),
WriteEncryptionMode::MultipartObjectKey { multipart_part_number } => {
variant::encrypt_part_under_object_key(reader, key, multipart_part_number)
}
};
HashReader::from_reader(encrypted, HashReader::SIZE_PRESERVE_LAYER, actual_size, None, None, false)
}
}
#[derive(Debug, Clone, Default)]
@@ -148,6 +176,19 @@ impl WritePlan {
let delegate_inner_etag = self.compression.is_none() && reader.is_etag_reader();
let encrypted = self.encryption.is_some();
let s3_content_etag = self.encryption.is_some_and(|enc| enc.s3_content_etag);
if s3_content_etag {
// The incoming hash may be disabled or use a bucket-specific algorithm.
// Hash the original stream so every SSE-S3 write has the same MD5 contract.
reader = HashReader::from_reader(
rustfs_rio::EtagReader::new(reader, None),
HashReader::SIZE_PRESERVE_LAYER,
actual_size,
None,
None,
false,
)?;
}
if let Some(algorithm) = self.compression {
reader = HashReader::from_reader(
compression_reader(reader, algorithm, encrypted),
@@ -159,7 +200,11 @@ impl WritePlan {
)?;
}
if let Some(encryption) = self.encryption {
if let Some(encryption) = self.encryption
&& encryption.s3_content_etag
{
reader = encryption.encrypt(reader, actual_size)?;
} else if let Some(encryption) = self.encryption {
let etag_nonce = match encryption.mode {
WriteEncryptionMode::Singlepart { base_nonce } => base_nonce,
WriteEncryptionMode::SinglepartObjectKey => [0u8; 12],
@@ -170,25 +215,13 @@ impl WritePlan {
};
let protected_reader = rustfs_rio::EtagReader::new_encrypted(reader, encryption.key_bytes, etag_nonce)?
.with_inner_etag_delegation(delegate_inner_etag);
let key = encryption.key_bytes;
let encrypt_reader = match encryption.mode {
WriteEncryptionMode::SinglepartObjectKey => variant::encrypt_under_object_key(protected_reader, key),
WriteEncryptionMode::Singlepart { base_nonce } => variant::encrypt_singlepart(protected_reader, key, base_nonce),
WriteEncryptionMode::MultipartLegacy {
base_nonce,
multipart_part_number,
} => variant::encrypt_part(protected_reader, key, base_nonce, multipart_part_number),
WriteEncryptionMode::MultipartObjectKey { multipart_part_number } => {
variant::encrypt_part_under_object_key(protected_reader, key, multipart_part_number)
}
};
reader = HashReader::from_reader(encrypt_reader, HashReader::SIZE_PRESERVE_LAYER, actual_size, None, None, false)?;
reader = encryption.encrypt(protected_reader, actual_size)?;
}
// `ignore_value` deliberately avoids a second hasher over compressed or
// encrypted bytes. The inner reader still validates the plaintext request
// checksum while this outer reader exposes the request checksum context.
reader.encrypted_etag = encrypted;
reader.encrypted_etag = encrypted && !s3_content_etag;
reader.add_non_trailing_checksum(checksum, true)?;
reader.set_trailer(trailer);
@@ -205,6 +238,35 @@ mod tests {
use std::io::Cursor;
use tokio::io::AsyncReadExt;
#[tokio::test]
async fn sse_s3_content_etag_hashes_plaintext_before_compression_and_encryption() {
let data = b"same bytes through each write plan";
let size = data.len() as i64;
let mut control = HashReader::from_stream(Cursor::new(data), size, size, None, None, false).unwrap();
control.read_to_end(&mut Vec::new()).await.unwrap();
let expected = control.try_resolve_etag().unwrap();
for encryption in [
WriteEncryption::singlepart([1; 32], [2; 12]),
WriteEncryption::singlepart_object_key([1; 32]),
WriteEncryption::multipart([1; 32], [2; 12], 1),
WriteEncryption::multipart_object_key([1; 32], 1),
] {
for compress in [false, true] {
let mut plan = WritePlan::new().with_encryption(encryption.for_sse_type(SSEType::SseS3));
if compress {
plan = plan.with_compression(CompressionAlgorithm::default());
}
let source = HashReader::from_stream(Cursor::new(data), size, size, None, None, false).unwrap();
let mut reader = plan.apply(source, size).unwrap();
let mut stored = Vec::new();
reader.read_to_end(&mut stored).await.unwrap();
assert_ne!(stored, data);
assert_eq!(reader.try_resolve_etag().as_ref(), Some(&expected));
assert!(!reader.encrypted_etag, "a plaintext MD5 cannot attest an opaque ETag");
}
}
}
#[tokio::test]
async fn write_plan_encryption_persists_protected_etags_for_every_mode() {
let data = b"Salary 2026: 85000 EUR";
+10 -2
View File
@@ -5591,10 +5591,18 @@ impl SetDisks {
.with_attempt(attempt))
}
async fn object_write_namespace_lock(&self, op: &str, bucket: &str, object: &str) -> Result<NamespaceLockWrapper> {
let mut lock = self.new_ns_lock(bucket, object).await?;
if op == "put_object_commit" {
lock.order_object_writes();
}
Ok(lock)
}
async fn acquire_write_lock_diag(&self, op: &'static str, bucket: &str, object: &str) -> Result<ObjectLockDiagGuard> {
crate::hp_guard!("SetDisks::acquire_write_lock");
let diag_enabled = is_object_lock_diag_enabled();
let ns_lock = self.new_ns_lock(bucket, object).await?;
let ns_lock = self.object_write_namespace_lock(op, bucket, object).await?;
let acquire_start = Instant::now();
let acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "write", acquire_timeout);
@@ -5637,7 +5645,7 @@ impl SetDisks {
) -> Result<ObjectLockDiagGuard> {
crate::hp_guard!("SetDisks::acquire_write_lock");
let diag_enabled = is_object_lock_diag_enabled();
let ns_lock = self.new_ns_lock(bucket, object).await?;
let ns_lock = self.object_write_namespace_lock(op, bucket, object).await?;
let acquire_start = Instant::now();
let acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "write", acquire_timeout);
+29 -7
View File
@@ -11576,12 +11576,9 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let mut vers = Vec::with_capacity(vers_map.len());
for (_, mut fi_vers) in vers_map {
// Apply explicit removals before creating markers. Every versioned
// marker has its own response ID and must reach the disk quorum.
fi_vers.versions.sort_by_key(|a| a.deleted);
if let Some(index) = fi_vers.versions.iter().position(|fi| fi.deleted) {
fi_vers.versions.truncate(index + 1);
}
vers.push(fi_vers);
}
@@ -31451,7 +31448,7 @@ mod degraded_missing_delete_tests {
}
#[tokio::test]
async fn degraded_missing_delete_versioned_batch_commits_markers() {
async fn degraded_versioned_batch_persists_each_reported_marker_for_repeated_keys() {
use rustfs_gateway_types::persistence::PersistedVersioningConfiguration;
let (_dirs, disks, set) = hermetic_set_disks_isolated(3).await;
@@ -31459,6 +31456,21 @@ mod degraded_missing_delete_tests {
for disk in &disks {
disk.make_volume(bucket).await.expect("create fixture bucket");
}
let original = set
.put_object(
bucket,
"existing",
&mut PutObjReader::from_vec(b"original".to_vec()),
&ObjectOptions {
versioned: true,
write_completion: crate::object_api::WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("put a version before the batch")
.version_id
.expect("versioned put has a version ID");
disks[0].force_offline_for_test();
let snapshot = Arc::new(DeleteReplicationConfigSnapshot::from_configs_for_test(
PersistedVersioningConfiguration {
@@ -31467,7 +31479,7 @@ mod degraded_missing_delete_tests {
},
None,
));
let names = ["absent", "never/created/deep/key"];
let names = ["absent", "existing", "never/created/deep/key", "absent", "existing", "absent"];
let (deleted, errors) = set
.delete_objects(
bucket,
@@ -31487,9 +31499,11 @@ mod degraded_missing_delete_tests {
.await;
assert!(errors.iter().all(Option::is_none), "versioned missing batch must succeed: {errors:?}");
assert_eq!(deleted.len(), names.len());
let mut markers = std::collections::HashSet::new();
for (result, name) in deleted.iter().zip(names) {
assert!(result.delete_marker);
let version = result.delete_marker_version_id.expect("marker identity must be reported");
assert!(markers.insert(version), "each versioned deletion creates its own marker");
for disk in disks.iter().skip(1) {
let persisted = disk
.read_version("", bucket, name, &version.to_string(), &crate::disk::ReadOptions::default())
@@ -31499,6 +31513,14 @@ mod degraded_missing_delete_tests {
assert_eq!(persisted.version_id, Some(version));
}
}
for disk in disks.iter().skip(1) {
let data = disk
.read_version("", bucket, "existing", &original.to_string(), &crate::disk::ReadOptions::default())
.await
.expect("original data version");
assert!(!data.deleted);
assert_eq!(data.version_id, Some(original));
}
}
#[tokio::test]
@@ -308,12 +308,12 @@ async fn replica_write_with_waiting_metadata_writer(multipart: bool) {
.new_ns_lock(".rustfs.sys", &format!("bucket-targets/{bucket}/transaction.lock"))
.await
.expect("create metadata writer");
let writer = lock.get_write_lock(Duration::from_secs(5));
let writer = lock.get_write_lock(Duration::from_secs(30));
tokio::pin!(writer);
// Leave the writer registered while the replica continues. A second read
// acquisition would queue behind this writer, which needs our first read.
assert!(futures::poll!(&mut writer).is_pending());
timeout(Duration::from_secs(2), async {
let commit = async {
if let Some((upload_id, parts)) = upload {
store
.clone()
@@ -323,10 +323,13 @@ async fn replica_write_with_waiting_metadata_writer(multipart: bool) {
let mut data = PutObjReader::from_vec(b"replicated version".to_vec());
store.put_object(bucket, "object", &mut data, &opts).await
}
})
.await
.expect("replica must reuse its metadata read lock instead of waiting behind the writer")
.expect("replica PUT should commit");
};
// The queued writer bounds a recursive read. Disk publication may take longer on a busy filesystem.
tokio::select! {
biased;
_ = &mut writer => panic!("metadata writer finished before the replica committed under its snapshot"),
result = commit => result.expect("replica PUT should commit"),
};
assert!(futures::poll!(&mut writer).is_pending(), "the snapshot must still fence metadata updates");
let read_opts = ObjectOptions {
version_id: opts.version_id.clone(),
+115 -17
View File
@@ -705,6 +705,7 @@ pub struct DistributedLock {
namespace: Arc<str>,
/// Quorum size for exclusive/write operations
quorum: usize,
order_object_writes: bool,
}
type LockAcquireTaskResult = (usize, Result<LockResponse>);
@@ -762,9 +763,14 @@ impl DistributedLock {
clients,
namespace,
quorum: q,
order_object_writes: false,
}
}
pub(crate) fn order_object_writes(&mut self) {
self.order_object_writes = true;
}
/// Get namespace identifier
pub fn namespace(&self) -> &str {
&self.namespace
@@ -1876,7 +1882,8 @@ impl DistributedLock {
let mut attempt_request = request.clone();
// Only retryable contention reaches another round. Give later writer
// attempts enough queue time to outlast readers that entered the gap.
let peer_wait_limit = if request.lock_type == LockType::Exclusive && attempt > 1 {
let retrying_writer = attempt > 1 && request.lock_type == LockType::Exclusive;
let peer_wait_limit = if retrying_writer {
LOCK_PEER_WRITER_RETRY_TIMEOUT
} else {
LOCK_PEER_ACQUIRE_TIMEOUT
@@ -1887,7 +1894,10 @@ impl DistributedLock {
// A peer may grant promptly but deliver its response after its local
// contention budget. Keep this round's owners until a response proves
// quorum impossible or the caller's remaining budget expires.
let result = self.acquire_lock_quorum_once(&attempt_request, remaining).await?;
let ordered_writer = retrying_writer || (self.order_object_writes && request.lock_type == LockType::Exclusive);
let result = self
.acquire_lock_quorum_round(&attempt_request, remaining, ordered_writer)
.await?;
if !result.response.success {
tracing::trace!(
target: "rustfs_lock::namespace_owner",
@@ -1973,7 +1983,12 @@ impl DistributedLock {
/// Quorum-based lock acquisition: success if at least the required quorum succeeds.
/// Collects all individual lock_ids from successful clients and creates an aggregate lock_id.
/// Returns the LockResponse with aggregate lock_id and individual lock mappings.
async fn acquire_lock_quorum_once(&self, request: &LockRequest, quorum_timeout: Duration) -> Result<LockAcquireQuorumResult> {
async fn acquire_lock_quorum_round(
&self,
request: &LockRequest,
quorum_timeout: Duration,
ordered_writer: bool,
) -> Result<LockAcquireQuorumResult> {
let voter_count =
u32::try_from(self.clients.len().max(1)).map_err(|_| LockError::internal("lock voter count exceeds u32"))?;
let required_quorum = self.required_quorum(request.lock_type);
@@ -1987,13 +2002,16 @@ impl DistributedLock {
fallback_lock_id: request.lock_id.clone(),
};
let mut next_client_index = 0usize;
let initial_fanout = required_quorum
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
.min(self.clients.len());
// Hot object writers queue at the same first voter before taking partial grants on other voters.
// The remaining voters are contacted on its response or the first hedge, whichever comes first.
self.spawn_lock_requests_until(
&mut round.pending,
request,
&mut next_client_index,
required_quorum
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
.min(self.clients.len()),
if ordered_writer { 1 } else { initial_fanout },
);
let mut last_failure = None;
let mut last_failure_kind = None;
@@ -2006,7 +2024,12 @@ impl DistributedLock {
// Spread additional hedges across the existing attempt budget; fast
// quorums still use only the initial quorum-plus-spare requests.
let hedge_interval = request.acquire_timeout / voter_count;
let hedge_timer = tokio::time::sleep(hedge_interval);
let first_hedge = if ordered_writer {
request.acquire_timeout.min(quorum_timeout / 2)
} else {
hedge_interval
};
let hedge_timer = tokio::time::sleep(first_hedge);
tokio::pin!(hedge_timer);
while !round.pending.is_empty() {
@@ -2051,7 +2074,11 @@ impl DistributedLock {
}
_ = &mut hedge_timer, if next_client_index < self.clients.len() => {
if start.elapsed() < quorum_timeout {
let target_in_flight = round.pending.len().saturating_add(1);
let target_in_flight = if ordered_writer && next_client_index == 1 {
initial_fanout
} else {
round.pending.len().saturating_add(1)
};
self.spawn_lock_requests_until(
&mut round.pending, request, &mut next_client_index, target_in_flight,
);
@@ -2362,7 +2389,7 @@ mod batch_retry_tests;
#[cfg(test)]
mod tests {
use super::{
BatchLockPeerDiagnostics, DEFERRED_UNLOCK_BACKOFF, DistributedLock, LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF,
BatchLockPeerDiagnostics, DEFERRED_UNLOCK_BACKOFF, DistributedLock, HeldLockEntry, LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF,
LOCK_ACQUIRE_SPARE_HEDGES, LOCK_PEER_ACQUIRE_TIMEOUT, LOCK_PEER_WRITER_RETRY_TIMEOUT, LockAcquireFailureKind,
LockLostSignal, UNLOCK_RETRY_ATTEMPTS, UNLOCK_RETRY_BACKOFF, is_definitive_lock_contention, is_remote_lock_rpc_failure,
should_warn_lock_failure,
@@ -2724,6 +2751,75 @@ mod tests {
drop(guard);
}
#[tokio::test(start_paused = true)]
async fn a_new_writer_leaves_other_voters_free_while_waiting_for_the_first_vote() {
let peers: Vec<_> = (0..4)
.map(|index| {
let delay = if index == 0 {
Duration::from_millis(30)
} else {
Duration::ZERO
};
Arc::new(SequencedClient::new(
vec![AcquirePlan::Success { delay }],
Arc::new(Mutex::new(Vec::new())),
))
})
.collect();
let mut lock = DistributedLock::new(
"hot-write".to_owned(),
peers.iter().map(|peer| peer.clone() as Arc<dyn LockClient>).collect(),
3,
);
lock.order_object_writes();
let writer = tokio::spawn(async move {
let request = LockRequest::new(ObjectKey::new("bucket", "hot"), LockType::Exclusive, "writer")
.with_acquire_timeout(Duration::from_secs(5));
lock.acquire_guard(&request).await
});
while peers[0].requested_acquires.load(Ordering::SeqCst) == 0 {
tokio::task::yield_now().await;
}
tokio::time::advance(Duration::from_millis(10)).await;
assert!(
peers[1..]
.iter()
.all(|peer| peer.requested_acquires.load(Ordering::SeqCst) == 0)
);
let guard = writer.await.expect("writer task").expect("acquire").expect("write quorum");
assert_eq!(guard.entries.len(), 3);
}
#[tokio::test(start_paused = true)]
async fn contended_write_retry_can_form_a_quorum_without_the_first_voter() {
let peers = (0..4)
.map(|index| {
let delay = if index == 0 { Duration::from_secs(30) } else { Duration::ZERO };
Arc::new(SequencedClient::new(
vec![AcquirePlan::Success { delay }],
Arc::new(Mutex::new(Vec::new())),
)) as Arc<dyn LockClient>
})
.collect();
let lock = DistributedLock::new("hot-write-fallback".to_owned(), peers, 3);
let budget = Duration::from_secs(2);
let request =
LockRequest::new(ObjectKey::new("bucket", "hot"), LockType::Exclusive, "writer").with_acquire_timeout(budget);
let started = Instant::now();
let votes = lock
.acquire_lock_quorum_round(&request, budget, true)
.await
.expect("retry round");
assert!(votes.response.success);
assert_eq!(votes.individual_locks.len(), 3);
assert!(started.elapsed() < budget);
DistributedLock::release_entries(
votes.individual_locks.iter().map(HeldLockEntry::release_entry).collect(),
"test_ordered_retry",
)
.await;
}
#[tokio::test(start_paused = true)]
async fn fast_read_quorum_keeps_initial_fanout_bound() {
let peers: Vec<_> = (0..8)
@@ -4111,7 +4207,7 @@ mod tests {
let request = LockRequest::new(ObjectKey::new("bucket", "partial-grants"), LockType::Shared, "owner")
.with_acquire_timeout(Duration::from_secs(1));
let result = lock
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.acquire_lock_quorum_round(&request, request.acquire_timeout, false)
.await
.expect("partial quorum should return a timeout response");
assert!(!result.response.success);
@@ -4321,7 +4417,7 @@ mod tests {
let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_secs(2));
let result = lock
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.acquire_lock_quorum_round(&request, request.acquire_timeout, false)
.await
.expect("round result");
assert!(!result.response.success);
@@ -4343,7 +4439,7 @@ mod tests {
.with_acquire_timeout(Duration::from_secs(2));
let started = Instant::now();
let result = lock
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.acquire_lock_quorum_round(&request, request.acquire_timeout, false)
.await
.expect("round result");
assert!(!result.response.success);
@@ -4380,7 +4476,7 @@ mod tests {
.with_acquire_timeout(Duration::from_secs(2));
let started = Instant::now();
let result = lock
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.acquire_lock_quorum_round(&request, request.acquire_timeout, false)
.await
.expect("round result");
assert!(!result.response.success);
@@ -4408,7 +4504,7 @@ mod tests {
let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_secs(1));
let result = lock
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.acquire_lock_quorum_round(&request, request.acquire_timeout, false)
.await
.expect("round result");
assert!(!result.response.success);
@@ -4521,9 +4617,11 @@ mod tests {
);
let request = LockRequest::new(ObjectKey::new("bucket", "ready-after-deadline"), LockType::Shared, "owner")
.with_acquire_timeout(Duration::from_secs(5));
let mut attempt = Box::pin(tokio::task::unconstrained(
lock.acquire_lock_quorum_once(&request, request.acquire_timeout),
));
let mut attempt = Box::pin(tokio::task::unconstrained(lock.acquire_lock_quorum_round(
&request,
request.acquire_timeout,
false,
)));
assert!(matches!(poll!(&mut attempt), Poll::Pending));
tokio::time::timeout(Duration::from_secs(1), async {
while clients
+1
View File
@@ -32,6 +32,7 @@ pub mod metrics;
pub mod object_pool;
pub mod optimized_notify;
mod publication;
pub(crate) use publication::applies as is_publication_fence;
pub mod shard;
pub mod state;
pub mod types;
+1 -1
View File
@@ -14,7 +14,7 @@ use super::{
types::{LockMode, ObjectKey, ObjectLockRequest},
};
pub(super) fn applies(key: &ObjectKey) -> bool {
pub(crate) fn applies(key: &ObjectKey) -> bool {
key.version.is_none() && key.object.as_ref() == rustfs_common::table_catalog::TABLE_BUCKET_PUBLICATION_LOCK_PATH
}
+10
View File
@@ -52,6 +52,16 @@ impl NamespaceLockWrapper {
Self { lock, resource, owner }
}
/// Order distributed object PUTs at a common voter before competing for the remaining votes.
/// The table publication fence has its own FIFO on every voter.
pub fn order_object_writes(&mut self) {
if let NamespaceLock::Distributed(lock) = &mut self.lock
&& !crate::fast_lock::is_publication_fence(&self.resource)
{
lock.order_object_writes();
}
}
/// Get lock owner identifier used for acquisition.
pub fn owner(&self) -> &str {
&self.owner
+36
View File
@@ -1034,6 +1034,42 @@ async fn test_namespace_lock_distributed_reclaims_expired_same_resource_after_fa
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn four_ingress_nodes_contending_for_one_hot_write_key() {
let clients = (0..4)
.map(|_| Arc::new(LocalClient::with_manager(Arc::new(GlobalLockManager::new()))) as Arc<dyn LockClient>)
.collect::<Vec<_>>();
let coordinators = (0..4)
.map(|_| Arc::new(NamespaceLock::Distributed(DistributedLock::new("hot-key".to_owned(), clients.clone(), 3))))
.collect::<Vec<_>>();
let ready = Arc::new(tokio::sync::Barrier::new(32));
let active = Arc::new(AtomicUsize::new(0));
let mut writers = tokio::task::JoinSet::new();
for i in 0..32 {
let coordinator = coordinators[i % coordinators.len()].clone();
let ready = ready.clone();
let active = active.clone();
writers.spawn(async move {
ready.wait().await;
let guard = coordinator
.get_write_lock(ObjectKey::new("bucket", "same-key"), &format!("writer-{i}"), Duration::from_secs(5))
.await?;
assert_eq!(active.fetch_add(1, Ordering::SeqCst), 0);
tokio::time::sleep(Duration::from_millis(10)).await;
assert_eq!(active.fetch_sub(1, Ordering::SeqCst), 1);
drop(guard);
Ok::<(), crate::LockError>(())
});
}
let mut completed = 0;
while let Some(result) = writers.join_next().await {
if result.expect("writer task").is_ok() {
completed += 1;
}
}
assert_eq!(completed, 32);
}
#[tokio::test]
async fn four_node_failed_release_converges_without_replica_repair() {
let managers = (0..4).map(|_| Arc::new(GlobalLockManager::new())).collect::<Vec<_>>();
+1
View File
@@ -142,6 +142,7 @@ fn material_to_write_encryption(material: &EncryptionMaterial) -> SwiftWriteEncr
EncryptionKeyKind::Object => SwiftWriteEncryption::singlepart_object_key(material.key_bytes),
EncryptionKeyKind::Direct => SwiftWriteEncryption::singlepart(material.key_bytes, material.base_nonce),
}
.for_sse_type(material.sse_type)
}
/// Map an [`SseError`] into a sanitized [`SwiftError`].
+43
View File
@@ -2871,6 +2871,19 @@ impl Metrics {
}
}
/// Record the site runtime's durable admission decision. Replaying an existing operation does not queue a new run.
pub fn record_site_resync_admission<E>(&self, result: &Result<bool, E>) {
let work = ScannerSourceWorkUpdate {
checked: 1,
queued: u64::from(matches!(result, Ok(true))),
skipped: u64::from(matches!(result, Ok(false))),
missed: u64::from(result.is_err()),
..Default::default()
};
self.record_scanner_source_work(ScannerWorkSource::SiteReplication, work);
self.record_scanner_replication_repair_work(ScannerReplicationRepairKind::SiteActiveResync, work);
}
fn record_last_cycle_scanner_source_work(&self, source: ScannerWorkSource, work: ScannerSourceWorkUpdate) {
if let Some(counters) = self.last_scan_cycle_source_work.get(source.index()) {
counters.add(work);
@@ -4356,6 +4369,36 @@ mod tests {
assert_eq!(value["cycles_completed_at"][0].as_str(), Some("2023-11-14T22:14:20.987654Z"));
}
#[tokio::test]
async fn site_resync_admission_distinguishes_new_work_replays_and_rejections() {
let metrics = Metrics::new();
for admission in [Ok(true), Ok(false), Err(())] {
metrics.record_site_resync_admission(&admission);
}
let report = metrics.report().await;
let site = report
.source_work
.iter()
.find(|work| work.source == "site_replication")
.unwrap();
let active = report
.replication_repair
.iter()
.find(|work| work.kind == "active_resync")
.unwrap();
assert_eq!((site.checked, site.queued, site.skipped, site.missed, site.executed), (3, 1, 1, 1, 0));
assert_eq!(
(active.checked, active.queued, active.skipped, active.missed, active.executed),
(3, 1, 1, 1, 0)
);
let bucket = report
.source_work
.iter()
.find(|work| work.source == "bucket_replication")
.unwrap();
assert_eq!((bucket.checked, bucket.queued), (0, 0));
}
#[tokio::test]
async fn close_disk_guard_runs_cleanup_when_an_early_return_drops_it() {
let (closed_tx, closed_rx) = tokio::sync::oneshot::channel();
@@ -372,6 +372,29 @@ async fn committed_keys<S: ScannerObjectIO>(
Ok(known)
}
#[cfg(all(test, feature = "e2e-test-hooks"))]
impl DataUsageCache {
pub(crate) async fn committed_page_bytes_for_test<S: ScannerObjectIO>(
store: Arc<S>,
name: &str,
revisions: &DataUsageCacheRevisions,
) -> Option<(u64, u64)> {
let header = previous_header(store.clone(), name, &revisions.main).await.unwrap()?;
let head = header.manifest()?;
let keys = committed_keys(store.clone(), name, head, &Archive::default()).await.unwrap();
let mut live = 0;
for key in keys {
let block = read_block(store.clone(), name, head.bundle, key)
.await
.expect("read an authenticated checkpoint page");
live += u64::try_from(block.len()).unwrap();
}
// The production writer rotates a bundle once its retained pages would exceed twice the live pages.
assert!(live > 0 && (live..=2 * live).contains(&head.bundle_bytes));
Some((live, head.bundle_bytes))
}
}
pub(super) async fn decode<S: ScannerObjectIO>(store: Arc<S>, load_name: &str, bytes: &[u8]) -> StorageResult<DataUsageCache> {
if !is_manifest(bytes) {
return DataUsageCache::unmarshal(bytes).map_err(|_| invalid("invalid scanner cache"));
@@ -99,6 +99,19 @@ async fn compacted_checkpoint_advances_one_child_without_rewriting_300k_names()
.await
.expect("save compacted receipt");
let after = layout(&store).await;
#[cfg(feature = "e2e-test-hooks")]
{
let revisions = DataUsageCache::read_revisions(store.clone(), NAME).await.unwrap();
let (live, retained) = DataUsageCache::committed_page_bytes_for_test(store.clone(), NAME, &revisions)
.await
.expect("the compacted checkpoint is paged");
let stored: usize = after
.iter()
.filter(|(key, _)| key.contains(".bin.pages/"))
.map(|(_, (_, bytes))| bytes)
.sum();
assert!(live <= retained && retained <= u64::try_from(stored).unwrap());
}
if let Some(before) = before.as_ref() {
let (old_bytes, new_bytes) = page_bytes_after_save(before, &after);
eprintln!("300k-name checkpoint: {new_bytes} bytes in new pages, {old_bytes} bytes in existing pages");
@@ -410,7 +410,11 @@ async fn scoped_ack_publication_stale_root_cas_keeps_dirty_after_bucket_save() {
#[tokio::test]
#[serial]
async fn scoped_ack_publication_cannot_transfer_proof_between_real_scan_results() {
let (_directory, store) = candidate_store().await;
assert!(dirty_buckets_after_mismatched_root_proof().await > 0);
}
async fn dirty_buckets_after_mismatched_root_proof() -> usize {
let (directory, store) = candidate_store().await;
let (first_scan, first_candidate) = complete_candidate(&store, PROOF_CYCLE).await;
let (second_scan, second_candidate) = complete_candidate(&store, PROOF_CYCLE).await;
assert_eq!(first_candidate.scanner_epoch, second_candidate.scanner_epoch);
@@ -434,6 +438,11 @@ async fn scoped_ack_publication_cannot_transfer_proof_between_real_scan_results(
);
crate::scanner_io::clear_dirty_usage_buckets_for_tests();
drop(store);
let fixture_path = directory.path().to_path_buf();
directory.close().expect("remove mismatched root fixture");
assert!(!fixture_path.exists());
dirty.len()
}
#[tokio::test]
@@ -878,9 +887,7 @@ async fn usage_companion_write_failure_retains_dirty_responsibility() {
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-13", "status": "PASS"}));
}
#[tokio::test]
#[serial]
async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source() {
async fn all_source_ack_publication_evidence() -> serde_json::Value {
crate::scanner_io::clear_dirty_usage_buckets_for_tests();
let (directory, store) = setup_scanner_cycle_store_with_pool_count(false, 2).await;
store
@@ -907,6 +914,8 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
assert_eq!(fresh.buckets_usage[PROOF_BUCKET].objects_count, 2);
assert_eq!(fresh.buckets_usage[PROOF_BUCKET].size, 10);
let fresh_bytes = serde_json::to_vec(&fresh).expect("exact all-source root");
assert!(read_root(&store).await.0.is_none());
assert!(crate::scanner_io::dirty_usage_buckets_pending());
let publication = publish_candidate(&store, &fresh_scan, fresh, None).await;
assert_eq!(publication.outcome(), DataUsagePersistOutcome::Saved);
assert_eq!(read_root(&store).await.0.as_deref(), Some(fresh_bytes.as_slice()));
@@ -956,8 +965,10 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
candidate.buckets_usage[PROOF_BUCKET].usage_certification.is_none(),
"mixed source values cannot acquire a current certificate"
);
let pending_bytes = serde_json::to_vec(&candidate).expect("exact non-fresh root");
let publication = publish_candidate(&store, &scan, candidate, None).await;
assert_eq!(publication.outcome(), DataUsagePersistOutcome::Saved);
assert_eq!(read_root(&store).await.0.as_deref(), Some(pending_bytes.as_slice()));
let (_, pending, remote) = finalize_scanner_cycle_result(scan, publication);
assert!(pending);
assert!(remote.is_empty());
@@ -976,6 +987,13 @@ async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source()
let fixture_path = directory.path().to_path_buf();
directory.close().expect("remove all-source acknowledgement fixture");
assert!(!fixture_path.exists());
evidence
}
#[tokio::test]
#[serial]
async fn usage_durable_root_ack_requires_fresh_contributions_from_every_source() {
let evidence = all_source_ack_publication_evidence().await;
println!(
"usage_assertion: {}",
serde_json::json!({
@@ -157,3 +157,19 @@ async fn usage_duplicate_lost_and_reordered_ack_retains_post_walk_mutations() {
);
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-14", "status": "PASS"}));
}
#[tokio::test]
#[serial]
async fn usage_pending_bucket_never_falls_back_to_a_generation_ack() {
let retained = dirty_buckets_after_mismatched_root_proof().await;
assert!(retained > 0);
let sources = all_source_ack_publication_evidence().await;
println!(
"usage_assertion: {}",
serde_json::json!({
"case_id": "USAGE-14", "assertion_id": "USAGE-14-A02", "status": "PASS",
"evidence": {"retained_after_mismatched_root": retained, "source_publication": sources},
})
);
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-14", "status": "PASS"}));
}
@@ -3,6 +3,84 @@
use super::*;
#[tokio::test]
#[serial]
async fn decommission_keeps_stale_certificates_and_observations_out_of_both_publication_routes() {
let (directory, store) = candidate_store().await;
let (first_scan, first) = complete_candidate(&store, PROOF_CYCLE).await;
let certificate = first.buckets_usage[PROOF_BUCKET]
.usage_certification
.expect("measured baseline");
assert_eq!(
publish_candidate(&store, &first_scan, first, None).await.outcome(),
DataUsagePersistOutcome::Saved
);
let baseline = read_root(&store).await;
let companion_path = DATA_USAGE_OBSERVED_OBJ_NAME_PATH.as_str();
let previous_companion = read_config_with_revision(store.clone(), companion_path).await.unwrap();
let mut reader = PutObjReader::from_vec(b"second".to_vec());
store.pools[0].disk_set[0]
.put_object(PROOF_BUCKET, "second", &mut reader, &ObjectOptions::default())
.await
.unwrap();
crate::scanner_io::record_dirty_usage_bucket(PROOF_BUCKET);
let (scan, candidate) = complete_candidate(&store, PROOF_CYCLE + 1).await;
assert_eq!(candidate.buckets_usage[PROOF_BUCKET].objects_count, 2);
assert_ne!(candidate.buckets_usage[PROOF_BUCKET].usage_certification, Some(certificate));
let mut observation = candidate.clone();
observation.usage_snapshot_converged = Some(false);
observation.usage_snapshot_observational = true;
observation.buckets_usage.get_mut(PROOF_BUCKET).unwrap().mark_observed();
let dirty_before = crate::scanner_io::dirty_usage_buckets_for_tests();
store.pool_meta.write().await.pools[0].decommission = Some(crate::storage_api::owner::EcstorePoolDecommissionInfo {
failed: true,
..Default::default()
});
for pending in [candidate, observation.clone()] {
let result = publish_candidate(&store, &scan, pending, None).await;
assert_eq!(result.outcome(), DataUsagePersistOutcome::Deferred(ScannerCycleDeferReason::DataMovement));
assert_eq!(read_root(&store).await, baseline);
assert_eq!(
read_config_with_revision(store.clone(), companion_path).await.unwrap(),
previous_companion
);
assert_eq!(crate::scanner_io::dirty_usage_buckets_for_tests(), dirty_before);
}
let published: DataUsageInfo = serde_json::from_slice(baseline.0.as_ref().unwrap()).unwrap();
assert_eq!(published.buckets_usage[PROOF_BUCKET].objects_count, 1);
assert_eq!(published.buckets_usage[PROOF_BUCKET].usage_certification, Some(certificate));
store.pool_meta.write().await.pools[0].decommission = None;
let released = publish_candidate(&store, &scan, observation, None).await;
assert!(!matches!(
released.outcome(),
DataUsagePersistOutcome::Deferred(_) | DataUsagePersistOutcome::Failed
));
let companion = read_config_with_revision(store.clone(), companion_path).await.unwrap();
assert_ne!(companion, previous_companion, "the same observation is writable once the fence clears");
let observed: DataUsageInfo = serde_json::from_slice(companion.0.as_ref().unwrap()).unwrap();
assert_eq!(observed.buckets_usage[PROOF_BUCKET].objects_count, 2);
assert!(observed.buckets_usage[PROOF_BUCKET].usage_certification.is_none());
assert_eq!(read_root(&store).await, baseline);
crate::scanner_io::clear_dirty_usage_buckets_for_tests();
drop(store);
let path = directory.path().to_owned();
directory.close().expect("remove publication fixtures");
assert!(!path.exists());
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-15","assertion_id":"USAGE-15-A02","status":"PASS",
"evidence":{"decommission_fenced":["primary","observed companion"],"certified_objects":1,"candidate_objects":2,
"retained_dirty_buckets":dirty_before.len(),"companion_released_after_fence":true}})
);
println!(
"usage_cleanup: {}",
serde_json::json!({"case_id":"USAGE-15","status":"PASS","fixture_removed":true})
);
}
#[tokio::test]
#[serial]
async fn usage_drain_lease_and_epoch_loss_reject_real_root_without_restarting_deadline() {
+1 -1
View File
@@ -391,7 +391,7 @@ fn record_scanner_heal_admission(metrics: &Metrics, scan_mode: HealScanMode, adm
),
Ok(HealAdmissionResult::Full | HealAdmissionResult::Dropped(_)) | Err(_) => (ScannerSourceWorkUpdate::missed(1), false),
};
metrics.record_scanner_source_work(scanner_heal_source(scan_mode), work);
metrics.record_scanner_source_work(scanner_heal_source(scan_mode), ScannerSourceWorkUpdate { checked: 1, ..work });
admitted
}
@@ -1071,6 +1071,7 @@ async fn test_scanner_heal_admission_accounting_maps_normal_scan_to_heal() {
.find(|work| work.source == ScannerWorkSource::Bitrot.as_str())
.expect("bitrot source work should be visible");
assert_eq!((heal.checked, bitrot.checked), (5, 0));
assert_eq!(heal.queued, 1);
assert_eq!(heal.skipped, 1);
assert_eq!(heal.missed, 3);
@@ -1098,6 +1099,7 @@ async fn test_scanner_heal_admission_accounting_maps_deep_scan_to_bitrot() {
.find(|work| work.source == ScannerWorkSource::Bitrot.as_str())
.expect("bitrot source work should be visible");
assert_eq!((bitrot.checked, heal.checked), (3, 0));
assert_eq!(bitrot.queued, 1);
assert_eq!(bitrot.skipped, 1);
assert_eq!(bitrot.missed, 1);
@@ -215,18 +215,24 @@ async fn finish_resumed_walk(cache: DataUsageCache, original: &FolderScanner) ->
#[tokio::test]
#[serial]
async fn periodic_mixed_tail_requires_terminal_persistence_before_fresh_certification() {
let (periodic, identity, scanner, _guard) = nested_periodic_snapshot(false, (0, 0)).await;
let (directory, backend) = crate::scanner_io::tests::setup_local_scanner_store(1, 1).await;
let store = backend.pools[0].disk_set[0].clone();
let epoch = crate::ScannerConfigObjectDelete::scanner_data_usage_movement_generation(store.as_ref())
.await
.expect("physical cache owner epoch");
let (periodic, identity, scanner, guard) = nested_periodic_snapshot(false, (0, 0)).await;
assert!(periodic.has_scan_position(), "real periodic snapshot retains traversal position");
let store = FixtureStore::new();
let revisions = DataUsageCache::default()
let initial = DataUsageCache::default()
.load_with_revisions(store.clone(), CACHE_NAME)
.await
.expect("initial periodic fixture revisions");
periodic
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, &revisions, 0, CancellationToken::new())
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, &initial, epoch, CancellationToken::new())
.await
.expect("seed durable periodic snapshot");
let mut delayed_writer = None;
let mut snapshots = Vec::new();
for round in 0..3 {
let cycle = 12 + round;
let leader_epoch = 9 + round;
@@ -279,14 +285,20 @@ async fn periodic_mixed_tail_requires_terminal_persistence_before_fresh_certific
assert_eq!(totals.objects, usize::try_from(OBJECTS).expect("fixture count"));
assert_eq!(totals.size, usize::try_from(OBJECTS).expect("fixture bytes"));
store.reject_save.store(round == 0, Ordering::SeqCst);
// Reject the first candidate before its terminal CAS can become durable.
let expected = if round == 0 { &initial } else { &revisions };
let saved = terminal
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, &revisions, 0, CancellationToken::new())
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, expected, epoch, CancellationToken::new())
.await;
let mut retained = DataUsageCache::default();
let durable = retained
.load_with_revisions(store.clone(), CACHE_NAME)
.await
.expect("reopen the committed cache");
if round == 0 {
assert!(saved.is_err(), "injected terminal persistence failure must be observable");
assert!(matches!(saved, Err(crate::StorageError::PreconditionFailed)));
assert!(terminal.completed_bucket_observation().is_some());
let retained = store.strict_load().await;
assert_eq!(durable, revisions);
assert!(
retained.info.scan_bucket_observations.is_empty(),
"a failed CAS cannot publish the terminal companion"
@@ -297,15 +309,52 @@ async fn periodic_mixed_tail_requires_terminal_persistence_before_fresh_certific
retained.has_scan_position(),
"failed terminal save must leave periodic recovery state intact"
);
delayed_writer = Some((terminal, revisions));
} else {
saved.expect("persist terminal sweep");
let retained = store.strict_load().await;
assert!(!retained.has_scan_position());
assert_eq!(retained.info.snapshot_complete, round == 2);
assert_eq!(retained.completed_bucket_observation().is_some(), round == 1);
if round == 1 {
let observation = retained.completed_bucket_observation().expect("successor's observation");
assert_eq!(observation.completed_epoch, leader_epoch);
assert!(retained.info.scan_progress.is_some(), "mixed EOF keeps fresh-sweep responsibility");
let (old, old_revisions) = delayed_writer.take().expect("previous owner's uncommitted terminal");
assert!(old.completed_bucket_observation().unwrap().completed_epoch < leader_epoch);
let late = old
.save_with_revisions_for_epoch(store.clone(), CACHE_NAME, &old_revisions, epoch, CancellationToken::new())
.await;
assert!(matches!(late, Err(crate::StorageError::PreconditionFailed)));
let mut restarted = DataUsageCache::default();
assert_eq!(restarted.load_with_revisions(store.clone(), CACHE_NAME).await.unwrap(), durable);
assert_eq!(
serde_json::to_value(restarted.completed_bucket_observation().expect("recovered observation")).unwrap(),
serde_json::to_value(observation).unwrap()
);
assert_eq!(restarted.info.scan_progress, retained.info.scan_progress);
}
}
store.reject_save.store(false, Ordering::SeqCst);
snapshots.push(serde_json::json!({"leader_epoch": leader_epoch, "cursor": retained.has_scan_position(),
"observation": retained.completed_bucket_observation().is_some(), "fresh_sweep_debt": retained.info.scan_progress.is_some(),
"complete": retained.info.snapshot_complete}));
}
let walked_path = guard.temp_dir.as_ref().unwrap().clone();
drop(scanner);
drop(guard);
drop(store);
drop(backend);
let path = directory.path().to_path_buf();
directory.close().expect("remove checkpoint storage");
assert!(!walked_path.exists() && !path.exists());
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-10","assertion_id":"USAGE-10-A01","status":"PASS","evidence":{"disk_reloads":snapshots}})
);
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-10","assertion_id":"USAGE-10-A02","status":"PASS","evidence":{"delayed_writer_rejected":true,"successor_kept_mixed_observation":true,"fresh_objects":OBJECTS}})
);
println!("usage_cleanup: {}", serde_json::json!({"case_id":"USAGE-10","status":"PASS"}));
}
#[tokio::test]
@@ -7,6 +7,9 @@ use crate::scanner_budget::ScannerCycleBudgetConfig;
use std::cell::Cell;
use std::path::PathBuf;
#[cfg(feature = "e2e-test-hooks")]
mod large_directory;
const PHYSICAL_READ_COST: Duration = Duration::from_secs(60);
tokio::task_local! {
@@ -0,0 +1,127 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::*;
#[tokio::test]
#[serial]
async fn hundred_thousand_real_objects_and_a_nested_wide_directory_resume_from_disk() {
const WIDE: usize = 100_000;
const NESTED: usize = 2_048;
const ENTRIES_PER_ROUND: u64 = 16_384;
let files = tempfile::tempdir().expect("wide directory fixture");
let root = files.path().join("disk");
let mut cache = seed_flat_bucket(&root, 0).await;
let bucket = root.join("bucket");
tokio::task::spawn_blocking(move || {
for (prefix, count, first) in [("wide", WIDE, 1), ("wide/deep", NESTED, WIDE + 1)] {
let directory = bucket.join(prefix);
std::fs::create_dir_all(&directory).unwrap();
for offset in 0..count {
let name = format!("key-{offset:06}");
let object = format!("{prefix}/{name}");
let path = directory.join(name);
std::fs::create_dir(&path).unwrap();
let version = Uuid::from_u128((first + offset) as u128);
std::fs::write(path.join("xl.meta"), metadata_for_object_version("bucket", &object, Some(version))).unwrap();
}
}
assert_eq!(std::fs::read_dir(bucket.join("wide")).unwrap().count(), WIDE + 1);
assert_eq!(std::fs::read_dir(bucket.join("wide/deep")).unwrap().count(), NESTED);
})
.await
.expect("seed physical objects");
let (checkpoint_dir, backend) = crate::scanner_io::tests::setup_local_scanner_store(1, 1).await;
let set = backend.pools[0].disk_set[0].clone();
let epoch = crate::ScannerConfigObjectDelete::scanner_data_usage_movement_generation(set.as_ref())
.await
.unwrap();
let name = format!("bucket/{}", crate::DATA_USAGE_CACHE_NAME);
let mut revision = DataUsageCache::default()
.load_with_revisions(set.clone(), &name)
.await
.unwrap();
let mut wide_progress = Vec::new();
let mut serialized = Vec::new();
let mut page_bytes = Vec::new();
#[cfg(target_os = "linux")]
let mut peak_resident_bytes = Vec::new();
let mut finished = false;
let budget = ScannerCycleBudgetConfig {
max_entries: Some(ENTRIES_PER_ROUND),
max_objects: Some(ENTRIES_PER_ROUND),
..Default::default()
};
for _ in 0..32 {
let round = scan_one_restart_round(&root, cache, budget).await;
assert!(round.observed_entries <= ENTRIES_PER_ROUND);
round
.outcome
.save_with_revisions_for_epoch(set.clone(), &name, &revision, epoch, CancellationToken::new())
.await
.unwrap();
cache = DataUsageCache::default();
revision = cache.load_with_revisions(set.clone(), &name).await.unwrap();
serialized.push(cache.marshal_msg().unwrap().len());
page_bytes.push(DataUsageCache::committed_page_bytes_for_test(set.clone(), &name, &revision).await);
#[cfg(target_os = "linux")]
{
let status = std::fs::read_to_string("/proc/self/status").expect("Linux process memory counters");
let peak = status
.lines()
.find_map(|line| line.strip_prefix("VmHWM:"))
.expect("peak resident memory");
let kib = peak.trim().strip_suffix(" kB").unwrap().parse::<u64>().unwrap();
peak_resident_bytes.push(kib * 1024);
}
if let Some(index) = cache.validated_raw_enumeration_page_index_for_parent("bucket/wide")
&& let Some(position) = index.durable_progress()
{
let entries = position.committed_entries();
if wide_progress.last().is_none_or(|previous| entries > *previous) {
wide_progress.push(entries);
}
}
if round.finished {
finished = true;
break;
}
}
assert!(finished && cache.info.snapshot_complete);
assert!(
wide_progress.len() >= 2 && wide_progress[1] > 0,
"durable raw coverage: {wide_progress:?}"
);
let expected = WIDE + NESTED;
let totals = cache
.checked_flatten_complete_scope("bucket")
.expect("complete persisted bucket");
assert_eq!((totals.objects, totals.versions, totals.size), (expected, expected, expected));
assert!(page_bytes.iter().flatten().count() >= 2, "at least two paged roots must be measured");
drop(set);
drop(backend);
let roots = [files.path().to_owned(), checkpoint_dir.path().to_owned()];
files.close().unwrap();
checkpoint_dir.close().unwrap();
assert!(roots.iter().all(|path| !path.exists()));
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-06","assertion_id":"USAGE-06-A01","status":"PASS","evidence":{"wide_objects":WIDE,"nested_objects":NESTED,"durable_frontier_entries":wide_progress,"checkpoint_wire_bytes_by_round":serialized,"certified_objects":totals.objects,"certified_versions":totals.versions,"certified_bytes":totals.size}})
);
#[cfg(target_os = "linux")]
{
// The fixed-size acceptance workload runs in a 4 GiB, swap-free scope on the SSD fleet.
const MEMORY_LIMIT: u64 = 4 * 1024 * 1024 * 1024;
assert!(peak_resident_bytes.iter().all(|&peak| peak > 0 && peak < MEMORY_LIMIT));
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-06","assertion_id":"USAGE-06-A02","status":"PASS","evidence":{"peak_resident_bytes_by_round":peak_resident_bytes,"memory_limit_bytes":MEMORY_LIMIT,"live_and_retained_page_bytes_by_round":page_bytes,"max_retained_multiple":2,"certified_objects":totals.objects,"certified_versions":totals.versions,"certified_bytes":totals.size}})
);
}
println!(
"usage_cleanup: {}",
serde_json::json!({"case_id":"USAGE-06","status":"PASS","fixtures_removed":true})
);
}
@@ -19,6 +19,8 @@ use rustfs_data_usage::{ReplicationAllStats, ReplicationTargetUsage, TierAccount
const TEST_PLAN_DIGEST: DataUsageScanPlanDigest = DataUsageScanPlanDigest([7; 32]);
const TEST_COVERAGE_DIGEST: DataUsageScanPlanDigest = DataUsageScanPlanDigest([6; 32]);
mod structural_changes;
#[test]
fn partial_progress_requires_complete_scope_and_no_hard_failure() {
for plan_complete in [false, true] {
@@ -0,0 +1,113 @@
// Copyright 2026 RustFS Team
// SPDX-License-Identifier: Apache-2.0
use super::*;
use crate::storage_api::scan::{BucketOperations as _, MakeBucketOptions};
#[tokio::test]
#[serial_test::serial]
async fn changed_pool_membership_epoch_and_tier_reject_obsolete_coverage() {
let (directory, store) = crate::scanner_io::tests::setup_local_scanner_store(2, 1).await;
let bucket = "structural-coverage";
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
let mut sources = Vec::new();
let mut identities = Vec::new();
for pool in &store.pools {
let set = &pool.disk_set[0];
sources.push(DataUsageCacheSource::new(set.pool_index, set.set_index));
identities.push(
scanner_bucket_checkpoint_identity(set, bucket, 5, 7, HealScanMode::Normal)
.await
.unwrap()
.unwrap(),
);
}
assert_eq!(sources.len(), 2);
assert_ne!(sources[0], sources[1]);
assert_eq!(identities[0].bucket_incarnation, identities[1].bucket_incarnation);
assert_ne!(identities[0].set_layout, identities[1].set_layout);
let roots = [
completed_root_cache(bucket, 2, 10, sources[0]),
completed_root_cache(bucket, 3, 20, sources[1]),
];
let first = HashSet::from([sources[0]]);
let both = HashSet::from([sources[0], sources[1]]);
let buckets = [bucket.to_owned()];
let publish = |roots: &[DataUsageCache], expected| completed_usage_for_scope(roots, expected, &buckets, &[], true, false);
assert_eq!(publish(&roots[..1], &first).unwrap().0.objects_total_count, 2);
assert!(publish(&roots[..1], &both).is_none(), "the added pool has yet to report");
assert_eq!(publish(&roots, &both).unwrap().0.objects_total_count, 5);
assert!(
publish(&roots, &first).is_none(),
"the retired pool must not contribute its previous objects"
);
let mut checkpoint = DataUsageCache {
info: DataUsageCacheInfo {
name: bucket.to_owned(),
source: Some(sources[0]),
next_cycle: 8,
leader_epoch: 11,
last_update: Some(SystemTime::now()),
snapshot_complete: true,
scan_identity: Some(identities[0]),
scan_plan_digest: Some(TEST_PLAN_DIGEST),
scan_coverage_digest: Some(TEST_COVERAGE_DIGEST),
tier_registry_generation: Some(7),
cache_key_format: DATA_USAGE_CACHE_KEY_FORMAT,
..Default::default()
},
..Default::default()
};
checkpoint.replace(
bucket,
"",
DataUsageEntry {
objects: 2,
size: 32,
..Default::default()
},
);
let epoch = crate::DataUsageScanIdentity {
publication_epoch: 6,
..identities[0]
};
let tier = crate::DataUsageScanIdentity {
tier_registry_generation: 8,
..identities[0]
};
for (label, source, identity) in [
("original", sources[0], identities[0]),
("replaced layout", sources[0], identities[1]),
("changed source", sources[1], identities[0]),
("movement epoch", sources[0], epoch),
("tier generation", sources[0], tier),
] {
let mut candidate = checkpoint.clone();
let options = DataUsageCacheReuseOptions {
require_source: true,
tier_registry_generation: Some(identity.tier_registry_generation),
checkpoint_identity: Some(identity),
checkpoint_plan_digest: Some(TEST_COVERAGE_DIGEST),
completed_checkpoint_cycle_floor: Some(7),
};
let state =
current_cache_root_or_prepare_with_generation(&mut candidate, bucket, source, 9, 12, TEST_PLAN_DIGEST, options);
assert_eq!(matches!(state, DataUsageCacheScanState::Current(_)), label == "original", "{label}");
}
drop(store);
let path = directory.path().to_owned();
directory.close().expect("remove both formatted pools");
assert!(!path.exists());
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-15","assertion_id":"USAGE-15-A01","status":"PASS",
"evidence":{"formatted_pool_sources":sources,"published_objects":[2,5],"rejected_obsolete_membership":["expansion","decommission"],
"rejected_checkpoint_inputs":["replaced layout","changed source","movement epoch","tier generation"]}})
);
println!(
"usage_cleanup: {}",
serde_json::json!({"case_id":"USAGE-15","status":"PASS","removed_pools":2})
);
}
+13
View File
@@ -556,6 +556,19 @@ pub(crate) async fn setup_local_scanner_store(pool_count: usize, drives_per_set:
(temp_dir, store)
}
// The RPC entry point resolves a process-wide store. Serial worker tests share the resolver,
// but each test owns its store and can drop the entire disk fixture.
fn select_test_rpc_store(store: &Arc<ECStore>) {
static CURRENT: StdMutex<std::sync::Weak<ECStore>> = StdMutex::new(std::sync::Weak::new());
static REGISTER: std::sync::Once = std::sync::Once::new();
REGISTER.call_once(|| {
assert!(crate::storage_api::owner::ecstore_set_object_store_resolver(Arc::new(|| {
CURRENT.lock().unwrap().upgrade()
})));
});
*CURRENT.lock().unwrap() = Arc::downgrade(store);
}
#[tokio::test]
async fn epoch_fenced_cache_save_uses_background_admission_on_every_disk() {
#[derive(Clone)]
@@ -671,10 +671,7 @@ async fn remote_checkpoint_resumes_across_restart_and_maintenance_identity_chang
budget: serde_json::Value,
}
let (_temp_dir, store) = setup_local_scanner_store(1, 1).await;
let resolved = Arc::downgrade(&store);
assert!(crate::storage_api::owner::ecstore_set_object_store_resolver(Arc::new(
move || resolved.upgrade()
)));
select_test_rpc_store(&store);
rustfs_credentials::set_global_rpc_secret("remote-checkpoint-test-secret".to_string()).expect("test RPC secret");
let set = store.pools[0].disk_set[0].clone();
let disk = scanner_set_disk_inventory(&set).await.pop().expect("local worker disk");
@@ -579,11 +579,13 @@ fn source_turn_zero_new_frontier_stops_requeuing_without_starving_other_sources(
}
async fn source_turn_zero_new_frontier_stops_requeuing_without_starving_other_sources_case() {
temp_env::async_with_vars([(ENV_SCANNER_MAX_CONCURRENT_SET_SCANS, Some("1"))], async {
let evidence = temp_env::async_with_vars([(ENV_SCANNER_MAX_CONCURRENT_SET_SCANS, Some("1"))], async {
crate::runtime_config::refresh_scanner_runtime_config_for_tests();
let (_dir, store) = setup_two_pool_scanner_store().await;
let (dir, store) = setup_two_pool_scanner_store().await;
clear_dirty_usage_buckets_for_tests();
create_cohort_bucket_objects(&store, "blocked-frontier", 3).await;
record_dirty_usage_bucket("blocked-frontier");
let generation = dirty_usage_buckets_for_tests()["blocked-frontier"];
let budget = quantum_budget(crate::scanner_budget::ScannerBucketQuantum {
max_objects: Some(1),
..Default::default()
@@ -600,10 +602,23 @@ async fn source_turn_zero_new_frontier_stops_requeuing_without_starving_other_so
assert_eq!(result.status, ScannerCycleStatus::Incomplete);
assert!(usage.is_none(), "partial sources cannot publish complete usage");
assert!(!budget.budget_elapsed());
assert!(!result.has_dirty_usage_to_acknowledge());
assert!(result.clear_verified_usage().is_empty());
assert_eq!(dirty_usage_buckets_for_tests()["blocked-frontier"], generation);
clear_dirty_usage_buckets_for_tests();
drop(store);
let path = dir.path().to_path_buf();
dir.close().expect("remove the partial source fixture");
assert!(!path.exists());
serde_json::json!({"physical_sources": sources, "source_turns": admissions, "complete_totals": false, "retained_dirty_generation": generation})
})
.await;
crate::runtime_config::refresh_scanner_runtime_config_for_tests();
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-07","assertion_id":"USAGE-07-A03","status":"PASS","evidence":evidence})
);
println!("usage_cleanup: {}", serde_json::json!({"case_id":"USAGE-07","status":"PASS"}));
}
#[test]
@@ -649,7 +664,11 @@ fn fair_prefix_quantum_without_durable_motion_ends_the_bucket_turn() {
}
async fn fair_prefix_quantum_without_durable_motion_ends_the_bucket_turn_case() {
let (_dir, store) = setup_local_scanner_store(1, 4).await;
assert_eq!(service_turns_without_progress().await, 1);
}
async fn service_turns_without_progress() -> u64 {
let (dir, store) = setup_local_scanner_store(1, 4).await;
clear_dirty_usage_buckets_for_tests();
create_cohort_bucket_objects(&store, "a-flat", 6).await;
let cohort = Arc::new(StdMutex::new(ScannerServiceCohort::default()));
@@ -667,6 +686,83 @@ async fn fair_prefix_quantum_without_durable_motion_ends_the_bucket_turn_case()
);
assert_eq!(ledger.failure_debt(), (0, None));
clear_dirty_usage_buckets_for_tests();
drop(store);
let path = dir.path().to_path_buf();
dir.close().expect("remove zero-progress fixture");
assert!(!path.exists());
ledger.buckets["a-flat"].service_quanta
}
#[test]
#[serial]
fn usage_shared_budget_serves_three_cold_buckets_and_stops_empty_turns() {
run_cohort_test(
"usage-cold-budget",
usage_shared_budget_serves_three_cold_buckets_and_stops_empty_turns_case,
);
}
async fn usage_shared_budget_serves_three_cold_buckets_and_stops_empty_turns_case() {
let (dir, store) = setup_local_scanner_store(1, 4).await;
clear_dirty_usage_buckets_for_tests();
create_cohort_bucket_objects(&store, "a-hot", 6).await;
let cold = ["z-cold-one", "z-cold-two", "z-cold-three"];
for bucket in cold {
create_cohort_bucket(&store, bucket).await;
}
let cohort = Arc::new(StdMutex::new(ScannerServiceCohort::default()));
let share = crate::scanner_budget::ScannerBucketQuantum {
max_objects: Some(2),
..Default::default()
};
let owner = CancellationToken::new();
let budget = ScannerCycleBudget::new_with_progress_tracking(
&owner,
ScannerCycleBudgetConfig {
max_objects: Some(5),
bucket_quantum: Some(share),
..Default::default()
},
);
let (partial, usage) = run_cohort_cycle(&store, cohort.clone(), 1, budget.clone()).await;
assert_eq!(partial.status, ScannerCycleStatus::Incomplete);
assert!(usage.is_none());
assert_eq!(budget.reason(), Some(crate::scanner_budget::ScannerCycleBudgetReason::Objects));
assert_eq!(budget.progress().0, 5, "the parent must continue past the first two-object share");
assert!(!owner.is_cancelled());
let next = quantum_budget(share);
let (result, usage) = run_cohort_cycle(&store, cohort, 2, next.clone()).await;
assert_eq!(result.status, ScannerCycleStatus::Complete);
assert!(!next.budget_elapsed());
let usage = usage.expect("complete physical-source inventory");
assert_eq!(usage.objects_total_count, 9);
let ledger = load_set_cache(&store)
.await
.info
.scan_bucket_service
.expect("durable service ledger");
let quanta = cold.map(|bucket| {
assert_eq!(usage.buckets_usage[bucket].objects_count, 1);
let turns = ledger.buckets[bucket].service_quanta;
assert!(turns > 0);
turns
});
clear_dirty_usage_buckets_for_tests();
drop(store);
let path = dir.path().to_path_buf();
dir.close().expect("remove shared-budget fixture");
assert!(!path.exists());
let zero_turns = service_turns_without_progress().await;
assert_eq!(zero_turns, 1);
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-05","assertion_id":"USAGE-05-A02","status":"PASS","evidence":{"cycle_objects":budget.progress().0,"bucket_object_limit":share.max_objects,"remaining_owner":!owner.is_cancelled()}})
);
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-05","assertion_id":"USAGE-05-A03","status":"PASS","evidence":{"cold_bucket_service_quanta":quanta,"objects":usage.objects_total_count,"zero_progress_turns":zero_turns}})
);
println!("usage_cleanup: {}", serde_json::json!({"case_id":"USAGE-05","status":"PASS"}));
}
/// A one-object share stops inside its first child, so the frontier never
@@ -49,6 +49,8 @@ pub(crate) fn walker_disks(set: &Arc<SetDisks>, buckets: &[BucketInfo], disks: V
struct DrainTransport {
source_cache: DataUsageCache,
source_store: Arc<SetDisks>,
worker_disk: Option<crate::DiskStore>,
coverage_requests: StdMutex<Vec<DataUsageScanPlanDigest>>,
release_complete: CancellationToken,
opened: AtomicUsize,
writers: StdMutex<Vec<tokio::task::JoinHandle<()>>>,
@@ -88,6 +90,30 @@ impl InternodeDataTransport for DrainTransport {
assert_eq!(request.leader_epoch, EPOCH);
self.opened.fetch_add(1, Ordering::AcqRel);
let (reader, writer) = tokio::io::duplex(64 * 1024);
if let Some(disk) = self.worker_disk.clone() {
#[derive(serde::Deserialize)]
struct RequestCapabilities {
checkpoint_plan_digest: DataUsageScanPlanDigest,
usage_watch: Option<serde::de::IgnoredAny>,
supports_complete_observation: bool,
supports_durable_progress: bool,
}
let wire: RequestCapabilities = rmp_serde::from_slice(&request.body).expect("coordinator request");
assert!(wire.supports_complete_observation && wire.supports_durable_progress);
assert!(
wire.usage_watch.is_none(),
"independent terminal and progress capabilities grant no watch"
);
self.coverage_requests.lock().unwrap().push(wire.checkpoint_plan_digest);
let request = crate::decode_remote_scanner_request(&request.body).expect("decode production request");
let task = tokio::spawn(async move {
crate::serve_remote_scanner_request(disk, request, writer, CancellationToken::new())
.await
.expect("serve production worker stream");
});
self.writers.lock().unwrap().push(task);
return Ok(Box::new(reader));
}
let mut cache = self.source_cache.clone();
if request.next_cycle == REGISTRY_CHANGE_CYCLE {
let identity = cache.info.scan_identity.as_mut().expect("fixture bucket identity");
@@ -168,7 +194,9 @@ fn request(
}
}
async fn setup_remote_drain_store() -> (tempfile::TempDir, Arc<ECStore>, Arc<SetDisks>, Arc<DrainTransport>, WalkerGuard) {
async fn setup_remote_drain_store(
physical_worker: bool,
) -> (tempfile::TempDir, Arc<ECStore>, Arc<SetDisks>, Arc<DrainTransport>, WalkerGuard) {
let _ = rustfs_credentials::set_global_rpc_secret("usage-native-controlled-transport-secret".to_string());
let (directory, store) = setup_local_scanner_store(1, 4).await;
clear_dirty_usage_buckets_for_tests();
@@ -211,9 +239,17 @@ async fn setup_remote_drain_store() -> (tempfile::TempDir, Arc<ECStore>, Arc<Set
let usage = cache_root_entry_info(&durable).expect("flatten the actual durable root");
assert_eq!(usage.entry.objects, 1);
assert_eq!(usage.entry.size, 11);
let worker_disk = if physical_worker {
select_test_rpc_store(&store);
Some(scanner_set_disk_inventory(&set).await.remove(0))
} else {
None
};
let transport = Arc::new(DrainTransport {
source_cache: durable,
source_store: set.clone(),
worker_disk,
coverage_requests: StdMutex::new(Vec::new()),
release_complete: CancellationToken::new(),
opened: AtomicUsize::new(0),
writers: StdMutex::new(Vec::new()),
@@ -238,10 +274,116 @@ async fn setup_remote_drain_store() -> (tempfile::TempDir, Arc<ECStore>, Arc<Set
(directory, store, set, transport, WalkerGuard)
}
#[tokio::test]
#[serial]
async fn peer_without_watch_capability_cannot_certify_a_cross_cycle_mutation() {
let (directory, store, set, transport, guard) = setup_remote_drain_store(true).await;
for i in 0..6 {
store
.put_object(
BUCKET,
&format!("p{i}/object"),
&mut ScannerPutObjReader::from_vec(vec![7; 9]),
&ScannerObjectOptions::default(),
)
.await
.unwrap();
}
wait_for_namespace_commit_tails(&store).await;
let cohort = Arc::new(StdMutex::new(ScannerServiceCohort::default()));
let mut totals = None;
let mut mixed = false;
for cycle in [REMOTE_CYCLE, REGISTRY_CHANGE_CYCLE, REPLANNED_CYCLE] {
if cycle == REGISTRY_CHANGE_CYCLE {
store
.put_object(
BUCKET,
"object",
&mut ScannerPutObjReader::from_vec(vec![8; 37]),
&ScannerObjectOptions::default(),
)
.await
.unwrap();
wait_for_namespace_commit_tails(&store).await;
record_dirty_usage_bucket(BUCKET);
}
save_config(
store.clone(),
DATA_USAGE_BLOOM_NAME_PATH.as_str(),
crate::scanner::encode_scanner_cycle_fence_for_test(cycle, EPOCH),
)
.await
.unwrap();
let owner = CancellationToken::new();
let budget = ScannerCycleBudget::new_with_progress_tracking(
&owner,
ScannerCycleBudgetConfig {
max_objects: (cycle == REMOTE_CYCLE).then_some(2),
..Default::default()
},
);
budget.use_production_drain_grace_for_tests();
let (tx, mut rx) = mpsc::channel(1);
let mut spec = request(&owner, &budget, tx, cycle);
spec.service_cohort = Some(cohort.clone());
let result = tokio::time::timeout(Duration::from_secs(60), nsscanner_with_storage_status_scoped(store.as_ref(), spec))
.await
.unwrap()
.unwrap();
let _ = rx.recv().await;
assert!(rx.recv().await.is_none());
let mut cache = DataUsageCache::default();
cache
.load(set.clone(), &path_join_buf(&[BUCKET, DATA_USAGE_CACHE_NAME]))
.await
.unwrap();
assert!(cache.info.scan_usage_watch.is_none());
assert!(result.usage_watch_proofs().is_empty());
if cycle == REMOTE_CYCLE {
assert!(
cache.has_scan_position() && !cache.info.snapshot_complete,
"the budget must interrupt an actual worker walk"
);
} else if cache.info.snapshot_complete {
let entry = cache.checked_flatten_complete_scope(BUCKET).expect("certified bucket tree");
assert_eq!(
(entry.objects, entry.size),
(7, 91),
"an old checkpoint would retain the overwritten size"
);
totals = Some((entry.objects, entry.size));
} else {
assert_ne!(cycle, REPLANNED_CYCLE, "fresh walk must converge");
assert!(!result.has_dirty_usage_to_acknowledge());
assert!(dirty_usage_buckets_for_tests().contains_key(BUCKET));
mixed = true;
}
}
let plans = transport.coverage_requests.lock().unwrap().clone();
assert_eq!(plans.len(), 3);
assert_ne!(plans[0], plans[1], "a watchless peer needs the strict mutation-dependent coverage plan");
let (objects, size) = totals.expect("complete physical readback after mutation");
drop(guard);
drop(transport);
drop(set);
drop(store);
let path = directory.path().to_owned();
directory.close().unwrap();
assert!(!path.exists());
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-12","assertion_id":"USAGE-12-A02","status":"PASS","evidence":{"worker_requests_without_watch":plans.len(),"strict_coverage_changed":true,"mixed_round_seen":mixed,"certified_objects":objects,"certified_bytes":size}})
);
println!(
"usage_cleanup: {}",
serde_json::json!({"case_id":"USAGE-12","status":"PASS","fixture_removed":true})
);
}
#[tokio::test]
#[serial]
async fn usage_remote_complete_after_count_stop_reaches_real_candidate() {
let (directory, store, set, transport, guard) = setup_remote_drain_store().await;
let (directory, store, set, transport, guard) = setup_remote_drain_store(false).await;
let owner = CancellationToken::new();
record_dirty_usage_bucket(BUCKET);
let dirty_before = dirty_usage_buckets_for_tests();
@@ -359,7 +501,7 @@ async fn tier_registry_change_preserves_dirty_and_set_root_until_fenced_replan()
use crate::scanner::{ScannerCycleOutcome, run_data_scanner_cycle};
use rustfs_scanner_metrics::metrics::CurrentCycle;
let (_directory, store, set, transport, _guard) = setup_remote_drain_store().await;
let (_directory, store, set, transport, _guard) = setup_remote_drain_store(false).await;
transport.release_complete.cancel();
record_dirty_usage_bucket(BUCKET);
let dirty = dirty_usage_buckets_for_tests();
@@ -228,3 +228,147 @@ async fn changed_watch_during_resume_preserves_an_observation_then_requires_a_fr
serde_json::json!({"case_id": "USAGE-03", "status": "PASS", "fixture_removed": true})
);
}
#[tokio::test]
#[serial]
async fn missing_producer_watch_keeps_the_strict_mutation_fallback() {
let (dir, store) = setup_local_scanner_store(1, 1).await;
clear_dirty_usage_buckets_for_tests();
for bucket in [BUCKET, "z-unrelated"] {
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
}
for index in 0..6 {
put(&store, BUCKET, &format!("prefix-{index:02}/object"), 16).await;
}
let cohort = Arc::new(StdMutex::new(ScannerServiceCohort::default()));
let (_, _, partial) = run(&store, cohort.clone(), 1, Some(2)).await;
assert!(partial.has_scan_position());
let proof = partial
.info
.scan_usage_watch
.expect("the first checkpoint has a producer watch");
assert!(proof.verify_with_store(&store).await);
// Retire only the producer token. The coordinator still has its original checkpoint and cohort.
assert!(
ScannerUsageWatchReleaseGuard::new(Some(store.clone()), vec![proof.clone()])
.finish()
.await
);
assert!(!proof.verify_with_store(&store).await);
let before = store.scanner_namespace_mutation_generation();
put(&store, "z-unrelated", "changed", 32).await;
let after = store.scanner_namespace_mutation_generation();
assert!(after > before);
record_dirty_usage_bucket(BUCKET);
let generation = dirty_usage_buckets_for_tests()[BUCKET];
let (result, _, mixed) = run(&store, cohort.clone(), 2, None).await;
assert!(mixed.completed_bucket_observation().is_some());
assert!(!mixed.info.snapshot_complete);
assert!(!mixed.has_scan_position());
assert!(result.usage_watch_proofs().iter().all(|proof| proof.bucket != BUCKET));
assert!(!result.has_dirty_usage_to_acknowledge());
assert_eq!(dirty_usage_buckets_for_tests()[BUCKET], generation);
let (_, _, fresh) = run(&store, cohort, 3, None).await;
let counts = fresh
.checked_flatten_complete_scope(BUCKET)
.expect("subsequent complete fresh scan");
assert_eq!((counts.objects, counts.size), (6, 96));
let evidence = serde_json::json!({
"starting_owners": proof.peers.len(), "unrelated_mutation_generation": [before, after],
"retained_dirty_generation": generation, "fresh_objects": counts.objects, "fresh_bytes": counts.size,
});
clear_dirty_usage_buckets_for_tests();
drop(store);
let path = dir.path().to_path_buf();
dir.close().expect("remove missing-watch fixture");
assert!(!path.exists());
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-12","assertion_id":"USAGE-12-A01","status":"PASS","evidence":evidence})
);
println!(
"usage_cleanup: {}",
serde_json::json!({"case_id":"USAGE-12","status":"PASS","fixture_removed":true})
);
}
#[tokio::test]
#[serial]
async fn cold_prefix_advances_durably_while_another_prefix_is_being_overwritten() {
let (dir, store) = setup_local_scanner_store(1, 1).await;
clear_dirty_usage_buckets_for_tests();
store.make_bucket(BUCKET, &MakeBucketOptions::default()).await.unwrap();
for index in 0..12 {
put(&store, BUCKET, &format!("cold/range-{index:02}/object"), 16).await;
}
put(&store, BUCKET, "hot/object", 16).await;
let cohort = Arc::new(StdMutex::new(ScannerServiceCohort::default()));
let stop = CancellationToken::new();
let (writes, mut observed) = tokio::sync::watch::channel(0_u64);
let writer = async {
let mut sequence = 0_u64;
while !stop.is_cancelled() {
sequence += 1;
put(&store, BUCKET, "hot/object", 16 + (sequence % 2) as usize).await;
writes.send_replace(sequence);
tokio::time::sleep(Duration::from_millis(5)).await;
}
sequence
};
let walk = async {
let _stop = stop.clone().drop_guard();
observed.changed().await.unwrap();
let mut cold = Vec::new();
let mut during = Vec::new();
for cycle in 1..=3 {
let before = *observed.borrow();
let (_, _, persisted) = run(&store, cohort.clone(), cycle, Some(3)).await;
let after = *observed.borrow();
assert!(after > before, "the hot prefix must be overwritten during each bounded scan");
assert!(persisted.has_scan_position());
assert!(!persisted.info.snapshot_complete);
let objects = persisted
.checked_flatten(&format!("{BUCKET}/cold"))
.map_or(0, |entry| entry.objects);
assert!(
cold.last().is_none_or(|previous| objects > *previous),
"cold coverage {cold:?} then {objects}"
);
cold.push(objects);
during.push(after - before);
}
(cold, during)
};
let (writes, (cold, during)) = tokio::join!(writer, walk);
record_dirty_usage_bucket(BUCKET);
let dirty_generation = dirty_usage_buckets_for_tests()[BUCKET];
let (result, _, mixed) = run(&store, cohort.clone(), 4, None).await;
let observation = mixed.completed_bucket_observation().expect("persisted mixed bucket result");
assert_eq!(observation.entry.objects, 13);
assert!(observation.entry.children.is_empty());
assert!(!mixed.info.snapshot_complete);
assert!(!result.has_dirty_usage_to_acknowledge());
assert!(result.clear_verified_usage().is_empty());
assert_eq!(dirty_usage_buckets_for_tests()[BUCKET], dirty_generation);
let (_, _, fresh) = run(&store, cohort, 5, None).await;
assert!(fresh.info.snapshot_complete);
let exact = fresh.checked_flatten_complete_scope(BUCKET).unwrap();
assert_eq!((exact.objects, exact.size), (13, 13 * 16 + (writes % 2) as usize));
clear_dirty_usage_buckets_for_tests();
drop(store);
let path = dir.path().to_path_buf();
dir.close().expect("remove hot and cold prefixes");
assert!(!path.exists());
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-04","assertion_id":"USAGE-04-A02","status":"PASS","evidence":{"durable_cold_objects":cold,"hot_overwrites_during_each_scan":during}})
);
println!(
"usage_assertion: {}",
serde_json::json!({"case_id":"USAGE-04","assertion_id":"USAGE-04-A03","status":"PASS","evidence":{"mixed_bucket_objects":observation.entry.objects,"prefix_entries":observation.entry.children.len(),"retained_dirty_generation":dirty_generation,"fresh_objects":exact.objects}})
);
println!(
"usage_cleanup: {}",
serde_json::json!({"case_id":"USAGE-04","status":"PASS","fixture_removed":true})
);
}
+8
View File
@@ -139,6 +139,13 @@ pub fn encryption_material_to_metadata(material: &EncryptionMaterial) -> Result<
.as_deref()
.ok_or_else(|| SseError::internal("managed SSE materials must carry an encrypted data key"))?;
record_managed_scheme(&mut metadata, material);
if material.sse_type == SSEType::SseS3 {
rustfs_utils::http::metadata_compat::insert_str(
&mut metadata,
rustfs_utils::http::SUFFIX_SSE_S3_ETAG,
"v1".to_owned(),
);
}
if material.key_kind == EncryptionKeyKind::Direct {
record_wrapped_data_key(&mut metadata, wrapped_data_key, material.base_nonce, material.algorithm.as_str());
@@ -239,6 +246,7 @@ pub fn strip_managed_encryption_metadata(metadata: &mut HashMap<String, String>)
metadata.remove(*key);
}
rustfs_utils::http::metadata_compat::remove_str(metadata, rustfs_utils::http::SUFFIX_OPAQUE_ENCRYPTED_ETAG);
rustfs_utils::http::metadata_compat::remove_str(metadata, rustfs_utils::http::SUFFIX_SSE_S3_ETAG);
}
pub fn mark_encrypted_multipart_metadata(metadata: &mut HashMap<String, String>) {
@@ -73,13 +73,15 @@ pub const REPLICATION_SSE_SEALED_KEY_HEADER: &str = "X-Rustfs-Replication-Server
pub const REPLICATION_ENCRYPTED_MULTIPART_HEADER: &str = "X-Rustfs-Replication-Encrypted-Multipart";
pub const SUFFIX_OPAQUE_ENCRYPTED_ETAG: &str = "server-side-encryption-opaque-etag";
/// The writer selected SSE-S3's content ETag for this object or multipart session.
pub const SUFFIX_SSE_S3_ETAG: &str = "server-side-encryption-s3-etag";
/// Old encrypted objects can carry a plaintext MD5. Keyless listings expose
/// an encrypted ETag only when its producer recorded the protected format.
/// Keyless listings require a writer marker for an opaque ETag or for the SSE-S3 content ETag.
/// Legacy multipart original-size fields alone do not establish encryption.
pub fn etag_can_be_listed(metadata: &HashMap<String, String>) -> bool {
let mut requires_proof = false;
let mut protected_format_seen = false;
let mut s3_format_seen = false;
for (key, value) in metadata {
if super::metadata_compat::matches_either_internal_key_ignore_ascii_case(key, SUFFIX_OPAQUE_ENCRYPTED_ETAG) {
// Every alias must attest the same protected format, even after a valid one.
@@ -87,13 +89,30 @@ pub fn etag_can_be_listed(metadata: &HashMap<String, String>) -> bool {
return false;
}
protected_format_seen = true;
} else if super::metadata_compat::matches_either_internal_key_ignore_ascii_case(key, SUFFIX_SSE_S3_ETAG) {
if value != "v1" {
return false;
}
s3_format_seen = true;
requires_proof = true;
} else if !requires_proof && !protected_format_seen {
requires_proof = super::is_object_encryption_marker(key)
|| key.eq_ignore_ascii_case(SSEC_ORIGINAL_SIZE_HEADER)
|| super::starts_with_ignore_ascii_case(key, RUSTFS_INTERNAL_ENCRYPTION_PREFIX);
}
}
!requires_proof || protected_format_seen
!requires_proof
|| protected_format_seen
|| (s3_format_seen
&& metadata
.get("x-amz-server-side-encryption")
.is_some_and(|value| value == "AES256")
&& contains_managed_encryption_metadata(metadata)
&& !metadata.keys().any(|key| {
super::starts_with_ignore_ascii_case(key, "x-amz-server-side-encryption-customer-")
|| key.eq_ignore_ascii_case(MINIO_INTERNAL_ENCRYPTION_SSEC_SEALED_KEY_HEADER)
|| key.eq_ignore_ascii_case("x-amz-server-side-encryption-aws-kms-key-id")
}))
}
/// Stored SSE-C metadata keys and the wire names they replicate under.
@@ -359,6 +378,22 @@ mod tests {
assert!(etag_can_be_listed(&both_sizes));
}
#[test]
fn keyless_listings_require_the_sse_s3_writer_marker_and_scheme() {
let mut metadata = HashMap::from([
("x-amz-server-side-encryption".to_owned(), "AES256".to_owned()),
(INTERNAL_ENCRYPTION_KEY_HEADER.to_owned(), "wrapped".to_owned()),
]);
assert!(!etag_can_be_listed(&metadata));
super::super::metadata_compat::insert_str(&mut metadata, SUFFIX_SSE_S3_ETAG, "v1".to_owned());
assert!(etag_can_be_listed(&metadata));
metadata.insert(SSEC_ALGORITHM_HEADER.to_owned(), "AES256".to_owned());
assert!(!etag_can_be_listed(&metadata));
metadata.remove(SSEC_ALGORITHM_HEADER);
metadata.insert("x-amz-server-side-encryption".to_owned(), "aws:kms".to_owned());
assert!(!etag_can_be_listed(&metadata));
}
#[test]
fn keyless_listings_hide_unproven_encrypted_etags() {
assert!(etag_can_be_listed(&HashMap::from([("content-type".to_owned(), "text/plain".to_owned())])));
+23 -12
View File
@@ -3,15 +3,26 @@
**Use this when:** upgrading encrypted storage or investigating missing ETags
in object listings after an upgrade.
New encrypted writes use a keyed fingerprint for the ETag rather than the
plaintext MD5. Single-part and part ETags are 32-character hexadecimal values;
completed multipart ETags retain their digest-and-part-count form. They stay
stable for the stored object. Request MD5 and checksum validation still apply
to the original plaintext. Encryption and decryption formats do not change.
New single-part SSE-S3 writes return the MD5 of the original bytes, including
when a bucket default selects AES256. Clients such as rclone use this value to
verify uploads. SSE-S3 parts use the same content MD5 and their completed
ETag combines the part digests and part count. SSE-C and SSE-KMS writes use
keyed fingerprints. Request checksums cover the original plaintext in every
mode. [Amazon S3 ETag semantics](https://docs.aws.amazon.com/AmazonS3/latest/API/API_Object.html)
## Listings and older objects
ListObjects, ListObjectsV2, and ListObjectVersions omit the optional ETag field for encrypted objects whose metadata does not attest to the protected format. This includes older encrypted objects and preserved source ETags without that proof. New single-part encrypted writes carry the internal format marker and expose their protected ETag in listings. Completed encrypted multipart uploads also carry that marker when every selected part has quorum-backed proof that its stored ETag came from the encryption reader and the final ETag is the aggregate of those parts. Unencrypted listings retain their existing ETags.
ListObjects, ListObjectsV2 and ListObjectVersions expose the stored ETag of an
SSE-S3 object created through the new writer. The same ETag appears on GET and
HEAD and in conditional requests. Earlier versions keep their stored ETags
and listing visibility, including opaque SSE-S3 fingerprints. Old writers can
omit the listing ETag for objects created by a new SSE-S3 writer during a
rolling upgrade. Older encrypted objects without a format marker require HEAD.
SSE-C and SSE-KMS expose keyed ETags in listings when the producer recorded
the protected format. Completed multipart uploads can attest an opaque ETag
when every selected part has quorum-backed proof and the final ETag matches
the aggregate of those parts.
Each new encrypted part records its producer proof in optional part metadata. Older part metadata defaults to unproven. Mixing proven and unproven selected parts, or preserving a different source ETag, keeps the completed object unproven. The proof is checked during completion using the existing part metadata reads, so listings need no additional object reads or KMS requests. Internal same-version data movement, including rebalance and decommission, retains an existing source proof when quorum-validated staging metadata and the completed object agree on the version and preserved ETag. Tier restore also retains the proof for the same version and ETag when it commits under the matching restore operation. Sources without proof continue to require authorized HEAD access or a credentialed rewrite.
@@ -21,10 +32,9 @@ Clients that require an ETag for unproven objects must issue an authorized HeadO
Bucket and site replication forward the stored ETag on `x-rustfs-source-etag`
(with its `x-minio-source-*` twin). A target that adopts it (RustFS, MinIO)
reports the fingerprint for the replica; a target that computes its own ETag
(AWS S3 and most compatible stores) reports the MD5 of the plaintext it
received, which never equals the fingerprint. The post-PUT replica ETag audit
therefore skips encrypted sources. Managed-SSE sources forward no checksum on
reports that ETag for the replica. A target that computes its own ETag can
return a different value for SSE-KMS or for an older SSE-S3 source. The
post-PUT replica ETag audit skips encrypted sources. Managed-SSE sources forward no checksum on
the replication PUT either, so a target that transforms their payload is not
detected. See
`docs/operations/replication-outbound-transport.md`.
@@ -62,8 +72,9 @@ already copied to backups, logs, caches, or replicas. Restrict access to those
copies separately. Rolling back to an older server also restores its listing
behavior, so keep the upgraded listing protection on every serving node.
To obtain a protected ETag, read the object with its encryption credentials and
write it through the upgraded encryption path. Verify the resulting plaintext
To migrate an older SSE-S3 object to a content MD5, read it with authorization
and upload it through the new SSE-S3 writer. SSE-C and SSE-KMS use the same
procedure to migrate to a protected ETag. Verify the resulting plaintext
and application references before retiring an old copy. A server-side copy
that preserves the source ETag is insufficient.
@@ -9,7 +9,7 @@
- For a single-part object, the checksum the source object was uploaded with, forwarded as its `x-amz-checksum-<algorithm>` header (the value the source verified on upload). A multipart replica is rebuilt through CreateMultipartUpload/UploadPart and carries no object-level checksum header. Managed-SSE objects forward none.
- On a PUT that carries Object Lock parameters and no forwarded checksum: `Content-MD5` derived from the source ETag, or an SDK CRC32 checksum when the ETag is not the MD5 of the wire bytes (rustfs#7082).
- The source ETag, mtime and version id on `x-rustfs-source-*` headers (with `x-minio-source-*` twins), and the Object Lock mode, retain-until date and legal hold of the source version when present.
- After the PUT, the target's ETag is compared with the source ETag when both are plain single-part MD5s and the source is unencrypted; a mismatch fails the replication instead of reporting a corrupted replica as COMPLETED. A managed-SSE (SSE-S3 / SSE-KMS) or SSE-C source is not audited this way: its stored ETag is a keyed fingerprint (new writes, see `docs/operations/encrypted-etags.md`) or a legacy plaintext MD5, and the target re-encrypts what it receives, so the two ETags are never comparable. Managed-SSE sources also forward no checksum (above), so a target that transforms their payload is not detected; an SSE-C ciphertext passthrough keeps its HEAD-back evidence audit.
- After the PUT, the target's ETag is compared with the source ETag when both are plain single-part MD5s and the source is unencrypted; a mismatch fails the replication instead of reporting a corrupted replica as COMPLETED. A managed-SSE (SSE-S3 / SSE-KMS) or SSE-C source is not audited this way: old SSE-S3 and SSE-KMS versions can have keyed fingerprints, new SSE-S3 writes have content MD5s, and a target can return its own ETag. See `docs/operations/encrypted-etags.md`. Managed-SSE sources also forward no checksum (above), so a target that transforms their payload is not detected; an SSE-C ciphertext passthrough keeps its HEAD-back evidence audit.
## Target classes and their known requirements
+37 -36
View File
@@ -796,9 +796,9 @@ dependencies = [
[[package]]
name = "aws-sdk-s3"
version = "1.162.0"
version = "1.163.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4"
checksum = "e9765cbe48081570df401ebc65cae8a9e32912fac5f4cf3c6bdb2547b8ecb62c"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -825,7 +825,7 @@ dependencies = [
"lru",
"percent-encoding",
"regex-lite",
"sha2 0.11.2",
"sha2 0.11.3",
"tracing",
"url",
]
@@ -924,7 +924,7 @@ dependencies = [
"http",
"p256",
"percent-encoding",
"sha2 0.11.2",
"sha2 0.11.3",
"subtle",
"time",
"tracing",
@@ -959,7 +959,7 @@ dependencies = [
"md-5",
"pin-project-lite",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"tracing",
]
@@ -3014,7 +3014,7 @@ checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2 0.11.2",
"sha2 0.11.3",
"signature 3.0.0",
"subtle",
]
@@ -3957,9 +3957,9 @@ dependencies = [
[[package]]
name = "io-uring"
version = "0.7.15"
version = "0.7.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb"
checksum = "42a8b27af47f173c8ccb750868620435d2afc8190ca314356f9dc29470274123"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
@@ -5055,7 +5055,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.2",
"sha2 0.11.3",
]
[[package]]
@@ -5422,7 +5422,7 @@ dependencies = [
"md-5",
"memchr",
"rand 0.10.4",
"sha2 0.11.2",
"sha2 0.11.3",
"stringprep",
]
@@ -6170,7 +6170,7 @@ dependencies = [
"pkcs1",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha2 0.11.2",
"sha2 0.11.3",
"signature 3.0.0",
"spki 0.8.1",
"zeroize",
@@ -6253,7 +6253,7 @@ dependencies = [
"http",
"md-5",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"xxhash-rust",
]
@@ -6299,7 +6299,7 @@ dependencies = [
"rand 0.10.4",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
]
@@ -6317,7 +6317,7 @@ dependencies = [
"rsa",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
]
@@ -6414,7 +6414,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"shadow-rs",
"slab",
"smallvec",
@@ -6476,7 +6476,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"time",
"tokio",
@@ -6510,7 +6510,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
"tokio",
"uuid",
@@ -6519,7 +6519,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-stream"
version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bitflags 2.13.2",
"bytes",
@@ -6530,7 +6530,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-types"
version = "0.44.0+aws.2026-10-02"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"bytes",
"crc-fast",
@@ -6542,7 +6542,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-xml",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
"twox-hash",
"unicode-normalization",
@@ -6552,7 +6552,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-xml"
version = "0.4.0"
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
dependencies = [
"quick-xml 0.41.0",
]
@@ -6606,7 +6606,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"socket2",
"thiserror",
"tracing",
@@ -6630,7 +6630,7 @@ dependencies = [
"rand 0.10.4",
"rustfs-kafka",
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"tokio",
"tokio-rustls",
"tracing",
@@ -6665,7 +6665,7 @@ dependencies = [
"serde",
"serde_ignored",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"subtle",
"thiserror",
"tokio",
@@ -6878,7 +6878,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"tokio",
"tokio-util",
@@ -6919,7 +6919,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"time",
"tokio",
@@ -7114,7 +7114,7 @@ dependencies = [
"rustls-native-certs",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"snap",
"sysinfo",
"thiserror",
@@ -7139,7 +7139,7 @@ dependencies = [
"rustls",
"rustls-pki-types",
"serde",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"tokio",
"tracing",
@@ -7148,8 +7148,9 @@ dependencies = [
[[package]]
name = "rustfs-uring"
version = "0.3.0"
source = "git+https://github.com/rustfs/uring.git?rev=eb8fc160e71d804427de1e905f5c226d580f71bf#eb8fc160e71d804427de1e905f5c226d580f71bf"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d9b7f02481f7a178db09da8dc3ed63c85debb370ecfa8b5a015706b58025ba"
dependencies = [
"io-uring",
"libc",
@@ -7183,7 +7184,7 @@ dependencies = [
"rustix",
"serde",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"siphasher",
"snap",
"tokio",
@@ -7551,9 +7552,9 @@ dependencies = [
[[package]]
name = "sha2"
version = "0.11.2"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -7902,9 +7903,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.4"
version = "0.40.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de"
checksum = "0ebe31c61260d7bc4bfc204a2d096c428a4c9ef59ca48bfa693d17fec4f129ad"
dependencies = [
"libc",
"memchr",
@@ -8156,7 +8157,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb"
dependencies = [
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"tokio",
"tokio-postgres",
"tokio-rustls",
+38 -2
View File
@@ -5881,7 +5881,11 @@ async fn start_site_bucket_resync(bucket: &str, target_arn: &str, resync_id: &st
let _committed_targets = match replication::commit_resync_target(
targets,
opts,
move |opts| async move { admission_pool.admit_bucket_resync(opts).await },
move |opts| async move {
let admission = admission_pool.admit_bucket_resync(opts).await;
rustfs_scanner_metrics::metrics::global_metrics().record_site_resync_admission(&admission);
admission
},
move |encoded| async move {
metadata_sys::update_bucket_targets_under_transaction_lock(&transaction_guard, bucket, encoded)
.await
@@ -6828,7 +6832,7 @@ async fn apply_iam_user_item(
if user.is_delete_req {
iam_sys.delete_user(&user.access_key, true).await.map_err(ApiError::from)?;
} else {
let Some(user_req) = user.user_req else {
let Some(mut user_req) = user.user_req else {
return Err(s3_error!(InvalidRequest, "userReq is required"));
};
let is_status_only_update = user_req.secret_key.is_empty() && user_req.policy.is_none();
@@ -6838,6 +6842,11 @@ async fn apply_iam_user_item(
.await
.map_err(ApiError::from)?;
} else {
// Older peers included the display policy on credential snapshots.
// Only a separate policy-mapping item can change the assignment.
if !user_req.secret_key.is_empty() {
user_req.policy = None;
}
iam_sys
.create_user_at(&user.access_key, &user_req, stamp)
.await
@@ -9403,6 +9412,33 @@ mod tests {
(serde_json::to_string(&doc.policy).expect("serialize policy"), doc.update_date)
}
#[tokio::test]
#[serial]
async fn durable_iam_state_legacy_bootstrap_user_leaves_grants_to_policy_mappings() {
publish_ready_iam_context().await;
seed_two_peer_state_for_iam_apply().await;
let iam = current_iam_handle().expect("test IAM");
let user = "sr-bootstrap-mapped-user";
let user_time = OffsetDateTime::now_utc() - time::Duration::hours(2);
let mapping_time = user_time - time::Duration::minutes(5);
let user_type = rustfs_iam::store::UserType::Reg;
let mut request = user_req("bootstrap-user-secret", rustfs_madmin::AccountStatus::Enabled);
request.policy = Some("readwrite".to_string());
apply_iam_item(sr_user_item(user, Some(request), user_time))
.await
.expect("legacy user snapshot");
assert_eq!(iam.get_user(user).await.expect("user").update_at, Some(user_time));
assert!(iam.get_mapped_policy_record(user, user_type, false).await.is_none());
apply_iam_item(sr_mapping_item(user, "readonly", mapping_time))
.await
.expect("separate mapping");
let mapping = iam.get_mapped_policy_record(user, user_type, false).await.expect("mapping");
assert_eq!(mapping.policies, "readonly");
assert_eq!(mapping.update_at, mapping_time);
clear_seeded_state().await;
}
/// Review finding on rustfs#7195 (P1): two source edits T1 < T2 that both
/// predate their delivery. The record T1 writes must carry T1 — not the
/// later receive time — or T2 is judged stale against it and the newer
+15 -20
View File
@@ -130,20 +130,16 @@ impl DefaultBucketUsecase {
.await
.map_err(ApiError::from)?;
let mut is_public = read_allowed || write_allowed;
let ignore_public_acls = match metadata_sys::get_public_access_block_config(bucket).await {
Ok((config, _)) => config.ignore_public_acls.unwrap_or(false),
Err(_) => false,
};
let _ = ignore_public_acls;
let policy_public = match metadata_sys::get_bucket_policy(bucket).await {
Ok((cfg, _)) => cfg.statements.iter().any(|statement| {
// Object grants can apply only to a prefix, even when the bucket cannot be listed.
matches!(statement.effect, Effect::Allow)
&& statement.principal.is_public()
&& statement.conditions.is_empty()
&& statement.actions.is_match(&Action::S3Action(S3Action::ListBucketAction))
&& statement
.actions
.iter()
.any(|action| matches!(action, Action::All | Action::S3Action(_)))
}),
Err(err) => {
if err == StorageError::ConfigNotFound {
@@ -154,13 +150,9 @@ impl DefaultBucketUsecase {
}
};
if policy_public {
is_public = true;
}
Ok(gateway_dto::GetBucketPolicyStatusOutput {
policy_status: Some(gateway_dto::PolicyStatus {
is_public: Some(is_public),
is_public: Some(read_allowed || write_allowed || policy_public),
}),
})
}
@@ -412,19 +404,22 @@ mod tests {
.await
.expect("Deny statement should not be rejected as a public grant");
// GetBucketPolicyStatus also classifies empty and `?` Allow principals as public.
let status_bucket = format!("policy-status-public-{}", uuid::Uuid::new_v4().simple());
store
.make_bucket(&status_bucket, &MakeBucketOptions::default())
.await
.expect("create status bucket");
for (label, principal_json, expected_public) in [
("empty_principal", r#"{"AWS":[""]}"#, true),
("leading_question_mark", r#"{"AWS":["?nobody"]}"#, true),
("named_principal", r#"{"AWS":["alice"]}"#, false),
for (label, principal_json, effect, action, suffix, expected_public) in [
("empty_principal", r#"{"AWS":[""]}"#, "Allow", "s3:ListBucket", "", true),
("leading_question_mark", r#"{"AWS":["?nobody"]}"#, "Allow", "s3:ListBucket", "", true),
("named_principal", r#"{"AWS":["alice"]}"#, "Allow", "s3:ListBucket", "", false),
("public_object_read", r#""*""#, "Allow", "s3:GetObject", "/*", true),
("public_object_prefix", r#""*""#, "Allow", "s3:GetObjectTagging", "/public/*", true),
("private_object_read", r#"{"AWS":["alice"]}"#, "Allow", "s3:GetObject", "/*", false),
("object_deny_only", r#""*""#, "Deny", "s3:GetObject", "/*", false),
] {
let policy = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Principal":{principal_json},"Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::{status_bucket}"]}}]}}"#
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"{effect}","Principal":{principal_json},"Action":"{action}","Resource":"arn:aws:s3:::{status_bucket}{suffix}"}}]}}"#
);
metadata_sys::update(&status_bucket, BUCKET_POLICY_CONFIG, policy.into_bytes())
.await
@@ -461,7 +461,7 @@ impl DefaultMultipartUsecase {
WriteEncryption::multipart(managed_material.key_bytes, managed_material.base_nonce, part_id)
}
};
write_plan = write_plan.with_encryption(managed_write);
write_plan = write_plan.with_encryption(managed_write.for_sse_type(managed_material.sse_type));
(Some(server_side_encryption), ssekms_key_id)
} else {
(None, None)
@@ -469,7 +469,7 @@ impl DefaultMultipartUsecase {
WriteEncryption::multipart(managed_material.key_bytes, managed_material.base_nonce, part_id)
}
};
write_plan = write_plan.with_encryption(managed_write);
write_plan = write_plan.with_encryption(managed_write.for_sse_type(managed_material.sse_type));
(Some(server_side_encryption), ssekms_key_id)
} else {
(None, None)
+44 -8
View File
@@ -1540,8 +1540,10 @@ fn validate_extract_expanded_pax_metadata_total(total: u64) -> S3Result<()> {
}
impl ExtractPaxOverrides {
fn overlay_record(&mut self, key: &str, value: &str) -> S3Result<()> {
fn overlay_record(&mut self, key: &str, value: impl AsRef<[u8]>) -> S3Result<()> {
let value = value.as_ref();
if key == "minio.versionId" {
let value = std::str::from_utf8(value).map_err(map_extract_pax_text_error)?;
if value.is_empty() {
self.version_id = None;
} else {
@@ -1553,6 +1555,7 @@ impl ExtractPaxOverrides {
let Some(meta_key) = key.strip_prefix("minio.metadata.") else {
return Ok(());
};
let value = std::str::from_utf8(value).map_err(map_extract_pax_text_error)?;
if meta_key.is_empty() {
return Ok(());
}
@@ -1637,8 +1640,7 @@ where
for ext in extensions {
let ext = ext.map_err(map_extract_archive_error)?;
let key = ext.key().map_err(map_extract_pax_text_error)?;
let value = ext.value().map_err(map_extract_pax_text_error)?;
overrides.overlay_record(key, value)?;
overrides.overlay_record(key, ext.value_bytes())?;
}
Ok(())
}
@@ -2179,7 +2181,7 @@ impl DefaultObjectUsecase {
(sse_customer_algorithm, sse_customer_key, sse_customer_key_md5, original_sse)
};
let bucket_sse_config = load_bucket_default_sse_config(&bucket).await?;
let (mut effective_sse, mut effective_kms_key_id) = resolve_bucket_default_sse(
let (effective_sse, effective_kms_key_id) = resolve_bucket_default_sse(
bucket_sse_config.as_ref().map(|(config, _timestamp)| config),
original_sse,
ssekms_key_id,
@@ -2664,8 +2666,6 @@ impl DefaultObjectUsecase {
}))
.await
) {
effective_sse = Some(material.server_side_encryption.clone());
effective_kms_key_id = material.response_kms_key_id();
write_plan = write_plan.with_encryption(material.write_encryption(None));
let encryption_metadata = extract_try!(encryption_material_to_metadata(&material));
metadata.extend(encryption_metadata.clone());
@@ -4970,7 +4970,7 @@ mod tests {
exact_headers
.overlay_record(
&format!("minio.metadata.{header_name}"),
&"v".repeat(EXTRACT_MAX_EFFECTIVE_PAX_HEADER_BYTES - header_name.len() + 1),
"v".repeat(EXTRACT_MAX_EFFECTIVE_PAX_HEADER_BYTES - header_name.len() + 1),
)
.is_err()
);
@@ -4986,7 +4986,7 @@ mod tests {
exact_user_metadata
.overlay_record(
&format!("minio.metadata.{user_name}"),
&"u".repeat(EXTRACT_MAX_EFFECTIVE_PAX_USER_METADATA_BYTES - user_name.len() + 1),
"u".repeat(EXTRACT_MAX_EFFECTIVE_PAX_USER_METADATA_BYTES - user_name.len() + 1),
)
.is_err()
);
@@ -5507,6 +5507,42 @@ mod tests {
assert_eq!(err.to_string(), "archive extension entry size limit exceeded");
}
#[tokio::test]
async fn pax_binary_xattr_leaves_object_metadata_intact() {
let mut record = pax_record("SCHILY.xattr.com.apple.provenance", &[0, 0xff, 0x80]);
record.extend(pax_record("minio.metadata.x-amz-meta-owner", b"archive-owner"));
let mut entry = entry_with_local_pax(&record, EntryType::Regular).await;
let mut overrides = ExtractPaxOverrides::default();
super::overlay_extract_pax_extensions(&mut entry, &mut overrides)
.await
.expect("unrelated binary file attributes should be ignored");
assert_eq!(overrides.headers.len(), 1);
assert_eq!(overrides.headers["x-amz-meta-owner"], "archive-owner");
}
#[tokio::test]
async fn pax_binary_object_metadata_still_requires_utf8() {
for key in [
"minio.metadata.x-amz-meta-owner",
"minio.versionId",
"minio.metadata.x-amz-meta-snowball-auto-extract",
"minio.metadata.",
] {
let mut entry = entry_with_local_pax(&pax_record(key, &[0xff]), EntryType::Regular).await;
let mut overrides = ExtractPaxOverrides::default();
let err = super::overlay_extract_pax_extensions(&mut entry, &mut overrides)
.await
.expect_err("object metadata and version IDs must be text");
assert_eq!(err.code().as_str(), "InvalidArgument");
assert!(overrides.headers.is_empty());
assert!(overrides.version_id.is_none());
}
}
#[tokio::test]
async fn pax_metadata_budget_counts_format_skipped_members() {
let record = pax_record("comment", b"oversized-symlink-metadata");
+5
View File
@@ -4423,6 +4423,7 @@ impl DefaultObjectUsecase {
manager: &ConcurrencyManager,
bucket: &str,
key: &str,
version_requested: bool,
info: ObjectInfo,
event_info: Option<ObjectInfo>,
final_stream: DynReader,
@@ -4589,10 +4590,12 @@ impl DefaultObjectUsecase {
let output_struct_start = rustfs_io_metrics::get_stage_metrics_enabled().then(std::time::Instant::now);
let parts_count = Self::get_object_parts_count(part_number, &info);
let response_etag = crate::storage::sse::read_response_etag(bucket, key, &info.user_defined, info.etag.as_deref()).await;
let tag_count = readable_object_tag_count(envelope, &info.user_tags, version_requested, false).await?;
let output = GetObjectOutputFacts {
body: Some(body),
etag: response_etag.as_deref().map(ResponseEtag::from_stored),
dto: gateway_dto::GetObjectOutput {
tag_count,
content_length: Some(http_content_length),
last_modified: last_modified.map(timestamp),
content_type: content_type.map(|value| value.to_string()),
@@ -5150,6 +5153,7 @@ impl DefaultObjectUsecase {
manager,
&bucket,
&key,
input.version_id.is_some(),
info,
event_info,
final_stream,
@@ -12597,6 +12601,7 @@ mod tests {
get_concurrency_manager(),
"test-bucket",
"path/raw",
false,
info.clone(),
Some(info),
wrap_reader(tokio::io::empty()),
+3 -33
View File
@@ -123,21 +123,6 @@ fn tagging_directive_is_access(headers: &http::HeaderMap) -> bool {
.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"ACCESS"))
}
async fn head_metadata_action_allowed(req: &RequestEnvelope, action: S3Action) -> S3Result<bool> {
// Metadata permissions still bind the owner when a policy explicitly denies them.
let mut probe = req.fork_for_authorization();
let Some(info) = probe.req_info_mut() else {
return Ok(false);
};
info.suppress_denial_log = true;
info.suppress_denial_audit = true;
match authorize_request(&mut probe, Action::S3Action(action)).await {
Ok(()) => Ok(true),
Err(err) if err.code() == &S3ErrorCode::AccessDenied => Ok(false),
Err(err) => Err(err),
}
}
/// Source HEAD seam for the on-demand migration passthrough: production goes
/// through [`SourceClient`], tests script the answers.
pub(super) trait OdmHeadSource {
@@ -698,14 +683,6 @@ impl DefaultObjectUsecase {
.map(|expires| expires.format(RFC1123).map_err(S3Error::internal_error))
.transpose()?;
// Calculate tag count from user_tags already in ObjectInfo
// This avoids an additional API call since user_tags is already populated by get_object_info
let tag_count = if !info.user_tags.is_empty() {
let tag_set = decode_tags(&info.user_tags);
tag_set.len()
} else {
0
};
let effective_ec_block_size = info.effective_ec_block_size();
let dto = gateway_dto::HeadObjectOutput {
content_length: Some(content_length),
@@ -766,14 +743,7 @@ impl DefaultObjectUsecase {
response.headers.insert(EC_BLOCK_SIZE_RESPONSE_HEADER, value);
}
// Add x-amz-tagging-count header if object has tags
// Per S3 API spec, this header should be present in HEAD object response when tags exist
let tagging_action = if has_version_id {
S3Action::GetObjectVersionTaggingAction
} else {
S3Action::GetObjectTaggingAction
};
if tag_count > 0 && (replication_check || head_metadata_action_allowed(&req, tagging_action).await?) {
if let Some(tag_count) = readable_object_tag_count(&req, &info.user_tags, has_version_id, replication_check).await? {
let header_name = http::HeaderName::from_static(AMZ_TAG_COUNT);
if let Ok(header_value) = tag_count.to_string().parse::<HeaderValue>() {
response.headers.insert(header_name, header_value);
@@ -800,7 +770,7 @@ impl DefaultObjectUsecase {
]
.iter()
.any(|key| metadata_map.contains_key(*key))
&& head_metadata_action_allowed(&req, S3Action::GetObjectRetentionAction).await?);
&& object_metadata_action_allowed(&req, S3Action::GetObjectRetentionAction).await?);
if let Some(retain_date) = metadata_map
.get(AMZ_OBJECT_LOCK_RETAIN_UNTIL_DATE_LOWER)
.or_else(|| metadata_map.get(AMZ_OBJECT_LOCK_RETAIN_UNTIL_DATE))
@@ -822,7 +792,7 @@ impl DefaultObjectUsecase {
if let Some(legal_hold) = metadata_map
.get(AMZ_OBJECT_LOCK_LEGAL_HOLD_LOWER)
.or_else(|| metadata_map.get(AMZ_OBJECT_LOCK_LEGAL_HOLD))
&& (replication_check || head_metadata_action_allowed(&req, S3Action::GetObjectLegalHoldAction).await?)
&& (replication_check || object_metadata_action_allowed(&req, S3Action::GetObjectLegalHoldAction).await?)
&& let Ok(header_name) = http::HeaderName::from_bytes(AMZ_OBJECT_LOCK_LEGAL_HOLD_LOWER.as_bytes())
&& let Ok(header_value) = HeaderValue::from_str(legal_hold)
{
+1 -1
View File
@@ -549,7 +549,7 @@ impl DefaultObjectUsecase {
WriteEncryption::multipart(managed_material.key_bytes, managed_material.base_nonce, part_number)
}
};
write_plan = write_plan.with_encryption(managed_write);
write_plan = write_plan.with_encryption(managed_write.for_sse_type(managed_material.sse_type));
}
reader = write_plan.apply(reader, actual_size).map_err(ApiError::from)?;
+38
View File
@@ -27,6 +27,44 @@ pub(super) const RUSTFS_EXPECTED_CURRENT_VERSION_ID: &str = "x-rustfs-expected-c
pub(super) type S3StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
pub(super) async fn object_metadata_action_allowed(req: &RequestEnvelope, action: S3Action) -> S3Result<bool> {
// Metadata permissions still bind the owner when a policy explicitly denies them.
let mut probe = req.fork_for_authorization();
let Some(info) = probe.req_info_mut() else {
return Ok(false);
};
info.suppress_denial_log = true;
info.suppress_denial_audit = true;
match authorize_request(&mut probe, Action::S3Action(action)).await {
Ok(()) => Ok(true),
Err(err) if err.code() == &S3ErrorCode::AccessDenied => Ok(false),
Err(err) => Err(err),
}
}
pub(super) async fn readable_object_tag_count(
req: &RequestEnvelope,
user_tags: &str,
version_requested: bool,
replication_check: bool,
) -> S3Result<Option<i32>> {
if user_tags.is_empty() {
return Ok(None);
}
let count = decode_tags(user_tags).len();
let action = if version_requested {
S3Action::GetObjectVersionTaggingAction
} else {
S3Action::GetObjectTaggingAction
};
if count == 0 || !(replication_check || object_metadata_action_allowed(req, action).await?) {
return Ok(None);
}
i32::try_from(count)
.map(Some)
.map_err(|_| s3_error!(InternalError, "Stored object tag count exceeds the response limit"))
}
pub(super) async fn read_answer<T>(
bucket: &str,
method: &http::Method,
+2 -1
View File
@@ -504,7 +504,8 @@ pub(crate) fn site_replication_bootstrap_plan(
is_delete_req: false,
user_req: Some(AddOrUpdateUserReq {
secret_key,
policy: user.policy_name.clone(),
// Policy mappings follow the identities and carry their own timestamps.
policy: None,
status,
}),
api_version: Some(SITE_REPL_API_VERSION.to_string()),
+21 -1
View File
@@ -3809,6 +3809,17 @@ fn test_bootstrap_plan_carries_users_from_the_credential_snapshot() {
},
);
let user_updated_at = OffsetDateTime::from_unix_timestamp(1_700_000_500).expect("timestamp");
let mapping_updated_at = OffsetDateTime::from_unix_timestamp(1_700_000_600).expect("timestamp");
info.user_policies.insert(
"alice".to_string(),
SRPolicyMapping {
user_or_group: "alice".to_string(),
user_type: sr_wire_user_type(UserType::Reg, false),
policy: "readwrite".to_string(),
updated_at: Some(mapping_updated_at),
..Default::default()
},
);
let mut credentials = SiteReplicationIamCredentials::default();
credentials.users.insert(
"alice".to_string(),
@@ -3828,9 +3839,18 @@ fn test_bootstrap_plan_carries_users_from_the_credential_snapshot() {
let req = alice.user_req.as_ref().expect("user request");
assert_eq!(req.secret_key, "alice-secret");
assert_eq!(req.status, rustfs_madmin::AccountStatus::Disabled);
assert_eq!(req.policy.as_deref(), Some("readwrite"));
assert!(req.policy.is_none(), "user credentials must be replayable without attaching a policy");
// the user record's own axis, not the policy-mapping time list_users reports
assert_eq!(users[0].updated_at, Some(user_updated_at));
let item = plan
.iam_items
.iter()
.find(|item| item.r#type == "policy-mapping")
.expect("mapping");
let mapping = item.policy_mapping.as_ref().expect("policy mapping body");
assert_eq!(mapping.user_or_group, "alice");
assert_eq!(mapping.policy, "readwrite");
assert_eq!(item.updated_at, Some(mapping_updated_at));
}
fn service_account_snapshot(access_key: &str, parent: &str, status: &str) -> SiteReplicationServiceAccountSnapshot {
+1
View File
@@ -510,6 +510,7 @@ impl EncryptionMaterialExt for EncryptionMaterial {
}
(EncryptionKeyKind::Direct, None) => WriteEncryption::singlepart(self.key_bytes, self.base_nonce),
}
.for_sse_type(self.sse_type)
}
}
@@ -0,0 +1,29 @@
--- a/s3tests/functional/test_s3.py
+++ b/s3tests/functional/test_s3.py
@@ -9230,7 +9230,7 @@
# stat the object, check header
response = client.head_object(Bucket=bucket_name, Key=key1)
assert response['ResponseMetadata']['HTTPStatusCode'] == 200
- assert check_lifecycle_expiration_header(response, datetime.datetime.now(None), 'rule1', 1)
+ assert check_lifecycle_expiration_header(response, _utcnow_naive(), 'rule1', 1)
# test that header is not returning when it should not
lifecycle={
@@ -9252,7 +9252,7 @@
# stat the object, check header
response = client.head_object(Bucket=bucket_name, Key=key1)
assert response['ResponseMetadata']['HTTPStatusCode'] == 200
- assert check_lifecycle_expiration_header(response, datetime.datetime.now(None), 'rule1', 1) == False
+ assert check_lifecycle_expiration_header(response, _utcnow_naive(), 'rule1', 1) == False
@pytest.mark.lifecycle
@pytest.mark.lifecycle_expiration
@@ -9298,7 +9298,7 @@
# stat the object, check header
response = client.head_object(Bucket=bucket_name, Key=key1)
assert response['ResponseMetadata']['HTTPStatusCode'] == 200
- assert check_lifecycle_expiration_header(response, datetime.datetime.now(None), 'rule1', 1) == False
+ assert check_lifecycle_expiration_header(response, _utcnow_naive(), 'rule1', 1) == False
@pytest.mark.lifecycle
def test_lifecycle_set_noncurrent():