Compare commits

..

6 Commits

Author SHA1 Message Date
overtrue b4613da240 ci: scope admitted collector interaction preflight 2026-10-28 12:45:48 +08:00
overtrue 097f7603db test(scanner): bound and isolate collector subprocess 2026-10-28 12:41:20 +08:00
overtrue 7952608c03 test: cover admitted scanner collector cycles 2026-10-28 12:28:56 +08:00
overtrue 5ad283e28f Merge commit '8e88419f3a0c4741073c5ea46dd43c434be7f138' into overtrue/scanner-cycle-collector-main-8e88
# Conflicts:
#	crates/scanner/src/scanner_io/tests.rs
2026-10-28 12:08:25 +08:00
overtrue 2aaf979def Merge commit '7a3bf8cdbd781116a0970585b995ade668c0e662' into overtrue/scanner-cycle-collector-main-7a3b 2026-10-28 11:13:23 +08:00
overtrue a92abd89e5 fix(scanner): report incomplete collector observations 2026-10-28 02:21:21 +08:00
83 changed files with 1355 additions and 7913 deletions
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-darwin=67251cb7d9978d38e899268cac4d7898297ff7e5b5c48c9c1546dc760b93568d
sha256-linux=673da76c2e5710c4622fe2fa32d2b297730895769487fcf1152ee1c2366f32f4
sha256-darwin=a67a347f26be186c598b5beaf68e6bcbe1855350a35e1423dd5b8a81bcba06a5
sha256-linux=ad4fabe811c6cca1aba89fad34ccd404b5832a6a955875c2826f6e0fa1ea4f1f
+1 -1
View File
@@ -1 +1 @@
sha256=e9dc896774122a304e2b8b90f28c82d4d4e0af8ded36a82b147b30945ec994e3
sha256=f065e7071aac9d48a7c1b301f328fa7cc14f11c4e7dc46da3e55057c4ea29bd5
+2 -2
View File
@@ -128,7 +128,7 @@ setup = 'ecstore-large-stack'
# path on a real store; measured with RUST_MIN_STACK on 2026-10-15 they need
# 2016-2040 KiB of the 2 MiB libtest default and overflowed on Linux CI.
[[profile.default.scripts]]
filter = '(package(rustfs) & test(/^(admin::handlers::replication::target_repair_tests::[a-z_]+|admin::handlers::plugin_attempt::v2_tests::delegation_v2_persists_and_vends_with_real_parent_intersection|admin::handlers::site_replication::tests::durable_iam_state_apply_iam_item_rejects_a_stale_recreate_after_a_replicated_delete|admin::service::federated_identity::tests::(binding_keeps_explicit_iam_mapping_strict|markerless_legacy_oidc_session_crosses_auth_and_iam_deletion_boundaries)|storage::scanner_dirty_journal::tests::(clear_callback_keeps_unknown_coverage_until_all_pending_work_is_confirmed|owned_journals_keep_peer_records_after_interleaved_writes_and_clear))$/)) | (package(rustfs-heal) & ((binary(heal_b5_versioned_regression_test) & test(/^serial_tests::(test_heal_unversioned_bucket_e2e|test_historical_null_recursive_heal_restores_physical_versions|test_recursive_deep_heal_reports_stale_delete_marker_repair)$/)) | (binary(usage_observation_read_repair_test) & test(=usage_observation_read_repair_survives_snapshot_cleanup)))) | (package(rustfs-test-utils) & test(=data_usage_snapshot_tests::data_usage_snapshot_recovery_wires_primary_backup_and_negative_cache))'
filter = '(package(rustfs) & test(/^(admin::handlers::replication::target_repair_tests::[a-z_]+|admin::handlers::site_replication::tests::durable_iam_state_apply_iam_item_rejects_a_stale_recreate_after_a_replicated_delete|admin::service::federated_identity::tests::(binding_keeps_explicit_iam_mapping_strict|markerless_legacy_oidc_session_crosses_auth_and_iam_deletion_boundaries)|storage::scanner_dirty_journal::tests::(clear_callback_keeps_unknown_coverage_until_all_pending_work_is_confirmed|owned_journals_keep_peer_records_after_interleaved_writes_and_clear))$/)) | (package(rustfs-heal) & ((binary(heal_b5_versioned_regression_test) & test(/^serial_tests::(test_heal_unversioned_bucket_e2e|test_historical_null_recursive_heal_restores_physical_versions|test_recursive_deep_heal_reports_stale_delete_marker_repair)$/)) | (binary(usage_observation_read_repair_test) & test(=usage_observation_read_repair_survives_snapshot_cleanup)))) | (package(rustfs-test-utils) & test(=data_usage_snapshot_tests::data_usage_snapshot_recovery_wires_primary_backup_and_negative_cache))'
setup = 'ecstore-base-stack'
[[profile.default.scripts]]
@@ -419,7 +419,7 @@ setup = 'ecstore-large-stack'
# These cross-crate real-storage fixtures need the same bounded stack as ECStore tests.
[[profile.ci.scripts]]
filter = '(package(rustfs) & test(/^(admin::handlers::replication::target_repair_tests::[a-z_]+|admin::handlers::plugin_attempt::v2_tests::delegation_v2_persists_and_vends_with_real_parent_intersection|admin::handlers::site_replication::tests::durable_iam_state_apply_iam_item_rejects_a_stale_recreate_after_a_replicated_delete|admin::service::federated_identity::tests::(binding_keeps_explicit_iam_mapping_strict|markerless_legacy_oidc_session_crosses_auth_and_iam_deletion_boundaries)|storage::scanner_dirty_journal::tests::(clear_callback_keeps_unknown_coverage_until_all_pending_work_is_confirmed|owned_journals_keep_peer_records_after_interleaved_writes_and_clear))$/)) | (package(rustfs-heal) & ((binary(heal_b5_versioned_regression_test) & test(/^serial_tests::(test_heal_unversioned_bucket_e2e|test_historical_null_recursive_heal_restores_physical_versions|test_recursive_deep_heal_reports_stale_delete_marker_repair)$/)) | (binary(usage_observation_read_repair_test) & test(=usage_observation_read_repair_survives_snapshot_cleanup)))) | (package(rustfs-test-utils) & test(=data_usage_snapshot_tests::data_usage_snapshot_recovery_wires_primary_backup_and_negative_cache))'
filter = '(package(rustfs) & test(/^(admin::handlers::replication::target_repair_tests::[a-z_]+|admin::handlers::site_replication::tests::durable_iam_state_apply_iam_item_rejects_a_stale_recreate_after_a_replicated_delete|admin::service::federated_identity::tests::(binding_keeps_explicit_iam_mapping_strict|markerless_legacy_oidc_session_crosses_auth_and_iam_deletion_boundaries)|storage::scanner_dirty_journal::tests::(clear_callback_keeps_unknown_coverage_until_all_pending_work_is_confirmed|owned_journals_keep_peer_records_after_interleaved_writes_and_clear))$/)) | (package(rustfs-heal) & ((binary(heal_b5_versioned_regression_test) & test(/^serial_tests::(test_heal_unversioned_bucket_e2e|test_historical_null_recursive_heal_restores_physical_versions|test_recursive_deep_heal_reports_stale_delete_marker_repair)$/)) | (binary(usage_observation_read_repair_test) & test(=usage_observation_read_repair_survives_snapshot_cleanup)))) | (package(rustfs-test-utils) & test(=data_usage_snapshot_tests::data_usage_snapshot_recovery_wires_primary_backup_and_negative_cache))'
setup = 'ecstore-base-stack'
[[profile.ci.scripts]]
+2 -6
View File
@@ -16,7 +16,7 @@ Every other label in this repository is capacity RustFS pays for. ARC pods and l
| `sm-standard-2` | RustFS | ARC pod, Ubuntu 24.04, minimal image: no `gh`, no C toolchain; Docker only on the `dind-` label | only a job that a hosted runner cannot run (see the placement rule) |
| `sm-standard-4` | RustFS | ARC pod, Ubuntu 24.04, 14 CPUs and 28 GB (the label is not the core count), large disk | workspace-scale Cargo builds |
| `ubicloud-standard-16-arm` | RustFS | Ubicloud VM, alias of `ubicloud-standard-16-arm-ubuntu-2404`: Ubuntu 24.04 arm64, 16 vCPU, 48 GB, 300 GB disk. Reached through the `build.yml` matrix, so `actionlint.yaml` does not list it | native aarch64 release builds (`linux-aarch64-musl`, `linux-aarch64-gnu`) |
| `dind-sm-standard-2` | RustFS | ARC pod with Docker-in-Docker | Docker workloads with a measured resource or environment requirement beyond the hosted runner |
| `dind-sm-standard-2` | RustFS | ARC pod with Docker-in-Docker | image builds that need `buildx` and a registry push |
| `smoke-testing`, `pf-testing` | RustFS | long-lived lab machines | the packaged functional chain and performance suites |
The self-hosted pods and the hosted image are both Ubuntu 24.04, so a binary built on one runs on the other; `ci.yml` builds the debug binary on `sm-standard-4` and runs it on both pools.
@@ -27,15 +27,11 @@ A job runs on `ubuntu-latest` unless it has one of these reasons, and the reason
1. **Disk.** It restores or produces the workspace `target/`: `cargo build` or `cargo test` with `--all-targets`, `cargo nextest run --all`, or any reader of the `ci-dev` / `ci-feat-*` caches. The workspace test build leaves about 64 GB in `target/`; a hosted runner has about 14 GB.
2. **Critical-path CPU.** It is a build that several downstream lanes wait on and would blow its timeout at 4 vCPU (`build-rustfs-debug-binary` gates the e2e and s3-tests lanes).
3. **Hardware or environment.** Native aarch64 or access to the lab machines. Docker alone is not a reason: hosted Ubuntu ships Docker and supports the QEMU and Buildx setup actions.
3. **Hardware.** Native aarch64, Docker-in-Docker, or the lab machines.
4. **Cache ownership.** It reads a `rust-cache` key that a self-hosted job writes (see the cache rule below).
Jobs that do only the following have no reason to be self-hosted: shell or Python scripts, `cargo fmt`, `cargo deny`, typos, actionlint, API calls (`gh`, dependency review, issue and stale bots, CLA checks), downloading an artifact and running a prebuilt binary, or a `cargo build -p rustfs` with its own cache key. `e2e-distributed.yml` and `e2e-upgrade.yml` build the server and the `e2e_test` harness on `ubuntu-latest` inside their budgets, so "it compiles something" alone is not a reason.
The functional chain's `prepare` and `complete-chain` jobs, the performance runner availability check, and runner hygiene use `ubuntu-latest`: they inspect APIs or artifacts, not the lab hosts. The actual functional and performance suites remain on their lab runners. Functional-chain health collection stays on the operator-managed `smoke-testing` runner as part of the automation environment. Docker image packaging also uses `ubuntu-latest` for both musl and glibc variants; it downloads release binaries rather than compiling the workspace, and still sets up QEMU and Buildx explicitly.
Moving these jobs off AKS reduces capacity demand, not necessarily the Azure bill immediately. VM costs fall only when nodes scale down or smaller capacity replaces them.
A hosted runner is also the only choice for a few things the pods cannot do: `mount -o loop` and `mount -t tmpfs` fail inside the ARC pods, and a container runtime cannot guarantee that `io_uring_setup` is allowed. `uring-integration` and `e2e-distributed` are on `ubuntu-latest` for that reason, not for cost.
## Cache rule
+1 -1
View File
@@ -337,7 +337,7 @@ jobs:
name: Build Docker Images
needs: build-check
if: needs.build-check.outputs.should_build == 'true'
runs-on: ubuntu-latest
runs-on: dind-sm-standard-2
timeout-minutes: 60
strategy:
fail-fast: false
+1 -1
View File
@@ -44,7 +44,7 @@ jobs:
check-ephemerality:
if: github.repository == 'rustfs/rustfs'
name: Check runner ephemerality
runs-on: ubuntu-latest
runs-on: sm-standard-2
timeout-minutes: 15
steps:
- name: Checkout repository
@@ -42,7 +42,7 @@ concurrency:
jobs:
prepare:
if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.event == 'schedule' }}
runs-on: ubuntu-latest
runs-on: smoke-testing
timeout-minutes: 10
outputs:
manifest: ${{ steps.candidate.outputs.manifest }}
@@ -188,7 +188,7 @@ jobs:
complete-chain:
needs: [prepare, upgrade, s3, kms, tier, storage, heal, pool, security, replication, fault-tolerance, table, performance]
if: ${{ always() && needs.prepare.result != 'skipped' }}
runs-on: ubuntu-latest
runs-on: smoke-testing
timeout-minutes: 10
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
@@ -90,7 +90,7 @@ env:
jobs:
runner-check:
if: ${{ inputs.chain_manifest != '' || github.event_name == 'workflow_dispatch' || github.event_name == 'repository_dispatch' }}
runs-on: ubuntu-latest
runs-on: sm-standard-2
timeout-minutes: 5
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
+124 -204
View File
@@ -1,224 +1,144 @@
# Copyright 2024 RustFS Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
name: Windows Filesystem Tests
name: Scanner admitted collector cycle preflight
on:
push:
branches: [ main ]
paths:
- "crates/ecstore/src/disk/**"
- "crates/ecstore/src/layout/**"
- "crates/ecstore/src/store/init_format.rs"
- "crates/ecstore/src/set_disk/ops/locking.rs"
- "crates/ecstore/src/object_api/write_commit_context.rs"
- "crates/ecstore/src/bucket/utils.rs"
- "crates/ecstore/Cargo.toml"
- "crates/utils/src/dunce.rs"
- "crates/utils/src/os/**"
- "crates/utils/Cargo.toml"
- "crates/utils/src/path.rs"
- "rustfs/build.rs"
- "rustfs/Cargo.toml"
- "rustfs/src/main.rs"
- "rustfs/src/server/runtime.rs"
- "rustfs/src/startup_*.rs"
- "Cargo.toml"
- "Cargo.lock"
- ".github/actions/setup/**"
- ".github/workflows/windows-filesystem.yml"
pull_request:
branches: [ main ]
paths:
- "crates/ecstore/src/disk/**"
- "crates/ecstore/src/layout/**"
- "crates/ecstore/src/store/init_format.rs"
- "crates/ecstore/src/set_disk/ops/locking.rs"
- "crates/ecstore/src/object_api/write_commit_context.rs"
- "crates/ecstore/src/bucket/utils.rs"
- "crates/ecstore/Cargo.toml"
- "crates/utils/src/dunce.rs"
- "crates/utils/src/os/**"
- "crates/utils/Cargo.toml"
- "crates/utils/src/path.rs"
- "rustfs/build.rs"
- "rustfs/Cargo.toml"
- "rustfs/src/main.rs"
- "rustfs/src/server/runtime.rs"
- "rustfs/src/startup_*.rs"
- "Cargo.toml"
- "Cargo.lock"
- ".github/actions/setup/**"
- ".github/workflows/windows-filesystem.yml"
workflow_dispatch:
inputs:
expected_head:
description: Exact workflow commit SHA
required: true
type: string
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
group: scanner-admitted-collector-${{ github.ref }}
cancel-in-progress: false
env:
CARGO_TERM_COLOR: always
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
RUST_BACKTRACE: 1
CARGO_TERM_COLOR: never
CARGO_INCREMENTAL: '0'
CARGO_BUILD_JOBS: '1'
RUST_BACKTRACE: '0'
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: 'true'
NO_PROXY: 127.0.0.1,localhost
jobs:
rename-safety:
name: Rename Safety
runs-on: windows-latest
timeout-minutes: 60
scoped-test:
runs-on: ubuntu-latest
timeout-minutes: 110
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Setup Rust environment
uses: ./.github/actions/setup
with:
rust-version: stable
cache-shared-key: build-x86_64-pc-windows-msvc
cache-save-if: 'false'
install-build-packaging-tools: 'false'
install-test-tools: 'false'
- name: Check production Windows dependencies
shell: pwsh
run: cargo check -p rustfs-ecstore --lib
- name: Test guarded rename publication
shell: pwsh
run: cargo test -p rustfs-ecstore --lib rename_all_ -- --nocapture
- name: Test multipart parent durability barriers
shell: pwsh
run: cargo test -p rustfs-ecstore --lib multipart_owned_record_parent_barriers_ -- --nocapture
- name: Test Windows path conversion
shell: pwsh
run: "cargo test -p rustfs-utils --no-default-features --features path --lib dunce:: -- --nocapture"
- name: Test Windows volume and disk-space probes
shell: pwsh
- name: Prepare evidence
shell: bash
run: |
# Map a drive letter to the temp drive's administrative share so the
# remote-volume probe also covers mapped network drives.
$drive = (Split-Path -Qualifier ([System.IO.Path]::GetTempPath())).TrimEnd(':')
net use R: "\\localhost\$drive`$" /persistent:no
if ($LASTEXITCODE -eq 0) {
$env:RUSTFS_TEST_WINDOWS_MAPPED_DRIVE = 'R:'
} else {
Write-Output "::warning::could not map R: to \\localhost\$drive`$; mapped-drive test will skip"
}
cargo test -p rustfs-utils --features os --lib os:: -- --nocapture
$status = $LASTEXITCODE
if ($env:RUSTFS_TEST_WINDOWS_MAPPED_DRIVE) { net use R: /delete /y | Out-Null }
exit $status
set -euo pipefail
evidence="$RUNNER_TEMP/scanner-admitted-collector"
mkdir -p "$evidence"
printf '%s\n' 'not-started' > "$evidence/build.exit"
printf '%s\n' 'not-started' > "$evidence/test.exit"
- name: Test Windows handle guards
shell: pwsh
run: cargo test -p rustfs-ecstore --lib windows_ -- --nocapture
- name: Test endpoint path parsing
shell: pwsh
run: "cargo test -p rustfs-ecstore --lib layout::endpoint:: -- --nocapture"
- name: Test startup temporary-directory cleanup
shell: pwsh
run: cargo test -p rustfs-ecstore --lib cleanup_tmp_on_startup_ -- --nocapture
- name: Test object key Windows admission
shell: pwsh
run: "cargo test -p rustfs-ecstore --lib bucket::utils:: -- --nocapture"
- name: Test Windows file-name rules
shell: pwsh
run: "cargo test -p rustfs-utils --no-default-features --features path --lib dunce:: -- --nocapture"
- name: Test fresh format publication
shell: pwsh
run: cargo test -p rustfs-ecstore --lib fresh_format_load_initializes_all_disks -- --nocapture
# The native Windows main thread only gets the 1 MiB PE stack reserve, while
# Linux and macOS hand out 8 MiB. Startup runs the whole root future on the
# thread that calls `block_on`, so a debug server once overflowed before it
# listened on Windows only. Start a real server to keep that covered.
startup-smoke:
name: Startup Smoke
runs-on: windows-latest
timeout-minutes: 90
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
- name: Checkout
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a
with:
fetch-depth: 5
persist-credentials: false
clean: false
- name: Setup Rust environment
uses: ./.github/actions/setup
with:
rust-version: stable
cache-shared-key: build-x86_64-pc-windows-msvc
cache-save-if: 'false'
install-build-packaging-tools: 'false'
install-test-tools: 'false'
- name: Build debug server binary
shell: pwsh
run: cargo build --locked -p rustfs --bin rustfs
- name: Print version
shell: pwsh
run: |
& .\target\debug\rustfs.exe --version
if ($LASTEXITCODE -ne 0) { throw "rustfs --version exited with $LASTEXITCODE" }
- name: Start server and wait for readiness
shell: pwsh
- name: Verify source and workflow
shell: bash
env:
RUSTFS_ACCESS_KEY: rustfsadmin
RUSTFS_SECRET_KEY: rustfsadmin
EXPECTED_HEAD: ${{ inputs.expected_head }}
run: |
$volume = Join-Path $env:RUNNER_TEMP 'rustfs-startup-smoke'
$stdout = Join-Path $env:RUNNER_TEMP 'rustfs-startup-smoke.out.log'
$stderr = Join-Path $env:RUNNER_TEMP 'rustfs-startup-smoke.err.log'
New-Item -ItemType Directory -Force -Path $volume | Out-Null
$server = Start-Process -FilePath .\target\debug\rustfs.exe `
-ArgumentList @('--address', '127.0.0.1:9000', "`"$volume`"") `
-RedirectStandardOutput $stdout -RedirectStandardError $stderr `
-NoNewWindow -PassThru
# Cache the process handle now; otherwise ExitCode reads back empty.
$null = $server.Handle
$ready = $false
try {
for ($i = 0; $i -lt 180; $i++) {
if ($server.HasExited) { break }
try {
$response = Invoke-WebRequest -Uri 'http://127.0.0.1:9000/health/ready' -UseBasicParsing -NoProxy -TimeoutSec 2
if ($response.StatusCode -eq 200) { $ready = $true; break }
} catch {}
Start-Sleep -Seconds 1
}
} finally {
if (-not $server.HasExited) { Stop-Process -Id $server.Id -Force }
$server.WaitForExit()
Write-Host '--- server stdout (tail) ---'
Get-Content $stdout -Tail 100 -ErrorAction SilentlyContinue
Write-Host '--- server stderr (tail) ---'
Get-Content $stderr -Tail 100 -ErrorAction SilentlyContinue
}
if (-not $ready) {
throw ("rustfs did not report ready on /health/ready (exit code: {0})" -f $server.ExitCode)
}
set -euo pipefail
evidence="$RUNNER_TEMP/scanner-admitted-collector"
workflow_sha=$(git rev-parse HEAD)
source_sha=$(git rev-parse HEAD^)
test_sha=$(git rev-parse HEAD^^)
combination_sha=$(git rev-parse HEAD^^^)
main_sha=$(git rev-parse "${combination_sha}^2")
source_tree=$(git rev-parse "${source_sha}^{tree}")
test_diff=$(git diff --binary --full-index "$combination_sha" "$source_sha" | sha256sum | cut -d' ' -f1)
fix_diff=$(git diff --binary --full-index "$test_sha" "$source_sha" | sha256sum | cut -d' ' -f1)
source_files=$(git diff --name-only "$combination_sha" "$source_sha")
workflow_files=$(git diff --name-only "$source_sha" "$workflow_sha")
printf 'expected_head=%s\nhead=%s\nsource=%s\ntest_parent=%s\ncombination=%s\nmain=%s\nsource_tree=%s\ntest_diff=%s\nfix_diff=%s\nsource_files=%s\nworkflow_files=%s\n' \
"$EXPECTED_HEAD" "$workflow_sha" "$source_sha" "$test_sha" "$combination_sha" "$main_sha" \
"$source_tree" "$test_diff" "$fix_diff" "$source_files" "$workflow_files" | tee "$evidence/source-proof.txt"
[[ "$GITHUB_EVENT_NAME" == 'workflow_dispatch' ]]
[[ "$EXPECTED_HEAD" =~ ^[0-9a-f]{40}$ ]]
[[ "$workflow_sha" == "$EXPECTED_HEAD" && "$workflow_sha" == "$GITHUB_SHA" ]]
[[ "$source_sha" == '097f7603db1090f15e390e7e2cde316d148e395f' ]]
[[ "$test_sha" == '7952608c03bf3d42a28909b0d9f861dd84a3264f' ]]
[[ "$combination_sha" == '5ad283e28ffa0d16b82007c64df75901aaea5b21' ]]
[[ "$main_sha" == '8e88419f3a0c4741073c5ea46dd43c434be7f138' ]]
[[ "$source_tree" == '67db91a7d0556b8beaa5b903ca602c0981bf7434' ]]
[[ "$test_diff" == '2687c156f166ee2dc38861140210b3063c7f4fc7df656b3e4e2a733b619e11a3' ]]
[[ "$fix_diff" == 'a50801c7f457af9d3468d421dc1d14efec87be45f67d5af43abb59bc5707b6d6' ]]
[[ "$source_files" == 'crates/scanner/src/scanner_io/tests/cycle_collector_diagnostics.rs' ]]
[[ "$workflow_files" == '.github/workflows/windows-filesystem.yml' ]]
[[ -z "$(git status --porcelain)" ]]
printf '%s\n' \
'One exact parent unit test starts one isolated child that checks complete, cancelled and competing-revision local cycles.' \
'The successful child output is checked inside the parent and is not emitted as a separate log.' \
'No rejected old coordinator RPC or MRF responsibility-release test is selected; normal storage background activity can occur.' \
'This scoped preflight does not replace complete CI or distributed acceptance.' | tee "$evidence/scope.txt"
df -h . | tee "$evidence/disk.txt"
- name: Setup Rust
uses: ./.github/actions/setup
with:
rust-version: stable
cache-shared-key: ci-e2e-distributed-hosted
cache-save-if: 'false'
install-build-packaging-tools: 'false'
install-test-tools: 'false'
- name: Compile scanner library tests
shell: bash
timeout-minutes: 80
run: |
set -euo pipefail
evidence="$RUNNER_TEMP/scanner-admitted-collector"
set +e
timeout --signal=TERM --kill-after=30s 75m \
cargo test --locked -p rustfs-scanner --lib --no-run > "$evidence/build.log" 2>&1
status=$?
set -e
printf '%s\n' "$status" > "$evidence/build.exit"
tail -n 100 "$evidence/build.log"
exit "$status"
- name: Run the exact collector test
shell: bash
timeout-minutes: 10
run: |
set -euo pipefail
evidence="$RUNNER_TEMP/scanner-admitted-collector"
test_name='scanner_io::tests::cycle_collector_diagnostics::collector_cycle_with_node_admission_preserves_cache_and_reports_outcomes'
printf '%s\n' "$test_name" > "$evidence/selection.txt"
if [[ -v RUSTFS_TEST_ADMITTED_COLLECTOR_CHILD ]]; then
printf '%s\n' 'Unexpected parent child marker' | tee "$evidence/environment.txt"
exit 1
fi
printf '%s\n' 'parent_child_marker=unset' | tee "$evidence/environment.txt"
set +e
timeout --signal=TERM --kill-after=15s 8m \
cargo test --locked -p rustfs-scanner --lib -- --exact "$test_name" --nocapture > "$evidence/test.log" 2>&1
status=$?
set -e
printf '%s\n' "$status" > "$evidence/test.exit"
tail -n 120 "$evidence/test.log"
selected=$(grep -Fxc 'running 1 test' "$evidence/test.log" || true)
passed=$(grep -Fxc "test $test_name ... ok" "$evidence/test.log" || true)
summary=$(grep -Fc 'test result: ok. 1 passed; 0 failed; 0 ignored;' "$evidence/test.log" || true)
printf 'exit=%s selected=%s passed=%s summary=%s\n' "$status" "$selected" "$passed" "$summary" | tee "$evidence/verification.txt"
[[ "$status" -eq 0 && "$selected" -eq 1 && "$passed" -eq 1 && "$summary" -eq 1 ]]
- name: Preserve evidence
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
name: scanner-admitted-collector-${{ github.run_id }}
path: ${{ runner.temp }}/scanner-admitted-collector/
if-no-files-found: error
retention-days: 14
-1
View File
@@ -100,7 +100,6 @@ when restoring `/rustfs/console` for a custom OEM build.
## S3 API environment variables
- `RUSTFS_API_OBJECT_MAX_VERSIONS` caps the number of retained versions for a single object. It defaults to `9223372036854775807`, matching MinIO's practical-unlimited default. Set a positive integer to enforce a lower per-object metadata bound.
- `RUSTFS_VEEAM_SOSAPI_ENABLE` serves Veeam SOSAPI `system.xml` and `capacity.xml` for an authenticated GET or HEAD of those exact bucket-root keys. It defaults to `true`. Explicit version reads use the normal object path. Capacity requests return `ServiceUnavailable` until the scanner publishes a complete snapshot certified for the current bucket incarnation and authoritative quota metadata can be read. Legacy or mixed-version snapshots without an incarnation proof cannot serve capacity until a compatible scanner publishes a certified snapshot. Capacity also returns `ServiceUnavailable` when cluster or disk observations are missing, stale, or degraded. Retry after scanner convergence and storage or metadata recovery. Capacity assumes shard paths have independent backing space; shared physical storage can make the estimate optimistic. Set the flag to `false` to restore the normal object path, including deletion of a real object previously stored at that key.
- `MINIO_API_OBJECT_MAX_VERSIONS` is accepted as a compatibility alias when the canonical RustFS variable is not set.
## Distributed endpoint locality
-10
View File
@@ -222,16 +222,6 @@ pub const ENV_RUSTFS_TLS_PATH: &str = "RUSTFS_TLS_PATH";
/// Environment variable for server KMS enable.
pub const ENV_RUSTFS_KMS_ENABLE: &str = "RUSTFS_KMS_ENABLE";
/// Environment variable for Veeam SOSAPI virtual system objects.
///
/// When true (the default), authenticated GET and HEAD of the two Veeam
/// SOSAPI keys return generated XML. When false, those keys use the normal
/// object path so an operator can remove a real object stored there earlier.
pub const ENV_VEEAM_SOSAPI_ENABLE: &str = "RUSTFS_VEEAM_SOSAPI_ENABLE";
/// Default Veeam SOSAPI enablement.
pub const DEFAULT_VEEAM_SOSAPI_ENABLE: bool = true;
/// Default KMS enable for server-side encryption
/// This is the default value for enabling KMS encryption for server-side encryption.
/// Default value: false
-31
View File
@@ -466,9 +466,6 @@ pub struct BucketTargetUsageInfo {
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BucketUsageInfo {
pub size: u64,
/// Bucket identity certified by every set contributing to this snapshot.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bucket_incarnation: Option<String>,
// Following five fields suffixed with V1 are here for backward compatibility
// Total Size for objects that have not yet been replicated
pub replication_pending_size_v1: u64,
@@ -2319,9 +2316,6 @@ impl BucketUsageInfo {
/// Add size summary to this bucket usage
/// Merge another BucketUsageInfo into this one
pub fn merge(&mut self, other: &BucketUsageInfo) {
if self.bucket_incarnation != other.bucket_incarnation {
self.bucket_incarnation = None;
}
self.size += other.size;
self.objects_count += other.objects_count;
self.versions_count += other.versions_count;
@@ -3305,31 +3299,6 @@ mod tests {
assert_eq!(usage1.versions_count, 15);
}
#[test]
fn bucket_usage_merge_discards_incompatible_incarnation_proofs() {
let id = "00000000-0000-4000-8000-000000000001";
let mut same = BucketUsageInfo {
bucket_incarnation: Some(id.into()),
..Default::default()
};
same.merge(&BucketUsageInfo {
bucket_incarnation: Some(id.into()),
..Default::default()
});
assert_eq!(same.bucket_incarnation.as_deref(), Some(id));
same.merge(&BucketUsageInfo::default());
assert!(same.bucket_incarnation.is_none());
let mut different = BucketUsageInfo {
bucket_incarnation: Some(id.into()),
..Default::default()
};
different.merge(&BucketUsageInfo {
bucket_incarnation: Some("00000000-0000-4000-8000-000000000002".into()),
..Default::default()
});
assert!(different.bucket_incarnation.is_none());
}
#[test]
fn size_summary_add_saturates_instead_of_overflowing() {
// The scanner folds one summary per object into a per-prefix total, so a
@@ -38,8 +38,6 @@ mod tests {
use tracing::info;
const PAGINATION_TIMEOUT: Duration = Duration::from_secs(120);
// Bound queued durable commits on the single fixture disk under CI I/O pressure.
const FIXTURE_PUT_CONCURRENCY: usize = 4;
// Fixture population can require thousands of durable PUTs. Bound the
// listing traversal itself with one deadline shared by every page.
@@ -566,7 +564,7 @@ mod tests {
let object_count = 1002;
// Finish every durable PUT before listing, with the same bounded fanout as the delimiter fixtures.
stream::iter(0..object_count)
.for_each_concurrent(FIXTURE_PUT_CONCURRENCY, |i| {
.for_each_concurrent(16, |i| {
let client = &client;
async move {
let key = format!("object{i:04}.txt");
@@ -577,7 +575,7 @@ mod tests {
.body(ByteStream::from_static(b"test content"))
.send()
.await
.unwrap_or_else(|err| panic!("Failed to put fixture object {key}: {err:?}"));
.unwrap_or_else(|err| panic!("Failed to put fixture object {key}: {err}"));
}
})
.await;
@@ -824,7 +822,7 @@ mod tests {
.flat_map(|dir| (0..10).map(move |file| format!("dir-{dir:03}/file{file:02}.txt")))
.collect();
stream::iter(&all_keys)
.for_each_concurrent(FIXTURE_PUT_CONCURRENCY, |key| {
.for_each_concurrent(16, |key| {
let client = &client;
async move {
client
@@ -834,7 +832,7 @@ mod tests {
.body(ByteStream::from_static(b"x"))
.send()
.await
.unwrap_or_else(|err| panic!("Failed to put fixture object {key}: {err:?}"));
.unwrap_or_else(|err| panic!("Failed to put fixture object {key}: {err}"));
}
})
.await;
@@ -1057,7 +1055,7 @@ mod tests {
let files_per_dir = 100;
let fixture_started = std::time::Instant::now();
stream::iter((0..dir_count).flat_map(|d| (0..files_per_dir).map(move |f| (d, f))))
.for_each_concurrent(FIXTURE_PUT_CONCURRENCY, |(d, f)| {
.for_each_concurrent(16, |(d, f)| {
let client = &client;
async move {
let key = format!("dir-{d:02}/file{f:03}.txt");
@@ -1068,7 +1066,7 @@ mod tests {
.body(ByteStream::from_static(b"x"))
.send()
.await
.unwrap_or_else(|err| panic!("Failed to put fixture object {key}: {err:?}"));
.unwrap_or_else(|err| panic!("Failed to put fixture object {key}: {err}"));
}
})
.await;
@@ -261,61 +261,6 @@ mod tests {
archive
}
#[tokio::test]
async fn snowball_auto_extract_rejects_veeam_virtual_members() -> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server_with_env(vec![], &[("RUSTFS_VEEAM_SOSAPI_ENABLE", "true")])
.await?;
let client = env.create_s3_client();
let bucket = "snowball-veeam-reserved";
client.create_bucket().bucket(bucket).send().await?;
let prefix = ".system-d26a9498-cb7c-4a87-a44a-8ae204f5ba6c";
for (member, destination, use_prefix) in [
(format!("{prefix}/system.xml"), format!("{prefix}/system.xml"), false),
("capacity.xml".to_string(), format!("{prefix}/capacity.xml"), true),
] {
let mut builder = tokio_tar::Builder::new(Cursor::new(Vec::new()));
append_typed_entry(&mut builder, &member, tokio_tar::EntryType::Regular, b"blocked").await?;
let archive = builder.into_inner().await?.into_inner();
let mut request = client
.put_object()
.bucket(bucket)
.key("fixture.tar")
.metadata("Snowball-Auto-Extract", "true")
.body(ByteStream::from(archive));
if use_prefix {
request = request
.metadata("Minio-Snowball-Prefix", prefix)
.metadata("Minio-Snowball-Ignore-Errors", "true");
}
let error = request.send().await.expect_err("virtual archive members must be rejected");
assert_eq!(error.code(), Some("MethodNotAllowed"));
let listed = client.list_objects_v2().bucket(bucket).prefix(&destination).send().await?;
assert!(listed.contents().is_empty(), "rejected virtual member must not be stored");
}
let mut builder = tokio_tar::Builder::new(Cursor::new(Vec::new()));
append_typed_entry(&mut builder, "ordinary.xml", tokio_tar::EntryType::Regular, b"ordinary").await?;
client
.put_object()
.bucket(bucket)
.key("fixture.tar")
.metadata("Snowball-Auto-Extract", "true")
.metadata("Minio-Snowball-Prefix", prefix)
.body(ByteStream::from(builder.into_inner().await?.into_inner()))
.send()
.await?;
let ordinary = client
.get_object()
.bucket(bucket)
.key(format!("{prefix}/ordinary.xml"))
.send()
.await?;
assert_eq!(ordinary.body.collect().await?.into_bytes().as_ref(), b"ordinary");
env.stop_server();
Ok(())
}
#[tokio::test]
async fn snowball_auto_extract_supports_minio_prefix_and_directory_markers() -> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
@@ -600,154 +600,6 @@ mod tests {
info!("✅ PASSED: Veeam backup workflow simulation completed successfully");
}
/// Veeam B&R discovers SOSAPI by GET/HEAD of two well-known keys.
#[tokio::test]
async fn test_veeam_sosapi_system_and_capacity() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
use crate::common::local_http_client;
const SYSTEM_KEY: &str = ".system-d26a9498-cb7c-4a87-a44a-8ae204f5ba6c/system.xml";
const CAPACITY_KEY: &str = ".system-d26a9498-cb7c-4a87-a44a-8ae204f5ba6c/capacity.xml";
init_logging();
info!("🧪 TEST: Veeam SOSAPI system.xml and capacity.xml");
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server_with_env(vec![], crate::common::FAST_DATA_USAGE_SCANNER_ENV)
.await?;
let client = create_s3_client(&env);
let bucket = "veeam-sosapi";
create_bucket(&client, bucket).await?;
let system = client.get_object().bucket(bucket).key(SYSTEM_KEY).send().await?;
let system_etag = system.e_tag().map(str::to_string);
let system_len = system.content_length();
assert_eq!(system.content_type(), Some("application/xml"));
let system_body = system.body.collect().await?.into_bytes();
let system_xml = std::str::from_utf8(&system_body)?;
assert!(system_xml.contains("<ProtocolVersion>\"1.0\"</ProtocolVersion>"), "{system_xml}");
assert!(
system_xml.contains("<ModelName>\"RustFS ") && system_xml.contains("\"</ModelName>"),
"{system_xml}"
);
assert!(system_xml.contains("<CapacityInfo>true</CapacityInfo>"));
assert!(system_xml.contains("<UploadSessions>false</UploadSessions>"));
assert!(system_xml.contains("<IAMSTS>false</IAMSTS>"));
assert!(!system_xml.contains("SystemRecommendations"));
assert!(!system_xml.contains("APIEndpoints"));
assert!(!system_xml.contains("&quot;"));
let head = client.head_object().bucket(bucket).key(SYSTEM_KEY).send().await?;
assert_eq!(head.content_type(), Some("application/xml"));
assert_eq!(head.content_length(), system_len);
assert_eq!(head.e_tag().map(str::to_string), system_etag);
assert!(head.last_modified().is_some());
let ranged = client
.get_object()
.bucket(bucket)
.key(SYSTEM_KEY)
.range("bytes=0-3")
.send()
.await?;
assert_eq!(ranged.content_length(), Some(4));
let ranged_header = ranged.content_range().unwrap_or("");
assert!(ranged_header.starts_with("bytes 0-3/"), "{ranged_header}");
let ranged_body = ranged.body.collect().await?.into_bytes();
assert_eq!(&ranged_body[..], &system_body[..4]);
let capacity = tokio::time::timeout(std::time::Duration::from_secs(180), async {
loop {
match client.get_object().bucket(bucket).key(CAPACITY_KEY).send().await {
Ok(capacity) => break Ok(capacity),
Err(err) if err.code() == Some("ServiceUnavailable") => {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
}
Err(err) => break Err(err),
}
}
})
.await??;
assert_eq!(capacity.content_type(), Some("application/xml"));
let capacity_body = capacity.body.collect().await?.into_bytes();
let capacity_xml = std::str::from_utf8(&capacity_body)?;
let capacity_value = xml_u64(capacity_xml, "Capacity")?;
let available_value = xml_u64(capacity_xml, "Available")?;
let used_value = xml_u64(capacity_xml, "Used")?;
assert!(used_value <= capacity_value, "{capacity_xml}");
assert!(available_value <= capacity_value.saturating_sub(used_value), "{capacity_xml}");
let put_err = client
.put_object()
.bucket(bucket)
.key(SYSTEM_KEY)
.body(ByteStream::from_static(b"overwrite"))
.send()
.await
.expect_err("SOSAPI put must fail");
assert_eq!(put_err.code(), Some("MethodNotAllowed"));
let delete_err = client
.delete_object()
.bucket(bucket)
.key(CAPACITY_KEY)
.send()
.await
.expect_err("SOSAPI delete must fail");
assert_eq!(delete_err.code(), Some("MethodNotAllowed"));
let normal_key = "Veeam/Backup/job.dat";
client
.put_object()
.bucket(bucket)
.key(normal_key)
.body(ByteStream::from_static(b"backup-bytes"))
.send()
.await?;
let normal = client.get_object().bucket(bucket).key(normal_key).send().await?;
let normal_body = normal.body.collect().await?.into_bytes();
assert_eq!(&normal_body[..], b"backup-bytes");
let anon = local_http_client()
.get(format!("{}/{bucket}/{SYSTEM_KEY}", env.url))
.send()
.await?;
assert_eq!(anon.status(), reqwest::StatusCode::FORBIDDEN);
let anon_body = anon.text().await?;
assert!(!anon_body.contains("ProtocolVersion"), "{anon_body}");
let now = time::OffsetDateTime::now_utc();
let scope_date = format!("{:04}{:02}{:02}", now.year(), u8::from(now.month()), now.day());
let amz_date = format!("{scope_date}T{:02}{:02}{:02}Z", now.hour(), now.minute(), now.second());
let bad = local_http_client()
.get(format!("{}/{bucket}/{SYSTEM_KEY}", env.url))
.header("x-amz-date", &amz_date)
.header("x-amz-content-sha256", "UNSIGNED-PAYLOAD")
.header(
"authorization",
format!(
"AWS4-HMAC-SHA256 Credential=bad/{scope_date}/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=0000000000000000000000000000000000000000000000000000000000000000"
),
)
.send()
.await?;
assert_eq!(bad.status(), reqwest::StatusCode::FORBIDDEN);
let bad_body = bad.text().await?;
assert!(!bad_body.contains("ProtocolVersion"), "{bad_body}");
info!("✅ PASSED: Veeam SOSAPI system.xml and capacity.xml");
Ok(())
}
fn xml_u64(xml: &str, element: &str) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
let start = format!("<{element}>");
let end = format!("</{element}>");
let start_idx = xml.find(&start).ok_or_else(|| format!("missing {element} in {xml}"))? + start.len();
let end_idx = xml[start_idx..]
.find(&end)
.ok_or_else(|| format!("unclosed {element} in {xml}"))?
+ start_idx;
Ok(xml[start_idx..end_idx].parse()?)
}
#[tokio::test]
async fn test_terraform_put_after_delete() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
init_logging();
+4 -14
View File
@@ -252,7 +252,7 @@ pub mod bucket {
pub mod quota {
pub use crate::bucket::quota::{
BucketQuota, QUOTA_RESERVATION_PROTOCOL_V1, QUOTA_RESERVATION_PROTOCOL_V2, QuotaCheckResult, QuotaError,
QuotaMigrationSkipReason, QuotaOperation, QuotaProtocolMigration, QuotaType,
QuotaMigrationSkipReason, QuotaOperation, QuotaProtocolMigration,
};
pub mod checker {
@@ -371,15 +371,6 @@ pub mod compression {
pub mod config {
pub mod com {
/// Preserve empty existing objects so callers can distinguish corruption from absence.
pub async fn read_config_preserve_empty_with_metadata_opts(
api: std::sync::Arc<crate::store::ECStore>,
file: &str,
opts: &crate::object_api::ObjectOptions,
) -> crate::error::Result<(Vec<u8>, crate::object_api::ObjectInfo)> {
crate::config::com::read_config_preserve_empty_with_metadata_opts(api, file, opts).await
}
pub use crate::config::com::{
COMMA_SEPARATED_LISTS, CONFIG_PREFIX, ENV_CONFIG_RECOVER_ON_CORRUPTION, STORAGE_CLASS_SUB_SYS,
ServerConfigCorruptError, ServerConfigSaveResult, ServerConfigSnapshot, delete_config, delete_config_no_lock,
@@ -425,10 +416,9 @@ pub mod data_usage {
DATA_USAGE_CACHE_NAME, apply_bucket_usage_memory_overlay, compute_bucket_usage,
init_compression_total_memory_from_backend, invalidate_admin_data_usage_snapshot_cache,
invalidate_data_usage_snapshot_cache, live_bucket_usage_computations, load_admin_data_usage_from_backend_cached,
load_bucket_usage_from_backend_cached, load_compression_total_from_memory, load_data_usage_from_backend,
load_data_usage_from_backend_cached, quota_object_size, record_bucket_delete_marker_memory,
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,
record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
load_compression_total_from_memory, load_data_usage_from_backend, load_data_usage_from_backend_cached, quota_object_size,
record_bucket_delete_marker_memory, record_bucket_object_delete_memory, record_bucket_object_version_write_memory,
record_bucket_object_write_memory, record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
refresh_bucket_usage_from_object_layer, refresh_versioned_bucket_usage_from_object_layer,
remove_bucket_usage_from_backend, replace_bucket_usage_memory_from_info, store_compression_total_in_backend,
store_data_usage_in_backend,
@@ -63,7 +63,14 @@ pub(crate) async fn get_expiry_configs_for_options(
bucket: &str,
opts: &crate::object_api::ObjectOptions,
) -> Result<LifecycleExpiryConfigs> {
let bucket_incarnation_id = metadata_sys::get_bucket_incarnation_id_for_options_in(&api.ctx, bucket, opts).await?;
let bucket_incarnation_id = match opts
.object_lock_config_snapshot
.as_ref()
.and_then(|snapshot| snapshot.validated_bucket_incarnation_for(api.id, bucket, opts.expected_bucket_incarnation_id))
{
Some(incarnation_id) => incarnation_id,
None => metadata_sys::get_bucket_incarnation_id_for_options_in(&api.ctx, bucket, opts).await?,
};
let metadata = get_authoritative_metadata(api, bucket, bucket_incarnation_id).await?;
let table_bucket_enabled = metadata.table_bucket_enabled();
+1 -28
View File
@@ -564,39 +564,12 @@ pub(crate) async fn validate_bucket_reconstruction_in(
Ok(())
}
/// Resolve the authoritative bucket incarnation id for `opts`:
/// 1. When namespace locking is enabled and `opts.object_lock_config_snapshot` is
/// present, validate and return the snapshot's incarnation under its held
/// lifecycle and metadata-transaction fences.
/// 2. When namespace locking is enabled and `opts.bucket_lifecycle_lock_fence` is
/// present and not lost, reuse the store's `BucketFenceRegistry` memo if a
/// registered lifecycle read guard is currently held without lock loss.
/// 3. Otherwise, acquire the bucket metadata transaction read lock (unless
/// already held on `opts`) and read the incarnation from disk.
/// Validate against disk while retaining an already-held Object Lock fence.
pub(crate) async fn get_bucket_incarnation_id_for_options_in(
ctx: &crate::runtime::instance::InstanceContext,
bucket: &str,
opts: &ObjectOptions,
) -> Result<Uuid> {
if !ctx.lock_manager().is_disabled() {
if let Some(snapshot) = opts.object_lock_config_snapshot.as_ref() {
let store = object_store_in(ctx).await?;
return snapshot
.validated_bucket_incarnation_for(store.id, bucket, opts.expected_bucket_incarnation_id)
.ok_or_else(|| {
Error::other("Object Lock snapshot does not hold a valid metadata transaction fence for this bucket")
});
}
if opts
.bucket_lifecycle_lock_fence
.as_ref()
.is_some_and(|fence| !fence.is_lock_lost())
&& let Some(store) = object_store_if_initialized_in(ctx).await
&& let Some(incarnation) = store.bucket_fence_registry.validated_incarnation(bucket)
{
return Ok(incarnation);
}
}
let sys = bucket_metadata_sys_of(ctx)?;
let sys = sys.read().await.clone();
let guard = acquire_bucket_metadata_transaction_read_lock_for_options_in(ctx, bucket, opts).await?;
-12
View File
@@ -488,18 +488,6 @@ where
Ok(data)
}
/// Read config bytes and metadata while preserving an existing empty payload.
pub(crate) async fn read_config_preserve_empty_with_metadata_opts<S>(
api: Arc<S>,
file: &str,
opts: &ObjectOptions,
) -> Result<(Vec<u8>, ObjectInfo)>
where
S: EcstoreObjectIO,
{
read_config_with_metadata_inner(api, file, opts, true, None).await
}
pub async fn read_config_no_lock<S>(api: Arc<S>, file: &str) -> Result<Vec<u8>>
where
S: ObjectIO<
-42
View File
@@ -1493,48 +1493,6 @@ pub async fn load_data_usage_from_backend_cached(store: Arc<ECStore>) -> Result<
project_data_usage_from_backend_cached(store, DataUsageInfo::clone).await
}
/// Read one bucket's persisted usage without cloning the complete snapshot.
pub async fn load_bucket_usage_from_backend_cached(
store: Arc<ECStore>,
bucket: &str,
incarnation: uuid::Uuid,
) -> Result<Option<u64>, Error> {
project_data_usage_from_backend_cached(store, |info| certified_bucket_usage(info, bucket, incarnation)).await
}
fn certified_bucket_usage(info: &DataUsageInfo, bucket: &str, incarnation: uuid::Uuid) -> Option<u64> {
if incarnation.is_nil()
|| !info.is_complete_bucket_usage_snapshot()
|| info.usage_snapshot_observational
|| info.scanner_cycle.is_none()
|| info.scanner_epoch.is_none()
{
return None;
}
let pending_count = u64::try_from(info.usage_snapshot_pending_buckets.len()).ok()?;
if pending_count != info.usage_snapshot_pending_bucket_count {
return None;
}
match info.usage_snapshot_converged {
Some(true) if pending_count == 0 => {}
Some(false)
if pending_count > 0
&& info.usage_snapshot_pending_buckets.windows(2).all(|pair| pair[0] < pair[1])
&& info
.usage_snapshot_pending_buckets
.binary_search_by(|pending| pending.as_str().cmp(bucket))
.is_err() => {}
_ => return None,
}
let usage = info.buckets_usage.get(bucket)?;
let certified = usage
.bucket_incarnation
.as_deref()
.and_then(|id| uuid::Uuid::parse_str(id).ok())
.filter(|id| !id.is_nil())?;
(certified == incarnation).then_some(usage.size)
}
// Project under the cache guard so scalar readers never copy the snapshot's
// bucket maps. The owned API shares the same TTL, refresh and invalidation path.
async fn project_data_usage_from_backend_cached<T>(
@@ -129,41 +129,6 @@ fn projected_publication_moves_bucket_maps_into_cache() {
);
}
#[test]
fn certified_bucket_usage_rejects_unproven_and_pending_data() {
let id = uuid::Uuid::from_u128(7);
let mut info = data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH);
info.usage_snapshot_converged = Some(true);
info.scanner_cycle = Some(1);
info.scanner_epoch = Some(1);
info.buckets_usage.get_mut("known").unwrap().bucket_incarnation = Some(id.to_string());
assert_eq!(certified_bucket_usage(&info, "known", id), Some(42));
assert_eq!(certified_bucket_usage(&info, "known", uuid::Uuid::from_u128(8)), None);
assert_eq!(certified_bucket_usage(&info, "known", uuid::Uuid::nil()), None);
let mut legacy = info.clone();
legacy.buckets_usage.get_mut("known").unwrap().bucket_incarnation = None;
assert_eq!(certified_bucket_usage(&legacy, "known", id), None);
legacy.buckets_usage.get_mut("known").unwrap().bucket_incarnation = Some("corrupt".into());
assert_eq!(certified_bucket_usage(&legacy, "known", id), None);
let mut pending = info.clone();
pending.usage_snapshot_converged = Some(false);
pending.usage_snapshot_pending_buckets = vec!["other".into()];
pending.usage_snapshot_pending_bucket_count = 1;
assert_eq!(certified_bucket_usage(&pending, "known", id), Some(42));
pending.usage_snapshot_pending_buckets = vec!["known".into()];
assert_eq!(certified_bucket_usage(&pending, "known", id), None);
pending.usage_snapshot_pending_bucket_count = 0;
assert_eq!(certified_bucket_usage(&pending, "known", id), None);
pending.usage_snapshot_pending_buckets = vec!["z".into(), "a".into()];
pending.usage_snapshot_pending_bucket_count = 2;
assert_eq!(certified_bucket_usage(&pending, "known", id), None);
let mut observational = info.clone();
observational.usage_snapshot_observational = true;
assert_eq!(certified_bucket_usage(&observational, "known", id), None);
info.usage_snapshot_converged = None;
assert_eq!(certified_bucket_usage(&info, "known", id), None);
}
#[tokio::test]
#[serial]
async fn persisted_scalar_projection_shares_cache_refresh_and_invalidation() {
@@ -175,13 +140,6 @@ async fn persisted_scalar_projection_shares_cache_refresh_and_invalidation() {
info.buckets_usage.insert("empty".to_string(), BucketUsageInfo::default());
info.bucket_sizes.insert("empty".to_string(), 0);
info.buckets_count = 2;
info.usage_snapshot_converged = Some(true);
info.scanner_cycle = Some(1);
info.scanner_epoch = Some(1);
let incarnation = uuid::Uuid::from_u128(7);
for usage in info.buckets_usage.values_mut() {
usage.bucket_incarnation = Some(incarnation.to_string());
}
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
@@ -193,29 +151,11 @@ async fn persisted_scalar_projection_shares_cache_refresh_and_invalidation() {
for (bucket, expected) in [("known", Some(42)), ("empty", Some(0)), ("missing", None)] {
assert_eq!(persisted_bucket_usage(store.clone(), bucket).await, expected);
assert_eq!(
load_bucket_usage_from_backend_cached(store.clone(), bucket, incarnation)
.await
.expect("project bucket usage"),
expected
);
let owned = load_data_usage_from_backend_cached(store.clone())
.await
.expect("owned cached snapshot");
assert_eq!(expected, owned.buckets_usage.get(bucket).map(|usage| usage.size));
}
assert_eq!(
load_bucket_usage_from_backend_cached(store.clone(), "known", uuid::Uuid::from_u128(8))
.await
.unwrap(),
None
);
assert_eq!(
load_bucket_usage_from_backend_cached(store.clone(), "known", uuid::Uuid::nil())
.await
.unwrap(),
None
);
info.buckets_usage.get_mut("known").expect("known bucket").size = 84;
info.bucket_sizes.insert("known".to_string(), 84);
save_config(
@@ -40,35 +40,9 @@ pub(crate) mod test_hooks {
use std::sync::{Arc, Mutex};
type Hook = Arc<dyn Fn() -> BoxFuture<'static, ()> + Send + Sync>;
type TransactionLockHook = Arc<dyn Fn(&rustfs_lock::NamespaceLockGuard) + Send + Sync>;
static BEFORE_GC_FINALIZE: Mutex<Vec<(String, String, Hook)>> = Mutex::new(Vec::new());
static CLEANUP_ATTEMPTS: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new());
static AFTER_TRANSACTION_LOCK: Mutex<Vec<(String, String, TransactionLockHook)>> = Mutex::new(Vec::new());
pub(crate) fn after_transaction_lock_acquired(bucket: &str, object: &str, hook: TransactionLockHook) {
AFTER_TRANSACTION_LOCK
.lock()
.expect("transaction lock hooks")
.push((bucket.to_owned(), object.to_owned(), hook));
}
pub(in crate::set_disk) fn run_after_transaction_lock_acquired(
bucket: &str,
object: &str,
guard: &rustfs_lock::NamespaceLockGuard,
) {
let hook = {
let mut hooks = AFTER_TRANSACTION_LOCK.lock().expect("transaction lock hooks");
hooks
.iter()
.position(|(hook_bucket, hook_object, _)| hook_bucket == bucket && hook_object == object)
.map(|index| hooks.remove(index).2)
};
if let Some(hook) = hook {
hook(guard);
}
}
pub(super) fn record_cleanup_attempt(bucket: &str, object: &str) {
CLEANUP_ATTEMPTS
@@ -138,7 +112,6 @@ pub(crate) struct DeleteRecoveryContext<'a> {
/// Only the locked heal path may repair a live marker-creation source.
pub repair_marker_source: bool,
pub namespace_owner: Option<Arc<dyn Send + Sync>>,
pub transaction_guard: Option<Arc<rustfs_lock::NamespaceLockGuard>>,
pub recovery_ticket: Option<crate::store::delete_recovery_runtime::DeleteRecoveryTicket>,
pub published_hint: Option<(Uuid, &'a [Result<DeleteRecoveryInspection>])>,
pub can_commit: &'a (dyn Fn() -> bool + Sync),
@@ -152,7 +125,6 @@ impl<'a> DeleteRecoveryContext<'a> {
explicit_delete: false,
repair_marker_source: false,
namespace_owner: None,
transaction_guard: None,
recovery_ticket: None,
published_hint: None,
can_commit,
@@ -401,22 +373,9 @@ impl SetDisks {
write_quorum: usize,
mut context: DeleteRecoveryContext<'_>,
) -> Result<()> {
let transaction_guard = match context.transaction_guard.take() {
Some(guard) => guard,
None => self
.acquire_delete_transaction_lock(bucket, object)
.await
.map_err(DiskError::other)?,
};
let outer_can_commit = context.can_commit;
let can_commit = || outer_can_commit() && !transaction_guard.is_lock_lost();
context.can_commit = &can_commit;
context.transaction_guard = Some(Arc::clone(&transaction_guard));
let owner = context
.namespace_owner
.take()
.unwrap_or_else(|| self.ctx.begin_namespace_commit());
context.namespace_owner = Some(Arc::new((owner, Arc::clone(&transaction_guard))));
if context.namespace_owner.is_none() {
context.namespace_owner = Some(self.ctx.begin_namespace_commit());
}
let can_commit = context.can_commit;
let states = inspect(disks, bucket, object, transaction).await;
let untouched_absence = |state: &Result<DeleteRecoveryInspection>| matches!(state, Ok(state) if state.state == DeleteRecoveryState::Absent && state.current_digest.is_none());
@@ -588,25 +547,8 @@ impl SetDisks {
&self,
bucket: &str,
object: &str,
mut context: DeleteRecoveryContext<'_>,
context: DeleteRecoveryContext<'_>,
) -> Result<DeleteRecoverySummary> {
let transaction_guard = match context.transaction_guard.take() {
Some(guard) => guard,
None => self
.acquire_delete_transaction_lock(bucket, object)
.await
.map_err(DiskError::other)?,
};
let outer_can_commit = context.can_commit;
let can_commit = || outer_can_commit() && !transaction_guard.is_lock_lost();
context.can_commit = &can_commit;
if !context.dry_run {
let owner = context
.namespace_owner
.take()
.unwrap_or_else(|| self.ctx.begin_namespace_commit());
context.namespace_owner = Some(Arc::new((owner, Arc::clone(&transaction_guard))));
}
let DeleteRecoveryContext {
incarnation,
dry_run,
@@ -616,7 +558,6 @@ impl SetDisks {
published_hint,
can_commit,
recovery_ticket: _,
transaction_guard: _,
} = context;
let disks = self.disk_inventory().await;
let complete_inventory = disks.len() == self.set_drive_count && disks.iter().all(Option::is_some);
@@ -1316,135 +1257,6 @@ mod tests {
assert_eq!(body(&store, bucket, None).await, original);
}
#[tokio::test]
async fn delete_recovery_deferred_batch_discards_released_alias_fence_and_preserves_caller_fence() {
use crate::bucket::metadata_sys::ObjectLockConfigState;
use crate::object_api::{NamespaceLockFence, NamespaceLockSignalTestFence, ObjectLockConfigSnapshot};
use crate::storage_api_contracts::object::ObjectToDelete;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
for lose_caller in [false, true] {
let bucket = if lose_caller {
"deferred-batch-lost-caller"
} else {
"deferred-batch-released-alias"
};
let (_dirs, store, disks) = fixture(bucket).await;
put(&store, bucket, &[27; 4096], false).await;
let transaction = applied(&store, &disks, bucket, None, disks.len()).await;
let before = join_all(
disks
.iter()
.map(|disk| disk.inspect_delete_transaction(bucket, "object", transaction)),
)
.await
.into_iter()
.collect::<Result<Vec<_>>>()
.expect("capture pending recovery evidence");
let mut set = (*store.pools[0].disk_set[0]).clone();
set.lockers = vec![Arc::new(rustfs_lock::LocalClient::with_manager(Arc::new(
rustfs_lock::GlobalLockManager::Enabled(Arc::new(rustfs_lock::FastObjectLockManager::new())),
)))];
set.ctx
.update_erasure_type(crate::layout::endpoints::SetupType::DistErasure)
.await;
let (caller_fence, caller_lost) = NamespaceLockFence::loss_handle_for_test();
let released_alias_lost = Arc::new(AtomicBool::new(false));
let signal_fence = Arc::new(Mutex::new(None));
let captured_signal_fence = Arc::clone(&signal_fence);
let captured_alias_lost = Arc::clone(&released_alias_lost);
test_hooks::after_transaction_lock_acquired(
bucket,
"object",
Arc::new(move |guard| {
let signal = guard.lock_lost_signal().expect("distributed alias signal");
let fence = NamespaceLockSignalTestFence::install_with_loss_handle(&signal, Arc::clone(&captured_alias_lost));
// Retain the signal so a later allocation cannot reuse its
// registry identity after the original guard is dropped.
*captured_signal_fence.lock().expect("captured alias fence") = Some((fence, signal));
}),
);
let replay_started = Arc::new(AtomicBool::new(false));
let captured_replay_started = Arc::clone(&replay_started);
let expired_alias = Arc::clone(&released_alias_lost);
test_hooks::after_transaction_lock_acquired(
bucket,
"object",
Arc::new(move |_| {
// Acquiring the same transaction key again proves the first
// lease was released. Only its copied fence becomes stale.
expired_alias.store(true, Ordering::Release);
caller_lost.store(lose_caller, Ordering::Release);
captured_replay_started.store(true, Ordering::Release);
}),
);
let (deleted, errors) = set
.delete_objects(
bucket,
vec![ObjectToDelete {
object_name: "object".into(),
..Default::default()
}],
ObjectOptions {
namespace_lock_fence: Some(caller_fence),
object_lock_config_snapshot: Some(Arc::new(ObjectLockConfigSnapshot::new(
ObjectLockConfigState::ConfirmedAbsent,
))),
..Default::default()
},
)
.await;
assert!(
replay_started.load(Ordering::Acquire),
"missing metadata must take the deferred replay path"
);
assert!(
released_alias_lost.load(Ordering::Acquire),
"the completed batch alias must be marked lost"
);
if lose_caller {
assert!(errors[0].is_some(), "losing the original caller fence must reject deferred replay");
for (disk, original) in disks.iter().zip(before) {
let after = disk
.inspect_delete_transaction(bucket, "object", transaction)
.await
.expect("retained proof");
assert_eq!(
after.fingerprint, original.fingerprint,
"lost caller authority must preserve every prepared journal"
);
}
} else {
assert!(
errors.iter().all(Option::is_none),
"released alias loss must not reject fresh recovery: {errors:?}"
);
assert!(
!deleted[0].found,
"fresh unversioned recovery commits absence before the idempotent batch retry"
);
for disk in &disks {
assert!(
discover(disk, bucket, Some("object"))
.await
.expect("final recovery evidence")
.is_empty()
);
assert_eq!(
disk.read_version("", bucket, "object", "", &ReadOptions::default())
.await
.expect_err("replayed delete must remove the source"),
DiskError::FileNotFound
);
}
}
drop(signal_fence);
}
}
#[tokio::test]
async fn delete_recovery_corrupt_bucket_does_not_prevent_other_bucket_rollback() {
let bad_bucket = "recover-corrupt-bucket";
+8 -27
View File
@@ -3634,18 +3634,6 @@ impl SetDisks {
return Ok((result, err.map(|e| e.into())));
}
// Keep the transaction key through both replay and the metadata heal
// based on that replay. The raw target key always precedes this key.
let transaction_guard =
if _write_lock_guard.is_some() && !opts.read_repair && !crate::bucket::utils::is_meta_bucketname(bucket) {
Some(self.acquire_delete_transaction_lock(bucket, object).await?)
} else {
None
};
let locks_lost = || {
_write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
|| transaction_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
};
let mut recovery_removed_version = false;
if !opts.read_repair
&& _write_lock_guard.is_some()
@@ -3667,17 +3655,12 @@ impl SetDisks {
dry_run: opts.dry_run,
explicit_delete,
repair_marker_source: true,
transaction_guard: transaction_guard.clone(),
namespace_owner: (!opts.dry_run).then(|| {
Arc::new((
scope.clone(),
self.ctx.begin_namespace_commit(),
_write_lock_guard.clone(),
transaction_guard.clone(),
)) as Arc<dyn Send + Sync>
Arc::new((scope.clone(), self.ctx.begin_namespace_commit(), _write_lock_guard.clone()))
as Arc<dyn Send + Sync>
}),
..crate::set_disk::DeleteRecoveryContext::new(Some(scope.incarnation), &|| {
scope.check().is_ok() && !locks_lost()
scope.check().is_ok() && !_write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
})
},
)
@@ -3769,7 +3752,7 @@ impl SetDisks {
&& errs
.iter()
.all(|err| matches!(err, Some(DiskError::FileNotFound | DiskError::FileVersionNotFound)))
&& !locks_lost()
&& !_write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
{
*absence = Some(HealedObjectAbsence {
pool_index: self.pool_index,
@@ -3784,10 +3767,8 @@ impl SetDisks {
// Pass no_lock=true since we already obtained write lock (or are already called with no_lock=true)
let mut inner_opts = *opts;
inner_opts.no_lock = true;
let commit_fence = || !locks_lost();
let namespace_owner = _write_lock_guard
.as_ref()
.map(|guard| Arc::new((Arc::clone(guard), transaction_guard.clone())) as Arc<dyn Send + Sync>);
let commit_fence = || !_write_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost());
let namespace_owner = _write_lock_guard.as_ref().map(|guard| guard.clone() as Arc<dyn Send + Sync>);
let (result, err) = pin_object_heal_future(|| {
self.heal_object_with_explicit_version_regen(
bucket,
@@ -3834,7 +3815,7 @@ impl SetDisks {
result,
err.map(Into::into),
absence,
locks_lost(),
_write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost()),
bucket,
object,
));
@@ -3846,7 +3827,7 @@ impl SetDisks {
result,
err.map(Into::into),
absence,
locks_lost(),
_write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost()),
bucket,
object,
))
+11 -39
View File
@@ -44,21 +44,6 @@ impl crate::storage_api_contracts::namespace::NamespaceLocking for SetDisks {
#[tracing::instrument(level = "trace", skip(self))]
async fn new_ns_lock(&self, bucket: &str, object: &str) -> Result<NamespaceLockWrapper> {
// Lock the file the disk resolves, not the spelling: on Windows `a\b`
// and `a/b` share one xl.meta, so they must share one lock. The key is
// folded by the requesting node only; lock servers compare it verbatim.
let resource = ObjectKey {
bucket: Arc::from(bucket),
object: Arc::from(object_name_disk_identity(object).as_ref()),
version: None,
};
Ok(self.namespace_lock_for_key(resource).await)
}
}
impl SetDisks {
async fn namespace_lock_for_key(&self, resource: ObjectKey) -> NamespaceLockWrapper {
// Resolved from this set's own instance context (backlog#1052), not the
// ambient facade: the facade tracks whichever context is currently
// published process-wide, so a second instance (or, in tests, another
@@ -84,33 +69,20 @@ impl SetDisks {
NamespaceLock::with_local_manager_shared(self.set_lock_namespace.clone(), self.local_lock_manager.clone())
};
NamespaceLockWrapper::new(set_lock, resource, self.locker_owner.clone())
}
// Lock the file the disk resolves, not the spelling: on Windows `a\b`
// and `a/b` share one xl.meta, so they must share one lock. The key is
// folded by the requesting node only; lock servers compare it verbatim.
let resource = ObjectKey {
bucket: Arc::from(bucket),
object: Arc::from(object_name_disk_identity(object).as_ref()),
version: None,
};
/// Raw object locks precede this set-local transaction lock. Its versioned
/// resource cannot collide with normal namespace keys, which use None.
/// Keeping the target set's clients avoids nesting overlapping raw quorums.
pub(in crate::set_disk) async fn acquire_delete_transaction_lock(
&self,
bucket: &str,
object: &str,
) -> Result<Arc<rustfs_lock::NamespaceLockGuard>> {
let resource = ObjectKey::with_version(
bucket,
object_name_disk_identity(object).as_ref(),
format!("rustfs:delete-transaction:{}:{}", self.pool_index, self.set_index),
);
let guard = self
.namespace_lock_for_key(resource)
.await
.get_write_lock(super::super::get_lock_acquire_timeout())
.await
.map_err(|error| self.map_namespace_lock_error(bucket, object, "delete_transaction", error))?;
#[cfg(test)]
super::delete_recovery::test_hooks::run_after_transaction_lock_acquired(bucket, object, &guard);
Ok(Arc::new(guard))
Ok(NamespaceLockWrapper::new(set_lock, resource, self.locker_owner.clone()))
}
}
impl SetDisks {
#[allow(dead_code, reason = "lock diagnostics formatter with no caller in this port (backlog#1823)")]
pub(in crate::set_disk) fn format_lock_error(&self, bucket: &str, object: &str, mode: &str, err: &LockResult) -> String {
match err {
+31 -178
View File
@@ -73,7 +73,6 @@ struct DeleteCommitContext<'a> {
incarnation: Option<Uuid>,
options: Option<&'a ObjectOptions>,
guard: Option<Arc<super::super::ObjectLockDiagGuard>>,
transaction_guard: Option<Arc<rustfs_lock::NamespaceLockGuard>>,
}
impl<'a> DeleteCommitContext<'a> {
@@ -82,37 +81,17 @@ impl<'a> DeleteCommitContext<'a> {
incarnation: options.expected_bucket_incarnation_id,
options: Some(options),
guard: guard.cloned(),
transaction_guard: None,
}
}
fn with_transaction_guard(mut self, guard: Option<&Arc<rustfs_lock::NamespaceLockGuard>>) -> Self {
self.transaction_guard = guard.cloned();
self
}
fn ensure_transaction_lock_held(&self, bucket: &str, object: &str) -> Result<()> {
if self.transaction_guard.as_ref().is_some_and(|guard| guard.is_lock_lost()) {
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "delete_transaction",
bucket: bucket.to_owned(),
object: object.to_owned(),
required: 1,
achieved: 0,
});
}
Ok(())
}
fn can_commit(&self, bucket: &str, object: &str) -> bool {
!self.transaction_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
&& self.options.is_none_or(|options| {
ensure_delete_commit_locks_held(self.guard.as_deref(), bucket, object, options).is_ok()
&& options
.scanner_publication_commit_scope
.as_ref()
.is_none_or(|scope| scope.can_commit())
})
self.options.is_none_or(|options| {
ensure_delete_commit_locks_held(self.guard.as_deref(), bucket, object, options).is_ok()
&& options
.scanner_publication_commit_scope
.as_ref()
.is_none_or(|scope| scope.can_commit())
})
}
}
@@ -3873,7 +3852,6 @@ impl SetDisks {
object: &str,
opts: &ObjectOptions,
lock_guard: Option<&Arc<super::super::ObjectLockDiagGuard>>,
transaction_guard: Option<&Arc<rustfs_lock::NamespaceLockGuard>>,
) -> Result<bool> {
if is_meta_bucketname(bucket)
|| opts.version_id.is_some()
@@ -3910,7 +3888,6 @@ impl SetDisks {
object,
DeleteRecoveryContext {
explicit_delete: true,
transaction_guard: transaction_guard.cloned(),
namespace_owner: Some(Arc::new((
self.ctx.begin_namespace_commit(),
lock_guard.cloned(),
@@ -8900,11 +8877,8 @@ impl SetDisks {
fi: &FileInfo,
force_del_marker: bool,
delete_marker_purge: Option<MrfDeleteMarkerPurge>,
mut commit_context: DeleteCommitContext<'_>,
commit_context: DeleteCommitContext<'_>,
) -> Result<()> {
if !is_meta_bucketname(bucket) && commit_context.transaction_guard.is_none() {
commit_context.transaction_guard = Some(self.acquire_delete_transaction_lock(bucket, object).await?);
}
let source_bucket_incarnation_id = commit_context.incarnation;
let transported = delete_file_info_with_replication_transport_metadata(fi);
let fi = &transported;
@@ -8913,7 +8887,6 @@ impl SetDisks {
Arc::new((
self.ctx.begin_namespace_commit(),
commit_context.guard.clone(),
commit_context.transaction_guard.clone(),
commit_context
.options
.and_then(|options| options.object_lock_config_snapshot.clone()),
@@ -8953,11 +8926,7 @@ impl SetDisks {
for disk in disks.iter() {
let disk_namespace_owner = namespace_owner.clone().map(|owner| owner as Arc<dyn Send + Sync>);
let transaction_guard = commit_context.transaction_guard.as_ref();
futures.push(async move {
if transaction_guard.is_some_and(|guard| guard.is_lock_lost()) {
return Err(DiskError::DiskOngoingReq);
}
if let Some(disk) = disk {
let options = DeleteOptions {
old_data_dir: Some(rollback_dir),
@@ -9007,7 +8976,6 @@ impl SetDisks {
}
}
commit_context.ensure_transaction_lock_held(bucket, object)?;
let mut quorum_result = resolve_tiered_decommission_write_quorum_result(&errs, write_quorum, bucket, object);
if !is_meta_bucketname(bucket) && errs.iter().flatten().any(super::delete_recovery::unsupported_recovery) {
quorum_result = Err(DiskError::UnsupportedDisk.into());
@@ -9040,7 +9008,6 @@ impl SetDisks {
write_quorum,
DeleteRecoveryContext {
recovery_ticket,
transaction_guard: commit_context.transaction_guard.clone(),
namespace_owner: namespace_owner.clone().map(|owner| owner as Arc<dyn Send + Sync>),
..DeleteRecoveryContext::new(source_bucket_incarnation_id, &|| commit_context.can_commit(bucket, object))
},
@@ -9050,7 +9017,6 @@ impl SetDisks {
}
#[cfg(test)]
pause_delete_before_cleanup(bucket).await;
commit_context.ensure_transaction_lock_held(bucket, object)?;
let mut rollback_futures = Vec::new();
for (index, err) in errs.iter().enumerate() {
if structured_cleanup {
@@ -9076,11 +9042,7 @@ impl SetDisks {
let object = object.to_string();
let fi = fi.clone();
let disk_namespace_owner = namespace_owner.clone().map(|owner| owner as Arc<dyn Send + Sync>);
let transaction_guard = commit_context.transaction_guard.as_ref();
rollback_futures.push(async move {
if transaction_guard.is_some_and(|guard| guard.is_lock_lost()) {
return;
}
if should_rollback {
// The dedicated undo path never forwards the marker-only creation flag.
if let Err(err) = disk
@@ -9137,7 +9099,6 @@ impl SetDisks {
}
join_all(rollback_futures).await;
commit_context.ensure_transaction_lock_held(bucket, object)?;
drop(namespace_owner);
if quorum_result.is_ok()
&& errs.iter().any(Option::is_some)
@@ -9597,8 +9558,9 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
&self,
bucket: &str,
objects: Vec<ObjectToDelete>,
mut opts: ObjectOptions,
opts: ObjectOptions,
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
let current_generations = opts.conditional_delete_generations.as_deref();
let mut del_objects = vec![DeletedObject::default(); objects.len()];
let mut accounting = vec![None; objects.len()];
let delete_config_snapshot = opts
@@ -9693,30 +9655,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
}
}
let outer_namespace_lock_fence = opts.namespace_lock_fence.clone();
let mut transaction_guards = std::collections::BTreeMap::new();
if !is_meta_bucketname(bucket) {
// Every raw batch lock is acquired first. Canonical sorting also
// gives aliases of one disk key exactly one transaction owner.
let keys: std::collections::BTreeSet<_> = locked_objects.iter().cloned().collect();
for key in keys {
match self.acquire_delete_transaction_lock(bucket, &key).await {
Ok(guard) => {
opts.add_namespace_lock_guard(&guard);
transaction_guards.insert(key, guard);
}
Err(error) => {
for (index, lock_name) in lock_names.iter().enumerate() {
if lock_name.as_ref() == key {
del_errs[index] = Some(error.clone());
}
}
}
}
}
}
let transaction_guards = Arc::new(transaction_guards);
let current_generations = opts.conditional_delete_generations.as_deref();
let object_lock_config = if is_meta_bucketname(bucket) {
Arc::new(ObjectLockConfigSnapshot::new(ObjectLockConfigState::ConfirmedAbsent))
} else {
@@ -9814,7 +9752,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
&dobj.object_name,
DeleteRecoveryContext {
dry_run: !opts.no_lock,
transaction_guard: transaction_guards.get(lock_names[i].as_ref()).cloned(),
namespace_owner: opts.delete_mutation_owner.clone(),
..DeleteRecoveryContext::new(opts.expected_bucket_incarnation_id, &|| {
ensure_delete_commit_locks_held(None, bucket, &dobj.object_name, &opts).is_ok()
@@ -10096,7 +10033,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let namespace_owner = (!is_meta_bucketname(bucket)).then(|| {
Arc::new((
self.ctx.begin_namespace_commit(),
Arc::clone(&transaction_guards),
opts.delete_mutation_owner.clone(),
opts.object_lock_config_snapshot.clone(),
opts.scanner_publication_commit_scope.clone(),
@@ -10272,24 +10208,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
}
let results = join_all(futures).await;
if transaction_guards.values().any(|guard| guard.is_lock_lost()) {
for (index, object) in objects.iter().enumerate() {
if del_errs[index].is_none() {
accounting[index] = None;
del_errs[index] = Some(StorageError::NamespaceLockQuorumUnavailable {
mode: "delete_transaction",
bucket: bucket.to_owned(),
object: object.object_name.clone(),
required: 1,
achieved: 0,
});
}
}
if dist_erasure {
self.release_dist_delete_object_locks_batch(dist_batch_lock_ids).await;
}
return (del_objects, del_errs, accounting);
}
let mut del_obj_errs: Vec<Vec<Option<DiskError>>> = vec![vec![None; objects.len()]; disks.len()];
@@ -10385,9 +10303,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let group = &vers[index];
let recovery_ticket = recovery_tickets[index].clone();
let namespace_owner = namespace_owner.clone();
let transaction_guard = transaction_guards
.get(object_name_disk_identity(&group.name).as_ref())
.cloned();
let disks = &disks;
let opts = &opts;
async move {
@@ -10408,7 +10323,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
DeleteRecoveryContext {
recovery_ticket,
namespace_owner,
transaction_guard,
..DeleteRecoveryContext::new(opts.expected_bucket_incarnation_id, &can_commit)
},
)
@@ -10455,11 +10369,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let object = fi_vers.name.clone();
let versions = fi_vers.clone();
let disk_namespace_owner = namespace_owner.clone();
let transaction_guard = transaction_guards.get(object_name_disk_identity(&object).as_ref()).cloned();
rollback_futures.push(async move {
if transaction_guard.as_ref().is_some_and(|guard| guard.is_lock_lost()) {
return;
}
if should_rollback {
let errs = disk
.delete_versions_with_namespace_owner(
@@ -10535,16 +10445,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
if del_errs[index].is_none() {
let object = &objects[index].object_name;
let result = match ensure_delete_commit_locks_held(None, bucket, object, &opts) {
Ok(()) => {
self.reclaim_missing_delete_residue(
bucket,
object,
&opts,
None,
transaction_guards.get(object_name_disk_identity(object).as_ref()),
)
.await
}
Ok(()) => self.reclaim_missing_delete_residue(bucket, object, &opts, None).await,
Err(err) => Err(err),
};
if let Err(err) = result {
@@ -10553,13 +10454,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
}
}
// Deferred recovery takes fresh raw and transaction locks. Discard the
// completed leases' deadlines while retaining every caller-owned fence.
opts.namespace_lock_fence = outer_namespace_lock_fence;
// Release inner owners before reacquiring any raw key lock.
drop(namespace_owner);
drop(transaction_guards);
// TODO(backlog): support partial object deletion for multi-part objects
if dist_erasure {
@@ -10669,16 +10563,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
} else {
None
};
// Lock order: the caller's raw object lock, then this target set's
// transaction key. The inner key remains distinct even when pool
// client quorums overlap, and no_lock never bypasses journal ownership.
let transaction_guard = if !is_meta_bucketname(bucket) && (!opts.delete_prefix || opts.delete_prefix_object) {
let guard = self.acquire_delete_transaction_lock(bucket, object).await?;
opts.add_namespace_lock_guard(&guard);
Some(guard)
} else {
None
};
if opts.delete_prefix {
let destructive_dispatch_phase = opts.lifecycle_delete_all.as_ref().is_none_or(|request| {
matches!(
@@ -10779,8 +10663,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
&delete_request,
false,
None,
DeleteCommitContext::request(&opts, _lock_guard.as_ref())
.with_transaction_guard(transaction_guard.as_ref()),
DeleteCommitContext::request(&opts, _lock_guard.as_ref()),
)
.await?;
if let Some((_, deleted_object)) = replication_delete {
@@ -10814,8 +10697,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
&delete_request,
false,
None,
DeleteCommitContext::request(&opts, _lock_guard.as_ref())
.with_transaction_guard(transaction_guard.as_ref()),
DeleteCommitContext::request(&opts, _lock_guard.as_ref()),
)
.await?;
}
@@ -10835,8 +10717,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
&delete_request,
false,
None,
DeleteCommitContext::request(&opts, _lock_guard.as_ref())
.with_transaction_guard(transaction_guard.as_ref()),
DeleteCommitContext::request(&opts, _lock_guard.as_ref()),
)
.await?;
}
@@ -10925,7 +10806,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
bucket,
object,
DeleteRecoveryContext {
transaction_guard: transaction_guard.clone(),
namespace_owner: Some(Arc::new((
self.ctx.begin_namespace_commit(),
_lock_guard.clone(),
@@ -10966,7 +10846,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
if is_err_object_not_found(err) {
ensure_delete_commit_locks_held(_lock_guard.as_deref(), bucket, object, &opts)?;
if self
.reclaim_missing_delete_residue(bucket, object, &opts, _lock_guard.as_ref(), transaction_guard.as_ref())
.reclaim_missing_delete_residue(bucket, object, &opts, _lock_guard.as_ref())
.await?
{
if let Some(scope) = scanner_publication_commit_scope.as_ref() {
@@ -11016,7 +10896,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
&dfi,
false,
None,
DeleteCommitContext::request(&opts, _lock_guard.as_ref()).with_transaction_guard(transaction_guard.as_ref()),
DeleteCommitContext::request(&opts, _lock_guard.as_ref()),
)
.await
.map_err(|e| to_object_err(e, vec![bucket, object]))?;
@@ -11118,7 +10998,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
&fi,
should_force_delete_marker_for_missing_version(&opts),
delete_marker_purge.clone(),
DeleteCommitContext::request(&opts, _lock_guard.as_ref()).with_transaction_guard(transaction_guard.as_ref()),
DeleteCommitContext::request(&opts, _lock_guard.as_ref()),
)
.await
.map_err(|e| to_object_err(e, vec![bucket, object]))?;
@@ -11183,7 +11063,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
&dfi,
opts.delete_marker,
delete_marker_purge,
DeleteCommitContext::request(&opts, _lock_guard.as_ref()).with_transaction_guard(transaction_guard.as_ref()),
DeleteCommitContext::request(&opts, _lock_guard.as_ref()),
)
.await
.map_err(|e| to_object_err(e, vec![bucket, object]))?;
@@ -11958,12 +11838,13 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let bucket_lifecycle_guard = if let Some(expected_incarnation_id) = opts.expected_bucket_incarnation_id
&& opts.bucket_lifecycle_lock_fence.is_none()
{
Some(
metadata_sys::object_store_in(&self.ctx)
.await?
.acquire_bucket_incarnation_fence_with_options(bucket, expected_incarnation_id, Some(opts))
.await?,
)
let guard = metadata_sys::object_store_in(&self.ctx)
.await?
.acquire_bucket_lifecycle_read_lock(bucket)
.await?;
self.validate_bucket_incarnation(bucket, expected_incarnation_id, opts)
.await?;
Some(guard)
} else {
None
};
@@ -25525,7 +25406,6 @@ mod delete_objects_lock_gating_tests {
}
#[tokio::test]
#[serial_test::serial]
async fn delete_object_aborts_when_outer_lock_is_lost_at_commit() {
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
let bucket = "single-lost-outer-lock";
@@ -25746,13 +25626,6 @@ mod delete_objects_lock_gating_tests {
.as_fast_lock_manager()
.expect("isolated fixture should use the local lock manager");
let lock_metrics = lock_manager.get_metrics().shard_metrics;
let raw_key = ObjectKey::new(bucket, "obj-a");
let raw_holder = lock_manager.get_lock_info(&raw_key).expect("outer holder must be visible");
let transaction_key = ObjectKey::with_version(
bucket,
"obj-a",
format!("rustfs:delete-transaction:{}:{}", set_disks.pool_index, set_disks.set_index),
);
assert_eq!(lock_manager.current_lock_counts(), (1, 0));
let mut delete = Box::pin(set_disks.delete_objects(
bucket,
@@ -25769,43 +25642,23 @@ mod delete_objects_lock_gating_tests {
// than a second on CI without waiting for the namespace lock at all.
let deletion = futures::future::poll_fn(|cx| {
let result = std::future::Future::poll(delete.as_mut(), cx);
let current_holder = lock_manager.get_lock_info(&raw_key).expect("outer holder must remain held");
assert_eq!(
(current_holder.mode, &current_holder.owner, current_holder.acquired_at),
(raw_holder.mode, &raw_holder.owner, raw_holder.acquired_at),
"no_lock must preserve the original raw object holder"
);
let transaction_holder = lock_manager.get_lock_info(&transaction_key);
if let Some(holder) = &transaction_holder {
assert_eq!(holder.mode, rustfs_lock::LockMode::Exclusive);
}
assert_eq!(
lock_manager.current_lock_counts(),
(1 + u64::from(transaction_holder.is_some()), 0),
"only the distinct transaction owner may be added, without raw-key waiters"
(1, 0),
"no_lock batch delete must preserve the outer holder without adding lock waiters"
);
let current = lock_manager.get_metrics().shard_metrics;
assert!(
current.total_acquisitions() <= lock_metrics.total_acquisitions() + 1,
"the transaction owner must be reused by inline recovery"
assert_eq!(
(current.total_acquisitions(), current.timeouts),
(lock_metrics.total_acquisitions(), lock_metrics.timeouts),
"no_lock batch delete must not acquire or time out on another namespace lock"
);
assert_eq!(current.timeouts, lock_metrics.timeouts, "the raw key must never be reacquired");
result
});
let (deleted, errs) = tokio::time::timeout(Duration::from_secs(30), deletion)
.await
.expect("no_lock batch delete disk work should complete");
assert_eq!(lock_manager.current_lock_counts(), (1, 0));
assert!(
lock_manager.get_lock_info(&transaction_key).is_none(),
"the transaction owner must be released"
);
assert_eq!(
lock_manager.get_metrics().shard_metrics.total_acquisitions(),
lock_metrics.total_acquisitions() + 1,
"no_lock still requires exactly one distinct transaction owner"
);
assert!(errs[0].is_none(), "no_lock batch delete should not fail with a lock error: {:?}", errs[0]);
assert!(deleted[0].found, "existing object must still be deleted");
for disk in &disk_stores {
+3 -81
View File
@@ -448,14 +448,6 @@ impl ECStore {
await_orphan_bucket_recovery(bucket, &publication_guard, &lifecycle_guard, &metadata_guard, &ns_guard, recover).await
}
/// Read quota and bucket identity from one authoritative metadata snapshot.
pub async fn bucket_quota_and_incarnation_from_disk(
&self,
bucket: &str,
) -> Result<(Option<crate::bucket::quota::BucketQuota>, Uuid, OffsetDateTime)> {
metadata_sys::get_quota_config_and_incarnation_from_disk_in(&self.ctx, bucket).await
}
pub async fn get_bucket_metadata(&self, bucket: &str) -> Result<Arc<BucketMetadata>> {
let sys = metadata_sys::require_bucket_metadata_sys_in(&self.ctx)?;
sys.read().await.get(bucket).await
@@ -572,83 +564,13 @@ impl ECStore {
.await
}
pub(crate) async fn acquire_bucket_incarnation_fence_with_options(
pub(super) async fn acquire_bucket_incarnation_fence_with_options(
&self,
bucket: &str,
expected: Uuid,
opts: Option<&ObjectOptions>,
) -> Result<super::BucketIncarnationFenceGuard> {
Ok(self
.acquire_bucket_incarnation_fence_for_options(bucket, Some(expected), opts)
.await?
.0)
}
pub(crate) async fn acquire_bucket_incarnation_fence_for_options(
&self,
bucket: &str,
expected: Option<Uuid>,
opts: Option<&ObjectOptions>,
) -> Result<(super::BucketIncarnationFenceGuard, Uuid)> {
let inner = self.acquire_bucket_lifecycle_read_lock(bucket).await?;
self.validate_bucket_incarnation_fence_guard_with_options(bucket, inner, expected, opts)
.await
}
/// Acquire lexicographically ordered bucket lifecycle read locks for a copy
/// operation and validate both bucket incarnations through [`super::BucketFenceRegistry`].
pub async fn acquire_copy_bucket_incarnation_fences(
&self,
source_bucket: &str,
expected_source: Option<Uuid>,
destination_bucket: &str,
expected_destination: Option<Uuid>,
) -> Result<(super::BucketIncarnationFenceGuard, Uuid, Option<super::BucketIncarnationFenceGuard>, Uuid)> {
let (source_guard, destination_guard) = if source_bucket == destination_bucket {
(self.acquire_bucket_lifecycle_read_lock(source_bucket).await?, None)
} else if source_bucket < destination_bucket {
let source_guard = self.acquire_bucket_lifecycle_read_lock(source_bucket).await?;
let destination_guard = self.acquire_bucket_lifecycle_read_lock(destination_bucket).await?;
(source_guard, Some(destination_guard))
} else {
let destination_guard = self.acquire_bucket_lifecycle_read_lock(destination_bucket).await?;
let source_guard = self.acquire_bucket_lifecycle_read_lock(source_bucket).await?;
(source_guard, Some(destination_guard))
};
let (source_guard, current_source_incarnation_id) = self
.validate_bucket_incarnation_fence_guard_with_options(source_bucket, source_guard, expected_source, None)
.await?;
let (destination_guard, current_destination_incarnation_id) = if let Some(destination_guard) = destination_guard {
let (destination_guard, destination_incarnation_id) = self
.validate_bucket_incarnation_fence_guard_with_options(
destination_bucket,
destination_guard,
expected_destination,
None,
)
.await?;
(Some(destination_guard), destination_incarnation_id)
} else {
if expected_destination.is_some_and(|expected| expected != current_source_incarnation_id) {
return Err(StorageError::BucketNotFound(destination_bucket.to_owned()));
}
(None, current_source_incarnation_id)
};
Ok((
source_guard,
current_source_incarnation_id,
destination_guard,
current_destination_incarnation_id,
))
}
async fn validate_bucket_incarnation_fence_guard_with_options(
&self,
bucket: &str,
inner: rustfs_lock::NamespaceLockGuard,
expected: Option<Uuid>,
opts: Option<&ObjectOptions>,
) -> Result<(super::BucketIncarnationFenceGuard, Uuid)> {
let mut guard = super::BucketIncarnationFenceGuard::new(
Arc::clone(&self.bucket_fence_registry),
bucket,
@@ -664,10 +586,10 @@ impl ECStore {
}
})
.await?;
if expected.is_some_and(|expected| current != expected) {
if current != expected {
return Err(StorageError::BucketNotFound(bucket.to_owned()));
}
Ok((guard, current))
Ok(guard)
}
/// Hold this guard through recursive-delete authorization and mutation so
+1 -22
View File
@@ -149,18 +149,6 @@ impl BucketFenceRegistry {
}
}
}
/// Return the memoized incarnation id for `bucket` when at least one
/// registered lifecycle read guard is currently held without lock loss.
pub(crate) fn validated_incarnation(&self, bucket: &str) -> Option<Uuid> {
let mut entries = self.entries.lock().expect("bucket fence registry poisoned");
let entry = entries.get_mut(bucket)?;
if entry.guards.iter().any(|guard| guard.loss_probe.is_lost()) {
entry.validated = None;
return None;
}
entry.validated
}
}
/// Owns continuous lifecycle coverage and its incarnation validation memo.
@@ -233,7 +221,7 @@ impl BucketIncarnationFenceGuard {
}
}
pub fn is_lock_lost(&self) -> bool {
pub(crate) fn is_lock_lost(&self) -> bool {
self.inner.as_ref().is_some_and(NamespaceLockGuard::is_lock_lost)
}
@@ -322,16 +310,9 @@ mod tests {
let (first_probe, first_lost) = controllable_probe();
let first = reg.enter("b", first_probe);
assert_eq!(first.memoized, None);
assert_eq!(reg.validated_incarnation("b"), None);
reg.memoize("b", uuid(7));
assert_eq!(reg.validated_incarnation("b"), Some(uuid(7)));
first_lost.store(true, std::sync::atomic::Ordering::SeqCst);
assert_eq!(
reg.validated_incarnation("b"),
None,
"live lost guard must clear and block validated_incarnation"
);
let second = reg.enter("b", live_probe());
assert_eq!(second.memoized, None, "live lost guard must force disk revalidation");
@@ -339,11 +320,9 @@ mod tests {
let third = reg.enter("b", live_probe());
assert_eq!(third.memoized, None, "memo remains blocked while the lost guard is live");
assert_eq!(reg.validated_incarnation("b"), None);
reg.exit("b", first.token, true);
reg.memoize("b", uuid(8));
assert_eq!(reg.validated_incarnation("b"), Some(uuid(8)));
let fourth = reg.enter("b", live_probe());
assert_eq!(fourth.memoized, Some(uuid(8)), "memo resumes after lost coverage leaves");
-150
View File
@@ -21384,141 +21384,6 @@ mod tests {
shutdown.cancel();
}
#[tokio::test]
#[serial_test::serial(storage_class_env)]
async fn put_object_metadata_and_copy_object_reuse_overlapping_incarnation_fence() {
let temp = tempfile::tempdir().expect("create metadata/copy fence store");
let (_ctx, store, shutdown) =
without_storage_class_env(build_isolated_test_store(temp.path(), "metadata-copy-fence-reuse", &[4])).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("metadata-copy-fence-{}", Uuid::new_v4());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
let mut seed_reader = PutObjReader::from_vec(b"seed payload".to_vec());
let versioned_opts = ObjectOptions {
versioned: true,
..Default::default()
};
let mut src_info = store
.put_object(&bucket, "src.bin", &mut seed_reader, &versioned_opts)
.await
.expect("seed source object");
let src_version_id = src_info
.version_id
.expect("versioned PUT should return a version ID")
.to_string();
let expected = store.bucket_incarnation_id(&bucket).await.expect("read incarnation");
let coverage = store
.acquire_bucket_incarnation_fence(&bucket, expected)
.await
.expect("validate continuous coverage");
let metadata_writer = crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, &bucket)
.await
.expect("hold metadata writer during covered metadata and copy operations");
let updated = tokio::time::timeout(
Duration::from_secs(10),
store.put_object_metadata(
&bucket,
"src.bin",
&ObjectOptions {
version_id: Some(src_version_id.clone()),
versioned: true,
eval_metadata: Some(HashMap::from([("x-amz-meta-fenced".to_string(), "true".to_string())])),
..Default::default()
},
),
)
.await
.expect("covered put_object_metadata must not reacquire the metadata transaction lock")
.expect("update object metadata using authoritative memo");
assert_eq!(updated.user_defined.get("x-amz-meta-fenced").map(String::as_str), Some("true"));
Arc::make_mut(&mut src_info.user_defined).insert("x-amz-meta-copied".to_string(), "true".to_string());
let src_copy_opts = ObjectOptions {
version_id: Some(src_version_id),
versioned: true,
..Default::default()
};
let copied = tokio::time::timeout(
Duration::from_secs(10),
store.copy_object(&bucket, "src.bin", &bucket, "src.bin", &mut src_info, &src_copy_opts, &versioned_opts),
)
.await
.expect("covered versioned copy_object must not reacquire the metadata transaction lock")
.expect("versioned copy using authoritative memo");
assert_eq!(copied.user_defined.get("x-amz-meta-copied").map(String::as_str), Some("true"));
let (src_guard, src_incarnation, dst_guard, dst_incarnation) = tokio::time::timeout(
Duration::from_secs(10),
store.acquire_copy_bucket_incarnation_fences(&bucket, Some(expected), &bucket, Some(expected)),
)
.await
.expect("covered acquire_copy_bucket_incarnation_fences must not reacquire the metadata transaction lock")
.expect("validate same-bucket copy fences using authoritative memo");
assert!(dst_guard.is_none());
assert_eq!(src_incarnation, expected);
assert_eq!(dst_incarnation, expected);
let mut borrowed_fence_opts = ObjectOptions {
expected_bucket_incarnation_id: Some(expected),
..Default::default()
};
src_guard.attach_to_object_options(&mut borrowed_fence_opts);
let fenced_incarnation = tokio::time::timeout(
Duration::from_secs(10),
crate::bucket::metadata_sys::get_bucket_incarnation_id_for_options_in(&store.ctx, &bucket, &borrowed_fence_opts),
)
.await
.expect("borrowed fence under active coverage must not reacquire the metadata transaction lock")
.expect("resolve incarnation under borrowed fence");
assert_eq!(fenced_incarnation, expected);
assert!(
matches!(
store
.acquire_copy_bucket_incarnation_fences(&bucket, Some(expected), &bucket, Some(Uuid::new_v4()))
.await,
Err(StorageError::BucketNotFound(_))
),
"same-bucket copy fence must reject a mismatched destination incarnation"
);
drop(src_guard);
let stale_opts = ObjectOptions {
expected_bucket_incarnation_id: Some(Uuid::new_v4()),
versioned: true,
..Default::default()
};
assert!(
matches!(
store.put_object_metadata(&bucket, "src.bin", &stale_opts).await,
Err(StorageError::BucketNotFound(_))
),
"put_object_metadata must reject a stale expected incarnation even under warm coverage"
);
assert!(
matches!(
store
.copy_object(
&bucket,
"src.bin",
&bucket,
"src.bin",
&mut src_info,
&ObjectOptions::default(),
&stale_opts,
)
.await,
Err(StorageError::BucketNotFound(_))
),
"copy_object must reject a stale expected incarnation even under warm coverage"
);
drop(metadata_writer);
drop(coverage);
shutdown.cancel();
}
#[tokio::test]
#[serial_test::serial(storage_class_env)]
async fn multipart_snapshot_bypasses_initializer_queued_behind_metadata_writer() {
@@ -21604,25 +21469,10 @@ mod tests {
.acquire_bucket_incarnation_fence(&bucket, old)
.await
.expect("validate with no-op lock");
let snapshot = store
.object_lock_config_snapshot_under_lifecycle_fence(&bucket, &crate::object_api::NamespaceLockFence::new())
.await
.expect("capture snapshot under no-op lock");
let current = Uuid::new_v4();
crate::bucket::metadata::save_bucket_incarnation(store.clone(), &bucket, current)
.await
.expect("replace authority while no-op guard provides no exclusion");
let snapshot_opts = ObjectOptions {
expected_bucket_incarnation_id: Some(old),
object_lock_config_snapshot: Some(snapshot),
..Default::default()
};
assert_eq!(
crate::bucket::metadata_sys::get_bucket_incarnation_id_for_options_in(&store.ctx, &bucket, &snapshot_opts)
.await
.expect("disabled lock manager must re-read incarnation from disk instead of trusting snapshot"),
current
);
assert!(
matches!(
store.acquire_bucket_incarnation_fence(&bucket, old).await,
+6 -9
View File
@@ -1030,19 +1030,16 @@ impl ECStore {
// Lock order matches writes: bucket lifecycle, metadata validation,
// then object namespace. Borrow fences supplied by an outer operation.
let bucket_guard = if opts.bucket_lifecycle_lock_fence.is_none() {
let guard = self
.acquire_bucket_incarnation_fence_with_options(bucket, bucket_incarnation_id, Some(&opts))
.await?;
guard.attach_to_object_options(&mut opts);
let guard = self.acquire_bucket_lifecycle_read_lock(bucket).await?;
opts.add_bucket_lifecycle_lock_guard(&guard);
Some(guard)
} else {
let incarnation =
crate::bucket::metadata_sys::get_bucket_incarnation_id_for_options_in(&self.ctx, bucket, &opts).await?;
if incarnation != bucket_incarnation_id {
return Err(Error::BucketNotFound(bucket.to_owned()));
}
None
};
let incarnation = crate::bucket::metadata_sys::get_bucket_incarnation_id_for_options_in(&self.ctx, bucket, &opts).await?;
if incarnation != bucket_incarnation_id {
return Err(Error::BucketNotFound(bucket.to_owned()));
}
let metadata_sys = crate::bucket::metadata_sys::bucket_metadata_sys_of(&self.ctx)?;
let metadata_sys = metadata_sys.read().await.clone();
let (versioning, _) = metadata_sys.get_versioning_config(bucket).await?;
+1 -1
View File
@@ -412,7 +412,7 @@ impl ECStore {
/// Multipart lock order is bucket lifecycle, generation validation, then
/// object/upload locks in the selected set.
pub(super) async fn guard_multipart_bucket_incarnation(
async fn guard_multipart_bucket_incarnation(
&self,
bucket: &str,
opts: &ObjectOptions,
+47 -218
View File
@@ -30,8 +30,8 @@ use crate::bucket::lifecycle::{
},
};
use crate::bucket::metadata_sys::{
acquire_bucket_metadata_transaction_read_lock_in, get_cached_bucket_incarnation_id_in, get_delete_config_from_disk_in,
get_object_lock_config_and_incarnation_from_disk_in,
acquire_bucket_metadata_transaction_read_lock_in, get_bucket_incarnation_id_for_options_in,
get_cached_bucket_incarnation_id_in, get_delete_config_from_disk_in, get_object_lock_config_and_incarnation_from_disk_in,
};
use crate::bucket::object_lock::objectlock_sys::{
check_object_lock_for_deletion_with_state, ensure_recursive_force_delete_allowed_for_state,
@@ -4883,20 +4883,24 @@ impl ECStore {
if !is_meta_bucketname(dst_bucket) && dst_opts.expected_bucket_incarnation_id.is_none() {
dst_opts.expected_bucket_incarnation_id = Some(self.bucket_incarnation_id(dst_bucket).await?);
}
let (_bucket_lifecycle_guard, current_bucket_incarnation_id) =
if is_meta_bucketname(dst_bucket) || dst_opts.bucket_lifecycle_lock_fence.is_some() {
(None, dst_opts.expected_bucket_incarnation_id)
} else {
let (guard, current_incarnation_id) = self
.acquire_bucket_incarnation_fence_for_options(
dst_bucket,
dst_opts.expected_bucket_incarnation_id,
Some(&dst_opts),
)
.await?;
guard.attach_to_object_options(&mut dst_opts);
(Some(guard), Some(current_incarnation_id))
};
let _bucket_lifecycle_guard = if is_meta_bucketname(dst_bucket) || dst_opts.bucket_lifecycle_lock_fence.is_some() {
None
} else {
Some(self.acquire_bucket_lifecycle_read_lock(dst_bucket).await?)
};
let current_bucket_incarnation_id = if let Some(guard) = _bucket_lifecycle_guard.as_ref() {
dst_opts.add_bucket_lifecycle_lock_guard(guard);
let current_incarnation_id = get_bucket_incarnation_id_for_options_in(&self.ctx, dst_bucket, &dst_opts).await?;
if dst_opts
.expected_bucket_incarnation_id
.is_some_and(|expected| expected != current_incarnation_id)
{
return Err(StorageError::BucketNotFound(dst_bucket.to_string()));
}
Some(current_incarnation_id)
} else {
dst_opts.expected_bucket_incarnation_id
};
if dst_opts
.bucket_lifecycle_lock_fence
.as_ref()
@@ -6500,8 +6504,24 @@ impl ECStore {
opts: &ObjectOptions,
) -> Result<()> {
let object = encode_dir_object(object);
let opts = transition_restore_pool_opts(opts);
let (mut opts, _bucket_lifecycle_guard) = self.guard_multipart_bucket_incarnation(bucket, &opts).await?;
let mut opts = transition_restore_pool_opts(opts);
if !is_meta_bucketname(bucket) && opts.expected_bucket_incarnation_id.is_none() {
opts.expected_bucket_incarnation_id = Some(self.bucket_incarnation_id(bucket).await?);
}
let bucket_lifecycle_guard = if is_meta_bucketname(bucket) {
None
} else {
Some(self.acquire_bucket_lifecycle_read_lock(bucket).await?)
};
if let Some(guard) = bucket_lifecycle_guard.as_ref() {
opts.add_bucket_lifecycle_lock_guard(guard);
}
if !is_meta_bucketname(bucket) {
let current_incarnation_id = get_bucket_incarnation_id_for_options_in(&self.ctx, bucket, &opts).await?;
if opts.expected_bucket_incarnation_id != Some(current_incarnation_id) {
return Err(StorageError::BucketNotFound(bucket.to_string()));
}
}
if opts.overwrites_existing_version() && !is_meta_bucketname(bucket) {
let expected_incarnation_id = opts
.expected_bucket_incarnation_id
@@ -6569,11 +6589,16 @@ impl ECStore {
let bucket_lifecycle_guard = if is_meta_bucketname(bucket) {
None
} else {
let (guard, current_incarnation_id) = self
.acquire_bucket_incarnation_fence_for_options(bucket, opts.expected_bucket_incarnation_id, Some(&opts))
.await?;
let guard = self.acquire_bucket_lifecycle_read_lock(bucket).await?;
let current_incarnation_id = get_bucket_incarnation_id_for_options_in(&self.ctx, bucket, &opts).await?;
if opts
.expected_bucket_incarnation_id
.is_some_and(|expected| expected != current_incarnation_id)
{
return Err(StorageError::BucketNotFound(bucket.to_string()));
}
opts.expected_bucket_incarnation_id = Some(current_incarnation_id);
guard.attach_to_object_options(&mut opts);
opts.add_bucket_lifecycle_lock_guard(&guard);
if guard.is_lock_lost() {
return Err(Error::other("bucket lifecycle lock was lost before the metadata update"));
}
@@ -13142,202 +13167,6 @@ mod tests {
})
.await;
}
async fn assert_delete_excludes_recovery_across_pool_lock_domains(topology: &str, batch: bool) {
let ctx = Arc::new(crate::runtime::instance::InstanceContext::new());
let (_first_dirs, first_set) = make_local_set_disks_with_ctx(4, 2, Arc::clone(&ctx)).await;
let (_second_dirs, second_set) = make_local_set_disks_with_ctx(4, 2, Arc::clone(&ctx)).await;
let mut store = new_prepared_reader_test_store_with_ctx(&[first_set, second_set], Arc::clone(&ctx)).await;
let clients: Vec<Arc<dyn rustfs_lock::LockClient>> = (0..4)
.map(|_| {
Arc::new(rustfs_lock::LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::Enabled(
Arc::new(rustfs_lock::FastObjectLockManager::new()),
)))) as Arc<dyn rustfs_lock::LockClient>
})
.collect();
let domains = match topology {
"disjoint" => [vec![clients[0].clone()], vec![clients[1].clone()]],
"identical" => [clients[..3].to_vec(), clients[..3].to_vec()],
"overlapping" => [clients[..3].to_vec(), clients[1..].to_vec()],
_ => panic!("unknown lock topology"),
};
for (pool, lockers) in store.pools.iter_mut().zip(domains) {
let mut set = (*pool.disk_set[0]).clone();
set.lockers = lockers;
Arc::make_mut(pool).disk_set[0] = Arc::new(set);
}
let store = Arc::new(store);
crate::bucket::metadata_sys::init_bucket_metadata_sys(Arc::clone(&store), Vec::new()).await;
let bucket = "delete-nonzero-pool-lock";
let object = "object.bin";
store
.handle_make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create the bucket in both pools");
if batch {
// Latest-marker routing sends this batch only to the nonzero pool,
// so the cleanup barrier observes its prepared journal directly.
store
.update_bucket_metadata_config(
bucket,
crate::bucket::metadata::BUCKET_VERSIONING_CONFIG,
b"<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>".to_vec(),
)
.await
.expect("enable versioning for the routed batch");
}
let target = store.pools[1].get_disks_by_key(object);
let source = target
.put_object(
bucket,
object,
&mut PutObjReader::from_vec(b"delete lock regression".to_vec()),
&ObjectOptions {
versioned: batch,
..Default::default()
},
)
.await
.expect("seed an object only in the nonzero pool");
ctx.update_erasure_type(SetupType::DistErasure).await;
let object_barrier = (!batch).then(|| crate::set_disk::DeleteObjectCommitBarrier::install(bucket, object));
let batch_barrier = batch.then(|| crate::set_disk::DeleteCleanupBarrier::install(bucket));
let delete_store = Arc::clone(&store);
let delete = tokio::spawn(async move {
if batch {
let (_, errors) = delete_store
.delete_objects(
bucket,
vec![ObjectToDelete {
object_name: object.to_owned(),
..Default::default()
}],
ObjectOptions::default(),
)
.await;
match errors.into_iter().flatten().next() {
Some(error) => Err(error),
None => Ok(()),
}
} else {
delete_store
.delete_object(bucket, object, ObjectOptions::default())
.await
.map(|_| ())
}
});
if let Some(barrier) = &object_barrier {
barrier.wait_until_paused().await;
}
if let Some(barrier) = &batch_barrier {
barrier.wait_until_paused().await;
}
let recovery_store = Arc::clone(&store);
let mut recovery = tokio::spawn(async move {
recovery_store
.recover_delete_transactions_at_incarnation(
bucket,
Some(object),
None,
&HealOpts {
pool: Some(1),
set: Some(0),
..Default::default()
},
)
.await
});
let early_recovery = tokio::time::timeout(Duration::from_millis(100), &mut recovery).await;
let recovery_was_blocked = early_recovery.is_err();
if let Some(barrier) = &object_barrier {
barrier.release();
}
if let Some(barrier) = &batch_barrier {
barrier.release();
}
tokio::time::timeout(Duration::from_secs(10), delete)
.await
.expect("the delete should finish after releasing its commit barrier")
.expect("the delete task should join")
.expect("the delete should succeed");
let recovered = match early_recovery {
Ok(result) => result,
Err(_) => tokio::time::timeout(Duration::from_secs(10), recovery)
.await
.expect("recovery should finish after the frontend delete"),
};
recovered
.expect("the recovery task should join")
.expect("recovery should succeed");
assert!(
recovery_was_blocked,
"recovery must not inspect an in-flight frontend delete with {topology} pool lock clients"
);
if batch {
let marker = target
.get_object_info(bucket, object, &ObjectOptions::default())
.await
.expect("the versioned batch must publish a current delete marker");
assert!(marker.delete_marker && marker.is_latest);
assert_eq!(marker.num_versions, 2, "the source version must remain beside the new marker");
assert_ne!(marker.version_id, source.version_id);
let mut reader = target
.get_object_reader(
bucket,
object,
None,
HeaderMap::new(),
&ObjectOptions {
version_id: Some(source.version_id.expect("versioned source identity").to_string()),
..Default::default()
},
)
.await
.expect("the original source version must remain readable");
let mut body = Vec::new();
reader
.stream
.read_to_end(&mut body)
.await
.expect("read the retained source version");
assert_eq!(body, b"delete lock regression");
} else {
let error = target
.get_object_info(bucket, object, &ObjectOptions::default())
.await
.expect_err("the deleted object must be absent");
assert!(is_err_object_not_found(&error));
}
}
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn batch_delete_excludes_recovery_on_nonzero_pool() {
assert_delete_excludes_recovery_across_pool_lock_domains("disjoint", true).await;
}
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn delete_excludes_recovery_with_disjoint_pool_lock_clients() {
assert_delete_excludes_recovery_across_pool_lock_domains("disjoint", false).await;
}
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn delete_excludes_recovery_with_identical_pool_lock_clients() {
assert_delete_excludes_recovery_across_pool_lock_domains("identical", false).await;
}
#[tokio::test]
#[serial_test::serial]
#[serial_test::serial(storage_class_env)]
async fn delete_excludes_recovery_with_overlapping_pool_lock_clients() {
assert_delete_excludes_recovery_across_pool_lock_domains("overlapping", false).await;
}
}
#[cfg(test)]
+1 -37
View File
@@ -16,7 +16,7 @@ use rustfs_io_metrics::internode_metrics::INTERNODE_OPERATION_PUT_FILE_STREAM;
use rustfs_rio::{InternodeHttpError, InternodeHttpErrorKind};
use thiserror::Error;
use super::heal::{DiskError, EcstoreError, storage_api::owner::EcstorePoolMetadataFailure};
use super::heal::{DiskError, EcstoreError};
const HEAL_DANGLING_DELETE_GRACE_MESSAGE: &str = "dangling object deletion deferred by heal grace window";
pub(crate) const MRF_MISSING_PROOF_PREFIX: &str = "Missing exact storage proof for durable MRF repair ";
@@ -236,14 +236,6 @@ pub(crate) fn classify_heal_error(error: &Error) -> HealErrorClass {
/// with object absence, the conflation that once let an offline drive be
/// recorded as absent and skipped (backlog#856 / #799 B7).
pub(crate) fn classify_storage_error(error: &EcstoreError) -> HealErrorClass {
if let Some(failure) = error.pool_metadata_failure() {
return match failure.kind {
EcstorePoolMetadataFailure::ReadUnavailable | EcstorePoolMetadataFailure::TransactionUnknown => {
HealErrorClass::Transient
}
EcstorePoolMetadataFailure::RecoveryRequired | EcstorePoolMetadataFailure::FenceLost => HealErrorClass::Permanent,
};
}
if let EcstoreError::Lock(lock_error) = error {
return if lock_error.is_fatal() {
HealErrorClass::Permanent
@@ -443,34 +435,6 @@ mod tests {
use super::Error;
use crate::heal::{DiskError, EcstoreError};
#[test]
fn pool_metadata_failures_keep_their_typed_recovery_classification() {
use crate::heal::storage_api::owner::{EcstorePoolMetadataError, EcstorePoolMetadataFailure};
for (kind, retryable) in [
(EcstorePoolMetadataFailure::ReadUnavailable, true),
(EcstorePoolMetadataFailure::TransactionUnknown, true),
(EcstorePoolMetadataFailure::RecoveryRequired, false),
(EcstorePoolMetadataFailure::FenceLost, false),
] {
let error = EcstoreError::other(EcstorePoolMetadataError {
kind,
operation: "bucket heal".to_owned(),
phase: "native_heal",
since: std::time::UNIX_EPOCH.into(),
source: Some(std::sync::Arc::new(EcstoreError::SlowDown)),
});
let text = error.to_string();
for error in [error.clone(), error] {
assert_eq!(Error::Storage(error).is_recoverable_heal(), retryable, "{kind:?}");
}
assert!(
!Error::Storage(EcstoreError::other(text)).is_recoverable_heal(),
"display text must not grant recovery authority"
);
}
}
#[test]
fn namespace_lock_quorum_is_recoverable_across_io_error_conversions() {
for (required, achieved) in [(2, 1), (1, 0)] {
+1 -8
View File
@@ -26,11 +26,7 @@ pub(crate) use rustfs_ecstore::api::disk::{
RUSTFS_META_BUCKET as ECSTORE_RUSTFS_META_BUCKET, ReplacementExecutionLease as EcstoreReplacementExecutionLease,
};
pub(crate) use rustfs_ecstore::api::disk::{DiskOption as EcstoreDiskOption, new_disk as ecstore_new_disk};
#[cfg(test)]
pub(crate) use rustfs_ecstore::api::error::PoolMetadataError as EcstorePoolMetadataError;
pub(crate) use rustfs_ecstore::api::error::{
Error as EcstoreErrorType, PoolMetadataFailure as EcstorePoolMetadataFailure, StorageError as EcstoreStorageError,
};
pub(crate) use rustfs_ecstore::api::error::{Error as EcstoreErrorType, StorageError as EcstoreStorageError};
#[cfg(test)]
pub(crate) use rustfs_ecstore::api::layout::{
EndpointServerPools as EcstoreEndpointServerPools, Endpoints as EcstoreEndpoints, PoolEndpoints as EcstorePoolEndpoints,
@@ -57,9 +53,6 @@ pub(crate) use rustfs_ecstore::api::storage::{
use rustfs_storage_api as storage_contracts;
pub(crate) mod owner {
#[cfg(test)]
pub(crate) use super::EcstorePoolMetadataError;
pub(crate) use super::EcstorePoolMetadataFailure;
pub(crate) use super::storage_contracts::{ObjectIO, ObjectOperations};
pub(crate) use super::{
+9 -3
View File
@@ -306,7 +306,9 @@ impl HealTask {
let mut progress = self.progress.write().await;
progress.update_stage(3, 3);
}
Err(e)
Err(Error::TaskExecutionFailed {
message: format!("Failed to heal bucket {bucket}: {e}"),
})
}
}
}
@@ -518,7 +520,9 @@ impl HealTask {
error = %err,
"Heal cluster pool metadata failed"
);
Err(err)
Err(Error::TaskExecutionFailed {
message: format!("Failed to heal cluster pool metadata: {err}"),
})
}
Err(Error::TaskCancelled) => Err(Error::TaskCancelled),
Err(Error::TaskTimeout) => Err(Error::TaskTimeout),
@@ -535,7 +539,9 @@ impl HealTask {
error = %err,
"Heal cluster pool metadata failed"
);
Err(err)
Err(Error::TaskExecutionFailed {
message: format!("Failed to heal cluster pool metadata: {err}"),
})
}
}
}
+8 -143
View File
@@ -16,7 +16,6 @@ use super::super::{DiskOption, DiskStore, Endpoint, new_disk};
use super::*;
use crate::heal::EcstoreError;
use crate::heal::storage::HealStorageObjectResult;
use crate::heal::storage_api::owner::{EcstorePoolMetadataError, EcstorePoolMetadataFailure};
mod absent_verdict;
mod concurrent_delete;
@@ -785,10 +784,7 @@ mod canonical_outcome {
async fn untraversable_bucket_does_not_claim_complete_cluster_coverage() {
let storage = Arc::new(MockStorage {
listed_buckets: Mutex::new(Some(vec!["bucket-a".to_string(), "bucket-b".to_string()])),
bucket_heal_errors: Mutex::new(HashMap::from([(
"bucket-a".to_string(),
VecDeque::from([Error::other("metadata unavailable")]),
)])),
bucket_heal_errors: Mutex::new(HashMap::from([("bucket-a".to_string(), VecDeque::from(["metadata unavailable"]))])),
..Default::default()
});
let task = HealTask::from_request(
@@ -1570,7 +1566,7 @@ struct MockStorage {
include_object_dir_candidate: Mutex<bool>,
listed_buckets: Mutex<Option<Vec<String>>>,
bucket_discovery_incomplete: bool,
bucket_heal_errors: Mutex<HashMap<String, VecDeque<Error>>>,
bucket_heal_errors: Mutex<HashMap<String, VecDeque<&'static str>>>,
bucket_heal_calls: Mutex<Vec<String>>,
delete_recovery_results: Mutex<HashMap<String, Result<Option<HealResultItem>>>>,
delete_recovery_calls: Mutex<Vec<String>>,
@@ -1994,7 +1990,6 @@ fn replacement_identity(
#[derive(Clone)]
enum MockHealObjectOutcome {
PoolMetadata { kind: EcstorePoolMetadataFailure, outer: bool },
LegacyAmbiguous { outer: bool },
MissingObject { outer: bool },
MissingVersion,
@@ -2014,16 +2009,6 @@ enum MockHealObjectOutcome {
PermanentOther(&'static str),
}
fn pool_metadata_error(kind: EcstorePoolMetadataFailure) -> Error {
Error::Storage(EcstoreError::other(EcstorePoolMetadataError {
kind,
operation: "bucket heal".to_owned(),
phase: "native_heal",
since: std::time::UNIX_EPOCH.into(),
source: None,
}))
}
fn unavailable_drive_heal_result(state: DriveState) -> (HealResultItem, Option<Error>) {
(
HealResultItem {
@@ -2195,14 +2180,6 @@ impl HealStorageAPI for MockStorage {
.and_then(VecDeque::pop_front)
{
return match outcome {
MockHealObjectOutcome::PoolMetadata { kind, outer } => {
let error = pool_metadata_error(kind);
if outer {
Err(error)
} else {
Ok((HealResultItem::default(), Some(error)))
}
}
MockHealObjectOutcome::LegacyAmbiguous { outer } => {
let error = Error::Storage(EcstoreError::DeleteRecoveryLegacyAmbiguous);
if outer {
@@ -2279,14 +2256,6 @@ impl HealStorageAPI for MockStorage {
}
if let Some(outcome) = self.heal_object_outcome.lock().unwrap().take() {
return match outcome {
MockHealObjectOutcome::PoolMetadata { kind, outer } => {
let error = pool_metadata_error(kind);
if outer {
Err(error)
} else {
Ok((HealResultItem::default(), Some(error)))
}
}
MockHealObjectOutcome::LegacyAmbiguous { outer } => {
let error = Error::Storage(EcstoreError::DeleteRecoveryLegacyAmbiguous);
if outer {
@@ -2418,14 +2387,14 @@ impl HealStorageAPI for MockStorage {
async fn heal_bucket(&self, bucket: &str, opts: &HealOpts) -> Result<HealResultItem> {
self.bucket_heal_calls.lock().unwrap().push(bucket.to_string());
self.bucket_heal_opts.lock().unwrap().push(*opts);
if let Some(error) = self
if let Some(message) = self
.bucket_heal_errors
.lock()
.unwrap()
.get_mut(bucket)
.and_then(VecDeque::pop_front)
{
return Err(error);
return Err(Error::other(message));
}
Ok(HealResultItem::default())
}
@@ -3460,70 +3429,13 @@ async fn cluster_recreate_fails_when_pool_metadata_heal_fails() {
.await
.expect_err("cluster recreate heal must not hide pool metadata failure");
assert!(matches!(err, Error::Other(ref message) if message == "pool metadata missing"));
assert!(matches!(err, Error::TaskExecutionFailed { .. }));
assert_eq!(
storage.heal_object_calls.lock().expect("object calls").as_slice(),
["object-a".to_string(), "object-b".to_string(), POOL_META_NAME.to_string()]
);
}
#[tokio::test]
async fn cluster_pool_metadata_failures_preserve_recovery_classification_in_both_response_shapes() {
for outer in [false, true] {
for (kind, retryable) in [
(EcstorePoolMetadataFailure::ReadUnavailable, true),
(EcstorePoolMetadataFailure::TransactionUnknown, true),
(EcstorePoolMetadataFailure::RecoveryRequired, false),
(EcstorePoolMetadataFailure::FenceLost, false),
] {
let storage = Arc::new(MockStorage {
listed_buckets: Mutex::new(Some(Vec::new())),
..Default::default()
});
storage.heal_object_outcomes.lock().expect("object outcomes").insert(
POOL_META_NAME.to_string(),
VecDeque::from([MockHealObjectOutcome::PoolMetadata { kind, outer }]),
);
let mut request = HealRequest::new(
HealType::Cluster,
HealOptions {
recreate_missing: true,
timeout: None,
..Default::default()
},
HealPriority::Normal,
);
request.source = HealRequestSource::Admin;
let task = HealTask::from_request(request, storage.clone());
let error = task
.execute()
.await
.expect_err("pool metadata failure must reach the scheduler");
assert!(
matches!(&error, Error::Storage(error) if error.pool_metadata_failure().is_some_and(|failure| failure.kind == kind)),
"the original typed pool metadata state must survive either response shape: {error}"
);
assert_eq!(error.is_recoverable_heal(), retryable, "{kind:?}, outer={outer}");
assert_eq!(storage.heal_object_calls.lock().expect("object calls").as_slice(), [POOL_META_NAME]);
if retryable {
let retry = task
.retry_request_with_remaining_timeout()
.await
.expect("existing retry request");
assert_eq!(retry.id, task.id, "recovery retains the accepted task token");
HealTask::from_request(retry, storage.clone())
.execute()
.await
.expect("the same task should complete after pool metadata recovery");
assert_eq!(
storage.heal_object_calls.lock().expect("object calls").as_slice(),
[POOL_META_NAME, POOL_META_NAME]
);
}
}
}
}
#[tokio::test]
async fn cluster_dry_run_does_not_heal_pool_metadata() {
let storage = Arc::new(MockStorage::default());
@@ -3887,10 +3799,7 @@ async fn test_recursive_bucket_heal_reports_typed_exhausted_and_permanent_failur
async fn test_cluster_heal_continues_after_bucket_failure() {
let storage = Arc::new(MockStorage {
listed_buckets: Mutex::new(Some(vec!["bucket-a".to_string(), "bucket-b".to_string()])),
bucket_heal_errors: Mutex::new(HashMap::from([(
"bucket-a".to_string(),
VecDeque::from([Error::other("metadata unavailable")]),
)])),
bucket_heal_errors: Mutex::new(HashMap::from([("bucket-a".to_string(), VecDeque::from(["metadata unavailable"]))])),
..Default::default()
});
let request = HealRequest::new(
@@ -3922,10 +3831,7 @@ async fn test_cluster_heal_continues_after_bucket_failure() {
async fn test_cluster_heal_retries_only_recoverable_bucket() {
let storage = Arc::new(MockStorage {
listed_buckets: Mutex::new(Some(vec!["bucket-a".to_string(), "bucket-b".to_string()])),
bucket_heal_errors: Mutex::new(HashMap::from([(
"bucket-a".to_string(),
VecDeque::from([Error::other("lock acquisition timeout")]),
)])),
bucket_heal_errors: Mutex::new(HashMap::from([("bucket-a".to_string(), VecDeque::from(["lock acquisition timeout"]))])),
..Default::default()
});
let request = HealRequest::new(
@@ -3949,47 +3855,6 @@ async fn test_cluster_heal_retries_only_recoverable_bucket() {
);
}
#[tokio::test(start_paused = true)]
async fn cluster_bucket_heal_retries_only_recoverable_pool_metadata_failures() {
for (kind, retryable) in [
(EcstorePoolMetadataFailure::ReadUnavailable, true),
(EcstorePoolMetadataFailure::TransactionUnknown, true),
(EcstorePoolMetadataFailure::RecoveryRequired, false),
(EcstorePoolMetadataFailure::FenceLost, false),
] {
let storage = Arc::new(MockStorage {
bucket_incarnation_id: Mutex::new(Some(Uuid::new_v4())),
bucket_heal_errors: Mutex::new(HashMap::from([("bucket-a".to_owned(), VecDeque::from([pool_metadata_error(kind)]))])),
..Default::default()
});
let mut request = HealRequest::new(
HealType::Cluster,
HealOptions {
recursive: true,
timeout: None,
..Default::default()
},
HealPriority::Normal,
);
request.source = HealRequestSource::Admin;
let task = HealTask::from_request(request, storage.clone());
let result = task.execute().await;
if retryable {
result.expect("a recoverable pool metadata state must not terminate the root heal");
assert_eq!(task.get_status().await, HealTaskStatus::Completed);
assert_eq!(
storage.bucket_heal_calls.lock().expect("bucket calls").as_slice(),
["bucket-a", "bucket-a"]
);
} else {
result.expect_err("operator recovery and lost fences must remain terminal");
let failure = task.take_batch_failure().await.expect("permanent cluster failure");
assert_eq!((failure.retryable, failure.permanent), (0, 1));
assert_eq!(storage.bucket_heal_calls.lock().expect("bucket calls").as_slice(), ["bucket-a"]);
}
}
}
#[tokio::test]
async fn test_recursive_bucket_heal_does_not_remove_bucket_metadata() {
let storage = Arc::new(MockStorage::default());
@@ -4752,7 +4617,7 @@ async fn erasure_set_bucket_prepass_failure_stops_before_object_heal() {
let storage = Arc::new(MockStorage {
bucket_heal_errors: Mutex::new(HashMap::from([(
"bucket-a".to_string(),
VecDeque::from([Error::other("injected bucket prepass failure")]),
VecDeque::from(["injected bucket prepass failure"]),
)])),
resume_disk: Mutex::new(Some(disk)),
..Default::default()
-313
View File
@@ -1,313 +0,0 @@
// Copyright 2026 RustFS Team
// SPDX-License-Identifier: Apache-2.0
//! Durable restrictions owned by an authenticated user. A record is not an IAM
//! grant or credential; issuing credentials still requires current IAM checks.
use crate::{error::is_err_config_not_found, store::Store};
use serde::{Deserialize, Serialize};
const PREFIX: &str = "config/iam/plugin-delegations/v1";
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Restrictions {
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present_value")]
pub version: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present_value")]
pub output_bucket: Option<String>,
pub deployment: String,
pub bucket: String,
pub input_prefix: String,
pub output_prefix: String,
pub expires_at_unix_seconds: u64,
}
// An absent v1 field is compatible; an explicitly null v2 field is invalid.
fn present_value<'de, T: Deserialize<'de>, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<T>, D::Error> {
T::deserialize(deserializer).map(Some)
}
impl Restrictions {
pub fn output_bucket(&self) -> Result<&str, DelegationError> {
match (self.version, self.output_bucket.as_deref()) {
(None, None) => Ok(&self.bucket),
(Some(2), Some(output)) => Ok(output),
_ => Err(DelegationError::Invalid),
}
}
pub fn validate(&self, now: u64) -> Result<(), DelegationError> {
let output_bucket = self.output_bucket()?;
let names: [&str; 5] = [
&self.deployment,
&self.bucket,
&self.input_prefix,
&self.output_prefix,
output_bucket,
];
if names
.iter()
.any(|s| s.is_empty() || s.len() > 1024 || s.contains("${") || s.chars().any(char::is_control))
|| self.bucket.contains('/')
|| self.bucket.contains('*')
|| self.bucket.contains('?')
|| output_bucket.contains('/')
|| output_bucket.contains('*')
|| output_bucket.contains('?')
|| self.input_prefix.contains('*')
|| self.input_prefix.contains('?')
|| self.output_prefix.contains('*')
|| self.output_prefix.contains('?')
|| self.expires_at_unix_seconds <= now
|| self.expires_at_unix_seconds.saturating_sub(now) > 86400
{
return Err(DelegationError::Invalid);
}
Ok(())
}
}
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Delegation {
pub version: u32,
pub id: String,
pub revision: String,
pub owner_access_key: String,
pub created_at_unix_seconds: u64,
pub restrictions: Restrictions,
}
#[derive(Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
struct Tombstone {
version: u32,
id: String,
revision: String,
owner_access_key: String,
}
#[derive(Debug, thiserror::Error)]
pub enum DelegationError {
#[error("invalid delegation restriction")]
Invalid,
#[error("delegation not found")]
NotFound,
#[error("delegation owner rejected")]
OwnerRejected,
#[error("delegation unavailable")]
Unavailable,
#[error("delegation revoked")]
Revoked,
#[error("delegation expired")]
Expired,
}
fn record_path(id: &str) -> Result<String, DelegationError> {
if id.len() != 32 || !id.bytes().all(|c| c.is_ascii_hexdigit()) {
return Err(DelegationError::Invalid);
}
Ok(format!("{PREFIX}/{id}/record.json"))
}
async fn load<T: Store>(store: &T, id: &str) -> Result<Delegation, DelegationError> {
let record: Delegation = store.load_iam_config_strict(record_path(id)?).await.map_err(|error| {
if is_err_config_not_found(&error) {
DelegationError::NotFound
} else {
DelegationError::Unavailable
}
})?;
if !matches!(record.version, 1 | 2)
|| record.version != record.restrictions.version.unwrap_or(1)
|| record.id != id
|| record.revision != id
|| record.owner_access_key.is_empty()
{
return Err(DelegationError::Unavailable);
}
record
.restrictions
.validate(record.created_at_unix_seconds)
.map_err(|_| DelegationError::Unavailable)?;
Ok(record)
}
pub(crate) async fn create<T: Store>(
store: &T,
owner: &str,
restrictions: Restrictions,
now: u64,
) -> Result<Delegation, DelegationError> {
restrictions.validate(now)?;
if owner.is_empty() {
return Err(DelegationError::OwnerRejected);
}
// IDs are generated exclusively here; no update operation accepts an ID.
let id = format!("{:032x}", rand::random::<u128>());
let path = record_path(&id)?;
match store.load_iam_config_strict::<Delegation>(&path).await {
Err(error) if is_err_config_not_found(&error) => {}
_ => return Err(DelegationError::Unavailable),
}
let record = Delegation {
version: restrictions.version.unwrap_or(1),
revision: id.clone(),
id,
owner_access_key: owner.to_owned(),
created_at_unix_seconds: now,
restrictions,
};
store
.save_iam_config(&record, path)
.await
.map_err(|_| DelegationError::Unavailable)?;
if load(store, &record.id).await? != record {
return Err(DelegationError::Unavailable);
}
Ok(record)
}
pub(crate) async fn revoke<T: Store>(store: &T, owner: &str, id: &str) -> Result<(), DelegationError> {
let record = load(store, id).await?;
if record.owner_access_key != owner {
return Err(DelegationError::OwnerRejected);
}
let tombstone = Tombstone {
version: 1,
id: record.id,
revision: record.revision,
owner_access_key: record.owner_access_key,
};
let path = format!("{PREFIX}/{id}/revoked.json");
// Every retry writes exactly the same revocation; active records never change.
store
.save_iam_config(&tombstone, &path)
.await
.map_err(|_| DelegationError::Unavailable)?;
let saved: Tombstone = store
.load_iam_config_strict(path)
.await
.map_err(|_| DelegationError::Unavailable)?;
if saved != tombstone {
return Err(DelegationError::Unavailable);
}
Ok(())
}
pub(crate) async fn read_active<T: Store>(store: &T, owner: &str, id: &str, now: u64) -> Result<Delegation, DelegationError> {
let record = load(store, id).await?;
if record.owner_access_key != owner {
return Err(DelegationError::OwnerRejected);
}
check_active(store, record, now).await
}
pub(crate) async fn read_owned<T: Store>(store: &T, owner: &str, id: &str) -> Result<Delegation, DelegationError> {
let record = load(store, id).await?;
if record.owner_access_key != owner {
return Err(DelegationError::OwnerRejected);
}
Ok(record)
}
pub(crate) async fn read_active_for_broker<T: Store>(store: &T, id: &str, now: u64) -> Result<Delegation, DelegationError> {
let record = load(store, id).await?;
check_active(store, record, now).await
}
async fn check_active<T: Store>(store: &T, record: Delegation, now: u64) -> Result<Delegation, DelegationError> {
let id = &record.id;
match store
.load_iam_config_strict::<Tombstone>(format!("{PREFIX}/{id}/revoked.json"))
.await
{
Ok(_) => return Err(DelegationError::Revoked),
Err(error) if is_err_config_not_found(&error) => {}
Err(_) => return Err(DelegationError::Unavailable),
}
if now >= record.restrictions.expires_at_unix_seconds {
return Err(DelegationError::Expired);
}
Ok(record)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn delegation_v1_json_remains_compatible() {
let legacy = serde_json::json!({"deployment":"runner-a","bucket":"photos",
"input_prefix":"inputs/","output_prefix":"outputs/","expires_at_unix_seconds":200});
let restriction: Restrictions = serde_json::from_value(legacy.clone()).expect("legacy restriction");
restriction.validate(100).expect("legacy validation");
assert_eq!(restriction.output_bucket().expect("v1 output"), "photos");
assert_eq!(serde_json::to_value(restriction).expect("legacy serialization"), legacy);
let record = serde_json::json!({"version":1,"id":"a".repeat(32),"revision":"a".repeat(32),
"owner_access_key":"owner","created_at_unix_seconds":100,"restrictions":legacy});
let decoded: Delegation = serde_json::from_value(record.clone()).expect("legacy record");
assert_eq!(serde_json::to_value(decoded).expect("legacy record serialization"), record);
}
#[test]
fn delegation_v2_requires_explicit_output_bucket() {
let valid = serde_json::json!({"version":2,"deployment":"runner-a","bucket":"photos",
"input_prefix":"inputs/","output_bucket":"artifacts","output_prefix":"outputs/",
"expires_at_unix_seconds":200});
let restriction: Restrictions = serde_json::from_value(valid.clone()).expect("v2 restriction");
restriction.validate(100).expect("explicit output bucket");
assert_eq!(restriction.output_bucket().expect("v2 output"), "artifacts");
assert_eq!(serde_json::to_value(restriction).expect("v2 serialization"), valid);
for key in ["version", "output_bucket"] {
let mut bad = valid.clone();
bad.as_object_mut().expect("object").remove(key);
assert!(
serde_json::from_value::<Restrictions>(bad).map_or(true, |r| r.validate(100).is_err()),
"v2 required {key}"
);
}
for (key, value) in [
("version", serde_json::json!(1)),
("version", serde_json::json!(3)),
("version", serde_json::Value::Null),
("output_bucket", serde_json::Value::Null),
("output_bucket", serde_json::json!("")),
("output_bucket", serde_json::json!("other/*")),
("output_bucket", serde_json::json!("${aws:username}")),
("output_bucket", serde_json::json!("other?")),
("output_bucket", serde_json::json!("other\n")),
("unknown", serde_json::json!(true)),
] {
let mut bad = valid.clone();
bad[key] = value;
assert!(
serde_json::from_value::<Restrictions>(bad).map_or(true, |r| r.validate(100).is_err()),
"invalid v2 {key}"
);
}
}
#[test]
fn restrictions_are_literal_bounded_and_expiring() {
let mut restriction = Restrictions {
version: None,
output_bucket: None,
deployment: "runner-a".into(),
bucket: "photos".into(),
input_prefix: "inputs/".into(),
output_prefix: "outputs/".into(),
expires_at_unix_seconds: 200,
};
assert!(restriction.validate(100).is_ok());
restriction.output_prefix = "outputs/*".into();
assert!(matches!(restriction.validate(100), Err(DelegationError::Invalid)));
restriction.output_prefix = "outputs/".into();
assert!(matches!(restriction.validate(200), Err(DelegationError::Invalid)));
restriction.expires_at_unix_seconds = 200;
restriction.input_prefix = "inputs/${aws:username}/".into();
assert!(
matches!(restriction.validate(100), Err(DelegationError::Invalid)),
"C07_LITERAL_SCOPE_BOUND: policy variables are not literal restrictions"
);
assert!(record_path("../../users").is_err());
}
}
-1
View File
@@ -28,7 +28,6 @@ pub(crate) const EVENT_OIDC_DIAGNOSTICS: &str = "oidc_diagnostics";
const EVENT_OIDC_STATE: &str = "oidc_state";
pub mod cache;
pub mod delegation;
pub mod error;
pub mod federation;
pub mod keyring;
-1
View File
@@ -91,7 +91,6 @@ pub(crate) mod crate_boundary {
pub(crate) mod object_store {
pub(crate) use super::storage_contracts::{HTTPPreconditions, ListOperations, ObjectInfoOrErr, ObjectOperations};
pub(crate) use rustfs_ecstore::api::config::com::read_config_preserve_empty_with_metadata_opts;
}
pub(crate) mod runtime {
-5
View File
@@ -26,11 +26,6 @@ pub trait Store: Clone + Send + Sync + 'static {
fn has_watcher(&self) -> bool;
async fn save_iam_config<Item: Serialize + Send>(&self, item: Item, path: impl AsRef<str> + Send) -> Result<()>;
async fn load_iam_config<Item: DeserializeOwned>(&self, path: impl AsRef<str> + Send) -> Result<Item>;
/// Only confirmed storage absence may return ConfigNotFound. Corrupt or
/// undecryptable objects must remain errors, especially for revocations.
async fn load_iam_config_strict<Item: DeserializeOwned>(&self, _path: impl AsRef<str> + Send) -> Result<Item> {
Err(crate::error::Error::IamSysNotInitialized)
}
async fn delete_iam_config(&self, path: impl AsRef<str> + Send) -> Result<()>;
async fn save_user_identity(&self, name: &str, user_type: UserType, item: UserIdentity, ttl: Option<usize>) -> Result<()>;
-46
View File
@@ -42,7 +42,6 @@ use tracing::{debug, error, warn};
use crate::storage_api::object_store::{
HTTPPreconditions, ListOperations, ObjectInfoOrErr as StorageObjectInfoOrErr, ObjectOperations,
read_config_preserve_empty_with_metadata_opts,
};
pub static IAM_CONFIG_PREFIX: LazyLock<String> = LazyLock::new(|| format!("{IAM_CONFIG_ROOT_PREFIX}/iam"));
@@ -612,11 +611,6 @@ impl ObjectStore {
Ok(serde_json::from_slice(&outcome.plain)?)
}
fn decode_iam_config_strict<Item: DeserializeOwned>(data: &[u8]) -> Result<Item> {
let outcome = Self::decrypt_data_with_source(data)?;
Ok(serde_json::from_slice(&outcome.plain)?)
}
/// Parameterized core of [`Store::load_user_identity`].
async fn load_user_identity_with(&self, name: &str, user_type: UserType, mode: LoadMode) -> Result<UserIdentity> {
let mut u: UserIdentity = self
@@ -830,12 +824,6 @@ impl Store for ObjectStore {
async fn load_iam_config<Item: DeserializeOwned>(&self, path: impl AsRef<str> + Send) -> Result<Item> {
self.load_iam_config_with(path, LoadMode::Locked).await
}
async fn load_iam_config_strict<Item: DeserializeOwned>(&self, path: impl AsRef<str> + Send) -> Result<Item> {
let (data, _) =
read_config_preserve_empty_with_metadata_opts(self.object_api.clone(), path.as_ref(), &LoadMode::Locked.read_opts())
.await?;
Self::decode_iam_config_strict(&data)
}
/// Saves IAM configuration with a retry mechanism on failure.
///
/// Attempts to save the IAM configuration up to 5 times if the storage layer is not ready,
@@ -1470,40 +1458,6 @@ mod tests {
assert!(result.is_err(), "corrupt stream_io data should fail decrypt");
}
#[test]
fn strict_revocation_load_keeps_real_crypto_failure_distinct_from_absence() {
let cred = test_cred();
let key = format!("{}:{}", cred.access_key, cred.secret_key);
let plain = br#"{"version":1,"id":"revoked"}"#;
let mut encrypted = rustfs_crypto::encrypt_stream_io(key.as_bytes(), plain).expect("real stored ciphertext");
// Exercise the exact decoder used after the actual object read.
assert!(ObjectStore::decode_iam_config_strict::<serde_json::Value>(&encrypted).is_ok());
encrypted[50] ^= 0xFF;
let error = ObjectStore::decode_iam_config_strict::<serde_json::Value>(&encrypted)
.expect_err("corrupt tombstone must not become missing");
assert!(
matches!(error, Error::CryptoError(_)),
"C07_REVOCATION_FAIL_CLOSED: preserve actual crypto error"
);
assert!(
!crate::error::is_err_config_not_found(&error),
"C07_REVOCATION_FAIL_CLOSED: corrupted revocation is not absence"
);
// The preserve-empty reader keeps an existing zero-byte object as
// Ok(empty); ecstore's read_config_preserve_empty_distinguishes_empty_object
// covers that storage boundary. Its payload must fail here, not become
// ConfigNotFound and reactivate a revoked delegation.
let empty =
ObjectStore::decode_iam_config_strict::<serde_json::Value>(&[]).expect_err("an existing empty tombstone is corrupt");
assert!(
!crate::error::is_err_config_not_found(&empty),
"C07_REVOCATION_FAIL_CLOSED: empty existing revocation is not absence"
);
let invalid_json =
ObjectStore::decode_iam_config_strict::<serde_json::Value>(br#"{"version": }"#).expect_err("invalid stored JSON");
assert!(!crate::error::is_err_config_not_found(&invalid_json));
}
#[test]
fn test_decrypt_data_short_data_fails() {
let short = &[0x00u8; 40]; // less than 41-byte stream_io header, not valid JSON
+7 -257
View File
@@ -75,7 +75,6 @@ pub const STATUS_ENABLED: &str = "enabled";
pub const STATUS_DISABLED: &str = "disabled";
pub const POLICYNAME: &str = "policy";
pub const PLUGIN_ATTEMPT_CREDENTIAL_CLAIM: &str = "rustfs:plugin-attempt-v1";
pub const SESSION_POLICY_NAME: &str = "sessionPolicy";
pub const SESSION_POLICY_NAME_EXTRACTED: &str = "sessionPolicy-extracted";
const VERIFIED_FEDERATED_POLICY_CLAIM: &str = "x-rustfs-internal-federated-policy";
@@ -169,12 +168,6 @@ enum PreparedServicePolicyMode {
#[derive(Clone)]
enum PreparedIamMode {
TerminalDeny,
PluginAttemptSts {
is_owner: bool,
combined_policy: Policy,
session_policy: PreparedSessionPolicy,
},
Opa,
Owner,
Deny,
@@ -209,7 +202,7 @@ impl PreparedIamAuth {
pub async fn needs_existing_object_tag_for_args(&self, args: &Args<'_>) -> bool {
match &self.mode {
PreparedIamMode::Opa => true,
PreparedIamMode::Owner | PreparedIamMode::Deny | PreparedIamMode::TerminalDeny => false,
PreparedIamMode::Owner | PreparedIamMode::Deny => false,
PreparedIamMode::Regular { combined_policy } => {
policy_needs_existing_object_tag_for_args(combined_policy, args).await
}
@@ -217,11 +210,6 @@ impl PreparedIamAuth {
combined_policy,
session_policy,
..
}
| PreparedIamMode::PluginAttemptSts {
combined_policy,
session_policy,
..
} => {
policy_needs_existing_object_tag_for_args(combined_policy, args).await
|| prepared_session_policy_needs_existing_object_tag_for_args(session_policy, args).await
@@ -251,56 +239,14 @@ impl PreparedIamAuth {
pub fn combined_policy_for_view(&self) -> Option<&Policy> {
match &self.mode {
PreparedIamMode::Regular { combined_policy } => Some(combined_policy),
PreparedIamMode::Sts { combined_policy, .. } | PreparedIamMode::PluginAttemptSts { combined_policy, .. } => {
Some(combined_policy)
}
PreparedIamMode::Sts { combined_policy, .. } => Some(combined_policy),
PreparedIamMode::ServiceAccount { combined_policy, .. } => Some(combined_policy),
PreparedIamMode::Opa | PreparedIamMode::Owner | PreparedIamMode::Deny | PreparedIamMode::TerminalDeny => None,
PreparedIamMode::Opa | PreparedIamMode::Owner | PreparedIamMode::Deny => None,
}
}
}
impl<T: Store> IamSys<T> {
/// For the authenticated, explicitly configured broker handler only.
pub async fn read_active_plugin_delegation_for_broker(
&self,
id: &str,
now: u64,
) -> std::result::Result<crate::delegation::Delegation, crate::delegation::DelegationError> {
crate::delegation::read_active_for_broker(&self.store.api, id, now).await
}
pub async fn create_plugin_delegation(
&self,
owner: &str,
restrictions: crate::delegation::Restrictions,
now: u64,
) -> std::result::Result<crate::delegation::Delegation, crate::delegation::DelegationError> {
crate::delegation::create(&self.store.api, owner, restrictions, now).await
}
pub async fn revoke_plugin_delegation(
&self,
owner: &str,
id: &str,
) -> std::result::Result<(), crate::delegation::DelegationError> {
crate::delegation::revoke(&self.store.api, owner, id).await
}
pub async fn read_active_plugin_delegation(
&self,
owner: &str,
id: &str,
now: u64,
) -> std::result::Result<crate::delegation::Delegation, crate::delegation::DelegationError> {
crate::delegation::read_active(&self.store.api, owner, id, now).await
}
/// Reads an owned delegation record for historical lookups, including expired or revoked records.
pub async fn read_owned_plugin_delegation(
&self,
owner: &str,
id: &str,
) -> std::result::Result<crate::delegation::Delegation, crate::delegation::DelegationError> {
crate::delegation::read_owned(&self.store.api, owner, id).await
}
/// Create a new IamSys instance with the given IamCache store
///
/// # Arguments
@@ -335,16 +281,6 @@ impl<T: Store> IamSys<T> {
*guard = PolicyPluginState::Ready(client);
}
/// Restricted credentials require the built-in parent/session intersection.
/// External authorization bypasses that path, so only Disabled is supported.
pub async fn ensure_restricted_credential_vending() -> Result<()> {
if matches!(Self::policy_plugin_state().await, PolicyPluginState::Disabled) {
Ok(())
} else {
Err(Error::IAMActionNotAllowed)
}
}
pub async fn get_policy_plugin_client() -> Option<rustfs_policy::policy::opa::AuthZPlugin> {
let policy_plugin_state = get_policy_plugin_state();
let guard = policy_plugin_state.read().await;
@@ -1447,50 +1383,17 @@ impl<T: Store> IamSys<T> {
/// 1) know whether policy evaluation may need `s3:ExistingObjectTag`, and
/// 2) evaluate with final conditions without re-merging identity policies.
pub async fn prepare_auth(&self, args: &Args<'_>) -> PreparedIamAuth {
let marked = args.claims.contains_key(PLUGIN_ATTEMPT_CREDENTIAL_CLAIM);
if args.is_owner && !marked {
if args.is_owner {
return PreparedIamAuth {
needs_existing_object_tag: false,
mode: PreparedIamMode::Owner,
};
}
// One observed state decides this request's path. Marked credentials
// never enter OPA, including after a restart or on another node.
let state = Self::policy_plugin_state().await;
if marked {
if args.is_owner
|| args.claims.get(PLUGIN_ATTEMPT_CREDENTIAL_CLAIM) != Some(&Value::Bool(true))
|| !matches!(state, PolicyPluginState::Disabled)
{
return PreparedIamAuth {
needs_existing_object_tag: false,
mode: PreparedIamMode::TerminalDeny,
};
}
let prepared = self.prepare_builtin_auth(args).await;
let mode = match prepared.mode {
PreparedIamMode::Sts {
is_owner,
combined_policy,
session_policy,
} => PreparedIamMode::PluginAttemptSts {
is_owner,
combined_policy,
session_policy,
},
_ => PreparedIamMode::TerminalDeny,
};
return PreparedIamAuth {
needs_existing_object_tag: prepared.needs_existing_object_tag,
mode,
};
}
if let Some(prepared) = state.prepared_iam_auth() {
if let Some(prepared) = Self::policy_plugin_state().await.prepared_iam_auth() {
return prepared;
}
self.prepare_builtin_auth(args).await
}
async fn prepare_builtin_auth(&self, args: &Args<'_>) -> PreparedIamAuth {
let Ok((is_svc, parent_user)) = self.is_service_account(args.account).await else {
return PreparedIamAuth {
needs_existing_object_tag: false,
@@ -1522,20 +1425,6 @@ impl<T: Store> IamSys<T> {
/// bucket policies on an IAM denial. An error must not become an implicit deny.
pub async fn try_eval_prepared(&self, prepared: &PreparedIamAuth, args: &Args<'_>) -> Result<bool> {
Ok(match &prepared.mode {
PreparedIamMode::TerminalDeny => return Err(Error::IAMActionNotAllowed),
PreparedIamMode::PluginAttemptSts {
is_owner,
combined_policy,
session_policy,
} => {
// A false IAM result permits bucket-policy fallback. Restricted
// plugin credentials must instead terminate authorization.
let session_allowed = evaluate_prepared_session_policy(session_policy, args).await == Some(true);
if !session_allowed || !(*is_owner || combined_policy.is_allowed(args).await) {
return Err(Error::IAMActionNotAllowed);
}
true
}
PreparedIamMode::Opa => {
let Some(opa_enable) = Self::get_policy_plugin_client().await else {
tracing::warn!("eval_prepared: OPA mode requested but plugin is unavailable");
@@ -2238,145 +2127,6 @@ mod tests {
assert!(prepared.combined_policy_for_view().is_none());
}
#[tokio::test]
#[serial]
async fn marked_signed_sts_denial_is_terminal_before_public_bucket_fallback() {
let iam = IamSys::new(IamCache::new(StsTestMockStore::new(false)).await.unwrap());
let previous = IamSys::<StsTestMockStore>::policy_plugin_state().await;
let signing_key = "c07-test-token-signing-key";
let mut metadata=HashMap::from([
("parent".into(),Value::String("sts-fallback-test-parent".into())),
("exp".into(),serde_json::json!((OffsetDateTime::now_utc()+time::Duration::hours(1)).unix_timestamp())),
(SESSION_POLICY_NAME.into(),Value::String(base64_simd::URL_SAFE_NO_PAD.encode_to_string(br#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::mybucket/inside"]}]}"#))),
]);
metadata.insert(PLUGIN_ATTEMPT_CREDENTIAL_CLAIM.into(), Value::Bool(true));
let mut marked = get_new_credentials_with_metadata(&metadata, signing_key).unwrap();
marked.parent_user = "sts-fallback-test-parent".into();
let marked_claims: HashMap<String, Value> = rustfs_policy::utils::extract_claims(&marked.session_token, signing_key)
.expect("signed test credentials must decode")
.claims;
let marked_user = UserIdentity::from(marked.clone());
iam.store
.cache
.add_or_update_sts_account(&marked.access_key, &marked_user, OffsetDateTime::now_utc());
metadata.remove(PLUGIN_ATTEMPT_CREDENTIAL_CLAIM);
let mut ordinary = get_new_credentials_with_metadata(&metadata, signing_key).unwrap();
ordinary.parent_user = marked.parent_user.clone();
let ordinary_claims: HashMap<String, Value> = rustfs_policy::utils::extract_claims(&ordinary.session_token, signing_key)
.expect("signed test credentials must decode")
.claims;
iam.store.cache.add_or_update_sts_account(
&ordinary.access_key,
&UserIdentity::from(ordinary.clone()),
OffsetDateTime::now_utc(),
);
let groups = None;
let conditions = HashMap::new();
let args = Args {
account: &marked.access_key,
groups: &groups,
action: Action::S3Action(S3Action::GetObjectAction),
bucket: "mybucket",
object: "outside",
conditions: &conditions,
is_owner: false,
claims: &marked_claims,
deny_only: false,
};
*get_policy_plugin_state().write().await = PolicyPluginState::Disabled;
let denied = iam.prepare_auth(&args).await;
let disabled_terminal = matches!(iam.try_eval_prepared(&denied, &args).await, Err(Error::IAMActionNotAllowed));
let inside = Args {
object: "inside",
..args.clone()
};
let allowed = iam.prepare_auth(&inside).await;
let inside_allowed = matches!(iam.try_eval_prepared(&allowed, &inside).await, Ok(true));
let unmarked_args = Args {
account: &ordinary.access_key,
claims: &ordinary_claims,
..args.clone()
};
let unmarked = iam.prepare_auth(&unmarked_args).await;
let ordinary_false = matches!(iam.try_eval_prepared(&unmarked, &unmarked_args).await, Ok(false));
let public:rustfs_policy::policy::BucketPolicy=serde_json::from_value(serde_json::json!({"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":["*"]},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::mybucket/*"]}]})).unwrap();
let public_allows = public
.is_allowed(&rustfs_policy::policy::BucketPolicyArgs {
account: &marked.access_key,
groups: &groups,
action: args.action,
bucket: args.bucket,
object: args.object,
conditions: &conditions,
is_owner: false,
})
.await;
IamSys::<StsTestMockStore>::set_policy_plugin_client(opa::AuthZPlugin::new(opa::Args {
url: "http://127.0.0.1:8181/allow".into(),
auth_token: String::new(),
}))
.await;
let opa_marked = iam.prepare_auth(&args).await;
let ready_terminal = matches!(iam.try_eval_prepared(&opa_marked, &args).await, Err(Error::IAMActionNotAllowed));
let opa_ordinary = iam.prepare_auth(&unmarked_args).await;
let ordinary_keeps_opa = matches!(opa_ordinary.mode, PreparedIamMode::Opa);
// The captured Disabled preparation stays on built-in intersection even
// if an external policy client becomes ready before evaluation.
let captured_still_terminal = matches!(iam.try_eval_prepared(&denied, &args).await, Err(Error::IAMActionNotAllowed));
*get_policy_plugin_state().write().await = PolicyPluginState::Initializing;
let pending = iam.prepare_auth(&args).await;
let initializing_terminal = matches!(iam.try_eval_prepared(&pending, &args).await, Err(Error::IAMActionNotAllowed));
*get_policy_plugin_state().write().await = PolicyPluginState::Failed;
let failed = iam.prepare_auth(&args).await;
let failed_terminal = matches!(iam.try_eval_prepared(&failed, &args).await, Err(Error::IAMActionNotAllowed));
*get_policy_plugin_state().write().await = previous;
assert!(public_allows, "C07_PUBLIC_BUCKET_CONTROL: real public policy permits outside object");
assert!(
disabled_terminal && captured_still_terminal,
"C07_SCOPE_TERMINAL_BOUND: bucket policy must not rescue restricted scope denial"
);
assert!(
ready_terminal && initializing_terminal && failed_terminal,
"C07_EXTERNAL_POLICY_BOUND: marked persisted STS cannot enter OPA"
);
assert!(
inside_allowed && ordinary_false && ordinary_keeps_opa,
"C07_UNMARKED_COMPAT: preserve ordinary STS and valid marked scope"
);
}
#[tokio::test]
#[serial]
async fn restricted_vending_rejects_actual_external_policy_plugin_state() {
let previous = IamSys::<StsTestMockStore>::policy_plugin_state().await;
IamSys::<StsTestMockStore>::set_policy_plugin_client(opa::AuthZPlugin::new(opa::Args {
url: "http://127.0.0.1:8181/v1/data/rustfs/authz/allow".into(),
auth_token: String::new(),
}))
.await;
let active_rejected = IamSys::<StsTestMockStore>::ensure_restricted_credential_vending()
.await
.is_err();
*get_policy_plugin_state().write().await = PolicyPluginState::Initializing;
let initializing_rejected = IamSys::<StsTestMockStore>::ensure_restricted_credential_vending()
.await
.is_err();
*get_policy_plugin_state().write().await = PolicyPluginState::Failed;
let failed_rejected = IamSys::<StsTestMockStore>::ensure_restricted_credential_vending()
.await
.is_err();
*get_policy_plugin_state().write().await = PolicyPluginState::Disabled;
let disabled_allowed = IamSys::<StsTestMockStore>::ensure_restricted_credential_vending()
.await
.is_ok();
*get_policy_plugin_state().write().await = previous;
assert!(
active_rejected && initializing_rejected && failed_rejected,
"C07_EXTERNAL_POLICY_BOUND: external authorization cannot bypass minted session scope"
);
assert!(disabled_allowed);
}
#[tokio::test]
#[serial]
async fn test_prepare_auth_requests_existing_object_tags_in_opa_mode() {
-56
View File
@@ -568,24 +568,6 @@ pub enum AdminAction {
GetTableLifecycleAction,
#[strum(serialize = "admin:SetTableLifecycle")]
SetTableLifecycleAction,
#[strum(serialize = "admin:CreatePluginDelegation")]
CreatePluginDelegationAction,
#[strum(serialize = "admin:IssuePluginAttempt")]
IssuePluginAttemptAction,
#[strum(serialize = "admin:SubmitPluginJob")]
SubmitPluginJobAction,
#[strum(serialize = "admin:GetPluginRun")]
GetPluginRunAction,
#[strum(serialize = "admin:CancelPluginRun")]
CancelPluginRunAction,
#[strum(serialize = "admin:ListPluginRuns")]
ListPluginRunsAction,
#[strum(serialize = "admin:ReplayPluginRun")]
ReplayPluginRunAction,
#[strum(serialize = "admin:GetPluginDelegation")]
GetPluginDelegationAction,
#[strum(serialize = "admin:RevokePluginDelegation")]
RevokePluginDelegationAction,
#[strum(serialize = "admin:GetTableCredentials")]
GetTableCredentialsAction,
#[strum(serialize = "admin:RunTableMaintenance")]
@@ -731,15 +713,6 @@ impl AdminAction {
| AdminAction::GetTableLifecycleAction
| AdminAction::SetTableLifecycleAction
| AdminAction::GetTableCredentialsAction
| AdminAction::IssuePluginAttemptAction
| AdminAction::SubmitPluginJobAction
| AdminAction::GetPluginRunAction
| AdminAction::CancelPluginRunAction
| AdminAction::ListPluginRunsAction
| AdminAction::ReplayPluginRunAction
| AdminAction::GetPluginDelegationAction
| AdminAction::CreatePluginDelegationAction
| AdminAction::RevokePluginDelegationAction
| AdminAction::RunTableMaintenanceAction
| AdminAction::GetTableMetadataLocationAction
| AdminAction::SetTableMetadataLocationAction
@@ -940,35 +913,6 @@ mod tests {
assert_eq!(arr[0].as_str().unwrap(), "s3:*");
}
#[test]
fn plugin_delegation_actions_are_explicit_and_unscoped() {
for (name, expected) in [
("admin:GetPluginDelegation", AdminAction::GetPluginDelegationAction),
("admin:CreatePluginDelegation", AdminAction::CreatePluginDelegationAction),
("admin:RevokePluginDelegation", AdminAction::RevokePluginDelegationAction),
("admin:SubmitPluginJob", AdminAction::SubmitPluginJobAction),
("admin:GetPluginRun", AdminAction::GetPluginRunAction),
("admin:CancelPluginRun", AdminAction::CancelPluginRunAction),
("admin:ListPluginRuns", AdminAction::ListPluginRunsAction),
("admin:ReplayPluginRun", AdminAction::ReplayPluginRunAction),
] {
assert_eq!(AdminAction::try_from(name).unwrap(), expected);
assert!(expected.is_valid());
assert!(!expected.is_table_resource_scoped());
}
assert_eq!(
AdminAction::try_from("admin:IssuePluginAttempt").unwrap(),
AdminAction::IssuePluginAttemptAction
);
assert!(AdminAction::IssuePluginAttemptAction.is_valid());
assert!(AdminAction::SubmitPluginJobAction.is_valid());
assert!(AdminAction::GetPluginRunAction.is_valid());
assert!(AdminAction::CancelPluginRunAction.is_valid());
assert!(AdminAction::ListPluginRunsAction.is_valid());
assert!(AdminAction::ReplayPluginRunAction.is_valid());
assert!(AdminAction::try_from("admin:IssuePluginCredentials").is_err());
}
#[test]
fn test_get_replication_metrics_admin_action_is_valid() {
assert!(AdminAction::GetReplicationMetricsAction.is_valid());
+1 -14
View File
@@ -740,15 +740,6 @@ pub(super) fn completed_data_usage_info(
.map(|candidate| (candidate.data, candidate.last_update))
}
/// Certify an incarnation only when every contributing set reports the same non-nil identity.
fn certified_bucket_incarnation(results: &[DataUsageCache], bucket: &str) -> Option<uuid::Uuid> {
let mut identities = results
.iter()
.map(|result| result.info.scan_bucket_incarnations.get(bucket).copied());
let first = identities.next().flatten().filter(|id| !id.is_nil())?;
identities.all(|id| id == Some(first)).then_some(first)
}
pub(super) fn completed_usage_candidate(
results: &[DataUsageCache],
scope: &ScannerSnapshotScope<'_>,
@@ -801,11 +792,7 @@ pub(super) fn completed_usage_candidate(
let merged_last_update = validated.last_update;
let buckets_usage = bucket_entries
.into_iter()
.map(|(bucket, entry)| {
let mut usage = checked_bucket_usage_info(entry).ok_or(CandidateOutcome::UsageCounters)?;
usage.bucket_incarnation = certified_bucket_incarnation(results, &bucket).map(|id| id.to_string());
Ok((bucket, usage))
})
.map(|(bucket, entry)| Ok((bucket, checked_bucket_usage_info(entry).ok_or(CandidateOutcome::UsageCounters)?)))
.collect::<std::result::Result<HashMap<_, _>, CandidateOutcome>>()?;
let bucket_sizes = buckets_usage
.iter()
+2 -184
View File
@@ -238,71 +238,6 @@ pub enum ScannerDurableDirtyUsageReplayScope {
TopLevelEntries { entries: BTreeSet<String> },
}
impl ScannerDurableDirtyUsageReplayRecord {
/// Replays decoded producer hints with the canonical byte limit and semantic checks.
///
/// Callers must retain their framing and owner checks. This performs the same
/// state update as [`replay_durable_dirty_usage_producer_record`]; it does not
/// establish storage-verified source authority.
pub fn replay(self) -> std::result::Result<ScannerDirtyUsageState, ScannerDurableDirtyUsageReplayError> {
check_durable_dirty_usage_replay_bytes(&self)?;
replay_decoded_dirty_usage_record(&self)
}
}
struct ReplayByteLimit {
remaining: usize,
}
impl std::io::Write for ReplayByteLimit {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.remaining = self
.remaining
.checked_sub(bytes.len())
.ok_or_else(|| std::io::Error::other("dirty replay byte limit"))?;
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn check_durable_dirty_usage_replay_bytes(
record: &ScannerDurableDirtyUsageReplayRecord,
) -> std::result::Result<(), ScannerDurableDirtyUsageReplayError> {
// Bound structure traversal and string scanning before counting escaped JSON.
// Each entry or prefix contributes at least one additional serialized byte.
let mut remaining = SCANNER_DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES;
let mut charge = |size: usize| -> std::result::Result<(), ScannerDurableDirtyUsageReplayError> {
remaining = remaining
.checked_sub(size)
.ok_or(ScannerDurableDirtyUsageReplayError::ByteLimit)?;
Ok(())
};
charge(record.writer_epoch.len())?;
charge(record.entries.len())?;
for entry in &record.entries {
charge(entry.bucket.len())?;
if let ScannerDurableDirtyUsageReplayScope::TopLevelEntries { entries } = &entry.scope {
charge(entries.len())?;
for entry in entries {
charge(entry.len())?;
}
}
}
let mut limit = ReplayByteLimit {
remaining: SCANNER_DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES,
};
serde_json::to_writer(&mut limit, record).map_err(|error| {
if error.is_io() {
ScannerDurableDirtyUsageReplayError::ByteLimit
} else {
ScannerDurableDirtyUsageReplayError::InvalidJson
}
})
}
pub fn encode_durable_dirty_usage_producer_replay_record(
entries: Vec<ScannerDurableDirtyUsageReplayEntry>,
) -> std::result::Result<Vec<u8>, ScannerDurableDirtyUsageReplayError> {
@@ -328,13 +263,7 @@ pub fn replay_durable_dirty_usage_producer_record(
}
let record: ScannerDurableDirtyUsageReplayRecord =
serde_json::from_slice(bytes).map_err(|_| ScannerDurableDirtyUsageReplayError::InvalidJson)?;
replay_decoded_dirty_usage_record(&record)
}
fn replay_decoded_dirty_usage_record(
record: &ScannerDurableDirtyUsageReplayRecord,
) -> std::result::Result<ScannerDirtyUsageState, ScannerDurableDirtyUsageReplayError> {
let replay = validate_durable_dirty_usage_replay_record(record)?;
let replay = validate_durable_dirty_usage_replay_record(&record)?;
let max_generation = replay.iter().map(|entry| entry.generation).max().unwrap_or(0);
set_dirty_usage_generation_floor(max_generation)?;
let pending = {
@@ -843,109 +772,6 @@ mod scoped_dirty_usage_tests {
);
}
fn decoded_replay_fixture() -> ScannerDurableDirtyUsageReplayRecord {
ScannerDurableDirtyUsageReplayRecord {
schema: SCANNER_DURABLE_DIRTY_USAGE_REPLAY_SCHEMA,
cache_key_format: crate::DATA_USAGE_CACHE_KEY_FORMAT,
writer_epoch: "writer".to_string(),
entries: vec![ScannerDurableDirtyUsageReplayEntry {
bucket: "photos".to_string(),
generation: 7,
scope: ScannerDurableDirtyUsageReplayScope::TopLevelEntries {
entries: BTreeSet::from(["2026".to_string(), "archive".to_string()]),
},
producers: SegmentInvalidationProducerIdentity::REQUIRED_PRODUCTION.into_iter().collect(),
}],
}
}
#[test]
#[serial]
fn durable_dirty_usage_decoded_replay_matches_byte_replay_at_size_boundary() {
let record = decoded_replay_fixture();
let fixed_bytes = serde_json::to_vec(&record).expect("fixture encoding").len() - record.writer_epoch.len();
for size in [
SCANNER_DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES - 1,
SCANNER_DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES,
SCANNER_DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES + 1,
] {
clear_dirty_usage_buckets_for_tests();
let mut record = record.clone();
record.writer_epoch = "x".repeat(size - fixed_bytes);
let bytes = serde_json::to_vec(&record).expect("bounded fixture encoding");
assert_eq!(bytes.len(), size);
let expected = replay_durable_dirty_usage_producer_record(&bytes);
let buckets = dirty_usage_buckets_for_tests();
let scopes = dirty_usage_bucket_scopes_for_tests();
let identities = dirty_usage_producer_identities().clone();
let coverage = DIRTY_USAGE_PRODUCER_COVERAGE.load(Ordering::Acquire);
clear_dirty_usage_buckets_for_tests();
assert_eq!(record.replay(), expected, "canonical size {size}");
assert_eq!(dirty_usage_buckets_for_tests(), buckets);
assert_eq!(dirty_usage_bucket_scopes_for_tests(), scopes);
assert_eq!(*dirty_usage_producer_identities(), identities);
assert_eq!(DIRTY_USAGE_PRODUCER_COVERAGE.load(Ordering::Acquire), coverage);
}
clear_dirty_usage_buckets_for_tests();
}
#[test]
fn durable_dirty_usage_decoded_size_counts_escaped_utf8() {
for repeats in [6000, 8000] {
let mut record = decoded_replay_fixture();
record.writer_epoch = "\"\n雪\\".repeat(repeats);
let bytes = serde_json::to_vec(&record).expect("escaped fixture encoding");
let expected = if bytes.len() > SCANNER_DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES {
Err(ScannerDurableDirtyUsageReplayError::ByteLimit)
} else {
Ok(())
};
assert_eq!(check_durable_dirty_usage_replay_bytes(&record), expected);
}
}
#[test]
#[serial]
fn durable_dirty_usage_decoded_replay_rejects_large_values_before_state_changes() {
for field in ["epoch", "prefix", "entries"] {
clear_dirty_usage_buckets_for_tests();
let before = scanner_dirty_usage_state();
let mut record = decoded_replay_fixture();
match field {
"epoch" => record.writer_epoch = "x".repeat(1024 * 1024),
"prefix" => {
record.entries[0].scope = ScannerDurableDirtyUsageReplayScope::TopLevelEntries {
entries: BTreeSet::from(["x".repeat(1024 * 1024)]),
};
}
_ => record.entries = vec![record.entries[0].clone(); SCANNER_DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES + 1],
}
assert_eq!(record.replay(), Err(ScannerDurableDirtyUsageReplayError::ByteLimit), "{field}");
assert_eq!(scanner_dirty_usage_state(), before);
assert!(dirty_usage_buckets_for_tests().is_empty());
assert!(dirty_usage_bucket_scopes_for_tests().is_empty());
assert!(dirty_usage_producer_identities().is_empty());
assert_eq!(DIRTY_USAGE_PRODUCER_COVERAGE.load(Ordering::Acquire), 0);
}
clear_dirty_usage_buckets_for_tests();
}
#[test]
#[serial]
fn durable_dirty_usage_decoded_replay_preserves_generation_exhaustion() {
clear_dirty_usage_buckets_for_tests();
let generation = DIRTY_USAGE_BUCKET_GENERATION.swap(u64::MAX, Ordering::AcqRel);
let result = decoded_replay_fixture().replay();
DIRTY_USAGE_BUCKET_GENERATION.store(generation, Ordering::Release);
assert_eq!(result, Err(ScannerDurableDirtyUsageReplayError::InvalidGeneration));
assert!(dirty_usage_buckets_for_tests().is_empty());
assert!(dirty_usage_bucket_scopes_for_tests().is_empty());
assert!(dirty_usage_producer_identities().is_empty());
assert_eq!(DIRTY_USAGE_PRODUCER_COVERAGE.load(Ordering::Acquire), 0);
clear_dirty_usage_buckets_for_tests();
}
#[test]
#[serial]
fn durable_dirty_usage_replay_rejects_invalid_records_without_partial_state() {
@@ -1017,17 +843,9 @@ mod scoped_dirty_usage_tests {
for (bytes, expected_error) in invalid_cases {
clear_dirty_usage_buckets_for_tests();
let before = scanner_dirty_usage_state();
assert_eq!(replay_durable_dirty_usage_producer_record(&bytes), Err(expected_error.clone()));
assert_eq!(replay_durable_dirty_usage_producer_record(&bytes), Err(expected_error));
assert!(dirty_usage_buckets_for_tests().is_empty());
assert!(dirty_usage_bucket_scopes_for_tests().is_empty());
let record: ScannerDurableDirtyUsageReplayRecord = serde_json::from_slice(&bytes).expect("typed invalid record");
assert_eq!(record.replay(), Err(expected_error));
assert_eq!(scanner_dirty_usage_state(), before);
assert!(dirty_usage_buckets_for_tests().is_empty());
assert!(dirty_usage_bucket_scopes_for_tests().is_empty());
assert!(dirty_usage_producer_identities().is_empty());
assert_eq!(DIRTY_USAGE_PRODUCER_COVERAGE.load(Ordering::Acquire), 0);
}
clear_dirty_usage_buckets_for_tests();
+305 -3
View File
@@ -14,6 +14,102 @@
/// ScannerIO/ScannerIOCycle implementations for ECStore: bucket planning and per-set fan-out.
use super::*;
#[derive(Clone, Copy)]
struct CollectorSlotSample<'a> {
index: usize,
expected: DataUsageCacheSource,
observed: bool,
snapshot: &'a DataUsageCache,
}
#[derive(Default)]
struct CollectorSlotSummary<'a> {
observed: usize,
unobserved: usize,
incomplete: usize,
missing_last_update: usize,
missing_source: usize,
source_mismatch: usize,
cycle_mismatch: usize,
epoch_mismatch: usize,
missing_plan: usize,
plan_mismatch: usize,
anomalous: usize,
sample: Option<CollectorSlotSample<'a>>,
source_difference_sample: Option<CollectorSlotSample<'a>>,
}
fn summarize_collector_slots<'a>(
slots: impl IntoIterator<Item = (usize, DataUsageCacheSource, bool, &'a DataUsageCache)>,
cycle: u64,
leader_epoch: u64,
plan: DataUsageScanPlanDigest,
) -> CollectorSlotSummary<'a> {
let mut summary = CollectorSlotSummary::default();
for (index, expected, observed, snapshot) in slots {
let mut anomalous = !observed;
if observed {
summary.observed += 1;
let info = &snapshot.info;
let incomplete = !info.snapshot_complete;
let missing_last_update = info.last_update.is_none();
let missing_source = info.source.is_none();
let source_mismatch = info.source.is_some_and(|source| source != expected);
let cycle_mismatch = info.next_cycle != cycle;
let epoch_mismatch = info.leader_epoch != leader_epoch;
let missing_plan = info.scan_plan_digest.is_none();
let plan_mismatch = info.scan_plan_digest.is_some_and(|actual| actual != plan);
summary.incomplete += usize::from(incomplete);
summary.missing_last_update += usize::from(missing_last_update);
summary.missing_source += usize::from(missing_source);
summary.source_mismatch += usize::from(source_mismatch);
summary.cycle_mismatch += usize::from(cycle_mismatch);
summary.epoch_mismatch += usize::from(epoch_mismatch);
summary.missing_plan += usize::from(missing_plan);
summary.plan_mismatch += usize::from(plan_mismatch);
if source_mismatch {
let sample_key = (expected.pool_index, expected.set_index, index);
if summary
.source_difference_sample
.is_none_or(|sample| sample_key < (sample.expected.pool_index, sample.expected.set_index, sample.index))
{
summary.source_difference_sample = Some(CollectorSlotSample {
index,
expected,
observed,
snapshot,
});
}
}
anomalous = incomplete
|| missing_last_update
|| missing_source
|| cycle_mismatch
|| epoch_mismatch
|| missing_plan
|| plan_mismatch;
} else {
summary.unobserved += 1;
}
if anomalous {
summary.anomalous += 1;
let sample_key = (expected.pool_index, expected.set_index, index);
if summary
.sample
.is_none_or(|sample| sample_key < (sample.expected.pool_index, sample.expected.set_index, sample.index))
{
summary.sample = Some(CollectorSlotSample {
index,
expected,
observed,
snapshot,
});
}
}
}
summary
}
#[async_trait::async_trait]
impl ScannerIO for ECStore {
async fn nsscanner(
@@ -605,7 +701,8 @@ where
record_set_scans_active(0);
let results = vec![DataUsageCache::default(); total_results];
let results_mutex: Arc<Mutex<Vec<DataUsageCache>>> = Arc::new(Mutex::new(results));
let observed_slots = vec![false; total_results];
let results_mutex = Arc::new(Mutex::new((results, observed_slots)));
let first_err_mutex: Arc<Mutex<Option<Error>>> = Arc::new(Mutex::new(None));
let mut wait_futs = Vec::new();
@@ -659,7 +756,8 @@ where
let receiver_fut = tokio::spawn(async move {
while let Some(result) = rx.recv().await {
let mut results = results_mutex_clone.lock().await;
results[results_index_clone] = result;
results.0[results_index_clone] = result;
results.1[results_index_clone] = true;
}
});
wait_futs.push(AbortOnDropHandle::new(receiver_fut));
@@ -780,7 +878,7 @@ where
let first_err = first_err_mutex.lock().await.take();
let has_set_failure = first_err.is_some();
// Every collector has joined; transfer the caches without duplicating their trees.
let results = std::mem::take(&mut *results_mutex.lock().await);
let (results, observed_slots) = std::mem::take(&mut *results_mutex.lock().await);
let completed_all_sets = bucket_plan_complete && scanner_results_form_complete_snapshot(&results, &expected_sources);
let result = finalize_nsscanner_result(&results, first_err);
let failed_buckets = bucket_failures.hard.lock().await.clone();
@@ -871,6 +969,72 @@ where
dirty_usage_status,
activity_status,
);
if cycle_status == ScannerCycleStatus::Incomplete && result.is_ok() && !budget_elapsed && !ctx.is_cancelled() {
let slots =
set_disks
.iter()
.zip(&results)
.zip(&observed_slots)
.enumerate()
.map(|(index, ((set, snapshot), observed))| {
(index, DataUsageCacheSource::new(set.pool_index, set.set_index), *observed, snapshot)
});
let summary = summarize_collector_slots(slots, want_cycle, leader_epoch, scan_plan_digest);
let sample = summary.sample;
let source_difference = summary.source_difference_sample;
let sample_snapshot = sample.filter(|sample| sample.observed).map(|sample| sample.snapshot);
warn!(
target: "rustfs::scanner::io",
event = EVENT_SCANNER_SET_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_IO,
state = "incomplete_cycle_collector_summary",
cycle = want_cycle,
leader_epoch,
configured_sets = set_disks.len(),
expected_sources = expected_sources.len(),
collector_slots = results.len(),
bucket_plan_complete,
scan_scope_matches,
completed_candidate_present = completed_usage.is_some(),
structurally_complete_snapshot,
bucket_scan_status = ?bucket_scan_status,
dirty_usage_status = ?dirty_usage_status,
activity_status = ?activity_status,
has_set_failure,
observed_slots = summary.observed,
unobserved_slots = summary.unobserved,
observed_incomplete_slots = summary.incomplete,
observed_missing_last_update_slots = summary.missing_last_update,
observed_missing_source_slots = summary.missing_source,
observed_slot_source_differs = summary.source_mismatch,
slot_source_difference_omitted = summary.source_mismatch.saturating_sub(usize::from(source_difference.is_some())),
slot_source_difference_index = source_difference.map(|sample| sample.index),
slot_source_difference_expected_pool = source_difference.map(|sample| sample.expected.pool_index),
slot_source_difference_expected_set = source_difference.map(|sample| sample.expected.set_index),
slot_source_difference_snapshot_pool = source_difference.and_then(|sample| sample.snapshot.info.source.map(|source| source.pool_index)),
slot_source_difference_snapshot_set = source_difference.and_then(|sample| sample.snapshot.info.source.map(|source| source.set_index)),
observed_cycle_mismatch_slots = summary.cycle_mismatch,
observed_epoch_mismatch_slots = summary.epoch_mismatch,
observed_missing_plan_slots = summary.missing_plan,
observed_plan_mismatch_slots = summary.plan_mismatch,
anomalous_slots = summary.anomalous,
sample_omitted_slots = summary.anomalous.saturating_sub(usize::from(sample.is_some())),
sample_slot = sample.map(|sample| sample.index),
sample_expected_pool = sample.map(|sample| sample.expected.pool_index),
sample_expected_set = sample.map(|sample| sample.expected.set_index),
sample_observed = sample.map(|sample| sample.observed),
sample_snapshot_source_pool = sample_snapshot.and_then(|snapshot| snapshot.info.source.map(|source| source.pool_index)),
sample_snapshot_source_set = sample_snapshot.and_then(|snapshot| snapshot.info.source.map(|source| source.set_index)),
sample_snapshot_complete = sample_snapshot.map(|snapshot| snapshot.info.snapshot_complete),
sample_snapshot_has_last_update = sample_snapshot.map(|snapshot| snapshot.info.last_update.is_some()),
sample_snapshot_cycle = sample_snapshot.map(|snapshot| snapshot.info.next_cycle),
sample_snapshot_leader_epoch = sample_snapshot.map(|snapshot| snapshot.info.leader_epoch),
sample_snapshot_has_plan = sample_snapshot.map(|snapshot| snapshot.info.scan_plan_digest.is_some()),
sample_snapshot_plan_matches = sample_snapshot.and_then(|snapshot| snapshot.info.scan_plan_digest.map(|plan| plan == scan_plan_digest)),
"Scanner recorded collector observations for an incomplete cycle"
);
}
// Certification is per bucket: the pending set is read after the
// guardrail verdict so a bucket written during the walk is reported in
// the same publication that certifies the others. A bucket whose walk
@@ -940,3 +1104,141 @@ where
.with_scope_fallback(scope_fallback)
.with_publication_expectation(publication_expectation))
}
#[cfg(test)]
mod collector_summary_tests {
use super::*;
const PLAN: DataUsageScanPlanDigest = DataUsageScanPlanDigest([4; 32]);
fn complete(source: DataUsageCacheSource) -> DataUsageCache {
DataUsageCache {
info: DataUsageCacheInfo {
source: Some(source),
next_cycle: 7,
leader_epoch: 11,
scan_plan_digest: Some(PLAN),
last_update: Some(SystemTime::now()),
snapshot_complete: true,
..Default::default()
},
..Default::default()
}
}
#[test]
fn collector_distinguishes_an_unobserved_slot_from_an_observed_default() {
let default = DataUsageCache::default();
let first = DataUsageCacheSource::new(0, 0);
let second = DataUsageCacheSource::new(0, 1);
let summary = summarize_collector_slots([(0, first, true, &default), (1, second, false, &default)], 7, 11, PLAN);
assert_eq!((summary.observed, summary.unobserved), (1, 1));
assert_eq!((summary.incomplete, summary.missing_source), (1, 1));
assert_eq!(summary.anomalous, 2);
let sample = summary.sample.expect("a sample should be selected");
assert_eq!(sample.expected, first);
assert!(sample.observed, "an observed default is not an unobserved slot");
assert!(sample.snapshot.info.source.is_none());
}
#[test]
fn collector_reports_source_positions_without_inventing_a_slot_failure() {
let first = DataUsageCacheSource::new(0, 0);
let second = DataUsageCacheSource::new(0, 1);
let first_cache = complete(first);
let second_cache = complete(second);
let expected_sources = HashSet::from([first, second]);
let swapped = [second_cache, first_cache.clone()];
assert!(scanner_results_match_scan_scope(&swapped, &expected_sources));
let summary = summarize_collector_slots([(0, first, true, &swapped[0]), (1, second, true, &swapped[1])], 7, 11, PLAN);
assert_eq!(summary.source_mismatch, 2);
assert!(summary.sample.is_none(), "different positions alone do not identify a failed slot");
let difference = summary.source_difference_sample.expect("one bounded position difference");
assert_eq!(difference.expected, first);
assert_eq!(difference.snapshot.info.source, Some(second));
let duplicate = [first_cache.clone(), first_cache];
assert!(!scanner_results_match_scan_scope(&duplicate, &expected_sources));
let summary = summarize_collector_slots([(0, first, true, &duplicate[0]), (1, second, true, &duplicate[1])], 7, 11, PLAN);
assert_eq!(summary.source_mismatch, 1);
assert!(summary.sample.is_none(), "a duplicate source does not identify which slot caused it");
let difference = summary.source_difference_sample.expect("one bounded position difference");
assert_eq!(difference.expected, second);
assert_eq!(difference.snapshot.info.source, Some(first));
}
#[test]
fn collector_counts_generation_and_plan_differences_without_assigning_a_cause() {
let first = DataUsageCacheSource::new(0, 0);
let second = DataUsageCacheSource::new(0, 1);
let mut older = complete(first);
older.info.next_cycle = 6;
older.info.leader_epoch = 10;
older.info.scan_plan_digest = Some(DataUsageScanPlanDigest([9; 32]));
let mut missing_plan = complete(second);
missing_plan.info.scan_plan_digest = None;
let slots = [(1, second, true, &missing_plan), (0, first, true, &older)];
let summary = summarize_collector_slots(slots, 7, 11, PLAN);
assert_eq!((summary.cycle_mismatch, summary.epoch_mismatch), (1, 1));
assert_eq!((summary.plan_mismatch, summary.missing_plan), (1, 1));
assert_eq!(summary.anomalous, 2);
let sample = summary.sample.expect("one deterministic sample");
assert_eq!(sample.expected, first);
assert_eq!(sample.snapshot.info.next_cycle, 6);
assert_eq!(sample.snapshot.info.leader_epoch, 10);
assert_eq!(sample.snapshot.info.scan_plan_digest, Some(DataUsageScanPlanDigest([9; 32])));
let missing = summarize_collector_slots([(1, second, true, &missing_plan)], 7, 11, PLAN);
assert!(
missing
.sample
.expect("missing plan sample")
.snapshot
.info
.scan_plan_digest
.is_none()
);
}
#[test]
fn collector_sample_is_bounded_and_complete_slots_do_not_explain_other_incomplete_states() {
let first = DataUsageCacheSource::new(0, 0);
let second = DataUsageCacheSource::new(0, 1);
let first_cache = complete(first);
let second_cache = complete(second);
let complete_slots = [(0, first, true, &first_cache), (1, second, true, &second_cache)];
for (sets_complete, bucket_status, dirty_status) in [
(false, ScannerBucketScanStatus::PartialCarried, DirtyUsageSnapshotStatus::Current),
(true, ScannerBucketScanStatus::Partial, DirtyUsageSnapshotStatus::Current),
(true, ScannerBucketScanStatus::Complete, DirtyUsageSnapshotStatus::Unverified),
] {
assert_eq!(
classify_nsscanner_cycle(
sets_complete,
false,
false,
bucket_status,
dirty_status,
ScannerCycleActivityStatus::Unchanged,
),
ScannerCycleStatus::Incomplete
);
let summary = summarize_collector_slots(complete_slots, 7, 11, PLAN);
assert_eq!(summary.anomalous, 0);
assert!(summary.sample.is_none(), "complete slot observations do not explain another gate");
}
let default = DataUsageCache::default();
let slots = (0..12)
.rev()
.map(|index| (index, DataUsageCacheSource::new(0, index), false, &default));
let summary = summarize_collector_slots(slots, 7, 11, PLAN);
assert_eq!(summary.unobserved, 12);
assert_eq!(summary.anomalous, 12);
assert_eq!(summary.sample.expect("one bounded sample").expected, first);
}
}
@@ -996,73 +996,6 @@ fn completed_data_usage_info_adds_same_bucket_across_unique_sets() {
assert_eq!(bucket.delete_markers_count, 1);
}
#[test]
fn bucket_usage_incarnation_is_optional_and_old_readers_ignore_it() {
#[derive(serde::Deserialize)]
struct LegacyBucketUsage {
size: u64,
}
let legacy = BucketUsageInfo {
size: 42,
..Default::default()
};
let without = serde_json::to_value(&legacy).expect("encode legacy usage");
assert!(without.get("bucket_incarnation").is_none());
let restored: BucketUsageInfo = serde_json::from_value(without).expect("decode old usage");
assert_eq!(restored.bucket_incarnation, None);
let certified = BucketUsageInfo {
size: 42,
bucket_incarnation: Some(uuid::Uuid::from_u128(7).to_string()),
..Default::default()
};
let encoded = serde_json::to_vec(&certified).expect("encode certified usage");
let old: LegacyBucketUsage = serde_json::from_slice(&encoded).expect("old schema ignores additive field");
assert_eq!(old.size, 42);
let named = rmp_serde::to_vec_named(&certified).expect("encode certified named msgpack");
let old: LegacyBucketUsage = rmp_serde::from_slice(&named).expect("old named reader ignores additive field");
assert_eq!(old.size, 42);
let old_bytes = rmp_serde::to_vec_named(&legacy).expect("encode old shape");
let new: BucketUsageInfo = rmp_serde::from_slice(&old_bytes).expect("new reader accepts old shape");
assert_eq!(new.bucket_incarnation, None);
}
#[test]
fn completed_usage_certifies_only_matching_non_nil_bucket_incarnations() {
let buckets = vec!["bucket".to_string()];
let id = uuid::Uuid::from_u128(7);
let mut a = completed_root_cache("bucket", 2, 10, DataUsageCacheSource::new(0, 0));
let mut b = completed_root_cache("bucket", 3, 20, DataUsageCacheSource::new(1, 0));
a.info.scan_bucket_incarnations.insert("bucket".to_string(), id);
b.info.scan_bucket_incarnations.insert("bucket".to_string(), id);
let published = completed_data_usage_info_for_test(&[a.clone(), b.clone()], &buckets, false, false)
.unwrap()
.0;
assert_eq!(
published.buckets_usage["bucket"].bucket_incarnation.as_deref(),
Some(id.to_string().as_str())
);
let encoded = serde_json::to_vec(&published).expect("serialize certified usage");
let decoded: DataUsageInfo = serde_json::from_slice(&encoded).expect("read certified usage");
assert_eq!(decoded.buckets_usage["bucket"].bucket_incarnation, Some(id.to_string()));
b.info
.scan_bucket_incarnations
.insert("bucket".to_string(), uuid::Uuid::from_u128(8));
let mismatch = completed_data_usage_info_for_test(&[a.clone(), b.clone()], &buckets, false, false)
.unwrap()
.0;
assert_eq!(mismatch.buckets_usage["bucket"].bucket_incarnation, None);
b.info.scan_bucket_incarnations.remove("bucket");
let missing = completed_data_usage_info_for_test(&[a.clone(), b.clone()], &buckets, false, false)
.unwrap()
.0;
assert_eq!(missing.buckets_usage["bucket"].bucket_incarnation, None);
b.info
.scan_bucket_incarnations
.insert("bucket".to_string(), uuid::Uuid::nil());
let nil = completed_data_usage_info_for_test(&[a, b], &buckets, false, false).unwrap().0;
assert_eq!(nil.buckets_usage["bucket"].bucket_incarnation, None);
}
#[test]
fn checked_bucket_usage_info_moves_replication_keys_and_preserves_the_snapshot() {
let first_target = "arn:rustfs:replication:local::target-a".to_string();
@@ -1124,7 +1057,6 @@ fn checked_bucket_usage_info_moves_replication_keys_and_preserves_the_snapshot()
}
let expected = BucketUsageInfo {
size: 32768,
bucket_incarnation: None,
replication_pending_size_v1: 0,
replication_failed_size_v1: 0,
replicated_size_v1: 0,
+1
View File
@@ -46,6 +46,7 @@ use uuid::Uuid;
mod checkpoint_coverage_identity;
mod collector_lifecycle;
mod cycle_collector_diagnostics;
mod expiry_lock;
mod listing_window_scope;
mod node_admission;
@@ -0,0 +1,606 @@
// Copyright 2026 RustFS Team
// SPDX-License-Identifier: Apache-2.0
use super::*;
use rustfs_concurrency::adaptive::{FeedbackController, FeedbackObservation, NodeAdmission, ResourcePressure};
use std::num::NonZeroU16;
const LEADER_EPOCH: u64 = 11;
#[derive(Clone)]
struct LogWriter(Arc<StdMutex<Vec<u8>>>);
impl std::io::Write for LogWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().expect("collector log buffer").extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
async fn capture_cycle<F: std::future::Future>(future: F) -> (F::Output, Vec<serde_json::Value>) {
use tracing::instrument::WithSubscriber as _;
let buffer = Arc::new(StdMutex::new(Vec::new()));
let writer = Arc::clone(&buffer);
let subscriber = tracing_subscriber::fmt()
.json()
.without_time()
.with_ansi(false)
.with_max_level(tracing::Level::WARN)
.with_writer(move || LogWriter(Arc::clone(&writer)))
.finish();
let _interest_guard = tracing::Dispatch::new(tracing::subscriber::NoSubscriber::default());
let result = future.with_subscriber(subscriber).await;
let logs = buffer.lock().expect("collector log buffer");
let events = std::str::from_utf8(&logs)
.expect("collector logs should be UTF-8")
.lines()
.map(|line| serde_json::from_str(line).expect("collector event should be JSON"))
.collect();
(result, events)
}
async fn run_cycle(
store: &Arc<ECStore>,
cycle: u64,
max_objects: Option<u64>,
requires_full_scan: bool,
) -> (ScannerCycleResult, Option<DataUsageInfo>, bool) {
let ctx = CancellationToken::new();
let budget = ScannerCycleBudget::new_with_progress_tracking(
&ctx,
ScannerCycleBudgetConfig {
max_objects,
..Default::default()
},
);
let (updates, mut receiver) = mpsc::channel(1);
let result = tokio::time::timeout(
Duration::from_secs(60),
nsscanner_with_storage_status_scoped(
store.as_ref(),
ScannerCycleRequest {
ctx: budget.token(),
budget: Arc::clone(&budget),
updates,
want_cycle: cycle,
leader_epoch: LEADER_EPOCH,
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
observed_usage_candidate: None,
requires_full_scan,
service_cohort: None,
resolved_scope_observer: None,
post_walk_gate: None,
},
),
)
.await
.expect("cycle should finish within the test deadline")
.expect("cycle should return a status");
let snapshot = receiver.recv().await;
assert!(receiver.recv().await.is_none(), "a cycle emits at most one snapshot");
(result, snapshot, budget.budget_elapsed())
}
fn collector_events(events: &[serde_json::Value]) -> Vec<&serde_json::Value> {
events
.iter()
.filter(|event| event["fields"]["state"] == "incomplete_cycle_collector_summary")
.map(|event| &event["fields"])
.collect()
}
#[tokio::test]
#[serial]
async fn collector_reports_an_unobserved_slot_after_a_stale_set_snapshot() {
let (_temp_dir, store) = setup_local_scanner_store(1, 1).await;
clear_dirty_usage_buckets_for_tests();
store
.make_bucket("diagnostic-bucket", &MakeBucketOptions::default())
.await
.expect("fixture bucket should be created");
wait_for_namespace_commit_tails(store.as_ref()).await;
let set = Arc::clone(&store.pools[0].disk_set[0]);
let mut newer = complete_set_usage_cache(&[("diagnostic-bucket", 1)], DataUsageScanPlanDigest([1; 32]));
newer.info.source = Some(DataUsageCacheSource::new(0, 0));
newer.info.next_cycle = 7;
newer.info.leader_epoch = LEADER_EPOCH + 1;
newer
.save(set, DATA_USAGE_CACHE_NAME)
.await
.expect("newer set cache should persist");
let ((result, snapshot, budget_elapsed), events) = capture_cycle(run_cycle(&store, 7, None, true)).await;
assert_eq!(result.status, ScannerCycleStatus::Incomplete);
assert!(!budget_elapsed);
assert!(snapshot.is_none_or(|snapshot| !snapshot.usage_snapshot_complete));
let events = collector_events(&events);
assert_eq!(events.len(), 1, "a non-budget incomplete cycle needs one collector observation");
let fields = events[0];
assert_eq!(fields["cycle"], 7);
assert_eq!(fields["leader_epoch"], LEADER_EPOCH);
assert_eq!(fields["expected_sources"], 1);
assert_eq!(fields["observed_slots"], 0);
assert_eq!(fields["unobserved_slots"], 1);
assert_eq!(fields["sample_expected_pool"], 0);
assert_eq!(fields["sample_expected_set"], 0);
assert_eq!(fields["sample_observed"], false);
assert!(fields.get("sample_snapshot_source_pool").is_none());
assert!(fields.get("sample_snapshot_complete").is_none());
clear_dirty_usage_buckets_for_tests();
}
#[tokio::test]
#[serial]
async fn collector_reports_received_incomplete_cache_only_for_non_budget_partial() {
let (_temp_dir, store) = setup_local_scanner_store(1, 1).await;
clear_dirty_usage_buckets_for_tests();
store
.make_bucket("fresh-bucket", &MakeBucketOptions::default())
.await
.expect("fixture bucket should be created");
for object in ["p0/a", "p1/b", "p2/c", "p3/d"] {
let mut reader = ScannerPutObjReader::from_vec(vec![7; 16]);
store
.put_object("fresh-bucket", object, &mut reader, &ScannerObjectOptions::default())
.await
.expect("fixture object should persist");
}
record_dirty_usage_bucket("fresh-bucket");
wait_for_namespace_commit_tails(store.as_ref()).await;
let ((first, _, budget_elapsed), events) = capture_cycle(run_cycle(&store, 1, Some(2), true)).await;
assert_eq!(first.status, ScannerCycleStatus::Incomplete);
assert!(budget_elapsed);
assert!(collector_events(&events).is_empty(), "budget partials do not use this event");
let ((second, snapshot, budget_elapsed), events) = capture_cycle(run_cycle(&store, 2, None, false)).await;
assert_eq!(second.status, ScannerCycleStatus::Incomplete);
assert!(!budget_elapsed);
assert!(snapshot.is_none_or(|snapshot| !snapshot.usage_snapshot_complete));
let events = collector_events(&events);
assert_eq!(events.len(), 1, "a non-budget incomplete cycle needs one collector observation");
let fields = events[0];
assert_eq!(fields["observed_slots"], 1);
assert_eq!(fields["unobserved_slots"], 0);
assert_eq!(fields["sample_observed"], true);
assert_eq!(fields["sample_expected_pool"], 0);
assert_eq!(fields["sample_expected_set"], 0);
assert_eq!(fields["sample_snapshot_source_pool"], 0);
assert_eq!(fields["sample_snapshot_source_set"], 0);
assert_eq!(fields["sample_snapshot_complete"], false);
assert_eq!(fields["sample_snapshot_has_last_update"], false);
assert_eq!(fields["sample_snapshot_cycle"], 2);
assert_eq!(fields["sample_snapshot_leader_epoch"], LEADER_EPOCH);
assert_eq!(fields["sample_snapshot_has_plan"], true);
assert_eq!(fields["sample_snapshot_plan_matches"], true);
let ((third, snapshot, _), events) = capture_cycle(run_cycle(&store, 3, None, false)).await;
assert_eq!(third.status, ScannerCycleStatus::Complete);
assert!(snapshot.is_some_and(|snapshot| snapshot.usage_snapshot_complete));
assert!(
collector_events(&events).is_empty(),
"a complete cycle must not report incomplete collector slots"
);
clear_dirty_usage_buckets_for_tests();
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum AdmittedCycle {
Complete,
Cancelled,
CacheChanged,
}
fn recorded_events(buffer: &StdMutex<Vec<u8>>) -> Vec<serde_json::Value> {
let buffer = buffer.lock().expect("collector log buffer");
buffer
.split_inclusive(|byte| *byte == b'\n')
.filter(|line| line.ends_with(b"\n"))
.map(|line| serde_json::from_slice(line).expect("complete collector events should be JSON"))
.collect()
}
async fn admitted_collector_cycle(
store: &Arc<ECStore>,
owner: &Arc<NodeAdmission>,
logs: &Arc<StdMutex<Vec<u8>>>,
cycle: u64,
case: AdmittedCycle,
) {
const BUCKET: &str = "admitted-collector";
let set = Arc::clone(&store.pools[0].disk_set[0]);
let source = DataUsageCacheSource::new(0, 0);
let cache_name = format!("{BUCKET}/{DATA_USAGE_CACHE_NAME}");
record_dirty_usage_bucket(BUCKET);
let dirty_generation = dirty_usage_buckets_for_tests().get(BUCKET).copied();
assert!(dirty_generation.is_some(), "the fixture must start with dirty usage");
let original_bucket_revision = DataUsageCache::read_revisions(set.clone(), &cache_name)
.await
.expect("read bucket cache revisions before the cycle");
let original_set_revision = DataUsageCache::read_revisions(set.clone(), DATA_USAGE_CACHE_NAME)
.await
.expect("read set cache revisions before the cycle");
logs.lock().expect("collector log buffer").clear();
// The worker can acquire its cache lease but cannot start a node operation.
let mut blocker = Some(
tokio::time::timeout(Duration::from_secs(10), owner.acquire())
.await
.expect("fixture should acquire the node unit"),
);
assert_eq!(owner.snapshot().active, 1);
let ctx = CancellationToken::new();
let budget = ScannerCycleBudget::new_with_progress_tracking(&ctx, ScannerCycleBudgetConfig::default());
let (updates, mut receiver) = mpsc::channel(1);
let scan = nsscanner_with_storage_status_scoped(
store.as_ref(),
ScannerCycleRequest {
ctx: budget.token(),
budget: Arc::clone(&budget),
updates,
want_cycle: cycle,
leader_epoch: LEADER_EPOCH,
scan_mode: HealScanMode::Normal,
scan_scope: ScannerBucketScanScope::default(),
persisted_usage_baseline: None,
observed_usage_candidate: None,
requires_full_scan: true,
service_cohort: None,
resolved_scope_observer: None,
post_walk_gate: None,
},
);
tokio::pin!(scan);
let cache_ready = async {
loop {
if recorded_events(logs)
.iter()
.any(|event| event["fields"]["state"] == "cache_ready" && event["fields"]["bucket"] == BUCKET)
{
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
};
tokio::select! {
biased;
result = &mut scan => panic!("cycle ended before bucket cache admission: {result:?}"),
result = tokio::time::timeout(Duration::from_secs(60), cache_ready) => {
result.expect("worker should load its cache while the node is occupied");
}
}
let mut competing_lease = Some(tokio::select! {
biased;
result = &mut scan => panic!("cycle ended before yielding its cache lease: {result:?}"),
result = tokio::time::timeout(
Duration::from_secs(60), acquire_scanner_cache_locks(set.as_ref(), &cache_name, source),
) => result.expect("scanner should yield its cache lease").expect("competing cache lease"),
});
let expected_bucket_revision = if case == AdmittedCycle::CacheChanged {
let mut newer = DataUsageCache::default();
newer
.load(set.clone(), &cache_name)
.await
.expect("load the protected bucket cache");
assert!(newer.info.snapshot_complete, "the competing writer starts from the certified cache");
newer.info.next_cycle = cycle - 1;
newer
.save(set.clone(), &cache_name)
.await
.expect("persist the competing cache revision");
let updated = DataUsageCache::read_revisions(set.clone(), &cache_name)
.await
.expect("read the competing cache revision");
assert_ne!(updated, original_bucket_revision, "the competing write must change the revision");
Some(updated)
} else {
None
};
if case == AdmittedCycle::Cancelled {
ctx.cancel();
} else {
blocker.take().expect("held node unit").complete();
let admitted = async {
while owner.snapshot().active != 1 {
tokio::task::yield_now().await;
}
};
tokio::select! {
biased;
result = &mut scan => panic!("cycle ended before reacquiring node admission: {result:?}"),
result = tokio::time::timeout(Duration::from_secs(60), admitted) => {
result.expect("scanner should acquire the released node unit");
}
}
assert!(
!recorded_events(logs)
.iter()
.any(|event| event["fields"]["state"] == "scan_completed" && event["fields"]["bucket"] == BUCKET),
"the worker cannot complete the walk while the other lease is held"
);
}
if case != AdmittedCycle::Cancelled {
drop(competing_lease.take());
}
let result = tokio::time::timeout(Duration::from_secs(60), &mut scan)
.await
.expect("scanner cycle should finish")
.expect("scanner cycle should return a status");
let snapshot = tokio::time::timeout(Duration::from_secs(10), receiver.recv())
.await
.expect("cycle update channel should finish");
assert!(
tokio::time::timeout(Duration::from_secs(10), receiver.recv())
.await
.expect("cycle update channel should close")
.is_none(),
"a cycle emits at most one snapshot"
);
if case == AdmittedCycle::Cancelled {
assert_eq!(owner.snapshot().active, 1, "cancellation must not take the occupied node unit");
drop(blocker.take());
drop(competing_lease.take());
}
assert_eq!(owner.snapshot().active, 0, "the cycle must release its node capacity");
assert!(owner.try_acquire().is_some(), "the node queue must not retain the finished request");
let events = recorded_events(logs);
let root_summaries: Vec<_> = events
.iter()
.filter(|event| event["fields"]["state"] == "bucket_root_collector_drained")
.map(|event| &event["fields"])
.collect();
assert_eq!(root_summaries.len(), 1, "each real cycle drains one set collector");
let roots = root_summaries[0];
assert_eq!(roots["collector_cache_cycle"], cycle);
assert_eq!(roots["rejected_roots"], 0);
assert_eq!(dirty_usage_buckets_for_tests().get(BUCKET).copied(), dirty_generation);
match case {
AdmittedCycle::Complete => {
assert_eq!(result.status, ScannerCycleStatus::Complete);
let snapshot = snapshot.expect("complete cycle must produce a usage snapshot");
assert!(snapshot.usage_snapshot_complete);
assert_eq!(snapshot.objects_total_count, 4);
assert_eq!(roots["received_roots"], 1);
assert_eq!(roots["distinct_applied_roots"], 1);
assert_eq!(roots["cancelled_at_drain"], false);
assert!(collector_events(&events).is_empty());
}
AdmittedCycle::Cancelled | AdmittedCycle::CacheChanged => {
assert_eq!(result.status, ScannerCycleStatus::Incomplete);
assert!(!result.has_dirty_usage_to_acknowledge());
assert!(snapshot.is_none_or(|snapshot| !snapshot.usage_snapshot_complete));
assert_eq!(roots["received_roots"], 0);
assert_eq!(roots["distinct_applied_roots"], 0);
assert_eq!(roots["cancelled_at_drain"], case == AdmittedCycle::Cancelled);
assert_eq!(
DataUsageCache::read_revisions(set.clone(), DATA_USAGE_CACHE_NAME)
.await
.expect("read the retained set cache revisions"),
original_set_revision
);
let expected = expected_bucket_revision.unwrap_or(original_bucket_revision);
assert_eq!(
DataUsageCache::read_revisions(set.clone(), &cache_name)
.await
.expect("read the retained bucket cache revisions"),
expected
);
let summaries = collector_events(&events);
if case == AdmittedCycle::Cancelled {
assert!(summaries.is_empty(), "a cancelled cycle must not report an ordinary incomplete summary");
} else {
assert!(events.iter().any(|event| {
event["fields"]["state"] == "scan_failed"
&& event["fields"]["error"]
.as_str()
.is_some_and(|error| error.contains("scanner cache changed while waiting for node admission"))
}));
assert_eq!(summaries.len(), 1);
let fields = summaries[0];
assert_eq!(fields["cycle"], cycle);
assert_eq!(fields["leader_epoch"], LEADER_EPOCH);
assert_eq!(fields["expected_sources"], 1);
assert_eq!(fields["observed_slots"], 1);
assert_eq!(fields["unobserved_slots"], 0);
assert_eq!(fields["sample_observed"], true);
assert_eq!(fields["sample_snapshot_complete"], false);
assert_eq!(fields["sample_snapshot_cycle"], cycle);
}
}
}
let mut retained = DataUsageCache::default();
retained
.load(set, &cache_name)
.await
.expect("load the retained certified bucket cache");
assert!(retained.info.snapshot_complete);
assert_eq!(
retained.info.next_cycle,
match case {
AdmittedCycle::Complete | AdmittedCycle::Cancelled => 1,
AdmittedCycle::CacheChanged => 2,
}
);
assert_eq!(retained.checked_flatten(BUCKET).expect("retained bucket tree").objects, 4);
}
#[test]
fn collector_cycle_with_node_admission_preserves_cache_and_reports_outcomes() {
const TEST: &str = "scanner_io::tests::cycle_collector_diagnostics::collector_cycle_with_node_admission_preserves_cache_and_reports_outcomes";
const CHILD: &str = "RUSTFS_TEST_ADMITTED_COLLECTOR_CHILD";
if std::env::var(CHILD).ok().as_deref() != Some(TEST) {
struct ChildReaper(std::process::Child);
impl Drop for ChildReaper {
fn drop(&mut self) {
if !matches!(self.0.try_wait(), Ok(Some(_))) && self.0.kill().is_ok() {
let _ = self.0.wait();
}
}
}
// The production admission owner is process-global and cannot be reset.
// Snapshot only non-RustFS settings so concurrent environment tests cannot
// change the child fixture's scanner or storage configuration.
let child_env = std::env::vars_os().filter(|(name, _)| {
let name = name.to_string_lossy().to_ascii_uppercase();
!name.starts_with("RUSTFS_") && !name.starts_with("MINIO_")
});
let child = std::process::Command::new(std::env::current_exe().expect("test executable"))
.args(["--exact", TEST, "--nocapture", "--color", "never"])
.env_clear()
.envs(child_env)
.env(CHILD, TEST)
.env("RUSTFS_DATA_USAGE_UPDATE_DIR_CYCLES", "1")
.env("RUSTFS_SCANNER_IDLE_MODE", "false")
.env("RUSTFS_SCANNER_DISK_IO_BUDGET_IOPS", "off")
.env("RUSTFS_SCANNER_DISK_IO_BUDGET_BYTES_PER_SEC", "off")
.env("RUSTFS_LOCK_ACQUIRE_TIMEOUT", "30")
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("start the isolated collector cycle");
let mut child = ChildReaper(child);
let mut child_stdout = child.0.stdout.take().expect("child stdout pipe");
let mut child_stderr = child.0.stderr.take().expect("child stderr pipe");
// Drain both pipes while the child runs so neither can block its exit.
let stdout_reader = std::thread::spawn(move || {
let mut bytes = Vec::new();
let error = std::io::Read::read_to_end(&mut child_stdout, &mut bytes).err();
(bytes, error)
});
let stderr_reader = std::thread::spawn(move || {
let mut bytes = Vec::new();
let error = std::io::Read::read_to_end(&mut child_stderr, &mut bytes).err();
(bytes, error)
});
let started = std::time::Instant::now();
let mut timed_out = false;
let mut wait_error = None;
let status = loop {
match child.0.try_wait() {
Ok(Some(status)) => break status,
Ok(None) if started.elapsed() < Duration::from_secs(300) => {
std::thread::sleep(Duration::from_millis(50));
}
Ok(None) => {
timed_out = true;
if let Err(error) = child.0.kill() {
// The child can exit between the status check and kill.
if let Some(status) = child.0.try_wait().expect("check child after failed kill") {
break status;
}
panic!("failed to terminate the timed-out collector child: {error}");
}
break child.0.wait().expect("reap the timed-out collector child");
}
Err(error) => {
wait_error = Some(error);
if let Err(error) = child.0.kill() {
if let Some(status) = child.0.try_wait().expect("check child after failed kill") {
break status;
}
panic!("failed to terminate the collector child after a wait error: {error}");
}
break child.0.wait().expect("reap the collector child after a wait error");
}
}
};
let (stdout, stdout_error) = stdout_reader.join().expect("join child stdout reader");
let (stderr, stderr_error) = stderr_reader.join().expect("join child stderr reader");
let stdout = String::from_utf8_lossy(&stdout);
let stderr = String::from_utf8_lossy(&stderr);
assert!(
!timed_out
&& wait_error.is_none()
&& stdout_error.is_none()
&& stderr_error.is_none()
&& status.success()
&& stdout
.lines()
.any(|line| line.starts_with("test result: ok. 1 passed; 0 failed;")),
"the isolated collector cycle must finish within 300 seconds and run exactly once \
(status={status}, timed_out={timed_out}, wait_error={wait_error:?}, \
stdout_error={stdout_error:?}, stderr_error={stderr_error:?}): \
{stdout}\n{stderr}"
);
return;
}
let logs = Arc::new(StdMutex::new(Vec::new()));
let writer = Arc::clone(&logs);
tracing::subscriber::set_global_default(
tracing_subscriber::fmt()
.json()
.without_time()
.with_ansi(false)
.with_max_level(tracing::Level::DEBUG)
.with_writer(move || LogWriter(Arc::clone(&writer)))
.finish(),
)
.expect("install the isolated collector observer");
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.expect("create the isolated scanner runtime");
runtime.block_on(async {
let (_temp_dir, store) = setup_local_scanner_store(1, 1).await;
clear_dirty_usage_buckets_for_tests();
store
.make_bucket("admitted-collector", &MakeBucketOptions::default())
.await
.expect("create the fixture bucket");
for object in ["p0/a", "p1/b", "p2/c", "p3/d"] {
let mut reader = ScannerPutObjReader::from_vec(vec![7; 16]);
store
.put_object("admitted-collector", object, &mut reader, &ScannerObjectOptions::default())
.await
.expect("persist the fixture object");
}
wait_for_namespace_commit_tails(store.as_ref()).await;
assert!(!crate::scanner_is_erasure().await, "this fixture must not start scanner healing");
let owner = NodeAdmission::new(NonZeroU16::new(1).expect("one node unit"));
let observation = FeedbackObservation {
generation: 1,
max_concurrency: 1,
pressure: ResourcePressure::Unknown,
completed_units: None,
};
let mut controller = FeedbackController::new();
owner.update(&mut controller, Some(observation));
let sampler_stop = CancellationToken::new();
let sampler_cancel = sampler_stop.clone();
let sampler_owner = owner.clone();
let sampler = tokio::spawn(async move {
let mut tick = tokio::time::interval(Duration::from_secs(1));
loop {
tokio::select! {
_ = sampler_cancel.cancelled() => break,
_ = tick.tick() => { sampler_owner.update(&mut controller, Some(observation)); }
}
}
});
assert!(crate::set_scanner_node_admission(owner.clone()), "install the real node owner once");
admitted_collector_cycle(&store, &owner, &logs, 1, AdmittedCycle::Complete).await;
admitted_collector_cycle(&store, &owner, &logs, 2, AdmittedCycle::Cancelled).await;
admitted_collector_cycle(&store, &owner, &logs, 3, AdmittedCycle::CacheChanged).await;
sampler_stop.cancel();
sampler.await.expect("stop the admission feedback sampler");
});
}
+8 -20
View File
@@ -1471,7 +1471,6 @@ mod tests {
inner: QueueStore<QueuedPayload>,
fail_put_failed_raw: Arc<std::sync::atomic::AtomicBool>,
fail_del: Arc<std::sync::atomic::AtomicBool>,
delete_attempts: Arc<Semaphore>,
}
impl Store<QueuedPayload> for FailingFailedStore {
@@ -1500,13 +1499,10 @@ mod tests {
self.inner.get_raw(key)
}
fn del(&self, key: &Self::Key) -> Result<(), Self::Error> {
let result = if self.fail_del.load(Ordering::SeqCst) {
Err(StoreError::Internal("injected del failure".to_string()))
} else {
self.inner.del(key)
};
self.delete_attempts.add_permits(1);
result
if self.fail_del.load(Ordering::SeqCst) {
return Err(StoreError::Internal("injected del failure".to_string()));
}
self.inner.del(key)
}
fn delete(&self) -> Result<(), Self::Error> {
self.inner.delete()
@@ -1990,7 +1986,6 @@ mod tests {
inner: inner.clone(),
fail_put_failed_raw: fail_flag.clone(),
fail_del: Arc::new(std::sync::atomic::AtomicBool::new(false)),
delete_attempts: Arc::new(Semaphore::new(0)),
};
// The target's terminal move writes through the rejecting failed handle, so the injected
// failure is what the move hits.
@@ -2047,7 +2042,6 @@ mod tests {
inner: inner.clone(),
fail_put_failed_raw: Arc::new(std::sync::atomic::AtomicBool::new(false)),
fail_del: Arc::new(std::sync::atomic::AtomicBool::new(true)),
delete_attempts: Arc::new(Semaphore::new(0)),
};
let target = Arc::new(ProgrammedTarget::new(
Some(TargetError::JetStreamPublish {
@@ -2059,15 +2053,8 @@ mod tests {
let tally = Arc::new(ReplayTally::default());
let (cancel_tx, worker) = spawn_failing_store_worker(&store, target, tally.clone());
// Observe repeated durable overwrites without auto-advancing through thousands of
// real filesystem writes. Keep the original virtual observation bound on progress.
tokio::time::timeout(Duration::from_secs(300), store.delete_attempts.acquire_many(8))
.await
.expect("replay should retry the failing delete eight times")
.expect("delete progress remains open")
.forget();
cancel_tx.send(()).await.expect("replay worker should remain cancellable");
worker.await.expect("replay worker should drain after cancellation");
// Many scans run while the live delete keeps failing.
tokio::time::sleep(Duration::from_secs(300)).await;
assert_eq!(
tally.permanent_failure.load(Ordering::SeqCst),
0,
@@ -2076,6 +2063,8 @@ mod tests {
assert_eq!(inner.len(), 1, "the live entry stays for the next scan");
assert_eq!(inner.failed_len(), 1, "the durable failed copy landed exactly once");
let _ = cancel_tx.send(()).await;
let _ = worker.await;
let _ = inner.delete();
}
@@ -2095,7 +2084,6 @@ mod tests {
inner: store.clone(),
fail_put_failed_raw: Arc::new(std::sync::atomic::AtomicBool::new(false)),
fail_del: Arc::new(std::sync::atomic::AtomicBool::new(false)),
delete_attempts: Arc::new(Semaphore::new(0)),
};
let target = Arc::new(ProgrammedTarget::new(
Some(TargetError::JetStreamPublish {
-1
View File
@@ -50,7 +50,6 @@ Required headings and strings in these files are asserted by `scripts/check_arch
| [scanner-usage-authority-decision.md](scanner-usage-authority-decision.md) | deciding whether quota admission depends on scanner data usage, removing scanner publication layers, or designing a scanner storage boundary |
| [scanner-per-bucket-convergence.md](scanner-per-bucket-convergence.md) | changing what makes a scanner cycle `Complete`, `Superseded`, or converged, adding or re-classifying a dirty-usage producer, deciding whether a background writeback may invalidate a cycle, changing scanner worker concurrency or throttling, or activating scoped dirty acknowledgements |
| [config-model-boundary-adr.md](config-model-boundary-adr.md) | touching the server-config model (`Config`, `KV`, `KVS`) or its persistence, or asking which crate owns which part of server configuration |
| [plugin-delegation.md](plugin-delegation.md) | changing original-user plugin delegation, attempt credentials, or Runner task APIs |
| [admin-route-action-snapshot.md](admin-route-action-snapshot.md) | adding, moving, or re-authorizing an admin route and needing to know where the route → handler → `AdminAction` contract is enforced |
| [kms-bulk-rekey-contract.md](kms-bulk-rekey-contract.md) | changing the bulk envelope re-wrap sweep, its admin endpoints, the re-wrap primitive, or which objects a rekey may touch |
| [remote-credential-sealing-adr.md](remote-credential-sealing-adr.md) | adding, reading, or persisting a stored remote credential (replication target, remote tier, on-demand migration source), or needing the sealed-envelope format, the mixed-version rules, or the reason this is worth doing in one deployment and not in another |
-142
View File
@@ -1,142 +0,0 @@
# Plugin delegation
**Use this when:** changing plugin delegation registration, revocation, broker identity, or the scope of attempt credentials.
## Integration boundary
Runner owns scheduling, leases, container execution and result publication. RustFS provides original-user delegation, scoped temporary credentials and authenticated task API forwarding. Inputs and outputs use ordinary versioned S3 buckets; event-driven jobs use the existing bucket notification/Webhook path. Managed artifact sealing, inventory, garbage collection and backup retention require separate storage contracts and are outside this integration.
Set `RUSTFS_PLUGIN_RUNNER_URL` to the Controller HTTPS URL ending in `/v1/ingress/manual/jobs`, and `RUSTFS_PLUGIN_RUNNER_DEPLOYMENT` to the delegation deployment. Forwarding requires the published outbound mTLS client identity and uses the published trust roots when configured. Connections are reused within a TLS generation; publishing new TLS material replaces the pool, and removing the client identity rejects new forwarding requests.
## Authority
A delegation is an immutable restriction record owned by an ordinary IAM user. It is neither a permission grant nor a credential. Creating it requires that user's real signed request and `admin:CreatePluginDelegation`; reading and revoking require the corresponding `admin:GetPluginDelegation` and `admin:RevokePluginDelegation` actions. Root, temporary credentials and service accounts cannot own records.
The record binds a deployment, an input bucket, literal input and output prefixes, and an expiry of at most 24 hours. The v1 profile writes to that same bucket; v2 explicitly names the output bucket. Wildcards, control characters and IAM variable expressions are rejected. Its random ID is also its immutable revision. There is no update operation.
The Controller is responsible for validating accepted task identity, current lease, epoch, node session and control generation before requesting credentials. RustFS authenticates the configured broker and enforces the delegation and current parent IAM. RustFS does not independently verify a remote Controller lease.
```mermaid
sequenceDiagram
participant U as Original IAM user
participant C as Controller broker
participant R as RustFS
participant P as Plugin
U->>R: Signed delegation registration
R-->>U: Immutable ID and revision
C->>C: Validate task and current lease
C->>R: Signed issue-attempt request
R->>R: Broker mapping + active record + current IAM
R->>R: Persist scoped STS and recheck authority
R-->>C: Short-lived credentials
C-->>P: Attempt credentials
P->>R: Exact version GET / attempt-prefix PUT
R->>R: Current parent IAM intersected with session policy
```
## Persistence and revocation
`crates/iam/src/delegation.rs` owns record validation and immutable revocation tombstones. Records use the existing IAM store under `config/iam/plugin-delegations/v1`. Writes require a successful readback. Revocation is idempotent and durable; it does not delete or overwrite the restriction record.
`ObjectStore::load_iam_config_strict` distinguishes a missing object from an empty object, invalid JSON or failed decryption. Only a genuinely absent tombstone permits an active record. Corrupt or unavailable storage rejects access rather than treating revocation as absent. Existing non-delegation readers keep their compatibility behavior.
Revocation prevents future issuance. It does not promise immediate invalidation of credentials already delivered; those remain subject to their expiration and current parent IAM. Registration, IAM changes and issuance are not one atomic transaction. Issuance rechecks after persistence and deletes the generated STS account if authority changed. Failed persistence or invalidation acknowledgment is reported as unknown issuance, never as safe retry permission.
Manual job submission reads the active delegation before calling the Runner. A submission that passed this check is in flight and may be admitted if revocation races with the outbound request; revocation prevents submissions whose authority check occurs afterward, but does not cancel an admitted job. Callers must treat a successful submit receipt as accepted work even if the delegation is revoked later. After an ambiguous timeout or service error, retry the same idempotency key while the delegation remains active; after revocation or expiry, query status instead of retrying submission.
`POST /rustfs/admin/v3/plugin-delegations/{id}/runs/query` accepts `{version:1,run_id}` and requires an ordinary IAM user with `admin:GetPluginRun` who owns the delegation in `{id}`. It reads the immutable owner record without checking expiry or revocation, then queries Runner using the record's delegation ID and revision and the authenticated access key. The result can contain only that caller's run status and committed manifest; it does not perform object reads or reauthorize object access. The Runner response must match the requested run ID and the strict status schema before RustFS returns it.
`POST /rustfs/admin/v3/plugin-delegations/{id}/runs/cancel` accepts the same request and requires `admin:CancelPluginRun` plus ownership of `{id}`. Expiry and revocation do not block cancelling an existing run. Runner scopes the run to that owner; missing and other-owner runs share the same not-found response, while successful and failed runs return conflict. Success returns `{version:1,run_id,state:"CANCELLED",cleanup_pending}` and does not imply that asynchronous cleanup has finished.
`POST /rustfs/admin/v3/plugin-delegations/{id}/runs/page` accepts `{version:1,limit,cursor?}` with a limit from 1 to 100 and requires `admin:ListPluginRuns` plus ownership of `{id}`. Expiry and revocation do not hide historical runs. RustFS supplies signer and delegation identity from authenticated IAM state; the Runner page is scoped to the exact caller and deployment. The strict response contains run summaries and an opaque-to-clients stable cursor; callers pass the returned cursor unchanged until it is null. RustFS bounds request/response sizes and rejects malformed, unordered, over-limit, or identity-invalid summaries.
`POST /rustfs/admin/v3/plugin-delegations/{id}/runs/history` accepts `{version:1,run_id}` and requires `admin:ListPluginRuns` plus ownership of `{id}`. RustFS derives signer and delegation identity from the authenticated user and IAM record, then proxies Runner's bounded history response. The response contains at most the latest 32 committed state events in Runner's history-ID order and a `has_older` flag; timestamps are display data and are not used to reorder events. Missing and foreign runs share the same not-found response. RustFS rejects malformed, empty, over-limit, unexpected-state, or mismatched-run responses and bounds both request and response bodies.
`POST /rustfs/admin/v3/plugin-delegations/{id}/runs/replay` accepts `{version:1,origin_run_id,idempotency_key,deadline_unix_micros}` and requires `admin:ReplayPluginRun`, current IAM authorization, ownership, and an active unexpired delegation. Caller identity fields are not accepted; RustFS derives signer and delegation revision from the authenticated request and IAM record. Runner accepts only an owned failed origin, preserves its fixed plugin/configuration/input version, and requires a new deadline no later than its configured run timeout. RustFS requires a positive Unix-microsecond deadline and verifies the strict receipt echoes it. Missing or foreign origins share not-found behavior; conflicts map to an operation conflict. Requests and receipts are bounded, and responses use `Cache-Control: no-store`.
## Broker profile
`rustfs/src/admin/handlers/plugin_attempt.rs` implements `POST /rustfs/admin/v3/plugin-delegations/{id}/issue-attempt`. The signer must be an ordinary IAM user with `admin:IssuePluginAttempt`, independently listed in `RUSTFS_PLUGIN_BROKERS`:
```json
{"broker-access-key":"deployment-name"}
```
This configuration contains public access keys, not secrets. It is immutable per process. Missing or invalid configuration disables broker issuance. The broker is a trusted Controller identity; ordinary users cannot substitute their own request fields for Controller validation.
The request carries `tenant`, `run_id`, `attempt_id`, `revision`, `deployment`, `input_bucket`, `input_key`, `input_version`, `output_bucket`, `output_prefix` and `ttl_seconds`. IDs must be non-nil. Both profiles accept one exact input version and an output prefix equal to:
```text
<delegation-output-prefix><lowercase-hex-tenant>/<run-uuid>/<attempt-uuid>/
```
The session policy permits only `s3:GetObjectVersion` for that input with an exact `s3:VersionId`, and `s3:PutObject` beneath that attempt prefix. Credential lifetime is at most 900 seconds and cannot exceed delegation expiry. The Controller must additionally cap it to its validated lease and hard deadline.
The original user's current IAM remains the parent permission boundary on every S3 request. The server's signing key only seals the token; it is not the plugin's authorization identity. Broker identity and original user identity are separate.
External policy plugins must be disabled: their authorization path does not enforce this built-in session-policy boundary. Initializing, failed and ready plugin states all reject issuance. Attempt tokens carry a signed, persisted marker: after restart or on another node, marked credentials are accepted only by built-in STS authorization. A denied marked request returns a terminal error, so public bucket policies cannot bypass its session scope. The first profile also rejects parent policies containing conditions, because a broker request cannot reconstruct the original user's IP, MFA or other request context. It does not silently replace that context with the broker's.
## Response and failures
Successful issuance returns `version`, `delegation_id`, `delegation_revision`, `owner_access_key`, `access_key_id`, `secret_access_key`, `session_token` and `expires_at_unix_seconds`, with `Cache-Control: no-store`. The Controller verifies the returned delegation and owner against the accepted caller before delivery. Credentials must never enter logs, metrics or task result manifests.
Missing records and records owned by a different user have the same read response. Revoked or expired records reject access. Storage failures remain errors. Post-persistence failures carry static `error_code`, `issued` and `issuance_unknown` facts without credentials; callers must reconcile an unknown outcome rather than automatically mint another credential.
The route/action inventory is maintained in `rustfs/src/admin/route_policy.rs`. This contract does not imply event capture, physical container cleanup, restart reconciliation or upstream release acceptance.
## Cross-bucket restriction profile v2
The existing registration endpoint accepts this explicit v2 restriction:
```json
{
"version": 2,
"deployment": "runner-production",
"bucket": "source-images",
"input_prefix": "inputs/",
"output_bucket": "plugin-artifacts",
"output_prefix": "outputs/",
"expires_at_unix_seconds": 1893456000
}
```
The example expiry must be replaced by a future value within the existing
24-hour limit. `bucket` still identifies the input bucket. The existing
`issue-attempt` request and credential response do not change: its
`input_bucket` must equal `bucket`, and `output_bucket` must equal the explicit
v2 output bucket. Neither a different bucket nor a sibling attempt prefix can
be supplied by the broker. The exact input version and deterministic output
prefix checks remain in force.
A v1 restriction has neither `version` nor `output_bucket`; its JSON fields
and same-bucket behavior are unchanged. V2 requires both `version: 2` and a
nonempty, bounded, literal `output_bucket`. Missing pairs, explicit nulls,
unknown versions and unknown fields are rejected rather than downgraded to v1.
The immutable record envelope carries version 1 or 2 to match its restriction
profile. Both remain in the existing IAM record namespace; no data migration
or mutable record update is introduced. Readers reject mismatched envelope
and restriction versions. Older readers reject v2, so deploy compatible
readers before creating v2 records.
V2 does not grant the original user additional permissions. Issuance retains
its current-parent checks and post-persistence recheck/invalidation, and each
S3 request still requires both the original user's current IAM policy and the
attempt session policy to allow it. An explicit parent Deny or removal of
output permission prevents writes even with an already issued token. No
administrator credential substitutes for missing parent permission.
Focused tests are `delegation_v1_json_remains_compatible`,
`delegation_v2_requires_explicit_output_bucket`,
`attempt_v2_policy_keeps_input_version_and_output_bucket` and
`delegation_v2_persists_and_vends_with_real_parent_intersection`.
The last uses the actual issuance handler, persistent IAM and four-disk
storage, including a real input version and a third bucket allowed by the
parent but forbidden by the delegation. Removing only the output-bucket
comparison must fail `A03_CROSS_BUCKET_OUTPUT_BOUND`; parent intersection is
checked independently with issued temporary credentials. These are internal
handler/IAM tests, not signed HTTP or complete cross-bucket S3 execution.
This profile adds no bucket-creation API, Runner binding support, credential
endpoint or GC permission. Coordinating Runner's pinned binding with its
result storage bucket remains a separate integration requirement.
@@ -182,18 +182,6 @@ requires a compatibility window and a dedicated cleanup entry.
| `.scanner-cycle.lock` | scanner runtime lock | Serializes cycle-level work. A missing lock object is not itself usage evidence. |
| `.scanner-pause-backlog.json` | scanner pause and catch-up ledger | Tracks dirty usage, discovered lifecycle work, and full-scan catch-up while authoritative publication is fenced by data movement. It never grants publication admission. |
The authoritative snapshot may include an optional `bucket_incarnation` in each
bucket usage entry. The coordinator writes it only when every contributing set
reports the same non-nil bucket UUID. Missing or conflicting identities leave
that entry uncertified; they do not reject the usage publication or change quota
admission. Veeam SOSAPI capacity reads require this proof to match the bucket
incarnation read from authoritative storage. An old snapshot, a mixed-version
writer that omits the field, a pending target bucket, or an unavailable identity
therefore yields a retryable capacity error until a compatible scanner publishes
a certified entry. The optional field is omitted when unavailable so older
snapshot readers continue to see the original shape. This proof identifies the
bucket generation; it does not make scanner usage a real-time quota ledger.
## Observed Snapshots
Observed snapshots are a diagnostic and availability layer. They may be served
+1 -1
View File
@@ -297,7 +297,7 @@ tokio-rustls = { workspace = true, default-features = false, features = ["loggin
aws-smithy-runtime-api = { workspace = true, features = ["http-1x"] }
aws-smithy-types = { workspace = true }
google-cloud-auth = { workspace = true, optional = true }
moka = { workspace = true, features = ["future", "sync"] }
moka = { workspace = true, features = ["sync"] }
xxhash-rust = { workspace = true, features = ["xxh3"] }
aws-sdk-s3 = { workspace = true, default-features = false, features = ["sigv4a", "default-https-client", "rt-tokio"] }
tokio-stream.workspace = true
-2
View File
@@ -52,8 +52,6 @@ pub mod object_data_cache;
pub mod object_zip_download;
pub mod oidc;
pub mod on_demand_migration;
pub mod plugin_attempt;
pub mod plugin_delegation;
pub mod plugins_catalog;
pub mod plugins_instances;
pub mod policies;
-568
View File
@@ -1,568 +0,0 @@
// Copyright 2026 RustFS Team
// SPDX-License-Identifier: Apache-2.0
//! Restricted vending for explicitly configured brokers, never AssumeRole chaining.
use super::plugin_delegation::{owner, response, storage_error};
use crate::{
admin::{
router::{AdminOperation, Operation, S3Router},
runtime_sources,
storage_api::s3::{self, Body, S3Error, S3ErrorCode, S3Request, S3Response, S3Result},
},
auth::check_key_valid_with_context,
server::ADMIN_PREFIX,
};
use http::{Method, StatusCode};
use matchit::Params;
use rustfs_iam::{
delegation::Delegation,
sys::{PLUGIN_ATTEMPT_CREDENTIAL_CLAIM, SESSION_POLICY_NAME},
};
use rustfs_policy::{
auth::get_new_credentials_with_metadata,
policy::{
Args, Policy,
action::{Action, AdminAction, S3Action},
},
};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
sync::OnceLock,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use time::OffsetDateTime;
// Operator configuration contains public signer access keys, not credentials.
// Empty/invalid configuration disables the endpoint. It is immutable per process.
static BROKERS: OnceLock<Option<HashMap<String, String>>> = OnceLock::new();
fn configured_deployment(key: &str) -> Option<&'static str> {
BROKERS
.get_or_init(|| {
let raw = std::env::var("RUSTFS_PLUGIN_BROKERS").ok()?;
let map: HashMap<String, String> = serde_json::from_str(&raw).ok()?;
if map.is_empty()
|| map
.iter()
.any(|(k, v)| k.is_empty() || v.is_empty() || k.len() > 1024 || v.len() > 1024)
{
return None;
}
Some(map)
})
.as_ref()?
.get(key)
.map(String::as_str)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Attempt {
tenant: String,
run_id: uuid::Uuid,
attempt_id: uuid::Uuid,
revision: String,
deployment: String,
input_bucket: String,
input_key: String,
input_version: String,
output_bucket: String,
output_prefix: String,
ttl_seconds: u64,
}
#[derive(Serialize)]
struct Issued {
version: u32,
delegation_id: String,
delegation_revision: String,
owner_access_key: String,
access_key_id: String,
secret_access_key: String,
session_token: String,
expires_at_unix_seconds: i64,
}
pub fn register_plugin_attempt_route(router: &mut S3Router<AdminOperation>) -> std::io::Result<()> {
router.insert(
Method::POST,
&format!("{ADMIN_PREFIX}/v3/plugin-delegations/{{id}}/issue-attempt"),
AdminOperation(&Issue),
)?;
Ok(())
}
fn now() -> S3Result<u64> {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.map_err(|_| s3::error(S3ErrorCode::InternalError, "clock unavailable"))
}
fn literal(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 1024
&& !value.contains("${")
&& !value.chars().any(|c| c.is_control() || matches!(c, '*' | '?'))
}
fn session_policy(record: &Delegation, attempt: &Attempt) -> S3Result<Policy> {
let restriction = &record.restrictions;
// Stored records from earlier versions must obey the same literal rules.
restriction.validate(record.created_at_unix_seconds).map_err(storage_error)?;
let exact_output = format!(
"{}{}/{}/{}/",
restriction.output_prefix,
hex_simd::encode_to_string(attempt.tenant.as_bytes(), hex_simd::AsciiCase::Lower),
attempt.run_id,
attempt.attempt_id
);
if attempt.tenant.is_empty()
|| attempt.tenant.len() > 1024
|| attempt.run_id.is_nil()
|| attempt.attempt_id.is_nil()
|| attempt.output_prefix != exact_output
|| attempt.revision != record.revision
|| attempt.deployment != restriction.deployment
|| attempt.input_bucket != restriction.bucket
|| attempt.output_bucket != restriction.output_bucket().map_err(storage_error)?
|| !literal(&attempt.input_key)
|| !attempt.input_key.starts_with(&restriction.input_prefix)
|| !literal(&attempt.input_version)
|| attempt.input_version == "null"
|| !literal(&attempt.output_prefix)
|| !attempt.output_prefix.starts_with(&restriction.output_prefix)
|| attempt.output_prefix == restriction.output_prefix
|| !attempt.output_prefix.ends_with('/')
|| !(1..=900).contains(&attempt.ttl_seconds)
{
return Err(s3::error(S3ErrorCode::AccessDenied, "attempt restriction rejected"));
}
let value = serde_json::json!({"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:GetObjectVersion"],"Resource":[format!("arn:aws:s3:::{}/{}",attempt.input_bucket,attempt.input_key)],"Condition":{"StringEquals":{"s3:VersionId":attempt.input_version}}},
{"Effect":"Allow","Action":["s3:PutObject"],"Resource":[format!("arn:aws:s3:::{}/{}*",attempt.output_bucket,attempt.output_prefix)]}
]});
// Condition operators borrow their keys while the policy is decoded.
let bytes = serde_json::to_vec(&value).map_err(|_| s3::error(S3ErrorCode::InternalError, "attempt policy unavailable"))?;
serde_json::from_slice(&bytes).map_err(|_| s3::error(S3ErrorCode::InternalError, "attempt policy unavailable"))
}
fn issuance_error(code: &'static str, issued: bool, unknown: bool) -> S3Result<S3Response<(StatusCode, Body)>> {
let mut answer = response(&serde_json::json!({"error_code":code,"issued":issued,"issuance_unknown":unknown}))?;
answer.output.0 = StatusCode::SERVICE_UNAVAILABLE;
Ok(answer)
}
fn same_parent_authority(before_names: &[String], before_policy: &Policy, after_names: &[String], after_policy: &Policy) -> bool {
fn names(names: &[String]) -> Vec<&str> {
let mut names: Vec<_> = names.iter().map(String::as_str).collect();
names.sort_unstable();
names.dedup();
names
}
fn statements(policy: &Policy) -> Option<Vec<Vec<u8>>> {
let mut statements = policy
.statements
.iter()
.map(serde_json::to_vec)
.collect::<Result<Vec<_>, _>>()
.ok()?;
statements.sort_unstable();
Some(statements)
}
names(before_names) == names(after_names)
&& matches!(
(statements(before_policy), statements(after_policy)),
(Some(before), Some(after)) if before == after
)
}
async fn require_builtin_authorization() -> S3Result<()> {
rustfs_iam::sys::IamSys::<rustfs_iam::store::object::ObjectStore>::ensure_restricted_credential_vending()
.await
.map_err(|_| s3::error(S3ErrorCode::AccessDenied, "external policy plugin unsupported for attempt credentials"))
}
struct Issue;
#[async_trait::async_trait]
impl Operation for Issue {
async fn call(&self, mut req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
require_builtin_authorization().await?;
let (iam, broker) = owner(&req, AdminAction::IssuePluginAttemptAction).await?;
let deployment =
configured_deployment(&broker).ok_or_else(|| s3::error(S3ErrorCode::AccessDenied, "broker deployment rejected"))?;
let context = runtime_sources::app_context_from_req(&req)
.ok_or_else(|| s3::error(S3ErrorCode::InternalError, "application context unavailable"))?;
let bytes = tokio::time::timeout(Duration::from_secs(10), req.input.store_all_limited(16384))
.await
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "attempt body unavailable"))?
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "attempt body unavailable"))?;
let attempt: Attempt =
serde_json::from_slice(&bytes).map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "invalid attempt request"))?;
if attempt.deployment != deployment {
return Err(s3::error(S3ErrorCode::AccessDenied, "broker deployment rejected"));
}
let id = params
.get("id")
.ok_or_else(|| s3::error(S3ErrorCode::InvalidRequest, "delegation id required"))?;
let record = iam
.read_active_plugin_delegation_for_broker(id, now()?)
.await
.map_err(storage_error)?;
let policy = session_policy(&record, &attempt)?;
let (principal, root) = check_key_valid_with_context("", &record.owner_access_key, Some(context.as_ref())).await?;
if root || principal.is_temp() || principal.is_service_account() {
return Err(s3::error(S3ErrorCode::AccessDenied, "original user required"));
}
// A broker request cannot reconstruct the original user's IP/MFA/tag
// conditions. This first profile rejects conditional parent policies.
let policies = iam
.policy_db_get(&principal.access_key, &principal.groups)
.await
.map_err(|_| s3::error(S3ErrorCode::InternalError, "parent policy unavailable"))?;
let parent_policy = iam.get_combined_policy(&policies).await;
if policies.is_empty() || parent_policy.statements.iter().any(|s| !s.conditions.is_empty()) {
return Err(s3::error(S3ErrorCode::AccessDenied, "parent condition context unsupported"));
}
let mut conditions = HashMap::new();
conditions.insert("s3:VersionId".to_owned(), vec![attempt.input_version.clone()]);
if !iam
.is_allowed(&Args {
account: &principal.access_key,
groups: &principal.groups,
action: Action::S3Action(S3Action::GetObjectVersionAction),
bucket: &attempt.input_bucket,
object: &attempt.input_key,
conditions: &conditions,
is_owner: false,
claims: principal.claims_or_empty(),
deny_only: false,
})
.await
{
return Err(s3::error(S3ErrorCode::AccessDenied, "parent input rejected"));
}
let expiration = now()?
.checked_add(attempt.ttl_seconds)
.ok_or_else(|| s3::error(S3ErrorCode::InvalidRequest, "invalid expiration"))?
.min(record.restrictions.expires_at_unix_seconds);
let expires_at = OffsetDateTime::from_unix_timestamp(
i64::try_from(expiration).map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "invalid expiration"))?,
)
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "invalid expiration"))?;
let mut claims = principal.claims.clone().unwrap_or_default();
claims.insert(PLUGIN_ATTEMPT_CREDENTIAL_CLAIM.into(), serde_json::Value::Bool(true));
claims.insert("exp".into(), serde_json::json!(expires_at.unix_timestamp()));
claims.insert("parent".into(), serde_json::json!(principal.access_key));
let bytes =
serde_json::to_vec(&policy).map_err(|_| s3::error(S3ErrorCode::InternalError, "attempt policy unavailable"))?;
claims.insert(
SESSION_POLICY_NAME.into(),
serde_json::json!(base64_simd::URL_SAFE_NO_PAD.encode_to_string(&bytes)),
);
let fresh = iam
.read_active_plugin_delegation_for_broker(id, now()?)
.await
.map_err(storage_error)?;
if fresh != record {
return Err(s3::error(S3ErrorCode::AccessDenied, "attempt authority changed"));
}
owner(&req, AdminAction::IssuePluginAttemptAction).await?;
require_builtin_authorization().await?;
let signing = context
.action_credentials()
.get()
.ok_or_else(|| s3::error(S3ErrorCode::InternalError, "token signer unavailable"))?;
// The server key seals the token only. Authorization above uses the
// original user's current IAM, and S3 continues its parent intersection.
let mut credential = get_new_credentials_with_metadata(&claims, &signing.secret_key)
.map_err(|_| s3::error(S3ErrorCode::InternalError, "attempt credential unavailable"))?;
credential.parent_user = principal.access_key.clone();
if iam.set_temp_user(&credential.access_key, &credential, None).await.is_err() {
return issuance_error("PLUGIN_ATTEMPT_ISSUANCE_UNKNOWN", false, true);
}
// No atomic IAM/delegation transaction spans persistence. Recheck and
// invalidate the generated credential if any authority changed.
let valid = async {
require_builtin_authorization().await?;
let after = iam
.read_active_plugin_delegation_for_broker(id, now()?)
.await
.map_err(storage_error)?;
let (current, current_root) =
check_key_valid_with_context("", &record.owner_access_key, Some(context.as_ref())).await?;
let names = iam
.policy_db_get(&current.access_key, &current.groups)
.await
.map_err(|_| s3::error(S3ErrorCode::InternalError, "parent policy unavailable"))?;
let current_policy = iam.get_combined_policy(&names).await;
if after != record
|| current_root
|| current.is_temp()
|| current.is_service_account()
|| current.secret_key != principal.secret_key
|| !same_parent_authority(&policies, &parent_policy, &names, &current_policy)
{
return Err(s3::error(S3ErrorCode::AccessDenied, "attempt authority changed"));
}
// Re-evaluate the broker against its real signed request context.
owner(&req, AdminAction::IssuePluginAttemptAction).await?;
Ok::<(), S3Error>(())
}
.await;
if valid.is_err() {
if iam.delete_temp_account(&credential.access_key, true).await.is_err() {
return issuance_error("PLUGIN_ATTEMPT_INVALIDATION_UNKNOWN", true, true);
}
return issuance_error("PLUGIN_ATTEMPT_POST_ISSUANCE_REJECTED", true, false);
}
response(&Issued {
version: 1,
delegation_id: record.id,
delegation_revision: record.revision,
owner_access_key: record.owner_access_key,
access_key_id: credential.access_key,
secret_access_key: credential.secret_key,
session_token: credential.session_token,
expires_at_unix_seconds: expires_at.unix_timestamp(),
})
}
}
#[cfg(test)]
#[path = "plugin_attempt_v2_tests.rs"]
mod v2_tests;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parent_authority_recheck_ignores_policy_order_but_detects_changes() {
let first: Policy = serde_json::from_value(serde_json::json!({
"Version":"2012-10-17",
"Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::photos/input/*"},
{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::photos/output/*"}
]
}))
.unwrap();
let reordered: Policy = serde_json::from_value(serde_json::json!({
"Version":"2012-10-17",
"Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::photos/output/*"},
{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::photos/input/*"}
]
}))
.unwrap();
let before_names = vec!["owner-policy".to_owned(), "bucket-policy".to_owned()];
let after_names = vec!["bucket-policy".to_owned(), "owner-policy".to_owned()];
assert!(same_parent_authority(&before_names, &first, &after_names, &reordered));
let changed: Policy = serde_json::from_value(serde_json::json!({
"Version":"2012-10-17",
"Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::photos/input/*"},
{"Effect":"Allow","Action":"s3:DeleteObject","Resource":"arn:aws:s3:::photos/output/*"}
]
}))
.unwrap();
assert!(!same_parent_authority(&before_names, &first, &after_names, &changed));
let changed_resource: Policy = serde_json::from_value(serde_json::json!({
"Version":"2012-10-17",
"Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::photos/input/*"},
{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::photos/private/*"}
]
}))
.unwrap();
assert!(!same_parent_authority(&before_names, &first, &after_names, &changed_resource));
let added_deny: Policy = serde_json::from_value(serde_json::json!({
"Version":"2012-10-17",
"Statement":[
{"Effect":"Deny","Action":"s3:GetObject","Resource":"arn:aws:s3:::photos/input/private/*"},
{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::photos/input/*"},
{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::photos/output/*"}
]
}))
.unwrap();
assert!(!same_parent_authority(&before_names, &first, &after_names, &added_deny));
assert!(!same_parent_authority(&before_names, &first, &["other-policy".to_owned()], &first));
}
#[tokio::test]
async fn attempt_policy_keeps_exact_version_and_narrow_output() {
let record = Delegation {
version: 1,
id: "a".repeat(32),
revision: "a".repeat(32),
owner_access_key: "user".into(),
created_at_unix_seconds: 1,
restrictions: rustfs_iam::delegation::Restrictions {
version: None,
output_bucket: None,
deployment: "runner".into(),
bucket: "photos".into(),
input_prefix: "input/".into(),
output_prefix: "output/".into(),
expires_at_unix_seconds: 1000,
},
};
let run_id = uuid::Uuid::new_v4();
let attempt_id = uuid::Uuid::new_v4();
let output_prefix = format!(
"output/{}/{}/{}/",
hex_simd::encode_to_string(b"tenant", hex_simd::AsciiCase::Lower),
run_id,
attempt_id
);
let mut attempt = Attempt {
tenant: "tenant".into(),
run_id,
attempt_id,
revision: record.revision.clone(),
deployment: "runner".into(),
input_bucket: "photos".into(),
input_key: "input/photo.png".into(),
input_version: "version-1".into(),
output_bucket: "photos".into(),
output_prefix: output_prefix.clone(),
ttl_seconds: 60,
};
let policy = session_policy(&record, &attempt).unwrap();
let scoped_output = format!("{output_prefix}result");
let groups = None;
let claims = HashMap::new();
for (action, object, version, expected) in [
(S3Action::GetObjectVersionAction, "input/photo.png", Some("version-1"), true),
(S3Action::GetObjectVersionAction, "input/photo.png", Some("version-2"), false),
(S3Action::GetObjectVersionAction, "input/photo.png", None, false),
(S3Action::GetObjectAction, "input/photo.png", None, false),
(S3Action::PutObjectAction, scoped_output.as_str(), None, true),
(S3Action::PutObjectAction, "outside/result", None, false),
(S3Action::PutObjectAction, "output/result", None, false),
] {
let conditions = version
.map(|value| HashMap::from([("versionid".into(), vec![value.into()])]))
.unwrap_or_default();
assert_eq!(
policy
.is_allowed(&Args {
account: "user",
groups: &groups,
action: Action::S3Action(action),
bucket: "photos",
object,
conditions: &conditions,
is_owner: false,
claims: &claims,
deny_only: false,
})
.await,
expected,
"attempt policy action={action:?} object={object} version={version:?}"
);
}
attempt.output_bucket = "artifacts".into();
assert!(
session_policy(&record, &attempt).is_err(),
"v1 still requires the input bucket for output"
);
attempt.output_bucket = "photos".into();
attempt.output_prefix = "output/".into();
assert!(session_policy(&record, &attempt).is_err());
attempt.output_prefix = output_prefix;
attempt.input_key = "outside/photo.png".into();
assert!(session_policy(&record, &attempt).is_err());
}
#[tokio::test]
async fn attempt_v2_policy_keeps_input_version_and_output_bucket() {
let record: Delegation = serde_json::from_value(serde_json::json!({
"version":2,"id":"a".repeat(32),"revision":"a".repeat(32),"owner_access_key":"user",
"created_at_unix_seconds":1,"restrictions":{"version":2,"deployment":"runner","bucket":"photos",
"input_prefix":"input/","output_bucket":"artifacts","output_prefix":"output/","expires_at_unix_seconds":1000}
}))
.expect("explicit v2 delegation");
let run_id = uuid::Uuid::new_v4();
let attempt_id = uuid::Uuid::new_v4();
let output = format!("output/74656e616e74/{run_id}/{attempt_id}/");
let mut attempt = Attempt {
tenant: "tenant".into(),
run_id,
attempt_id,
revision: record.revision.clone(),
deployment: "runner".into(),
input_bucket: "photos".into(),
input_key: "input/photo.png".into(),
input_version: "version-1".into(),
output_bucket: "artifacts".into(),
output_prefix: output.clone(),
ttl_seconds: 60,
};
let policy = session_policy(&record, &attempt).expect("v2 scope");
let result = format!("{output}result");
for (action, bucket, object, version, expected) in [
(S3Action::GetObjectVersionAction, "photos", "input/photo.png", Some("version-1"), true),
(S3Action::GetObjectVersionAction, "photos", "input/photo.png", Some("version-2"), false),
(S3Action::GetObjectVersionAction, "artifacts", "input/photo.png", Some("version-1"), false),
(S3Action::PutObjectAction, "artifacts", result.as_str(), None, true),
(S3Action::PutObjectAction, "photos", result.as_str(), None, false),
(S3Action::PutObjectAction, "third", result.as_str(), None, false),
(S3Action::PutObjectAction, "artifacts", "output/other/result", None, false),
] {
let conditions = version
.map(|v| HashMap::from([("versionid".into(), vec![v.into()])]))
.unwrap_or_default();
assert_eq!(
policy
.is_allowed(&Args {
account: "user",
groups: &None,
action: Action::S3Action(action),
bucket,
object,
conditions: &conditions,
claims: &HashMap::new(),
is_owner: false,
deny_only: false
})
.await,
expected,
"A03_CROSS_BUCKET_SCOPE: bucket={bucket} object={object}"
);
}
attempt.output_bucket = "third".into();
assert!(session_policy(&record, &attempt).is_err(), "A03_CROSS_BUCKET_OUTPUT_BOUND");
attempt.output_bucket = "photos".into();
assert!(session_policy(&record, &attempt).is_err(), "A03_CROSS_BUCKET_OUTPUT_BOUND");
attempt.output_bucket = "artifacts".into();
attempt.input_bucket = "artifacts".into();
assert!(session_policy(&record, &attempt).is_err(), "A03_CROSS_BUCKET_INPUT_BOUND");
}
#[tokio::test]
async fn actual_policy_variable_resolution_is_rejected_by_literal_scope() {
let resource = rustfs_policy::policy::resource::Resource::S3("photos/input/${aws:username}.png".into());
let conditions = HashMap::from([("username".into(), vec!["alice".into()])]);
let resolver =
rustfs_policy::policy::variables::VariableResolver::new(rustfs_policy::policy::variables::VariableContext {
username: Some("alice".into()),
..Default::default()
});
assert!(
resource
.is_match_with_resolver("photos/input/alice.png", &conditions, Some(&resolver))
.await,
"C07_LITERAL_SCOPE_BOUND: actual policy engine substitutes resource variables"
);
assert!(
!literal("input/${aws:username}.png"),
"C07_LITERAL_SCOPE_BOUND: requested resources must stay literal"
);
let restriction = rustfs_iam::delegation::Restrictions {
version: None,
output_bucket: None,
deployment: "runner".into(),
bucket: "photos".into(),
input_prefix: "input/${aws:username}/".into(),
output_prefix: "output/".into(),
expires_at_unix_seconds: 200,
};
assert!(
restriction.validate(100).is_err(),
"C07_LITERAL_SCOPE_BOUND: legacy stored variable restrictions are rejected"
);
}
}
@@ -1,365 +0,0 @@
// Copyright 2026 RustFS Team
// SPDX-License-Identifier: Apache-2.0
//! Real handler, persisted IAM and four-disk storage; this is not a signed HTTP/S3 end-to-end test.
use super::*;
use crate::admin::{
runtime_sources::{AppContext, IamInterface, KmsInterface, ServerContextSlot},
storage_api::{
ECStore,
contract::bucket::{BucketOperations as _, MakeBucketOptions},
contract::object::ObjectIO as _,
},
};
use crate::storage::storage_api::{StorageObjectOptions, StoragePutObjReader};
use http_body_util::BodyExt as _;
use rustfs_iam::{
store::{
Store as _, UserType,
object::{IAM_CONFIG_PREFIX, ObjectStore},
},
sys::IamSys,
};
use rustfs_madmin::{AccountStatus, AddOrUpdateUserReq};
use serde_json::{Value, json};
use std::sync::Arc;
const PARENT: &str = "cross-parent";
const BROKER: &str = "cross-broker";
const SECRET: &str = "cross-bucket-test-secret";
const ROOT: &str = "cross-root";
const ROOT_SECRET: &str = "cross-bucket-root-test-secret";
struct RequestIam(Arc<IamSys<ObjectStore>>);
impl IamInterface for RequestIam {
fn handle(&self) -> Arc<IamSys<ObjectStore>> {
self.0.clone()
}
fn is_ready(&self) -> bool {
true
}
}
struct RequestKms;
impl KmsInterface for RequestKms {
fn handle(&self) -> Arc<rustfs_kms::KmsServiceManager> {
Arc::new(rustfs_kms::KmsServiceManager::new())
}
}
struct Fixture {
_root: tempfile::TempDir,
store: Arc<ECStore>,
iam: Arc<IamSys<ObjectStore>>,
context: Arc<AppContext>,
input_version: String,
}
impl Fixture {
async fn new() -> Self {
let root = tempfile::tempdir().expect("cross-bucket storage root");
let env = rustfs_test_utils::TestECStoreEnv::builder()
.base_dir(root.path())
.disk_count(4)
.build()
.await;
assert_eq!(env.disk_paths.len(), 4);
let store = env.ecstore;
for bucket in ["photos", "artifacts", "third"] {
store
.make_bucket(
bucket,
&MakeBucketOptions {
versioning_enabled: true,
..Default::default()
},
)
.await
.expect("real versioned bucket");
}
let object = store
.put_object(
"photos",
"input/photo.png",
&mut StoragePutObjReader::from_vec(vec![0xA5; 273]),
&StorageObjectOptions {
versioned: true,
..Default::default()
},
)
.await
.expect("real input version");
let input_version = object.version_id.expect("exact input version").to_string();
ObjectStore::new(store.clone())
.save_iam_config(json!({"version":1}), format!("{}/format.json", *IAM_CONFIG_PREFIX))
.await
.expect("persistent IAM format");
let iam = rustfs_iam::build_iam_sys(store.clone()).await.expect("real IAM");
let context = Arc::new(AppContext::new(store.clone(), Arc::new(RequestIam(iam.clone())), Arc::new(RequestKms)));
assert!(context.publish_action_credentials(rustfs_credentials::Credentials {
access_key: ROOT.into(),
secret_key: ROOT_SECRET.into(),
status: "on".into(),
..Default::default()
}));
let fixture = Self {
_root: root,
store,
iam,
context,
input_version,
};
fixture.user(PARENT, Self::parent_policy(true, false)).await;
fixture
.user(
BROKER,
json!({"Version":"2012-10-17","Statement":[{
"Effect":"Allow","Action":"admin:IssuePluginAttempt"}]}),
)
.await;
fixture
}
fn parent_policy(output: bool, deny: bool) -> Value {
let mut resources = vec!["arn:aws:s3:::photos/output/*", "arn:aws:s3:::third/output/*"];
if output {
resources.push("arn:aws:s3:::artifacts/output/*");
}
let mut statements = vec![
json!({"Effect":"Allow","Action":"s3:GetObjectVersion","Resource":"arn:aws:s3:::photos/input/*"}),
json!({"Effect":"Allow","Action":"s3:PutObject","Resource":resources}),
];
if deny {
statements.push(json!({"Effect":"Deny","Action":"s3:PutObject","Resource":"arn:aws:s3:::artifacts/*"}));
}
json!({"Version":"2012-10-17","Statement":statements})
}
async fn policy(&self, name: &str, value: Value) {
let policy = Policy::parse_config(&serde_json::to_vec(&value).expect("policy JSON")).expect("real IAM policy");
self.iam.set_policy(name, policy).await.expect("persist policy");
}
async fn user(&self, name: &str, policy: Value) {
self.iam
.create_user(
name,
&AddOrUpdateUserReq {
secret_key: SECRET.into(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.expect("create real user");
self.policy(name, policy).await;
self.iam
.policy_db_set(name, UserType::Reg, false, name)
.await
.expect("attach actual IAM policy");
}
fn request(&self, body: &Value) -> S3Request<Body> {
let slot = ServerContextSlot::new();
assert!(slot.install(self.context.clone()));
let mut req = S3Request {
input: Body::from(serde_json::to_vec(body).expect("attempt JSON")),
method: Method::POST,
uri: http::Uri::default(),
headers: http::HeaderMap::new(),
extensions: http::Extensions::new(),
credentials: None,
region: None,
service: None,
trailing_headers: None,
};
req.extensions.insert(slot);
req.method = Method::POST;
req.credentials = Some(s3::auth::Credentials {
access_key: BROKER.into(),
secret_key: s3::auth::SecretKey::from(SECRET.to_owned()),
});
req
}
async fn issue(&self, record: &Delegation, body: &Value) -> S3Result<S3Response<(StatusCode, Body)>> {
let mut router = matchit::Router::new();
router.insert("/{id}", ()).expect("parameter route");
let path = format!("/{}", record.id);
Issue
.call(self.request(body), router.at(&path).expect("actual delegation ID").params)
.await
}
async fn allowed(
&self,
credential: &rustfs_credentials::Credentials,
action: S3Action,
bucket: &str,
object: &str,
version: Option<&str>,
) -> bool {
let conditions = version
.map(|v| HashMap::from([("versionid".into(), vec![v.into()])]))
.unwrap_or_default();
self.iam
.is_allowed(&Args {
account: &credential.access_key,
groups: &credential.groups,
action: Action::S3Action(action),
bucket,
object,
conditions: &conditions,
claims: credential.claims_or_empty(),
is_owner: false,
deny_only: false,
})
.await
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial_test::serial]
async fn delegation_v2_persists_and_vends_with_real_parent_intersection() {
temp_env::async_with_vars(
[
("RUSTFS_PLUGIN_BROKERS", Some(r#"{"cross-broker":"runner"}"#)),
("RUSTFS_SKIP_BACKGROUND_TASK", Some("1")),
],
async {
let fixture = Fixture::new().await;
let now = now().expect("clock");
let legacy = json!({"deployment":"runner","bucket":"photos","input_prefix":"input/",
"output_prefix":"output/","expires_at_unix_seconds":now+3600});
let v1 = fixture
.iam
.create_plugin_delegation(PARENT, serde_json::from_value(legacy.clone()).expect("v1"), now)
.await
.expect("persist legacy delegation");
assert_eq!(v1.version, 1);
assert_eq!(serde_json::to_value(&v1.restrictions).expect("v1 wire"), legacy);
let mut v2 = legacy;
v2["version"] = json!(2);
v2["output_bucket"] = json!("artifacts");
let record = fixture
.iam
.create_plugin_delegation(PARENT, serde_json::from_value(v2.clone()).expect("v2"), now)
.await
.expect("persist v2 delegation");
assert_eq!(record.version, 2);
let loaded = fixture
.iam
.read_active_plugin_delegation(PARENT, &record.id, now)
.await
.expect("strict stored v2");
assert!(loaded == record, "same persisted v2 identity");
assert_eq!(serde_json::to_value(&loaded.restrictions).expect("v2 wire"), v2);
// The record envelope and restriction profile cannot disagree on a persisted read.
let path = format!("config/iam/plugin-delegations/v1/{}/record.json", record.id);
let mut corrupt = serde_json::to_value(&record).expect("record JSON");
corrupt["version"] = json!(1);
ObjectStore::new(fixture.store.clone())
.save_iam_config(corrupt, &path)
.await
.expect("inject incompatible stored version");
assert!(
fixture
.iam
.read_active_plugin_delegation(PARENT, &record.id, now)
.await
.is_err(),
"mixed v1/v2 stored profiles fail closed"
);
ObjectStore::new(fixture.store.clone())
.save_iam_config(&record, &path)
.await
.expect("restore exact stored record");
let run = uuid::Uuid::new_v4();
let attempt = uuid::Uuid::new_v4();
let prefix = format!("output/74656e616e74/{run}/{attempt}/");
let body = json!({"tenant":"tenant","run_id":run,"attempt_id":attempt,"revision":record.revision,
"deployment":"runner","input_bucket":"photos","input_key":"input/photo.png","input_version":fixture.input_version,
"output_bucket":"artifacts","output_prefix":prefix,"ttl_seconds":60});
let loaded_v1 = fixture
.iam
.read_active_plugin_delegation(PARENT, &v1.id, now)
.await
.expect("read legacy record");
assert!(loaded_v1 == v1, "legacy persistent identity");
let mut legacy_body = body.clone();
legacy_body["revision"] = json!(v1.revision);
legacy_body["output_bucket"] = json!("photos");
let legacy_response = fixture.issue(&v1, &legacy_body).await.expect("legacy same-bucket issuance");
assert_eq!(legacy_response.output.0, StatusCode::OK);
let mut wrong = body.clone();
wrong["output_bucket"] = json!("third");
match fixture.issue(&record, &wrong).await {
Err(error) => assert_eq!(error.code(), &S3ErrorCode::AccessDenied),
Ok(_) => panic!("A03_CROSS_BUCKET_OUTPUT_BOUND"),
}
let response = fixture.issue(&record, &body).await.expect("actual v2 issuance");
assert_eq!(response.output.0, StatusCode::OK);
assert_eq!(response.headers[http::header::CACHE_CONTROL], "no-store");
let issued: Value =
serde_json::from_slice(&response.output.1.collect().await.expect("issued body").to_bytes()).expect("issued JSON");
let (credential, root) = check_key_valid_with_context(
issued["session_token"].as_str().expect("token"),
issued["access_key_id"].as_str().expect("access key"),
Some(fixture.context.as_ref()),
)
.await
.expect("persisted actual temporary identity");
assert!(!root && credential.is_temp());
let output = format!("{prefix}image.png");
for (action, bucket, object, version, expected) in [
(
S3Action::GetObjectVersionAction,
"photos",
"input/photo.png",
Some(fixture.input_version.as_str()),
true,
),
(
S3Action::GetObjectVersionAction,
"photos",
"input/photo.png",
Some("wrong-version"),
false,
),
(S3Action::GetObjectAction, "photos", "input/photo.png", None, false),
(S3Action::PutObjectAction, "artifacts", output.as_str(), None, true),
(S3Action::PutObjectAction, "photos", output.as_str(), None, false),
(S3Action::PutObjectAction, "third", output.as_str(), None, false),
(S3Action::PutObjectAction, "artifacts", "output/other/image.png", None, false),
] {
assert_eq!(
fixture.allowed(&credential, action, bucket, object, version).await,
expected,
"A03_CROSS_BUCKET_PARENT_INTERSECTION: bucket={bucket} object={object}"
);
}
fixture.policy(PARENT, Fixture::parent_policy(true, true)).await;
assert!(
!fixture
.allowed(&credential, S3Action::PutObjectAction, "artifacts", &output, None)
.await,
"explicit parent Deny remains effective"
);
fixture.policy(PARENT, Fixture::parent_policy(false, false)).await;
assert!(
!fixture
.allowed(&credential, S3Action::PutObjectAction, "artifacts", &output, None)
.await,
"removing parent output permission remains effective"
);
assert!(
fixture
.allowed(
&credential,
S3Action::GetObjectVersionAction,
"photos",
"input/photo.png",
Some(&fixture.input_version)
)
.await
);
fixture
.iam
.revoke_plugin_delegation(PARENT, &record.id)
.await
.expect("revoke v2");
assert!(fixture.issue(&record, &body).await.is_err(), "revoked v2 cannot issue again");
},
)
.await;
}
@@ -1,624 +0,0 @@
// Copyright 2026 RustFS Team
// SPDX-License-Identifier: Apache-2.0
//! Restriction registration only. These endpoints do not vend credentials.
use crate::admin::{
auth::{AdminResourceScope, validate_admin_action_with_bucket_object_for_iam},
plugin_runner::{self, ObjectReference, SubmitRequest},
router::{AdminOperation, Operation, S3Router},
runtime_sources,
storage_api::s3::{self, Body, S3Error, S3ErrorCode, S3Request, S3Response, S3Result},
};
use crate::{
auth::{check_key_valid_with_context, get_session_token},
server::{ADMIN_PREFIX, RemoteAddr},
};
use http::{HeaderMap, HeaderValue, Method, StatusCode};
use matchit::Params;
use rustfs_iam::delegation::{DelegationError, Restrictions};
use rustfs_policy::policy::action::{Action, AdminAction};
use serde::Deserialize;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub fn register_plugin_delegation_route(router: &mut S3Router<AdminOperation>) -> std::io::Result<()> {
router.insert(Method::POST, &format!("{ADMIN_PREFIX}/v3/plugin-delegations"), AdminOperation(&Create))?;
router.insert(Method::GET, &format!("{ADMIN_PREFIX}/v3/plugin-delegations/{{id}}"), AdminOperation(&Get))?;
router.insert(
Method::POST,
&format!("{ADMIN_PREFIX}/v3/plugin-delegations/{{id}}/revoke"),
AdminOperation(&Revoke),
)?;
router.insert(
Method::POST,
&format!("{ADMIN_PREFIX}/v3/plugin-delegations/{{id}}/submit"),
AdminOperation(&Submit),
)?;
router.insert(
Method::POST,
&format!("{ADMIN_PREFIX}/v3/plugin-delegations/{{id}}/runs/query"),
AdminOperation(&QueryRun),
)?;
router.insert(
Method::POST,
&format!("{ADMIN_PREFIX}/v3/plugin-delegations/{{id}}/runs/history"),
AdminOperation(&HistoryRun),
)?;
router.insert(
Method::POST,
&format!("{ADMIN_PREFIX}/v3/plugin-delegations/{{id}}/runs/cancel"),
AdminOperation(&CancelRun),
)?;
router.insert(
Method::POST,
&format!("{ADMIN_PREFIX}/v3/plugin-delegations/{{id}}/runs/page"),
AdminOperation(&PageRuns),
)?;
router.insert(
Method::POST,
&format!("{ADMIN_PREFIX}/v3/plugin-delegations/{{id}}/runs/replay"),
AdminOperation(&ReplayRun),
)?;
Ok(())
}
pub(super) fn storage_error(error: DelegationError) -> S3Error {
match error {
DelegationError::Invalid => s3::error(S3ErrorCode::InvalidRequest, "invalid delegation restriction"),
DelegationError::NotFound | DelegationError::OwnerRejected => s3::error(S3ErrorCode::NoSuchKey, "delegation not found"),
DelegationError::Unavailable => s3::error(S3ErrorCode::InternalError, "delegation unavailable"),
_ => s3::error(S3ErrorCode::AccessDenied, "delegation rejected"),
}
}
pub(super) async fn owner(
req: &S3Request<Body>,
action: AdminAction,
) -> S3Result<(std::sync::Arc<rustfs_iam::sys::IamSys<rustfs_iam::store::object::ObjectStore>>, String)> {
let signed = req
.credentials
.as_ref()
.ok_or_else(|| s3::error(S3ErrorCode::AccessDenied, "authentication required"))?;
if get_session_token(&req.uri, &req.headers).is_some() {
return Err(s3::error(S3ErrorCode::AccessDenied, "original user required"));
}
let context = runtime_sources::app_context_from_req(req)
.ok_or_else(|| s3::error(S3ErrorCode::InternalError, "application context unavailable"))?;
let (credentials, root) = check_key_valid_with_context("", &signed.access_key, Some(context.as_ref())).await?;
if root || credentials.is_temp() || credentials.is_service_account() {
return Err(s3::error(S3ErrorCode::AccessDenied, "original user required"));
}
if !context.iam().is_ready() {
return Err(s3::error(S3ErrorCode::InternalError, "iam unavailable"));
}
let iam = context.iam().handle();
validate_admin_action_with_bucket_object_for_iam(
iam.clone(),
&req.headers,
&credentials,
false,
Action::AdminAction(action),
req.extensions.get::<Option<RemoteAddr>>().and_then(|a| a.map(|a| a.0)),
AdminResourceScope::bucket_object("", ""),
)
.await?;
Ok((iam, credentials.access_key))
}
pub(super) fn response<T: serde::Serialize>(value: &T) -> S3Result<S3Response<(StatusCode, Body)>> {
let bytes =
serde_json::to_vec(value).map_err(|_| s3::error(S3ErrorCode::InternalError, "delegation response unavailable"))?;
let mut headers = HeaderMap::new();
headers.insert(http::header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
headers.insert(http::header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
Ok(S3Response::with_headers((StatusCode::OK, Body::from(bytes)), headers))
}
struct Create;
#[async_trait::async_trait]
impl Operation for Create {
async fn call(&self, mut req: S3Request<Body>, _params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let (iam, owner) = owner(&req, AdminAction::CreatePluginDelegationAction).await?;
let bytes = tokio::time::timeout(Duration::from_secs(10), req.input.store_all_limited(16384))
.await
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "delegation body unavailable"))?
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "delegation body unavailable"))?;
let restriction: Restrictions = serde_json::from_slice(&bytes)
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "invalid delegation restriction"))?;
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| s3::error(S3ErrorCode::InternalError, "clock unavailable"))?
.as_secs();
let record = iam
.create_plugin_delegation(&owner, restriction, now)
.await
.map_err(storage_error)?;
response(&record)
}
}
struct Get;
#[async_trait::async_trait]
impl Operation for Get {
async fn call(&self, req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let (iam, owner) = owner(&req, AdminAction::GetPluginDelegationAction).await?;
let id = params
.get("id")
.ok_or_else(|| s3::error(S3ErrorCode::InvalidRequest, "delegation id required"))?;
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| s3::error(S3ErrorCode::InternalError, "clock unavailable"))?
.as_secs();
let record = iam
.read_active_plugin_delegation(&owner, id, now)
.await
.map_err(storage_error)?;
response(&record)
}
}
struct Revoke;
#[async_trait::async_trait]
impl Operation for Revoke {
async fn call(&self, req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let (iam, owner) = owner(&req, AdminAction::RevokePluginDelegationAction).await?;
let id = params
.get("id")
.ok_or_else(|| s3::error(S3ErrorCode::InvalidRequest, "delegation id required"))?;
iam.revoke_plugin_delegation(&owner, id).await.map_err(storage_error)?;
response(&serde_json::json!({"revoked":true,"id":id}))
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SubmitInput {
version: u32,
instance_id: String,
idempotency_key: String,
object: SubmitObject,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SubmitObject {
bucket: String,
key: String,
version_id: String,
}
struct Submit;
#[async_trait::async_trait]
impl Operation for Submit {
async fn call(&self, mut req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let (iam, signer) = owner(&req, AdminAction::SubmitPluginJobAction).await?;
let id = params
.get("id")
.ok_or_else(|| s3::error(S3ErrorCode::InvalidRequest, "delegation id required"))?;
let bytes = tokio::time::timeout(Duration::from_secs(10), req.input.store_all_limited(16384))
.await
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "submit body unavailable"))?
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "submit body unavailable"))?;
let input: SubmitInput =
serde_json::from_slice(&bytes).map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "invalid submit request"))?;
if input.version != 1
|| !plugin_runner::literal(&input.instance_id)
|| !plugin_runner::valid_idempotency_key(&input.idempotency_key)
{
return Err(s3::error(S3ErrorCode::InvalidRequest, "invalid submit request"));
}
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| s3::error(S3ErrorCode::InternalError, "clock unavailable"))?
.as_secs();
let record = iam
.read_active_plugin_delegation(&signer, id, now)
.await
.map_err(storage_error)?;
let deployment = plugin_runner::configured_deployment()?;
if !plugin_runner::validate_delegation_scope(
&record,
&signer,
id,
&deployment,
ObjectReference {
bucket: &input.object.bucket,
key: &input.object.key,
version_id: &input.object.version_id,
},
now,
) {
return Err(s3::error(S3ErrorCode::AccessDenied, "submit restriction rejected"));
}
let receipt = plugin_runner::submit(&SubmitRequest {
version: input.version,
instance_id: &input.instance_id,
idempotency_key: &input.idempotency_key,
object: ObjectReference {
bucket: &input.object.bucket,
key: &input.object.key,
version_id: &input.object.version_id,
},
delegation_id: &record.id,
delegation_revision: &record.revision,
actual_signer_access_key: &signer,
})
.await?;
response(&receipt)
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct QueryRunInput {
version: u32,
run_id: uuid::Uuid,
}
struct QueryRun;
#[async_trait::async_trait]
impl Operation for QueryRun {
async fn call(&self, mut req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let (iam, signer) = owner(&req, AdminAction::GetPluginRunAction).await?;
let id = params
.get("id")
.ok_or_else(|| s3::error(S3ErrorCode::InvalidRequest, "delegation id required"))?;
let bytes = tokio::time::timeout(Duration::from_secs(10), req.input.store_all_limited(16384))
.await
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "query body unavailable"))?
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "query body unavailable"))?;
let input: QueryRunInput =
serde_json::from_slice(&bytes).map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "invalid query request"))?;
if input.version != 1 || input.run_id.is_nil() {
return Err(s3::error(S3ErrorCode::InvalidRequest, "invalid query request"));
}
let record = iam.read_owned_plugin_delegation(&signer, id).await.map_err(storage_error)?;
let result = plugin_runner::query(&plugin_runner::QueryRequest {
version: input.version,
run_id: input.run_id,
delegation_id: &record.id,
delegation_revision: &record.revision,
actual_signer_access_key: &signer,
})
.await?;
response(&result)
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HistoryRunInput {
version: u32,
run_id: uuid::Uuid,
}
fn valid_history_run_input(input: &HistoryRunInput) -> bool {
input.version == 1 && !input.run_id.is_nil()
}
struct HistoryRun;
#[async_trait::async_trait]
impl Operation for HistoryRun {
async fn call(&self, mut req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let (iam, signer) = owner(&req, AdminAction::ListPluginRunsAction).await?;
let id = params
.get("id")
.ok_or_else(|| s3::error(S3ErrorCode::InvalidRequest, "delegation id required"))?;
let bytes = tokio::time::timeout(Duration::from_secs(10), req.input.store_all_limited(16384))
.await
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "history body unavailable"))?
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "history body unavailable"))?;
let input: HistoryRunInput =
serde_json::from_slice(&bytes).map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "invalid history request"))?;
if !valid_history_run_input(&input) {
return Err(s3::error(S3ErrorCode::InvalidRequest, "invalid history request"));
}
let record = iam.read_owned_plugin_delegation(&signer, id).await.map_err(storage_error)?;
let result = plugin_runner::history(&plugin_runner::HistoryRequest {
version: input.version,
run_id: input.run_id,
delegation_id: &record.id,
delegation_revision: &record.revision,
actual_signer_access_key: &signer,
})
.await?;
response(&result)
}
}
struct CancelRun;
#[async_trait::async_trait]
impl Operation for CancelRun {
async fn call(&self, mut req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let (iam, signer) = owner(&req, AdminAction::CancelPluginRunAction).await?;
let id = params
.get("id")
.ok_or_else(|| s3::error(S3ErrorCode::InvalidRequest, "delegation id required"))?;
let bytes = tokio::time::timeout(Duration::from_secs(10), req.input.store_all_limited(16384))
.await
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "cancel body unavailable"))?
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "cancel body unavailable"))?;
let input: QueryRunInput =
serde_json::from_slice(&bytes).map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "invalid cancel request"))?;
if input.version != 1 || input.run_id.is_nil() {
return Err(s3::error(S3ErrorCode::InvalidRequest, "invalid cancel request"));
}
let record = iam.read_owned_plugin_delegation(&signer, id).await.map_err(storage_error)?;
let result = plugin_runner::cancel(&plugin_runner::CancelRequest {
version: input.version,
run_id: input.run_id,
delegation_id: &record.id,
delegation_revision: &record.revision,
actual_signer_access_key: &signer,
})
.await?;
response(&result)
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PageRunsInput {
version: u32,
limit: u32,
#[serde(default)]
cursor: Option<plugin_runner::RunPageCursor>,
}
fn valid_page_runs_input(input: &PageRunsInput) -> bool {
input.version == 1 && (1..=100).contains(&input.limit) && !input.cursor.is_some_and(|cursor| cursor.run_id.is_nil())
}
struct PageRuns;
#[async_trait::async_trait]
impl Operation for PageRuns {
async fn call(&self, mut req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let (iam, signer) = owner(&req, AdminAction::ListPluginRunsAction).await?;
let id = params
.get("id")
.ok_or_else(|| s3::error(S3ErrorCode::InvalidRequest, "delegation id required"))?;
let bytes = tokio::time::timeout(Duration::from_secs(10), req.input.store_all_limited(16384))
.await
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "page body unavailable"))?
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "page body unavailable"))?;
let input: PageRunsInput =
serde_json::from_slice(&bytes).map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "invalid page request"))?;
if !valid_page_runs_input(&input) {
return Err(s3::error(S3ErrorCode::InvalidRequest, "invalid page request"));
}
let record = iam.read_owned_plugin_delegation(&signer, id).await.map_err(storage_error)?;
let result = plugin_runner::page(&plugin_runner::PageRequest {
version: input.version,
actual_signer_access_key: &signer,
delegation_id: &record.id,
delegation_revision: &record.revision,
limit: input.limit,
cursor: input.cursor,
})
.await?;
response(&result)
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ReplayRunInput {
version: u32,
origin_run_id: uuid::Uuid,
idempotency_key: String,
deadline_unix_micros: i64,
}
fn valid_replay_run_input(input: &ReplayRunInput) -> bool {
input.version == 1
&& !input.origin_run_id.is_nil()
&& plugin_runner::valid_idempotency_key(&input.idempotency_key)
&& input.deadline_unix_micros > 0
}
struct ReplayRun;
#[async_trait::async_trait]
impl Operation for ReplayRun {
async fn call(&self, mut req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let (iam, signer) = owner(&req, AdminAction::ReplayPluginRunAction).await?;
let id = params
.get("id")
.ok_or_else(|| s3::error(S3ErrorCode::InvalidRequest, "delegation id required"))?;
let bytes = tokio::time::timeout(Duration::from_secs(10), req.input.store_all_limited(16384))
.await
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "replay body unavailable"))?
.map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "replay body unavailable"))?;
let input: ReplayRunInput =
serde_json::from_slice(&bytes).map_err(|_| s3::error(S3ErrorCode::InvalidRequest, "invalid replay request"))?;
if !valid_replay_run_input(&input) {
return Err(s3::error(S3ErrorCode::InvalidRequest, "invalid replay request"));
}
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| s3::error(S3ErrorCode::InternalError, "clock unavailable"))?
.as_secs();
let record = iam
.read_active_plugin_delegation(&signer, id, now)
.await
.map_err(storage_error)?;
let result = plugin_runner::replay(&plugin_runner::ReplayRequest {
version: input.version,
origin_run_id: input.origin_run_id,
idempotency_key: &input.idempotency_key,
deadline_unix_micros: input.deadline_unix_micros,
actual_signer_access_key: &signer,
delegation_id: &record.id,
delegation_revision: &record.revision,
})
.await?;
response(&result)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn delegation_mutations_require_authenticated_original_user() {
for operation in 0..8 {
let req = S3Request {
input: Body::from("{}".to_owned()),
method: Method::POST,
uri: http::Uri::from_static("/rustfs/admin/v3/plugin-delegations"),
headers: HeaderMap::new(),
extensions: http::Extensions::new(),
credentials: None,
region: None,
service: None,
trailing_headers: None,
};
let result = if operation == 0 {
Get.call(req, Params::new()).await
} else if operation == 1 {
Revoke.call(req, Params::new()).await
} else if operation == 2 {
Submit.call(req, Params::new()).await
} else if operation == 3 {
QueryRun.call(req, Params::new()).await
} else if operation == 4 {
HistoryRun.call(req, Params::new()).await
} else if operation == 5 {
CancelRun.call(req, Params::new()).await
} else if operation == 6 {
PageRuns.call(req, Params::new()).await
} else if operation == 7 {
ReplayRun.call(req, Params::new()).await
} else {
Create.call(req, Params::new()).await
};
let error = result.expect_err("unsigned mutations must not reach persistence");
assert_eq!(error.code(), &S3ErrorCode::AccessDenied);
}
}
#[test]
fn submit_dto_rejects_client_authority_fields_and_null_versions() {
assert!(serde_json::from_str::<SubmitInput>(
r#"{"version":1,"instance_id":"img","idempotency_key":"k","object":{"bucket":"b","key":"k","version_id":"v"},"actual_signer_access_key":"forged"}"#
)
.is_err());
let input: SubmitInput = serde_json::from_str(
r#"{"version":1,"instance_id":"img","idempotency_key":"k","object":{"bucket":"b","key":"a/x","version_id":"null"}}"#,
)
.unwrap();
let record = rustfs_iam::delegation::Delegation {
version: 1,
id: "a".repeat(32),
revision: "a".repeat(32),
owner_access_key: "owner".into(),
created_at_unix_seconds: 1,
restrictions: Restrictions {
version: None,
output_bucket: None,
deployment: "prod".into(),
bucket: "b".into(),
input_prefix: "a/".into(),
output_prefix: "out/".into(),
expires_at_unix_seconds: 100,
},
};
assert!(!plugin_runner::validate_delegation_scope(
&record,
"owner",
&record.id,
"prod",
ObjectReference {
bucket: &input.object.bucket,
key: &input.object.key,
version_id: &input.object.version_id,
},
2,
));
}
#[test]
fn query_run_dto_rejects_client_authority_fields() {
let run_id = uuid::Uuid::from_u128(1);
let input: QueryRunInput =
serde_json::from_str(&format!(r#"{{"version":1,"run_id":"{run_id}"}}"#)).expect("valid run query");
assert_eq!(input.run_id, run_id);
assert!(
serde_json::from_str::<QueryRunInput>(&format!(
r#"{{"version":1,"run_id":"{run_id}","actual_signer_access_key":"forged"}}"#
))
.is_err()
);
}
#[test]
fn history_run_dto_is_strict_and_rejects_nil_run() {
let run_id = uuid::Uuid::from_u128(1);
let input: HistoryRunInput =
serde_json::from_str(&format!(r#"{{"version":1,"run_id":"{run_id}"}}"#)).expect("valid history request");
assert!(valid_history_run_input(&input));
for raw in [
r#"{"version":1,"run_id":"00000000-0000-0000-0000-000000000000"}"#,
r#"{"version":2,"run_id":"00000000-0000-0000-0000-000000000001"}"#,
r#"{"version":1,"run_id":"00000000-0000-0000-0000-000000000001","actual_signer_access_key":"forged"}"#,
] {
let rejected = match serde_json::from_str::<HistoryRunInput>(raw) {
Ok(input) => !valid_history_run_input(&input),
Err(_) => true,
};
assert!(rejected, "accepted invalid history request: {raw}");
}
}
#[test]
fn page_runs_dto_is_strict_and_bounded() {
let cursor = plugin_runner::RunPageCursor {
created_at_unix_micros: 10,
run_id: uuid::Uuid::from_u128(1),
};
let input: PageRunsInput = serde_json::from_str(
r#"{"version":1,"limit":100,"cursor":{"created_at_unix_micros":10,"run_id":"00000000-0000-0000-0000-000000000001"}}"#,
)
.expect("valid page request");
assert_eq!(input.cursor, Some(cursor));
for raw in [
r#"{"version":1,"limit":0}"#,
r#"{"version":1,"limit":101}"#,
r#"{"version":1,"limit":1,"unknown":true}"#,
r#"{"version":1,"limit":1,"actual_signer_access_key":"forged"}"#,
r#"{"version":1,"limit":1,"cursor":{"created_at_unix_micros":10,"run_id":"00000000-0000-0000-0000-000000000000"}}"#,
] {
let rejected = match serde_json::from_str::<PageRunsInput>(raw) {
Ok(input) => !valid_page_runs_input(&input),
Err(_) => true,
};
assert!(rejected, "accepted invalid page request: {raw}");
}
}
#[test]
fn replay_run_dto_is_strict_and_bounded() {
let run_id = uuid::Uuid::from_u128(1);
let input: ReplayRunInput = serde_json::from_str(&format!(
r#"{{"version":1,"origin_run_id":"{run_id}","idempotency_key":"retry-1","deadline_unix_micros":123}}"#
))
.expect("valid replay request");
assert!(valid_replay_run_input(&input));
for raw in [
r#"{"version":1,"origin_run_id":"00000000-0000-0000-0000-000000000000","idempotency_key":"k","deadline_unix_micros":123}"#.to_string(),
format!(r#"{{"version":1,"origin_run_id":"{run_id}","idempotency_key":"","deadline_unix_micros":123}}"#),
format!(r#"{{"version":1,"origin_run_id":"{run_id}","idempotency_key":"k","deadline_unix_micros":0}}"#),
format!(
r#"{{"version":1,"origin_run_id":"{run_id}","idempotency_key":"k","deadline_unix_micros":123,"actual_signer_access_key":"forged"}}"#
),
format!(
r#"{{"version":1,"origin_run_id":"{run_id}","idempotency_key":"{}","deadline_unix_micros":123}}"#,
"x".repeat(1025)
),
] {
let rejected = match serde_json::from_str::<ReplayRunInput>(&raw) {
Ok(input) => !valid_replay_run_input(&input),
Err(_) => true,
};
assert!(rejected, "accepted invalid replay request: {raw}");
}
}
}
-3
View File
@@ -17,7 +17,6 @@ mod auth;
pub mod console;
pub mod handlers;
mod plugin_contract;
pub(crate) mod plugin_runner;
pub(crate) mod replication_metrics_wire;
// Contract inventory is validated by tests before later runtime integration.
pub(crate) mod route_policy;
@@ -65,8 +64,6 @@ pub fn make_admin_route(
fn register_admin_routes(r: &mut S3Router<AdminOperation>) -> std::io::Result<()> {
health::register_health_route(r)?;
sts::register_admin_auth_route(r)?;
handlers::plugin_delegation::register_plugin_delegation_route(r)?;
handlers::plugin_attempt::register_plugin_attempt_route(r)?;
account::register_account_route(r)?;
mfa::register_mfa_route(r)?;
File diff suppressed because it is too large Load Diff
-135
View File
@@ -25,15 +25,6 @@ const TLS_CERTIFICATE_PUBLISH: AdminActionRef = AdminActionRef::new("TLSCertific
const TLS_CERTIFICATE_STATUS: AdminActionRef = AdminActionRef::new("TLSCertificateStatusAdminAction");
const CONSOLE_LOG: AdminActionRef = AdminActionRef::new("ConsoleLogAdminAction");
const COMMIT_TABLE: AdminActionRef = AdminActionRef::new("CommitTableAction");
const ISSUE_PLUGIN_ATTEMPT: AdminActionRef = AdminActionRef::new("IssuePluginAttemptAction");
const SUBMIT_PLUGIN_JOB: AdminActionRef = AdminActionRef::new("SubmitPluginJobAction");
const GET_PLUGIN_RUN: AdminActionRef = AdminActionRef::new("GetPluginRunAction");
const CANCEL_PLUGIN_RUN: AdminActionRef = AdminActionRef::new("CancelPluginRunAction");
const LIST_PLUGIN_RUNS: AdminActionRef = AdminActionRef::new("ListPluginRunsAction");
const REPLAY_PLUGIN_RUN: AdminActionRef = AdminActionRef::new("ReplayPluginRunAction");
const GET_PLUGIN_DELEGATION: AdminActionRef = AdminActionRef::new("GetPluginDelegationAction");
const CREATE_PLUGIN_DELEGATION: AdminActionRef = AdminActionRef::new("CreatePluginDelegationAction");
const REVOKE_PLUGIN_DELEGATION: AdminActionRef = AdminActionRef::new("RevokePluginDelegationAction");
const CREATE_POLICY: AdminActionRef = AdminActionRef::new("CreatePolicyAdminAction");
const CREATE_USER: AdminActionRef = AdminActionRef::new("CreateUserAdminAction");
const CREATE_SERVICE_ACCOUNT: AdminActionRef = AdminActionRef::new("CreateServiceAccountAdminAction");
@@ -665,66 +656,6 @@ pub const ADMIN_ROUTE_POLICY_SPECS: &[AdminRouteSpec] = &[
SERVER_INFO,
RouteRiskLevel::Sensitive,
),
admin(
HttpMethod::Post,
"/rustfs/admin/v3/plugin-delegations/{id}/issue-attempt",
ISSUE_PLUGIN_ATTEMPT,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/rustfs/admin/v3/plugin-delegations/{id}/submit",
SUBMIT_PLUGIN_JOB,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/rustfs/admin/v3/plugin-delegations/{id}/runs/query",
GET_PLUGIN_RUN,
RouteRiskLevel::Sensitive,
),
admin(
HttpMethod::Post,
"/rustfs/admin/v3/plugin-delegations/{id}/runs/history",
LIST_PLUGIN_RUNS,
RouteRiskLevel::Sensitive,
),
admin(
HttpMethod::Post,
"/rustfs/admin/v3/plugin-delegations/{id}/runs/cancel",
CANCEL_PLUGIN_RUN,
RouteRiskLevel::Sensitive,
),
admin(
HttpMethod::Post,
"/rustfs/admin/v3/plugin-delegations/{id}/runs/page",
LIST_PLUGIN_RUNS,
RouteRiskLevel::Sensitive,
),
admin(
HttpMethod::Post,
"/rustfs/admin/v3/plugin-delegations/{id}/runs/replay",
REPLAY_PLUGIN_RUN,
RouteRiskLevel::Sensitive,
),
admin(
HttpMethod::Get,
"/rustfs/admin/v3/plugin-delegations/{id}",
GET_PLUGIN_DELEGATION,
RouteRiskLevel::Sensitive,
),
admin(
HttpMethod::Post,
"/rustfs/admin/v3/plugin-delegations",
CREATE_PLUGIN_DELEGATION,
RouteRiskLevel::High,
),
admin(
HttpMethod::Post,
"/rustfs/admin/v3/plugin-delegations/{id}/revoke",
REVOKE_PLUGIN_DELEGATION,
RouteRiskLevel::High,
),
admin(
HttpMethod::Get,
"/rustfs/admin/v4/plugins/catalog",
@@ -2002,72 +1933,6 @@ mod tests {
assert!(validate_admin_route_policy_specs().is_ok());
}
#[test]
fn plugin_submit_route_is_registered_as_high_risk_authenticated_action() {
let path = "/rustfs/admin/v3/plugin-delegations/{id}/submit";
assert_action(HttpMethod::Post, path, SUBMIT_PLUGIN_JOB);
let spec = ADMIN_ROUTE_POLICY_SPECS
.iter()
.find(|spec| spec.method() == HttpMethod::Post && spec.path() == path)
.expect("submit route policy");
assert_eq!(spec.risk_level(), RouteRiskLevel::High);
}
#[test]
fn plugin_run_query_route_uses_dedicated_authenticated_action() {
let path = "/rustfs/admin/v3/plugin-delegations/{id}/runs/query";
assert_action(HttpMethod::Post, path, GET_PLUGIN_RUN);
let spec = ADMIN_ROUTE_POLICY_SPECS
.iter()
.find(|spec| spec.method() == HttpMethod::Post && spec.path() == path)
.expect("plugin run query route policy");
assert_eq!(spec.risk_level(), RouteRiskLevel::Sensitive);
}
#[test]
fn plugin_run_history_route_uses_list_action() {
let path = "/rustfs/admin/v3/plugin-delegations/{id}/runs/history";
assert_action(HttpMethod::Post, path, LIST_PLUGIN_RUNS);
let spec = ADMIN_ROUTE_POLICY_SPECS
.iter()
.find(|spec| spec.method() == HttpMethod::Post && spec.path() == path)
.expect("plugin run history route policy");
assert_eq!(spec.risk_level(), RouteRiskLevel::Sensitive);
}
#[test]
fn plugin_run_cancel_route_uses_dedicated_authenticated_action() {
let path = "/rustfs/admin/v3/plugin-delegations/{id}/runs/cancel";
assert_action(HttpMethod::Post, path, CANCEL_PLUGIN_RUN);
let spec = ADMIN_ROUTE_POLICY_SPECS
.iter()
.find(|spec| spec.method() == HttpMethod::Post && spec.path() == path)
.expect("plugin run cancel route policy");
assert_eq!(spec.risk_level(), RouteRiskLevel::Sensitive);
}
#[test]
fn plugin_run_page_route_uses_dedicated_authenticated_action() {
let path = "/rustfs/admin/v3/plugin-delegations/{id}/runs/page";
assert_action(HttpMethod::Post, path, LIST_PLUGIN_RUNS);
let spec = ADMIN_ROUTE_POLICY_SPECS
.iter()
.find(|spec| spec.method() == HttpMethod::Post && spec.path() == path)
.expect("plugin run page route policy");
assert_eq!(spec.risk_level(), RouteRiskLevel::Sensitive);
}
#[test]
fn plugin_run_replay_route_uses_dedicated_authenticated_action() {
let path = "/rustfs/admin/v3/plugin-delegations/{id}/runs/replay";
assert_action(HttpMethod::Post, path, REPLAY_PLUGIN_RUN);
let spec = ADMIN_ROUTE_POLICY_SPECS
.iter()
.find(|spec| spec.method() == HttpMethod::Post && spec.path() == path)
.expect("plugin run replay route policy");
assert_eq!(spec.risk_level(), RouteRiskLevel::Sensitive);
}
#[test]
fn route_policy_inventory_has_no_internal_overlap() {
let mut seen = BTreeSet::new();
@@ -116,48 +116,6 @@ fn registered_admin_router() -> S3Router<AdminOperation> {
fn expected_admin_route_matrix() -> Vec<RouteMatrixEntry> {
vec![
admin_route(Method::POST, "/v3/plugin-delegations"),
admin_route_sample(Method::GET, "/v3/plugin-delegations/{id}", "/v3/plugin-delegations/test-delegation"),
admin_route_sample(
Method::POST,
"/v3/plugin-delegations/{id}/revoke",
"/v3/plugin-delegations/test-delegation/revoke",
),
admin_route_sample(
Method::POST,
"/v3/plugin-delegations/{id}/submit",
"/v3/plugin-delegations/test-delegation/submit",
),
admin_route_sample(
Method::POST,
"/v3/plugin-delegations/{id}/runs/query",
"/v3/plugin-delegations/test-delegation/runs/query",
),
admin_route_sample(
Method::POST,
"/v3/plugin-delegations/{id}/runs/history",
"/v3/plugin-delegations/test-delegation/runs/history",
),
admin_route_sample(
Method::POST,
"/v3/plugin-delegations/{id}/runs/cancel",
"/v3/plugin-delegations/test-delegation/runs/cancel",
),
admin_route_sample(
Method::POST,
"/v3/plugin-delegations/{id}/runs/page",
"/v3/plugin-delegations/test-delegation/runs/page",
),
admin_route_sample(
Method::POST,
"/v3/plugin-delegations/{id}/runs/replay",
"/v3/plugin-delegations/test-delegation/runs/replay",
),
admin_route_sample(
Method::POST,
"/v3/plugin-delegations/{id}/issue-attempt",
"/v3/plugin-delegations/test-delegation/issue-attempt",
),
route(Method::GET, HEALTH_PREFIX),
route(Method::HEAD, HEALTH_PREFIX),
route(Method::GET, HEALTH_READY_PATH),
+19 -24
View File
@@ -73,15 +73,14 @@ use super::trailer_adapter::trailer_source;
use crate::app::object::{
ConcurrencyManager, ForegroundWriteAdmission, get_concurrency_manager, guard_put_object_body_read_timeout,
put_object_body_read_timeout, reject_non_wildcard_write_if_none_match, reject_oversize_single_upload,
reject_veeam_sosapi_mutation,
};
use crate::app::object_data_cache::{
ObjectDataCacheAdapter, invalidate_object_data_cache_after_complete_multipart_success,
invalidate_object_data_cache_before_mutation,
};
use crate::app::object_usecase::{
apply_quota_admission, build_put_like_object_lock_metadata, map_quota_check_outcome, s3s_body_error_to_io,
validate_existing_object_lock_for_write,
acquire_copy_bucket_lifecycle_locks, apply_quota_admission, build_put_like_object_lock_metadata, map_quota_check_outcome,
s3s_body_error_to_io, validate_existing_object_lock_for_write,
};
use crate::app::runtime_sources::{
AppContext, current_app_context, current_object_data_cache_for_context, current_object_store_handle_for_context,
@@ -543,8 +542,6 @@ impl DefaultMultipartUsecase {
bucket, key, upload_id, ..
} = req.input;
reject_veeam_sosapi_mutation(|| self.object_store(), &bucket, &key).await?;
let Some(store) = self.object_store() else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init".to_string()));
};
@@ -613,7 +610,6 @@ impl DefaultMultipartUsecase {
..
} = input;
reject_veeam_sosapi_mutation(|| self.object_store(), &bucket, &key).await?;
reject_non_wildcard_write_if_none_match(if_none_match.as_ref(), &req.headers)?;
validate_table_catalog_object_mutation(&bucket, &key).await?;
@@ -1024,7 +1020,6 @@ impl DefaultMultipartUsecase {
return Err(s3_error!(InvalidStorageClass));
}
reject_veeam_sosapi_mutation(|| self.object_store(), &bucket, &key).await?;
validate_table_catalog_object_mutation(&bucket, &key).await?;
let Some(store) = self.object_store() else {
@@ -1248,7 +1243,6 @@ impl DefaultMultipartUsecase {
let part_id = parse_upload_part_number(part_number)?;
reject_veeam_sosapi_mutation(|| self.object_store(), &bucket, &key).await?;
validate_table_catalog_object_mutation(&bucket, &key).await?;
let size = resolve_upload_part_size(content_length, body.as_ref())?;
@@ -1647,7 +1641,6 @@ impl DefaultMultipartUsecase {
..
} = req.input;
reject_veeam_sosapi_mutation(|| self.object_store(), &bucket, &key).await?;
let params = parse_list_parts_params(part_number_marker, max_parts)?;
let Some(store) = self.object_store() else {
@@ -1709,7 +1702,6 @@ impl DefaultMultipartUsecase {
..
} = req.input;
reject_veeam_sosapi_mutation(|| self.object_store(), &bucket, &key).await?;
let (src_bucket, src_key, raw_src_version_id) = match copy_source {
CopySource::AccessPoint { .. } => return Err(s3_error!(NotImplemented)),
CopySource::Outpost { .. } => return Err(s3_error!(NotImplemented)),
@@ -1735,20 +1727,23 @@ impl DefaultMultipartUsecase {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init".to_string()));
};
let (
source_bucket_lifecycle_guard,
current_source_incarnation_id,
destination_bucket_lifecycle_guard_storage,
current_destination_incarnation_id,
) = store
.acquire_copy_bucket_incarnation_fences(
&src_bucket,
expected_source_incarnation_id,
&bucket,
expected_destination_incarnation_id,
)
let (source_bucket_lifecycle_guard, destination_bucket_lifecycle_guard_storage) =
acquire_copy_bucket_lifecycle_locks(store.as_ref(), &src_bucket, &bucket).await?;
let current_source_incarnation_id = store
.bucket_incarnation_id_from_disk(&src_bucket)
.await
.map_err(ApiError::from)?;
if expected_source_incarnation_id.is_some_and(|expected| expected != current_source_incarnation_id) {
return Err(ApiError::from(StorageError::BucketNotFound(src_bucket.clone())).into());
}
let current_destination_incarnation_id = if src_bucket == bucket {
current_source_incarnation_id
} else {
store.bucket_incarnation_id_from_disk(&bucket).await.map_err(ApiError::from)?
};
if expected_destination_incarnation_id.is_some_and(|expected| expected != current_destination_incarnation_id) {
return Err(ApiError::from(StorageError::BucketNotFound(bucket.clone())).into());
}
let destination_bucket_lifecycle_guard = destination_bucket_lifecycle_guard_storage
.as_ref()
.unwrap_or(&source_bucket_lifecycle_guard);
@@ -1767,9 +1762,9 @@ impl DefaultMultipartUsecase {
..Default::default()
};
if src_bucket != bucket {
source_bucket_lifecycle_guard.attach_to_object_options(&mut dst_opts);
dst_opts.add_bucket_lifecycle_lock_guard(&source_bucket_lifecycle_guard);
}
destination_bucket_lifecycle_guard.attach_to_object_options(&mut dst_opts);
dst_opts.add_bucket_lifecycle_lock_guard(destination_bucket_lifecycle_guard);
let mp_info = store
.get_multipart_info(&bucket, &key, &upload_id, &dst_opts)
+65 -35
View File
@@ -124,6 +124,48 @@ where
.map_err(|err| ApiError::from(copy_namespace_lock_error(bucket, &object, "write", err)).into())
}
pub(crate) async fn acquire_copy_bucket_lifecycle_lock<S>(store: &S, bucket: &str) -> S3Result<NamespaceLockGuard>
where
S: NamespaceLocking<Error = EcstoreError, NamespaceLock = rustfs_lock::NamespaceLockWrapper> + ?Sized,
{
let lock = store
.new_ns_lock(bucket, BUCKET_LIFECYCLE_LOCK_OBJECT)
.await
.map_err(ApiError::from)?;
lock.get_read_lock(get_lock_acquire_timeout()).await.map_err(|err| {
ApiError::from(copy_namespace_lock_error(
bucket,
BUCKET_LIFECYCLE_LOCK_OBJECT,
"bucket_lifecycle_read",
err,
))
.into()
})
}
pub(crate) async fn acquire_copy_bucket_lifecycle_locks<S>(
store: &S,
source_bucket: &str,
destination_bucket: &str,
) -> S3Result<(NamespaceLockGuard, Option<NamespaceLockGuard>)>
where
S: NamespaceLocking<Error = EcstoreError, NamespaceLock = rustfs_lock::NamespaceLockWrapper> + ?Sized,
{
if source_bucket == destination_bucket {
return Ok((acquire_copy_bucket_lifecycle_lock(store, source_bucket).await?, None));
}
if source_bucket < destination_bucket {
let source_guard = acquire_copy_bucket_lifecycle_lock(store, source_bucket).await?;
let destination_guard = acquire_copy_bucket_lifecycle_lock(store, destination_bucket).await?;
Ok((source_guard, Some(destination_guard)))
} else {
let destination_guard = acquire_copy_bucket_lifecycle_lock(store, destination_bucket).await?;
let source_guard = acquire_copy_bucket_lifecycle_lock(store, source_bucket).await?;
Ok((source_guard, Some(destination_guard)))
}
}
impl DefaultObjectUsecase {
pub fn execute_copy_object(
&self,
@@ -239,7 +281,6 @@ impl DefaultObjectUsecase {
// Validate both source and destination keys
validate_object_key(&src_key, "COPY (source)")?;
validate_object_key(&key, "COPY (dest)")?;
reject_veeam_sosapi_mutation(|| self.object_store(), &bucket, &key).await?;
validate_table_catalog_object_mutation(&bucket, &key).await?;
let replaces_metadata = match metadata_directive.as_ref().map(|directive| directive.as_str()) {
None | Some(MetadataDirective::COPY) => false,
@@ -342,20 +383,29 @@ impl DefaultObjectUsecase {
let Some(store) = self.object_store() else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init".to_string()));
};
let (
source_bucket_lifecycle_guard,
current_source_incarnation_id,
destination_bucket_lifecycle_guard_storage,
current_destination_incarnation_id,
) = store
.acquire_copy_bucket_incarnation_fences(
&src_bucket,
src_get_opts.expected_bucket_incarnation_id,
&bucket,
dst_opts.expected_bucket_incarnation_id,
)
let (source_bucket_lifecycle_guard, destination_bucket_lifecycle_guard_storage) =
acquire_copy_bucket_lifecycle_locks(store.as_ref(), &src_bucket, &bucket).await?;
let current_source_incarnation_id = store
.bucket_incarnation_id_from_disk(&src_bucket)
.await
.map_err(ApiError::from)?;
if src_get_opts
.expected_bucket_incarnation_id
.is_some_and(|expected| expected != current_source_incarnation_id)
{
return Err(ApiError::from(StorageError::BucketNotFound(src_bucket.clone())).into());
}
let current_destination_incarnation_id = if src_bucket == bucket {
current_source_incarnation_id
} else {
store.bucket_incarnation_id_from_disk(&bucket).await.map_err(ApiError::from)?
};
if dst_opts
.expected_bucket_incarnation_id
.is_some_and(|expected| expected != current_destination_incarnation_id)
{
return Err(ApiError::from(StorageError::BucketNotFound(bucket.clone())).into());
}
let destination_bucket_lifecycle_guard = destination_bucket_lifecycle_guard_storage
.as_ref()
.unwrap_or(&source_bucket_lifecycle_guard);
@@ -372,9 +422,9 @@ impl DefaultObjectUsecase {
src_get_opts.expected_bucket_incarnation_id = Some(current_source_incarnation_id);
dst_opts.expected_bucket_incarnation_id = Some(current_destination_incarnation_id);
if src_bucket != bucket {
source_bucket_lifecycle_guard.attach_to_object_options(&mut dst_opts);
dst_opts.add_bucket_lifecycle_lock_guard(&source_bucket_lifecycle_guard);
}
destination_bucket_lifecycle_guard.attach_to_object_options(&mut dst_opts);
dst_opts.add_bucket_lifecycle_lock_guard(destination_bucket_lifecycle_guard);
// Bucket metadata uses the bucket name as its namespace-lock key. Load
// every copy-time bucket snapshot before a same-object key can collide
@@ -1031,26 +1081,6 @@ mod tests {
assert_eq!(err.code(), &S3ErrorCode::InvalidRequest);
}
#[tokio::test]
async fn copy_object_rejects_reserved_catalog_destination_before_store_lookup() {
let input = CopyObjectInput::builder()
.copy_source(CopySource::Bucket {
bucket: "source-bucket".into(),
key: "source-key".into(),
version_id: None,
})
.bucket(format!("missing-{}", Uuid::new_v4()))
.key(".rustfs-table/metadata/current.json".to_string())
.build()
.unwrap();
let error = DefaultObjectUsecase::without_context()
.execute_copy_object(build_request(input, Method::PUT))
.await
.expect_err("reserved catalog destination must fail closed without bucket metadata");
assert_eq!(error.code(), &S3ErrorCode::InvalidRequest);
assert_eq!(error.message(), Some(crate::table_catalog::RESERVED_CATALOG_OBJECT_MESSAGE));
}
#[tokio::test]
async fn execute_copy_object_rejects_invalid_storage_class() {
let input = CopyObjectInput::builder()
-1
View File
@@ -1038,7 +1038,6 @@ impl DefaultObjectUsecase {
// Validate object key
validate_object_key(&key, "DELETE")?;
reject_veeam_sosapi_mutation(|| self.object_store(), &bucket, &key).await?;
let replica = req
.headers
-1
View File
@@ -2461,7 +2461,6 @@ impl DefaultObjectUsecase {
}
let table_data_plane_publication_guards = retained_table_data_plane_publication_guards(&auth_req);
drop(auth_req);
extract_try!(reject_veeam_sosapi_mutation(|| Some(Arc::clone(&commit_context.store)), &bucket, &fpath).await);
if archive_entry_mod_time.is_some() {
opts.mod_time = archive_entry_mod_time;
}
-52
View File
@@ -14,7 +14,6 @@
//! GetObject / GetObjectAttributes read path: cold fill, resume, stream tuning.
use super::veeam_sosapi;
use super::*;
use crate::app::storage_api::object_usecase::object_cache::{
GetObjectReadCondition, GetObjectReadMetadata, evaluate_read_preconditions, has_read_preconditions,
@@ -4146,37 +4145,6 @@ impl DefaultObjectUsecase {
result
}
async fn serve_veeam_sosapi_get(
&self,
req: &S3Request<GetObjectInput>,
store: &Arc<ECStore>,
kind: veeam_sosapi::SosapiKind,
part_number: Option<usize>,
range: Option<&HTTPRangeSpec>,
) -> S3Result<S3Response<GetObjectOutput>> {
let representation =
veeam_sosapi::read_representation(store, &req.input.bucket, kind, &req.headers, part_number, range).await?;
let content_type = ContentType::from_str(veeam_sosapi::CONTENT_TYPE)
.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, "invalid SOSAPI content type"))?;
let ranged = representation.content_range.is_some();
let output = GetObjectOutput {
body: Some(StreamingBlob::from(s3s::Body::from(representation.body))),
content_length: Some(representation.content_length),
content_type: Some(content_type),
content_range: representation.content_range,
e_tag: Some(to_s3s_etag(&representation.etag_hex)),
last_modified: Some(Timestamp::from(representation.last_modified)),
accept_ranges: Some(ACCEPT_RANGES_BYTES.to_string()),
..Default::default()
};
let mut response = wrap_response_with_cors(&req.input.bucket, &req.method, &req.headers, output).await;
inject_accept_ranges_header(&mut response.headers);
if ranged {
response.status = Some(StatusCode::PARTIAL_CONTENT);
}
Ok(response)
}
async fn execute_get_object_inner(&self, mut req: S3Request<GetObjectInput>) -> S3Result<S3Response<GetObjectOutput>> {
let helper = OperationHelper::new(&req, EventName::ObjectAccessedGet, S3Operation::GetObject).suppress_event();
@@ -4255,26 +4223,6 @@ impl DefaultObjectUsecase {
}
record_get_object_s3_handler_stage_duration(GET_OBJECT_STAGE_BUCKET_VALIDATION, bucket_validation_start);
if validated.version_id.is_none()
&& let Some(kind) = veeam_sosapi::handled_kind(&validated.key)
{
let served = self
.serve_veeam_sosapi_get(&req, &store, kind, validated.part_number, validated.rs.as_ref())
.await;
match served {
Ok(response) => {
lifecycle.finish_ok();
let result = Ok(response);
let _ = helper.complete(&result);
return result;
}
Err(err) => {
lifecycle.finish_err();
return Self::complete_get_object_error(helper, err);
}
}
}
let request_context_start = stage_metrics_enabled.then(std::time::Instant::now);
let request_context = match Self::prepare_get_object_request_context(validated, &req.headers).await {
Ok(request_context) => request_context,
-46
View File
@@ -14,7 +14,6 @@
//! HeadObject path.
use super::veeam_sosapi;
use super::*;
use crate::on_demand_migration::{
BucketOdmState, HeadPolicy, OdmLookup, OdmOp, OdmOutcome, OnDemandMigrationSys, SourceClient, SourceError, SourceHead,
@@ -299,40 +298,6 @@ impl DefaultObjectUsecase {
}
}
async fn serve_veeam_sosapi_head(
&self,
req: &S3Request<HeadObjectInput>,
store: &Arc<ECStore>,
kind: veeam_sosapi::SosapiKind,
part_number: Option<usize>,
range: Option<&HTTPRangeSpec>,
) -> S3Result<S3Response<HeadObjectOutput>> {
let representation =
veeam_sosapi::read_representation(store, &req.input.bucket, kind, &req.headers, part_number, range).await?;
let content_type = ContentType::from_str(veeam_sosapi::CONTENT_TYPE)
.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, "invalid SOSAPI content type"))?;
let content_range = representation.content_range;
let output = HeadObjectOutput {
content_length: Some(representation.content_length),
content_type: Some(content_type),
accept_ranges: Some(ACCEPT_RANGES_BYTES.to_string()),
last_modified: Some(Timestamp::from(representation.last_modified)),
e_tag: Some(to_s3s_etag(&representation.etag_hex)),
..Default::default()
};
let mut response = wrap_response_with_cors(&req.input.bucket, &req.method, &req.headers, output).await;
inject_accept_ranges_header(&mut response.headers);
if let Some(content_range) = content_range {
response.headers.insert(
http::header::CONTENT_RANGE,
HeaderValue::from_str(&content_range)
.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, "invalid content range"))?,
);
response.status = Some(StatusCode::PARTIAL_CONTENT);
}
Ok(response)
}
#[instrument(level = "debug", skip(self, req))]
pub async fn execute_head_object(&self, mut req: S3Request<HeadObjectInput>) -> S3Result<S3Response<HeadObjectOutput>> {
if let Some(context) = &self.context {
@@ -371,17 +336,6 @@ impl DefaultObjectUsecase {
};
validate_bucket_exists(&store, &bucket).await?;
if version_id.is_none()
&& let Some(kind) = veeam_sosapi::handled_kind(&key)
{
let response = self
.serve_veeam_sosapi_head(&req, &store, kind, part_number, rs.as_ref())
.await?;
let result = Ok(response);
let _ = helper.complete(&result);
return result;
}
let opts: ObjectOptions = get_opts(&bucket, &key, version_id, part_number, &req.headers)
.await
.map_err(ApiError::from)?;
+5 -3
View File
@@ -134,6 +134,7 @@ use rustfs_config::MI_B;
use rustfs_filemeta::{NULL_VERSION_ID, RestoreStatusOps, parse_restore_obj_status};
use rustfs_io_core::{BytesPool, PooledBuffer};
use rustfs_io_metrics;
use rustfs_lock::NamespaceLockGuard;
use rustfs_notify::EventArgsBuilder;
use rustfs_object_capacity::capacity_manager::get_capacity_manager;
use rustfs_policy::policy::action::{Action, S3Action};
@@ -219,8 +220,8 @@ mod restore;
pub(crate) mod shared;
#[cfg(test)]
mod test_support;
mod veeam_sosapi;
pub(crate) use self::copy::*;
#[cfg(test)]
pub(crate) use self::delete::*;
pub(crate) use self::extract::*;
@@ -263,8 +264,9 @@ use tracing::{debug, error, instrument, warn};
use uuid::Uuid;
use super::storage_api::object_usecase::{
GetObjectReader, StorageDeletedObject, StorageObjectInfo as ObjectInfo, StorageObjectLockDeleteOptions,
StorageObjectOptions as ObjectOptions, StorageObjectToDelete as ObjectToDelete, StoragePutObjReader as PutObjReader,
BUCKET_LIFECYCLE_LOCK_OBJECT, GetObjectReader, StorageDeletedObject, StorageObjectInfo as ObjectInfo,
StorageObjectLockDeleteOptions, StorageObjectOptions as ObjectOptions, StorageObjectToDelete as ObjectToDelete,
StoragePutObjReader as PutObjReader,
};
use crate::app::object_data_cache::{
ColdFillCoordinateOutcome, ColdFillDiskPermitOwner, ColdFillError, ColdFillProducer, GetObjectBodyCacheLookup,
-3
View File
@@ -1272,7 +1272,6 @@ impl DefaultObjectUsecase {
format!("{RUSTFS_MAX_CONTENT_LENGTH_QUERY} is not supported for archive extraction"),
));
}
reject_veeam_sosapi_mutation(|| self.object_store(), req.input.bucket.as_str(), req.input.key.as_str()).await?;
if is_put_object_extract_requested(&req.headers) && !inbound_replication_put {
return Box::pin(self.execute_put_object_extract(req)).await;
}
@@ -1506,8 +1505,6 @@ impl DefaultObjectUsecase {
sse_customer_key_md5,
} = sse;
reject_veeam_sosapi_mutation(|| self.object_store(), bucket.as_str(), key.as_str()).await?;
// The app check preserves the existing S3 error contract; the storage
// commit path reserves the exact net logical growth under its locks.
let quota_stage_start = put_stage_metrics_enabled.then(Instant::now);
+13 -16
View File
@@ -164,7 +164,6 @@ impl DefaultObjectUsecase {
..
} = req.input.clone();
reject_veeam_sosapi_mutation(|| self.object_store(), &bucket, &object).await?;
validate_table_catalog_object_mutation(&bucket, &object).await?;
// Typed S3 errors on every RestoreObject failure (backlog#2205): a
@@ -214,8 +213,8 @@ impl DefaultObjectUsecase {
// `apply_bucket_generation_guard` deliberately tolerates a missing guard
// (only the S3 access layer installs one), so this must not hard-require
// it. Resolve the current generation instead, exactly as the copy path
// does. The fence is unaffected: the value is validated under the
// lifecycle fence below, before the restore is admitted.
// does. The fence is unaffected: the value is re-read from disk and
// compared below, before the restore is admitted.
let restore_bucket_incarnation_id = match opts.expected_bucket_incarnation_id {
Some(incarnation_id) => incarnation_id,
None => {
@@ -247,12 +246,10 @@ impl DefaultObjectUsecase {
// in-flight commit on the same object) is transient — answer 503
// SlowDown so SDK clients back off and retry instead of treating it
// as a hard failure.
let mut restore_bucket_lifecycle_guard = Some(
store
.acquire_bucket_incarnation_fence(&bucket, restore_bucket_incarnation_id)
.await
.map_err(ApiError::from)?,
);
let mut restore_bucket_lifecycle_guard = Some(acquire_copy_bucket_lifecycle_lock(store.as_ref(), &bucket).await?);
if store.bucket_incarnation_id_from_disk(&bucket).await.map_err(ApiError::from)? != restore_bucket_incarnation_id {
return Err(ApiError::from(StorageError::BucketNotFound(bucket.clone())).into());
}
let mut accept_guard = {
let guard = store
.acquire_restore_accept_guard(&bucket, &object)
@@ -302,12 +299,12 @@ impl DefaultObjectUsecase {
S3Error::with_message(S3ErrorCode::RestoreAlreadyInProgress, "Object restore is already in progress.")
})?;
restore_bucket_lifecycle_guard = Some(
store
.acquire_bucket_incarnation_fence(&bucket, restore_bucket_incarnation_id)
.await
.map_err(ApiError::from)?,
);
restore_bucket_lifecycle_guard = Some(acquire_copy_bucket_lifecycle_lock(store.as_ref(), &bucket).await?);
if store.bucket_incarnation_id_from_disk(&bucket).await.map_err(ApiError::from)?
!= restore_bucket_incarnation_id
{
return Err(ApiError::from(StorageError::BucketNotFound(bucket.clone())).into());
}
accept_guard = Some(
store
.acquire_restore_accept_guard(&bucket, &object)
@@ -401,7 +398,7 @@ impl DefaultObjectUsecase {
..Default::default()
};
if let Some(guard) = restore_bucket_lifecycle_guard.as_ref() {
guard.attach_to_object_options(&mut restore_dst_opts);
restore_dst_opts.add_bucket_lifecycle_lock_guard(guard);
}
if let Some(guard) = accept_guard.as_ref() {
guard.add_namespace_lock_fence(&mut restore_dst_opts);
-23
View File
@@ -562,29 +562,6 @@ pub(super) fn inject_accept_ranges_header(headers: &mut HeaderMap) {
headers.insert(http::header::ACCEPT_RANGES, HeaderValue::from_static(ACCEPT_RANGES_BYTES));
}
/// Reject a mutation of a Veeam SOSAPI key while the feature is enabled.
///
/// The store closure runs only after the key matches, so ordinary object
/// writes pay two string compares. Bucket existence is checked first so a
/// missing bucket stays `NoSuchBucket`.
pub(crate) async fn reject_veeam_sosapi_mutation(
store: impl FnOnce() -> Option<Arc<ECStore>>,
bucket: &str,
key: &str,
) -> S3Result<()> {
if !super::veeam_sosapi::mutation_blocked(key) {
return Ok(());
}
let Some(store) = store() else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init".to_string()));
};
validate_bucket_exists(&store, bucket).await?;
Err(S3Error::with_message(
S3ErrorCode::MethodNotAllowed,
"Veeam SOSAPI system objects are read-only",
))
}
/// Derive the response-header echo pairs for an additional-checksum algorithm
/// (XXHash3/64/128, SHA-512) from the server-computed content checksum, for
/// PutObject to echo back (#1256). Returns empty for the five s3s-typed algorithms
-565
View File
@@ -1,565 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Veeam SOSAPI virtual objects.
//!
//! Authenticated GET and HEAD of two exact bucket-root keys return generated
//! XML. The objects are not stored: no `xl.meta`, version, or Object Lock
//! interaction. Mutations of those keys are rejected while the feature is on.
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use super::super::storage_api::s3::{S3Error, S3ErrorCode, S3Result};
use bytes::Bytes;
use md5::Digest as _;
use md5::Md5;
use moka::{future::Cache as AsyncCache, sync::Cache as SyncCache};
use time::OffsetDateTime;
use tracing::debug;
use super::super::storage_api::object_usecase::data_usage::load_bucket_usage_from_backend_cached;
use super::super::storage_api::object_usecase::{ECStore, StorageObjectInfo as ObjectInfo, check_preconditions};
use super::HTTPRangeSpec;
use super::shared::{LOG_COMPONENT_APP, LOG_SUBSYSTEM_OBJECT};
use crate::app::storage_api::admin_usecase::contract::StorageAdminApi;
use crate::app::storage_api::object_usecase::bucket::quota::{BucketQuota, QuotaType};
use http::HeaderMap;
use uuid::Uuid;
pub(super) const SYSTEM_KEY: &str = ".system-d26a9498-cb7c-4a87-a44a-8ae204f5ba6c/system.xml";
pub(super) const CAPACITY_KEY: &str = ".system-d26a9498-cb7c-4a87-a44a-8ae204f5ba6c/capacity.xml";
pub(super) const CONTENT_TYPE: &str = "application/xml";
const CAPACITY_XML_CACHE_TTL: Duration = Duration::from_secs(12);
const CAPACITY_HISTORY_IDLE: Duration = Duration::from_secs(3600);
const CAPACITY_CACHE_ENTRIES: u64 = 1024;
const CLUSTER_CACHE_ENTRIES: u64 = 16;
const MAX_BUCKET_REFRESHES: usize = 64;
const MAX_CLUSTER_REFRESHES: usize = 16;
const EVENT_USAGE_MISSING: &str = "veeam_sosapi_usage_missing";
const EVENT_QUOTA_UNAVAILABLE: &str = "veeam_sosapi_quota_unavailable";
static LOGGED_USAGE_MISSING: AtomicBool = AtomicBool::new(false);
static LOGGED_QUOTA_UNAVAILABLE: AtomicBool = AtomicBool::new(false);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SosapiKind {
System,
Capacity,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SosapiReadError {
InvalidRange,
PartNumber,
}
pub(super) struct SosapiRepresentation {
pub body: Bytes,
pub content_length: i64,
pub content_range: Option<String>,
pub etag_hex: String,
pub last_modified: OffsetDateTime,
}
pub(super) struct CapacityInputs {
pub used_bucket: u64,
pub hard_quota: Option<u64>,
pub capacity_cluster: u64,
pub free_cluster: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct CapacityFigures {
pub capacity: u64,
pub used: u64,
pub available: u64,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
struct CapacityCacheKey {
store_id: Uuid,
bucket: String,
incarnation: Uuid,
}
#[derive(Clone)]
struct CachedXml {
bytes: Bytes,
etag_hex: String,
modified_at: OffsetDateTime,
}
// Bucket refreshes may wait for a cluster permit; cluster probes never acquire a bucket permit.
struct CapacityCaches {
current: AsyncCache<CapacityCacheKey, CachedXml>,
history: SyncCache<CapacityCacheKey, CachedXml>,
refresh_permits: tokio::sync::Semaphore,
}
impl CapacityCaches {
fn new() -> Self {
Self {
current: AsyncCache::builder()
.max_capacity(CAPACITY_CACHE_ENTRIES)
.time_to_live(CAPACITY_XML_CACHE_TTL)
.build(),
history: SyncCache::builder()
.max_capacity(CAPACITY_CACHE_ENTRIES)
.time_to_idle(CAPACITY_HISTORY_IDLE)
.build(),
refresh_permits: tokio::sync::Semaphore::new(MAX_BUCKET_REFRESHES),
}
}
}
struct StableXml {
bytes: Bytes,
etag_hex: String,
modified_at: OffsetDateTime,
}
pub(super) fn match_sosapi_key(key: &str) -> Option<SosapiKind> {
match key {
SYSTEM_KEY => Some(SosapiKind::System),
CAPACITY_KEY => Some(SosapiKind::Capacity),
_ => None,
}
}
pub(super) fn veeam_sosapi_enabled() -> bool {
rustfs_utils::get_env_bool(rustfs_config::ENV_VEEAM_SOSAPI_ENABLE, rustfs_config::DEFAULT_VEEAM_SOSAPI_ENABLE)
}
/// SOSAPI key whose virtual read should run. `None` when the key is ordinary
/// or the operator turned the feature off.
pub(super) fn handled_kind(key: &str) -> Option<SosapiKind> {
let kind = match_sosapi_key(key)?;
veeam_sosapi_enabled().then_some(kind)
}
/// True only for an exact SOSAPI key while the feature is enabled.
///
/// Callers use this on the mutation hot path: a miss is two string compares
/// and does not read the object store.
pub(super) fn mutation_blocked(key: &str) -> bool {
match_sosapi_key(key).is_some() && veeam_sosapi_enabled()
}
pub(super) fn capacity_figures(inputs: CapacityInputs) -> CapacityFigures {
let used_bucket = inputs.used_bucket;
let capacity = inputs
.hard_quota
.filter(|quota| *quota > 0)
.unwrap_or(inputs.capacity_cluster);
let used = used_bucket.min(capacity);
let available = capacity.saturating_sub(used).min(inputs.free_cluster);
CapacityFigures {
capacity,
used,
available,
}
}
/// Full generated document. Range and part-number checks happen after read
/// preconditions so a failing `If-Match` stays 412.
async fn generated(store: &Arc<ECStore>, bucket: &str, kind: SosapiKind) -> S3Result<(Bytes, String, OffsetDateTime)> {
match kind {
SosapiKind::System => {
let stable = system_xml_stable();
Ok((stable.bytes.clone(), stable.etag_hex.clone(), stable.modified_at))
}
SosapiKind::Capacity => cached_or_build_capacity(store, bucket).await,
}
}
pub(super) async fn read_representation(
store: &Arc<ECStore>,
bucket: &str,
kind: SosapiKind,
headers: &HeaderMap,
part_number: Option<usize>,
range: Option<&HTTPRangeSpec>,
) -> S3Result<SosapiRepresentation> {
let (full, etag_hex, last_modified) = generated(store, bucket, kind).await?;
check_preconditions(
headers,
&ObjectInfo {
etag: Some(etag_hex.clone()),
mod_time: Some(last_modified),
..Default::default()
},
)?;
representation_from(full, etag_hex, last_modified, part_number, range).map_err(|err| match err {
SosapiReadError::InvalidRange => {
S3Error::with_message(S3ErrorCode::InvalidRange, "The requested range is not satisfiable")
}
SosapiReadError::PartNumber => {
S3Error::with_message(S3ErrorCode::InvalidArgument, "partNumber is not supported for Veeam SOSAPI objects")
}
})
}
fn representation_from(
full: Bytes,
etag_hex: String,
last_modified: OffsetDateTime,
part_number: Option<usize>,
range: Option<&HTTPRangeSpec>,
) -> Result<SosapiRepresentation, SosapiReadError> {
if part_number.is_some() {
return Err(SosapiReadError::PartNumber);
}
apply_range(full, etag_hex, last_modified, range)
}
fn apply_range(
full: Bytes,
etag_hex: String,
last_modified: OffsetDateTime,
range: Option<&HTTPRangeSpec>,
) -> Result<SosapiRepresentation, SosapiReadError> {
let total = i64::try_from(full.len()).unwrap_or(i64::MAX);
let Some(range) = range else {
return Ok(SosapiRepresentation {
content_length: total,
content_range: None,
body: full,
etag_hex,
last_modified,
});
};
let (start, length) = range.get_offset_length(total).map_err(|_| SosapiReadError::InvalidRange)?;
let length_usize = usize::try_from(length).map_err(|_| SosapiReadError::InvalidRange)?;
let end = start.checked_add(length_usize).ok_or(SosapiReadError::InvalidRange)?;
if end > full.len() {
return Err(SosapiReadError::InvalidRange);
}
let start_i64 = i64::try_from(start).map_err(|_| SosapiReadError::InvalidRange)?;
let end_inclusive = start_i64 + length - 1;
Ok(SosapiRepresentation {
body: full.slice(start..end),
content_length: length,
content_range: Some(format!("bytes {start_i64}-{end_inclusive}/{total}")),
etag_hex,
last_modified,
})
}
fn system_xml_stable() -> &'static StableXml {
static BODY: OnceLock<StableXml> = OnceLock::new();
BODY.get_or_init(|| {
let bytes = Bytes::from(system_xml(env!("CARGO_PKG_VERSION")));
let etag_hex = md5_hex(&bytes);
StableXml {
bytes,
etag_hex,
modified_at: OffsetDateTime::from_unix_timestamp(crate::version::build::BUILD_TIMESTAMP)
.unwrap_or(OffsetDateTime::UNIX_EPOCH),
}
})
}
fn system_xml(version: &str) -> String {
let version = xml_escape_text(version);
format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<SystemInfo>\n <ProtocolVersion>\"1.0\"</ProtocolVersion>\n <ModelName>\"RustFS {version}\"</ModelName>\n <ProtocolCapabilities>\n <CapacityInfo>true</CapacityInfo>\n <UploadSessions>false</UploadSessions>\n <IAMSTS>false</IAMSTS>\n </ProtocolCapabilities>\n</SystemInfo>\n"
)
}
fn capacity_xml(figures: &CapacityFigures) -> String {
format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CapacityInfo>\n <Capacity>{}</Capacity>\n <Available>{}</Available>\n <Used>{}</Used>\n</CapacityInfo>\n",
figures.capacity, figures.available, figures.used,
)
}
/// Escape XML text. Quotes stay as ASCII quotes: Veeam's parser requires that
/// spelling inside `ProtocolVersion` and `ModelName`.
fn xml_escape_text(value: &str) -> String {
let mut escaped = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'&' => escaped.push_str("&amp;"),
'<' => escaped.push_str("&lt;"),
'>' => escaped.push_str("&gt;"),
_ => escaped.push(ch),
}
}
escaped
}
fn md5_hex(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let digest = Md5::digest(bytes);
let mut out = String::with_capacity(32);
for byte in digest {
out.push(char::from(HEX[usize::from(byte >> 4)]));
out.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
out
}
fn capacity_caches() -> &'static CapacityCaches {
static CACHES: OnceLock<CapacityCaches> = OnceLock::new();
CACHES.get_or_init(CapacityCaches::new)
}
async fn cached_or_build_capacity(store: &Arc<ECStore>, bucket: &str) -> S3Result<(Bytes, String, OffsetDateTime)> {
let incarnation = store
.bucket_incarnation_id_from_disk(bucket)
.await
.map_err(|_| capacity_unavailable())?;
let key = CapacityCacheKey {
store_id: store.id,
bucket: bucket.to_owned(),
incarnation,
};
cached_or_load_capacity(capacity_caches(), &key, || async {
let inputs = load_capacity_inputs(store, bucket, incarnation).await?;
if store
.bucket_incarnation_id_from_disk(bucket)
.await
.map_err(|_| capacity_unavailable())?
!= incarnation
{
return Err(capacity_unavailable());
}
Ok(capacity_figures(inputs))
})
.await
}
async fn cached_or_load_capacity<F, Fut>(
caches: &CapacityCaches,
key: &CapacityCacheKey,
load: F,
) -> S3Result<(Bytes, String, OffsetDateTime)>
where
F: FnOnce() -> Fut,
Fut: Future<Output = S3Result<CapacityFigures>>,
{
let value = caches
.current
.try_get_with_by_ref(key, async {
let _permit = caches.refresh_permits.acquire().await.map_err(|_| capacity_unavailable())?;
let bytes = Bytes::from(capacity_xml(&load().await?));
let etag_hex = md5_hex(&bytes);
let modified_at = caches
.history
.get(key)
.filter(|entry| entry.bytes == bytes)
.map_or_else(OffsetDateTime::now_utc, |entry| entry.modified_at);
let value = CachedXml {
bytes,
etag_hex,
modified_at,
};
caches.history.insert(key.clone(), value.clone());
Ok::<_, S3Error>(value)
})
.await
.map_err(|_| capacity_unavailable())?;
Ok((value.bytes, value.etag_hex, value.modified_at))
}
fn capacity_unavailable() -> S3Error {
S3Error::with_message(S3ErrorCode::ServiceUnavailable, "Veeam SOSAPI capacity is temporarily unavailable")
}
async fn load_capacity_inputs(store: &Arc<ECStore>, bucket: &str, incarnation: Uuid) -> S3Result<CapacityInputs> {
let (quota, quota_incarnation, _) = store.bucket_quota_and_incarnation_from_disk(bucket).await.map_err(|_| {
log_quota_unavailable_once(bucket);
capacity_unavailable()
})?;
if quota_incarnation != incarnation {
return Err(capacity_unavailable());
}
let used_bucket = load_bucket_usage_from_backend_cached(Arc::clone(store), bucket, incarnation)
.await
.ok()
.flatten()
.ok_or_else(|| {
log_usage_missing_once(bucket);
capacity_unavailable()
})?;
let (capacity_cluster, free_cluster) = cached_cluster_capacity(store).await?;
Ok(CapacityInputs {
used_bucket,
hard_quota: quota.as_ref().and_then(hard_quota_bytes),
capacity_cluster,
free_cluster,
})
}
fn hard_quota_bytes(quota: &BucketQuota) -> Option<u64> {
match quota.quota_type {
QuotaType::Hard => quota.quota.filter(|size| *size > 0),
}
}
struct ClusterCapacityCache {
current: AsyncCache<Uuid, (u64, u64)>,
refresh_permits: tokio::sync::Semaphore,
}
impl ClusterCapacityCache {
fn new() -> Self {
Self {
current: AsyncCache::builder()
.max_capacity(CLUSTER_CACHE_ENTRIES)
.time_to_live(CAPACITY_XML_CACHE_TTL)
.build(),
refresh_permits: tokio::sync::Semaphore::new(MAX_CLUSTER_REFRESHES),
}
}
}
fn cluster_capacity_cache() -> &'static ClusterCapacityCache {
static CACHE: OnceLock<ClusterCapacityCache> = OnceLock::new();
CACHE.get_or_init(ClusterCapacityCache::new)
}
async fn cached_cluster_capacity(store: &Arc<ECStore>) -> S3Result<(u64, u64)> {
cached_cluster_capacity_with(cluster_capacity_cache(), store.id, || async {
let info = StorageAdminApi::storage_info(store.as_ref()).await;
if !cluster_capacity_observations_are_live(&info) {
return Err(capacity_unavailable());
}
conservative_cluster_capacity(&info).ok_or_else(capacity_unavailable)
})
.await
}
fn cluster_capacity_observations_are_live(info: &rustfs_madmin::StorageInfo) -> bool {
!info.disks.is_empty()
&& !info.observations.is_empty()
&& info
.observations
.iter()
.all(|observation| !observation.cached && observation.status == rustfs_madmin::StorageInfoProbeStatus::Succeeded)
&& info.disks.iter().all(|disk| {
(disk.state.eq_ignore_ascii_case("ok") || disk.state.eq_ignore_ascii_case("online"))
&& disk.capacity_observation_source.as_deref() == Some("live_probe")
})
}
async fn cached_cluster_capacity_with<F, Fut>(cache: &ClusterCapacityCache, store_id: Uuid, load: F) -> S3Result<(u64, u64)>
where
F: FnOnce() -> Fut,
Fut: Future<Output = S3Result<(u64, u64)>>,
{
cache
.current
.try_get_with(store_id, async {
let _permit = cache.refresh_permits.acquire().await.map_err(|_| capacity_unavailable())?;
load().await
})
.await
.map_err(|_| capacity_unavailable())
}
/// A set can consume only the space available on each of its shard disks.
/// This remains an estimate when multiple shard paths share a backing device.
fn conservative_cluster_capacity(info: &rustfs_madmin::StorageInfo) -> Option<(u64, u64)> {
let backend = &info.backend;
let pools = backend.drives_per_set.len();
if pools == 0
|| backend.total_sets.len() != pools
|| backend.standard_sc_data.len() != pools
|| backend.standard_sc_parities.len() != pools
{
return None;
}
let expected = backend
.drives_per_set
.iter()
.zip(&backend.total_sets)
.try_fold(0usize, |sum, (&width, &sets)| sum.checked_add(width.checked_mul(sets)?))?;
if expected != info.disks.len() {
return None;
}
let mut seen = HashSet::with_capacity(expected);
let mut sets: HashMap<(usize, usize), (u64, u64, usize)> = HashMap::new();
for disk in &info.disks {
let pool = usize::try_from(disk.pool_index).ok()?;
let set = usize::try_from(disk.set_index).ok()?;
let index = usize::try_from(disk.disk_index).ok()?;
let width = *backend.drives_per_set.get(pool)?;
if width == 0 || set >= *backend.total_sets.get(pool)? || index >= width || !seen.insert((pool, set, index)) {
return None;
}
let entry = sets.entry((pool, set)).or_insert((u64::MAX, u64::MAX, 0));
entry.0 = entry.0.min(disk.total_space);
entry.1 = entry.1.min(disk.available_space);
entry.2 = entry.2.checked_add(1)?;
}
let mut total = 0u64;
let mut free = 0u64;
for ((pool, _), (min_total, min_free, count)) in sets {
let width = backend.drives_per_set[pool];
let data = backend.standard_sc_data[pool];
if count != width
|| data == 0
|| data.checked_add(backend.standard_sc_parities[pool]) != Some(width)
|| min_total == 0
|| min_free > min_total
{
return None;
}
let data = u64::try_from(data).ok()?;
total = total.checked_add(min_total.checked_mul(data)?)?;
free = free.checked_add(min_free.checked_mul(data)?)?;
}
Some((total, free))
}
fn log_usage_missing_once(bucket: &str) {
if LOGGED_USAGE_MISSING
.compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
debug!(
event = EVENT_USAGE_MISSING,
component = LOG_COMPONENT_APP,
subsystem = LOG_SUBSYSTEM_OBJECT,
state = "snapshot_missing",
bucket = %bucket,
"Veeam SOSAPI capacity is unavailable because the data-usage snapshot is missing"
);
}
}
fn log_quota_unavailable_once(bucket: &str) {
if LOGGED_QUOTA_UNAVAILABLE
.compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
debug!(
event = EVENT_QUOTA_UNAVAILABLE,
component = LOG_COMPONENT_APP,
subsystem = LOG_SUBSYSTEM_OBJECT,
state = "quota_unavailable",
bucket = %bucket,
"Veeam SOSAPI capacity is unavailable because the bucket quota could not be read"
);
}
}
#[cfg(test)]
mod tests;
File diff suppressed because it is too large Load Diff
+2 -9
View File
@@ -107,14 +107,6 @@ pub(crate) mod data_usage {
crate::storage::storage_api::ecstore_data_usage::load_admin_data_usage_from_backend_cached(store).await
}
pub(crate) async fn load_bucket_usage_from_backend_cached(
store: Arc<crate::storage::storage_api::ECStore>,
bucket: &str,
incarnation: uuid::Uuid,
) -> Result<Option<u64>, crate::storage::storage_api::StorageError> {
crate::storage::storage_api::ecstore_data_usage::load_bucket_usage_from_backend_cached(store, bucket, incarnation).await
}
#[cfg(test)]
pub(crate) async fn load_data_usage_from_backend_cached(
store: Arc<crate::storage::storage_api::ECStore>,
@@ -687,8 +679,8 @@ pub(crate) mod bucket {
pub(crate) type QuotaChecker = crate::storage::storage_api::ecstore_bucket::quota::checker::QuotaChecker;
}
#[cfg(test)]
pub(crate) type BucketQuota = crate::storage::storage_api::ecstore_bucket::quota::BucketQuota;
pub(crate) type QuotaType = crate::storage::storage_api::ecstore_bucket::quota::QuotaType;
pub(crate) type QuotaOperation = crate::storage::storage_api::ecstore_bucket::quota::QuotaOperation;
pub(crate) type QuotaCheckResult = crate::storage::storage_api::ecstore_bucket::quota::QuotaCheckResult;
pub(crate) type QuotaError = crate::storage::storage_api::ecstore_bucket::quota::QuotaError;
@@ -1211,6 +1203,7 @@ pub(crate) mod bucket_usecase {
}
pub(crate) mod object_usecase {
pub(crate) use super::storage_contracts::BUCKET_LIFECYCLE_LOCK_OBJECT;
pub(crate) use super::storage_contracts::object::DeleteObjectCondition;
pub(crate) use crate::storage::storage_api::ecstore_object::{WriteCommitGuard, WriteCompletion};
+2 -14
View File
@@ -528,7 +528,6 @@ struct ConfigInfoJson {
kms_backend: String,
buffer_profile: String,
workload_profile: Option<WorkloadProfileJson>,
veeam_sosapi_enable: bool,
}
/// Workload profile information for JSON output
@@ -573,10 +572,6 @@ fn collect_config_info_json() -> ConfigInfoJson {
kms_backend: snapshot.kms_backend.clone(),
buffer_profile: snapshot.buffer_profile.clone(),
workload_profile,
veeam_sosapi_enable: rustfs_utils::get_env_bool(
rustfs_config::ENV_VEEAM_SOSAPI_ENABLE,
rustfs_config::DEFAULT_VEEAM_SOSAPI_ENABLE,
),
}
}
@@ -894,8 +889,6 @@ fn format_protocol_config_info() -> String {
rustfs_utils::get_env_u64(rustfs_config::ENV_WEBDAV_REQUEST_TIMEOUT, DEFAULT_WEBDAV_REQUEST_TIMEOUT_SECS);
let webdav_max_connections =
rustfs_utils::get_env_usize(rustfs_config::ENV_WEBDAV_MAX_CONNECTIONS, DEFAULT_WEBDAV_MAX_CONNECTIONS);
let veeam_sosapi_enable =
rustfs_utils::get_env_bool(rustfs_config::ENV_VEEAM_SOSAPI_ENABLE, rustfs_config::DEFAULT_VEEAM_SOSAPI_ENABLE);
format!(
"| FTPS | --- |\n\
@@ -916,9 +909,7 @@ fn format_protocol_config_info() -> String {
| WebDAV > CA File (`{}`) | {} |\n\
| WebDAV > Max Body Size (`{}`) | {} bytes |\n\
| WebDAV > Request Timeout (`{}`) | {} seconds |\n\
| WebDAV > Max Connections (`{}`) | {} |\n\
| Veeam SOSAPI | --- |\n\
| Veeam SOSAPI > Enabled (`{}`) | {} |",
| WebDAV > Max Connections (`{}`) | {} |",
if cfg!(feature = "ftps") { "enabled" } else { "disabled" },
rustfs_config::ENV_FTPS_ENABLE,
ftps_enable,
@@ -950,9 +941,7 @@ fn format_protocol_config_info() -> String {
rustfs_config::ENV_WEBDAV_REQUEST_TIMEOUT,
webdav_request_timeout,
rustfs_config::ENV_WEBDAV_MAX_CONNECTIONS,
webdav_max_connections,
rustfs_config::ENV_VEEAM_SOSAPI_ENABLE,
veeam_sosapi_enable
webdav_max_connections
)
}
@@ -1148,6 +1137,5 @@ mod tests {
assert!(output.contains("| WebDAV > Enabled (`RUSTFS_WEBDAV_ENABLE`) |"));
assert!(output.contains("| WebDAV > Address (`RUSTFS_WEBDAV_ADDRESS`) |"));
assert!(output.contains("| WebDAV > Max Body Size (`RUSTFS_WEBDAV_MAX_BODY_SIZE`) |"));
assert!(output.contains("| Veeam SOSAPI > Enabled (`RUSTFS_VEEAM_SOSAPI_ENABLE`) |"));
}
}
+2 -17
View File
@@ -64,13 +64,6 @@ use std::sync::OnceLock;
use time::OffsetDateTime;
use url::{Url, form_urlencoded};
fn iam_authorization_error(err: IamError) -> ApiError {
match err {
IamError::IAMActionNotAllowed => ApiError::access_denied(),
other => ApiError::from(other),
}
}
const EVENT_OBJECT_TAG_AUTHORIZATION: &str = "object_tag_authorization";
const LOG_COMPONENT_ACCESS: &str = "storage_access";
const LOG_SUBSYSTEM_AUTHORIZATION: &str = "authorization";
@@ -1490,7 +1483,7 @@ async fn authorize_request_with_location_constraint<T>(
let allowed = iam_store
.try_eval_prepared(&prepared, &final_args)
.await
.map_err(iam_authorization_error)?;
.map_err(ApiError::from)?;
if !allowed
&& matches!(
action,
@@ -1512,7 +1505,7 @@ async fn authorize_request_with_location_constraint<T>(
if !iam_store
.try_eval_prepared(&prepared, &final_args)
.await
.map_err(iam_authorization_error)?
.map_err(ApiError::from)?
{
return Err(denial.deny("iam_explicit_deny", action));
}
@@ -3625,14 +3618,6 @@ mod tests {
use std::{collections::HashMap, sync::Arc};
use time::OffsetDateTime;
#[test]
fn terminal_iam_denial_is_access_denied_and_backend_failure_stays_internal() {
let denied = s3s::S3Error::from(super::iam_authorization_error(rustfs_iam::error::Error::IAMActionNotAllowed));
assert_eq!(denied.code(), &S3ErrorCode::AccessDenied);
let unavailable = s3s::S3Error::from(super::iam_authorization_error(rustfs_iam::error::Error::IamSysNotInitialized));
assert_eq!(unavailable.code(), &S3ErrorCode::InternalError);
}
struct UnreadyIam;
impl IamInterface for UnreadyIam {
-16
View File
@@ -393,10 +393,6 @@ pub(crate) fn parse_object_version_id(version_id: Option<String>) -> S3Result<Op
}
}
async fn reject_veeam_sosapi_mutation(fs: &FS, bucket: &str, key: &str) -> S3Result<()> {
s3_api::reject_veeam_sosapi_mutation(|| fs.server_ctx.object_store(), bucket, key).await
}
async fn validate_table_catalog_object_mutation(bucket: &str, key: &str) -> S3Result<()> {
table_catalog::validate_bucket_object_mutation(bucket, key)
.await
@@ -667,7 +663,6 @@ impl S3 for FS {
..
} = req.input.clone();
reject_veeam_sosapi_mutation(self, &bucket, &object).await?;
validate_table_catalog_object_mutation(&bucket, &object).await?;
let Some(store) = self.server_ctx.object_store() else {
@@ -1009,8 +1004,6 @@ impl S3 for FS {
bucket, key, version_id, ..
} = req.input.clone();
reject_veeam_sosapi_mutation(self, &bucket, &key).await?;
let Some(store) = self.server_ctx.object_store() else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init".to_string()));
};
@@ -1120,8 +1113,6 @@ impl S3 for FS {
bucket, key, version_id, ..
} = req.input.clone();
reject_veeam_sosapi_mutation(self, &bucket, &key).await?;
let Some(store) = self.server_ctx.object_store() else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init".to_string()));
};
@@ -1165,8 +1156,6 @@ impl S3 for FS {
let bucket = req.input.bucket.as_str();
let object = req.input.key.as_str();
reject_veeam_sosapi_mutation(self, bucket, object).await?;
let Some(store) = self.server_ctx.object_store() else {
error!(
component = LOG_COMPONENT_STORAGE,
@@ -1575,8 +1564,6 @@ impl S3 for FS {
let key = &req.input.key;
let version_id = req.input.version_id.clone();
reject_veeam_sosapi_mutation(self, bucket, key).await?;
let Some(store) = self.server_ctx.object_store() else {
return Err(S3Error::with_message(S3ErrorCode::InternalError, "Not init".to_string()));
};
@@ -1617,7 +1604,6 @@ impl S3 for FS {
..
} = req.input.clone();
reject_veeam_sosapi_mutation(self, &bucket, &key).await?;
validate_table_catalog_object_mutation(&bucket, &key).await?;
let Some(store) = self.server_ctx.object_store() else {
@@ -1820,7 +1806,6 @@ impl S3 for FS {
..
} = req.input.clone();
reject_veeam_sosapi_mutation(self, &bucket, &key).await?;
validate_table_catalog_object_mutation(&bucket, &key).await?;
let Some(store) = self.server_ctx.object_store() else {
@@ -1938,7 +1923,6 @@ impl S3 for FS {
..
} = req.input.clone();
reject_veeam_sosapi_mutation(self, &bucket, &object).await?;
validate_table_catalog_object_mutation(&bucket, &object).await?;
crate::storage::s3_api::tagging::validate_object_tag_set(&tagging.tag_set)?;
+1 -1
View File
@@ -17,7 +17,7 @@
//! This file intentionally starts as skeleton-only. Behavior remains in place
//! until each helper is moved with dedicated small refactor steps.
pub(crate) use crate::app::object::{reject_veeam_sosapi_mutation, s3_response_version_id};
pub(crate) use crate::app::object::s3_response_version_id;
use crate::app::{
bucket_usecase::DefaultBucketUsecase, multipart_usecase::DefaultMultipartUsecase, object_usecase::DefaultObjectUsecase,
};
+24 -104
View File
@@ -222,12 +222,12 @@ impl JournalState {
Some(entries)
}
fn from_replay_record(record: &ScannerDurableDirtyUsageReplayRecord) -> Option<Self> {
fn from_replay_record(record: ScannerDurableDirtyUsageReplayRecord) -> Option<Self> {
if record.entries.is_empty() || record.entries.len() > DURABLE_DIRTY_USAGE_REPLAY_MAX_ENTRIES {
return None;
}
let mut state = JournalState::default();
for entry in &record.entries {
for entry in record.entries {
if entry.bucket.is_empty()
|| entry.bucket.contains(['/', '\\', '\0'])
|| entry.bucket == "."
@@ -242,7 +242,7 @@ impl JournalState {
{
return None;
}
let scope = match &entry.scope {
let scope = match entry.scope {
ScannerDurableDirtyUsageReplayScope::WholeBucket => JournalScope::WholeBucket,
ScannerDurableDirtyUsageReplayScope::TopLevelEntries { entries } => {
if entries.is_empty() || entries.len() > DURABLE_DIRTY_USAGE_REPLAY_MAX_TOP_LEVEL_ENTRIES {
@@ -254,18 +254,18 @@ impl JournalState {
{
return None;
}
JournalScope::TopLevelEntries(entries.clone())
JournalScope::TopLevelEntries(entries)
}
};
state.scope_bytes += journal_scope_bytes(&scope);
if state
.buckets
.insert(
entry.bucket.clone(),
entry.bucket,
JournalBucketState {
generation: entry.generation,
scope,
producers: entry.producers.clone(),
producers: entry.producers,
},
)
.is_some()
@@ -338,7 +338,7 @@ async fn replay_durable_dirty_usage_journal(store: Arc<ECStore>, owner: &str) ->
..Default::default()
};
};
match replay.replay() {
match rustfs_scanner::replay_durable_dirty_usage_producer_record(&replay) {
Ok(replayed) => {
debug!(
event = EVENT_SCANNER_DIRTY_USAGE_JOURNAL,
@@ -368,7 +368,7 @@ async fn replay_durable_dirty_usage_journal(store: Arc<ECStore>, owner: &str) ->
}
}
fn decode_owned_replay_record(owner: &str, bytes: &[u8]) -> Option<(JournalState, ScannerDurableDirtyUsageReplayRecord)> {
fn decode_owned_replay_record(owner: &str, bytes: &[u8]) -> Option<(JournalState, Vec<u8>)> {
if bytes.len() > DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES {
return None;
}
@@ -377,16 +377,13 @@ fn decode_owned_replay_record(owner: &str, bytes: &[u8]) -> Option<(JournalState
return None;
}
let replay = record.replay?;
let state = JournalState::from_replay_record(&replay)?;
Some((state, replay))
let bytes = serde_json::to_vec(&replay).ok()?;
let state = JournalState::from_replay_record(replay)?;
Some((state, bytes))
}
fn encode_owned_replay_record(owner: &str, state: &JournalState) -> Result<Vec<u8>, serde_json::Error> {
let mut entries = state.replay_entries();
let mut prefix = Vec::with_capacity(owner.len() + 32);
prefix.extend_from_slice(b"{\"owner\":");
serde_json::to_writer(&mut prefix, owner)?;
prefix.extend_from_slice(b",\"replay\":");
for compact in [false, true] {
if let Some(entries) = &mut entries {
if compact {
@@ -394,12 +391,13 @@ fn encode_owned_replay_record(owner: &str, state: &JournalState) -> Result<Vec<u
entry.scope = ScannerDurableDirtyUsageReplayScope::WholeBucket;
}
}
if let Ok(replay) = rustfs_scanner::encode_durable_dirty_usage_producer_replay_record(entries.clone()) {
// This producer already validated and serialized the complete frame.
let mut bytes = prefix.clone();
bytes.reserve(replay.len() + 1);
bytes.extend_from_slice(&replay);
bytes.push(b'}');
if let Ok(replay) = rustfs_scanner::encode_durable_dirty_usage_producer_replay_record(entries.clone())
&& let Ok(replay) = serde_json::from_slice(&replay)
{
let bytes = serde_json::to_vec(&OwnedReplayRecord {
owner: owner.to_string(),
replay: Some(replay),
})?;
if bytes.len() <= DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES {
return Ok(bytes);
}
@@ -407,8 +405,10 @@ fn encode_owned_replay_record(owner: &str, state: &JournalState) -> Result<Vec<u
}
}
// Never label a truncated record as complete producer coverage.
prefix.extend_from_slice(b"null}");
Ok(prefix)
serde_json::to_vec(&OwnedReplayRecord {
owner: owner.to_string(),
replay: None,
})
}
async fn run_durable_dirty_usage_journal(store: Arc<ECStore>, owner: String, shared: Weak<SharedJournal>, changed: Arc<Notify>) {
@@ -575,84 +575,6 @@ mod tests {
ENV.get_or_init(|| rustfs_test_utils::TestECStoreEnv::builder().build()).await
}
fn legacy_owned_encoding(owner: &str, state: &JournalState) -> Vec<u8> {
let mut entries = state.replay_entries();
for compact in [false, true] {
if let Some(entries) = &mut entries {
if compact {
for entry in entries.iter_mut() {
entry.scope = ScannerDurableDirtyUsageReplayScope::WholeBucket;
}
}
if let Ok(replay) = rustfs_scanner::encode_durable_dirty_usage_producer_replay_record(entries.clone())
&& let Ok(replay) = serde_json::from_slice(&replay)
{
let bytes = serde_json::to_vec(&OwnedReplayRecord {
owner: owner.to_string(),
replay: Some(replay),
})
.expect("legacy typed wrapper");
if bytes.len() <= DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES {
return bytes;
}
}
}
}
serde_json::to_vec(&OwnedReplayRecord {
owner: owner.to_string(),
replay: None,
})
.expect("legacy unknown marker")
}
#[test]
fn owned_encoding_reuses_the_producer_frame_without_changing_wire_bytes() {
let mut scoped = JournalState::default();
for producer in SegmentInvalidationProducerIdentity::REQUIRED_PRODUCTION {
scoped.record_mutation("bucket-a".to_string(), "quote\"雪/object", 17, producer);
}
scoped.record_mutation("bucket-b".to_string(), "object", 9, SegmentInvalidationProducerIdentity::PutObject);
let unknown = JournalState {
invalidated: true,
..Default::default()
};
for owner in ["owner", "quote\"slash\\newline\n", "所有者", "\0"] {
for state in [&scoped, &unknown, &JournalState::default()] {
let expected = legacy_owned_encoding(owner, state);
let actual = encode_owned_replay_record(owner, state).expect("complete owned encoding");
assert_eq!(actual, expected, "legacy bytes for owner {owner:?}");
}
}
}
#[test]
fn owned_unknown_marker_keeps_the_pinned_legacy_wire_fixture() {
let bytes = encode_owned_replay_record("owner", &JournalState::default()).expect("unknown marker");
assert_eq!(bytes, br#"{"owner":"owner","replay":null}"#);
assert!(decode_owned_replay_record("owner", &bytes).is_none());
}
#[test]
fn owned_replay_keeps_the_outer_json_recursion_boundary() {
// Ignored scope fields still consume the complete owned frame's depth
// budget. Parsing replay from a fresh JSON root must not bypass it.
for (depth, accepted) in [(122, true), (123, false)] {
let bytes = format!(
r#"{{"owner":"owner","replay":{{"schema":1,"cache_key_format":1,"writer_epoch":"epoch","entries":[{{"bucket":"bucket","generation":7,"scope":{{"type":"whole_bucket","ignored":{}0{}}},"producers":["put_object"]}}]}}}}"#,
"[".repeat(depth),
"]".repeat(depth),
);
assert!(bytes.len() < DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES);
let decoded = decode_owned_replay_record("owner", bytes.as_bytes());
assert_eq!(decoded.is_some(), accepted, "owned frame depth {depth}");
if let Some((state, _)) = decoded {
assert_eq!(state.buckets.len(), 1);
assert_eq!(state.buckets["bucket"].generation, 7);
assert_eq!(state.buckets["bucket"].scope, super::JournalScope::WholeBucket);
}
}
}
#[test]
fn journal_owner_is_stable_and_never_defaults_to_a_shared_identity() {
assert!(durable_dirty_usage_owner("").is_none());
@@ -732,7 +654,6 @@ mod tests {
}
assert!(state.scope_bytes <= DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES);
let bytes = encode_owned_replay_record(&owner, &state).expect("bounded record");
assert_eq!(bytes, legacy_owned_encoding(&owner, &state), "legacy compacted bytes");
assert!(bytes.len() <= DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES);
let (decoded, _) = decode_owned_replay_record(&owner, &bytes).expect("compacted replay");
assert_eq!(decoded.buckets.len(), 3);
@@ -752,7 +673,6 @@ mod tests {
assert!(!state.invalidated);
assert_eq!(state.buckets.len(), 1024);
let bytes = encode_owned_replay_record(&owner, &state).expect("unverified marker");
assert_eq!(bytes, legacy_owned_encoding(&owner, &state), "legacy unknown marker bytes");
assert!(bytes.len() <= DURABLE_DIRTY_USAGE_REPLAY_MAX_BYTES);
let record: OwnedReplayRecord = serde_json::from_slice(&bytes).expect("marker");
assert!(record.replay.is_none());
@@ -1064,7 +984,7 @@ mod tests {
producers: BTreeSet::from([SegmentInvalidationProducerIdentity::Replication]),
}],
};
let mut state = JournalState::from_replay_record(&record).expect("valid replay record should hydrate");
let mut state = JournalState::from_replay_record(record).expect("valid replay record should hydrate");
state.record_mutation(
"videos".to_string(),
"clips/object",
@@ -1091,7 +1011,7 @@ mod tests {
producers: BTreeSet::from([SegmentInvalidationProducerIdentity::Replication]),
}],
};
let mut state = JournalState::from_replay_record(&record).expect("valid replay record should hydrate");
let mut state = JournalState::from_replay_record(record).expect("valid replay record should hydrate");
state.record_mutation(
"photos".to_string(),
"2026/object",
+3 -3
View File
@@ -477,9 +477,9 @@ pub(crate) mod ecstore_config {
pub(crate) mod ecstore_data_usage {
pub(crate) use rustfs_ecstore::api::data_usage::{
apply_bucket_usage_memory_overlay, get_bucket_usage_memory, init_compression_total_memory_from_backend,
load_admin_data_usage_from_backend_cached, load_bucket_usage_from_backend_cached, load_data_usage_from_backend,
lookup_degraded_bucket_usage_baseline, quota_object_size, record_bucket_delete_marker_memory,
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,
load_admin_data_usage_from_backend_cached, load_data_usage_from_backend, lookup_degraded_bucket_usage_baseline,
quota_object_size, record_bucket_delete_marker_memory, record_bucket_object_delete_memory,
record_bucket_object_version_write_memory, record_bucket_object_write_memory,
record_bucket_object_write_unknown_previous_memory, store_compression_total_in_backend,
};
// Test-only observables for the rustfs/backlog#1306 revert detector.
+1 -18
View File
@@ -21682,6 +21682,7 @@ fn object_mutation_entrypoints_call_reserved_prefix_guard() {
for expected in [
"validate_object_key(&key, request_method_name)?;\n validate_table_catalog_object_mutation(&bucket, &key).await?;",
"validate_object_key(&key, \"COPY (dest)\")?;\n validate_table_catalog_object_mutation(&bucket, &key).await?;",
"if let Err(err) = validate_table_catalog_object_mutation(&bucket, &obj_id.key).await",
"validate_table_catalog_object_mutation(&bucket, &object).await?;",
"validate_object_key(&key, \"PUT\")?;\n validate_table_catalog_object_mutation(&bucket, &key).await?;",
@@ -21689,24 +21690,6 @@ fn object_mutation_entrypoints_call_reserved_prefix_guard() {
] {
assert!(source.contains(expected), "missing object mutation guard: {expected}");
}
let copy_object = include_str!("../app/object/copy.rs")
.split_once("async fn execute_copy_object_body(")
.map(|(_, body)| body.split_once("\n#[cfg(test)]").map_or(body, |(entrypoint, _)| entrypoint))
.expect("copy object entrypoint should remain in app/object/copy.rs");
let copy_key = copy_object
.find("validate_object_key(&key, \"COPY (dest)\")?;")
.expect("copy destination key validation");
let copy_guard = copy_object
.find("validate_table_catalog_object_mutation(&bucket, &key).await?;")
.expect("copy destination catalog guard");
let copy_store = copy_object
.find("let Some(store) = self.object_store()")
.expect("copy object store resolution");
assert!(
copy_key < copy_guard && copy_guard < copy_store,
"copy must guard the destination before store access"
);
assert!(
delete_object.contains("validate_object_key(&key, \"DELETE\")?;")
&& delete_object.contains("validate_table_catalog_object_mutation(&bucket, &key).await?;"),
+1 -3
View File
@@ -85,9 +85,7 @@ def histogram_point(point):
require(all(a < b for a, b in zip(bounds, bounds[1:])), "unordered histogram boundaries")
require(len(buckets) == len(bounds) + 1, "missing or inconsistent histogram buckets")
buckets = [uint(value, "bucket count") for value in buckets]
# Proto3 JSON conversion can omit a default-zero count. Without presence
# information, reject it instead of treating a missing observation as zero.
count = uint(point.get("count"), "histogram count")
count = uint(point.get("count", 0), "histogram count")
require(sum(buckets) == count, "histogram count does not match buckets")
return {**times, "kind": "histogram", "count": count, "bounds": bounds, "buckets": buckets}
-58
View File
@@ -11,11 +11,6 @@ import unittest
import scanner_otlp_window as collector
try:
from opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 import ExportMetricsServiceRequest
except ImportError:
ExportMetricsServiceRequest = None
METRIC = "rustfs_heal_admission_start_duration_seconds"
START = 1_800_000_000_000_000_001
@@ -43,21 +38,6 @@ def point(document):
return metric(document)["histogram"]["dataPoints"][0]
def protobuf_export(end, buckets):
request = ExportMetricsServiceRequest()
scope = request.resource_metrics.add().scope_metrics.add()
metric = scope.metrics.add()
metric.name = METRIC
metric.histogram.aggregation_temporality = 2
sample = metric.histogram.data_points.add()
sample.start_time_unix_nano = START
sample.time_unix_nano = end
sample.count = sum(buckets)
sample.bucket_counts.extend(buckets)
sample.explicit_bounds.extend([0.001, 0.01])
return request.SerializeToString()
class WindowTests(unittest.TestCase):
def setUp(self):
self.before = export(START + 10, [200, 100, 5])
@@ -86,44 +66,6 @@ class WindowTests(unittest.TestCase):
self.assertIsNone(row["p95"])
self.assertIsNone(row["p99"])
def test_missing_histogram_count_is_not_an_empty_sample(self):
self.before = export(START + 10, [0, 0, 0])
self.after = export(START + 20, [0, 0, 0])
del point(self.before)["count"]
with self.assertRaisesRegex(ValueError, "histogram count"):
self.result()
def test_explicit_zero_histogram_count_remains_a_valid_empty_sample(self):
self.before = export(START + 10, [0, 0, 0])
self.after = export(START + 20, [0, 0, 0])
row = self.result()["series"][0]
self.assertEqual(row["count"], 0)
self.assertIsNone(row["p95"])
self.assertIsNone(row["p99"])
@unittest.skipUnless(ExportMetricsServiceRequest is not None, "requires opentelemetry-proto")
def test_protobuf_default_zero_count_without_presence_is_rejected(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "zero.pb"
path.write_bytes(protobuf_export(START + 10, [0, 0, 0]))
before, _ = collector.load(path, "protobuf")
self.after = export(START + 20, [0, 0, 0])
with self.assertRaisesRegex(ValueError, "histogram count"):
collector.window(before, self.after, [METRIC])
@unittest.skipUnless(ExportMetricsServiceRequest is not None, "requires opentelemetry-proto")
def test_protobuf_nonzero_counts_produce_window_bounds(self):
with tempfile.TemporaryDirectory() as tmp:
before_path = Path(tmp) / "before.pb"
after_path = Path(tmp) / "after.pb"
before_path.write_bytes(protobuf_export(START + 10, [0, 1, 0]))
after_path.write_bytes(protobuf_export(START + 20, [0, 2, 0]))
before, _ = collector.load(before_path, "protobuf")
after, _ = collector.load(after_path, "protobuf")
row = collector.window(before, after, [METRIC], START + 10, START + 20)["series"][0]
self.assertEqual(row["count"], 1)
self.assertEqual(row["p99"], {"lower_exclusive": 0.001, "upper_inclusive": 0.01})
def test_open_tail_is_not_replaced_with_historical_max(self):
self.after = export(START + 20, [200, 100, 105])
self.assertEqual(self.result()["series"][0]["p95"],