mirror of
https://github.com/rustfs/rustfs.git
synced 2026-08-02 03:19:19 +00:00
Compare commits
74 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a2e5fc2de8 | |||
| 557a616ae6 | |||
| a29ae4e5cd | |||
| da6fc5314d | |||
| a12043f49f | |||
| a6599dbc32 | |||
| 7528a0b916 | |||
| 105af08a10 | |||
| f1a85c6a93 | |||
| 3cfe867dff | |||
| fc3896f479 | |||
| 6d8c19e71c | |||
| fbec33bd29 | |||
| 4c83bff81c | |||
| 51f9d1b74f | |||
| ed02899d31 | |||
| 81fc61db41 | |||
| a08fb56607 | |||
| c8016cbcdb | |||
| 56a7e3b707 | |||
| f2d09d1426 | |||
| 02aa383598 | |||
| 860ad68afd | |||
| 95e96e1bd5 | |||
| 816849a8ee | |||
| 5ef5eb8ea9 | |||
| ad721bff42 | |||
| 29dedcc7fd | |||
| 749cb2c1a1 | |||
| eb4f2d61ad | |||
| 3c00ad6048 | |||
| 85bc0d3ce2 | |||
| b8d2f1c84c | |||
| 59f69fbfb5 | |||
| be7ba1bba9 | |||
| 6363263f09 | |||
| 533896d045 | |||
| 0bf077f918 | |||
| 284faec03f | |||
| bfec547d36 | |||
| 0bd53becb5 | |||
| da389c0e21 | |||
| b7805caa58 | |||
| b0bb0bbd3a | |||
| bc41e567a5 | |||
| d5c6ba99d5 | |||
| 62d44d10b8 | |||
| 8218248000 | |||
| fd36bdfb1a | |||
| 322ce21b9a | |||
| 35e4415ed9 | |||
| 4e34f97dd7 | |||
| 782c78e0ef | |||
| 8387528c9b | |||
| 4ce0e280f2 | |||
| 793c193a6b | |||
| 5a6e850c67 | |||
| 2d8ad5caee | |||
| 3d4f4bb86d | |||
| 2b31bda6d1 | |||
| 68e344bf03 | |||
| 48c2fcb62b | |||
| 428fde069d | |||
| 364168c0ba | |||
| 3f4f31129e | |||
| 6c99d4fe22 | |||
| f5348d5cc4 | |||
| e2b2bdcc34 | |||
| b965bd6eef | |||
| 1524ed891f | |||
| 7354a5663d | |||
| 790bdc0e63 | |||
| 707d062174 | |||
| 4b6b6f14bd |
@@ -28,6 +28,8 @@ script-tests: ## Run shell script tests
|
||||
./scripts/test_entrypoint_credentials.sh
|
||||
./scripts/test_internode_grpc_ab_bench.sh
|
||||
./scripts/test_object_batch_bench_enhanced.sh
|
||||
./scripts/test_hotpath_warp_ab_gate.sh
|
||||
./scripts/test_hotpath_warp_abba.sh
|
||||
./scripts/test_exact_1mib_handoff_abba.sh
|
||||
./scripts/test_pinned_paired_abba_bench.sh
|
||||
./scripts/test_manual_transition_runbooks.sh
|
||||
|
||||
@@ -300,9 +300,6 @@ path = "junit.xml"
|
||||
# negative-path siblings of each family stay in as regression guards.
|
||||
# * rustfs#4843 — over-limit archive entry paths hard-reject the whole
|
||||
# archive even under ignore-errors semantics.
|
||||
# * rustfs#4846 — distributed-lock quorum tests misclassify as timeout
|
||||
# under parallel load (multi-node in-process clusters; natural home is
|
||||
# ci-7's nightly cluster lane).
|
||||
[profile.e2e-full]
|
||||
default-filter = """
|
||||
package(e2e_test)
|
||||
@@ -311,7 +308,6 @@ default-filter = """
|
||||
& !test(/^replication_extension_test::/)
|
||||
& !test(/^multipart_auth_test::test_signed_put_object_extract_skips_invalid_entry_when_ignore_errors_enabled$/)
|
||||
& !test(/^snowball_auto_extract_test::tests::snowball_auto_extract_(ignores_invalid_entries_when_requested|supports_standard_headers_with_combined_extract_options)$/)
|
||||
& !test(/^reliant::lock::test_distributed_lock_(2_nodes_grpc_read_survives_failed_node|4_nodes_grpc_read_write_quorum_split_with_two_failed_nodes)$/)
|
||||
"""
|
||||
fail-fast = false
|
||||
|
||||
|
||||
@@ -25,9 +25,13 @@ inputs:
|
||||
required: false
|
||||
default: "rustfs-deps"
|
||||
cache-save-if:
|
||||
description: "Condition for saving cache"
|
||||
description: >-
|
||||
Whether to save the cache. The fail-safe default is 'false': a caller that
|
||||
wants to populate a cache must opt in explicitly, so a forgotten input
|
||||
costs a cold cache (minutes) rather than silently consuming the
|
||||
repository-wide 10GB Actions cache quota and evicting other lanes.
|
||||
required: false
|
||||
default: "true"
|
||||
default: "false"
|
||||
install-cross-tools:
|
||||
description: "Install cross-compilation tools"
|
||||
required: false
|
||||
@@ -36,28 +40,43 @@ inputs:
|
||||
description: "Target architecture to add"
|
||||
required: false
|
||||
default: ""
|
||||
github-token:
|
||||
description: "GitHub token for API access"
|
||||
install-build-packaging-tools:
|
||||
description: >-
|
||||
Install musl-tools/zip/unzip, needed for musl linking and release
|
||||
packaging. Off for CI test lanes, which use none of them.
|
||||
required: false
|
||||
default: ""
|
||||
default: "true"
|
||||
install-test-tools:
|
||||
description: >-
|
||||
Install cargo-nextest and the rustfmt/clippy components. Off for release
|
||||
and audit lanes, which run no tests and no lints.
|
||||
required: false
|
||||
default: "true"
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
# protobuf-compiler is deliberately absent: the setup-protoc step below
|
||||
# installs 34.1 into the tool cache and prepends it to PATH, so the apt
|
||||
# build (older, and never version-matched) was shadowed on every run and
|
||||
# simply never used.
|
||||
- name: Install system dependencies (Ubuntu)
|
||||
if: runner.os == 'Linux'
|
||||
shell: bash
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
musl-tools \
|
||||
build-essential \
|
||||
pkg-config \
|
||||
libssl-dev \
|
||||
ripgrep \
|
||||
unzip \
|
||||
zip \
|
||||
protobuf-compiler
|
||||
ripgrep
|
||||
|
||||
# musl-gcc is needed by the native musl release leg, and zip/unzip by the
|
||||
# release packaging steps. No CI test lane touches any of them.
|
||||
- name: Install packaging and cross-linking dependencies (Ubuntu)
|
||||
if: runner.os == 'Linux' && inputs.install-build-packaging-tools == 'true'
|
||||
shell: bash
|
||||
run: sudo apt-get install -y musl-tools zip unzip
|
||||
|
||||
- name: Install protoc
|
||||
uses: rustfs/setup-protoc@a3705324d8f9bf5b6c3573fb6cf8ae421db55dd6 # v3.0.1
|
||||
@@ -75,7 +94,7 @@ runs:
|
||||
with:
|
||||
toolchain: ${{ inputs.rust-version }}
|
||||
targets: ${{ inputs.target }}
|
||||
components: rustfmt, clippy
|
||||
components: ${{ inputs.install-test-tools == 'true' && 'rustfmt, clippy' || '' }}
|
||||
|
||||
- name: Install Zig
|
||||
if: inputs.install-cross-tools == 'true'
|
||||
@@ -86,12 +105,24 @@ runs:
|
||||
uses: taiki-e/install-action@a21ae4029b089b9ddc45704028756f51ab8abe48 # cargo-zigbuild
|
||||
|
||||
- name: Install cargo-nextest
|
||||
if: inputs.install-test-tools == 'true'
|
||||
uses: taiki-e/install-action@96c7780c1d8a2b8723e12031def873a434d39d8d # nextest
|
||||
|
||||
- name: Setup Rust cache
|
||||
uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2
|
||||
with:
|
||||
cache-all-crates: true
|
||||
# false is rust-cache's own default. With true, cleanup.ts returns
|
||||
# *before* pruning ~/.cargo/registry/src, and config.ts archives the
|
||||
# whole registry — so every cache carried the unpacked source tree of
|
||||
# every dependency, not just "a few extra crates".
|
||||
#
|
||||
# No coverage is lost: getPackages runs `cargo metadata --all-features`,
|
||||
# a strict superset of any single lane's feature closure, and -sys crates
|
||||
# are explicitly exempted from pruning (their src timestamps would
|
||||
# otherwise trigger rebuilds). Anything pruned is re-unpacked from the
|
||||
# .crate files still in registry/cache, whose mtimes crates.io
|
||||
# normalises, so cargo fingerprints stay valid.
|
||||
cache-all-crates: false
|
||||
cache-on-failure: true
|
||||
shared-key: ${{ inputs.cache-shared-key }}
|
||||
save-if: ${{ inputs.cache-save-if }}
|
||||
|
||||
@@ -37,6 +37,7 @@ jobs:
|
||||
name: Cancel Closed PR Runs
|
||||
if: github.event_name == 'pull_request' && github.event.action == 'closed'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Explain cancellation run
|
||||
run: echo "PR closed; this run only cancels older runs in the same concurrency group."
|
||||
@@ -45,8 +46,11 @@ jobs:
|
||||
name: Architecture Migration Rules
|
||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install ripgrep
|
||||
run: |
|
||||
|
||||
@@ -39,7 +39,12 @@ on:
|
||||
- 'scripts/security/check_preview_release_workflow.sh'
|
||||
- 'scripts/security/check_workflow_pins.sh'
|
||||
schedule:
|
||||
- cron: '0 3 * * 0' # Weekly on Sunday 03:00 UTC (staggered after the midnight ci/build crons)
|
||||
# Daily, not weekly. This schedule exists to catch RustSec advisories
|
||||
# published against an unchanged dependency tree; at weekly cadence a new
|
||||
# advisory could sit unnoticed for seven days. The check list is unchanged —
|
||||
# splitting it into a light daily advisories-only run and a weekly full run
|
||||
# would create runs where sources/bans/licenses go unverified.
|
||||
- cron: '0 3 * * *' # Daily 03:00 UTC (staggered after the midnight ci/build crons)
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -59,6 +64,7 @@ jobs:
|
||||
name: Cancel Closed PR Runs
|
||||
if: github.event_name == 'pull_request' && github.event.action == 'closed'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Explain cancellation run
|
||||
run: echo "PR closed; this run only cancels older runs in the same concurrency group."
|
||||
@@ -74,11 +80,32 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
cache-shared-key: rustfs-cargo-deny
|
||||
persist-credentials: false
|
||||
|
||||
# cargo-deny compiles nothing, so the full setup composite (apt packages,
|
||||
# protoc, flatc, nextest, rustfmt/clippy) was pure overhead here. It does
|
||||
# still need a real cargo: `cargo deny check` runs `cargo metadata`, and
|
||||
# Cargo.toml pins datafusion and s3s as git dependencies, which must be
|
||||
# materialised into ~/.cargo/git — a cold clone is hundreds of MB, so the
|
||||
# cache stays.
|
||||
- name: Install Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
|
||||
|
||||
# Was relying on the composite's default, which used to be "true": every
|
||||
# PR touching Cargo.toml/Cargo.lock saved a second, PR-scoped copy of this
|
||||
# cache and pushed the main-scoped lanes out of the 10GB quota. The
|
||||
# default is now "false", but state it explicitly — see
|
||||
# scripts/security/check_cache_save_if.sh.
|
||||
- name: Setup Rust cache
|
||||
uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2
|
||||
with:
|
||||
# Same reasoning as the setup composite: true archives every
|
||||
# dependency's unpacked source tree.
|
||||
cache-all-crates: false
|
||||
cache-on-failure: true
|
||||
shared-key: rustfs-cargo-deny
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
|
||||
- name: Install cargo-deny
|
||||
uses: taiki-e/install-action@bffeee26d4db9be238a4ea78d8826604ebcb594d # v2
|
||||
@@ -96,16 +123,28 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Report unpinned GitHub Actions
|
||||
run: ./scripts/security/check_workflow_pins.sh --enforce
|
||||
|
||||
- name: Check setup cache-save-if is explicit
|
||||
run: ./scripts/security/check_cache_save_if.sh
|
||||
|
||||
- name: Check every job declares a timeout
|
||||
run: ./scripts/security/check_job_timeouts.sh
|
||||
|
||||
- name: Check checkouts clear their credentials
|
||||
run: ./scripts/security/check_persist_credentials.sh
|
||||
|
||||
- name: Check preview release workflow policy
|
||||
run: ./scripts/security/check_preview_release_workflow.sh
|
||||
|
||||
dependency-review:
|
||||
name: Dependency Review
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
if: github.event_name == 'pull_request' && github.event.action != 'closed'
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -113,6 +152,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Dependency Review
|
||||
uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5
|
||||
@@ -125,3 +166,28 @@ jobs:
|
||||
# conscious re-review of the license/provenance claim (backlog#1181).
|
||||
allow-dependencies-licenses: pkg:cargo/rustfs-uring@0.1.0
|
||||
comment-summary-in-pr: always
|
||||
|
||||
alert-on-failure:
|
||||
name: Alert on scheduled failure
|
||||
# dependency-review is deliberately excluded: it only runs on pull_request,
|
||||
# so it can never contribute a failure to a scheduled run.
|
||||
needs: [cargo-deny, workflow-pin-report]
|
||||
# A scheduled cargo-deny failure usually means the dependency tree just
|
||||
# matched a newly published advisory — the single most important signal this
|
||||
# workflow produces, and until now it was only visible to whoever happened to
|
||||
# open the Actions tab. Same ci-8 mechanism coverage.yml and
|
||||
# e2e-replication-nightly.yml already use.
|
||||
if: always() && github.event_name == 'schedule' && contains(needs.*.result, 'failure')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Open or update failure-tracking issue
|
||||
uses: ./.github/actions/schedule-failure-issue
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -50,12 +50,18 @@ on:
|
||||
- "**/*.svg"
|
||||
- ".gitignore"
|
||||
- ".dockerignore"
|
||||
- "flake.lock"
|
||||
schedule:
|
||||
- cron: "0 1 * * 0" # Weekly on Sunday 01:00 UTC (staggered after the ci.yml midnight cron)
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build_docker:
|
||||
description: "Build and push Docker images after binary build"
|
||||
# Advisory only. docker.yml triggers on workflow_run and its job-level
|
||||
# condition requires the triggering event to be a tag push, so a manual
|
||||
# dispatch of this workflow never produces images regardless of this
|
||||
# value. Kept because the summary step reports it; wiring it up would
|
||||
# mean teaching docker.yml's version parser a second event shape.
|
||||
description: "Build and push Docker images after binary build (ignored: dispatch runs never reach docker.yml)"
|
||||
required: false
|
||||
default: true
|
||||
type: boolean
|
||||
@@ -83,6 +89,7 @@ jobs:
|
||||
build-check:
|
||||
name: Build Strategy Check
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
outputs:
|
||||
should_build: ${{ steps.check.outputs.should_build }}
|
||||
build_type: ${{ steps.check.outputs.build_type }}
|
||||
@@ -92,6 +99,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Determine build strategy
|
||||
id: check
|
||||
@@ -164,6 +173,7 @@ jobs:
|
||||
name: Prepare Platform Matrix
|
||||
needs: build-check
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
outputs:
|
||||
matrix: ${{ steps.select.outputs.matrix }}
|
||||
selected: ${{ steps.select.outputs.selected }}
|
||||
@@ -171,10 +181,14 @@ jobs:
|
||||
- name: Select target platforms
|
||||
id: select
|
||||
shell: bash
|
||||
env:
|
||||
# via env, not interpolation: a dispatch input is free-form text and
|
||||
# would otherwise be pasted into the script for bash to evaluate.
|
||||
RAW_PLATFORMS: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.platforms || 'all' }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
selected="${{ github.event_name == 'workflow_dispatch' && github.event.inputs.platforms || 'all' }}"
|
||||
selected="$RAW_PLATFORMS"
|
||||
selected="$(echo "${selected}" | tr -d '[:space:]')"
|
||||
if [[ -z "${selected}" ]]; then
|
||||
selected="all"
|
||||
@@ -245,6 +259,7 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Rust environment
|
||||
@@ -253,9 +268,17 @@ jobs:
|
||||
rust-version: stable
|
||||
target: ${{ matrix.target }}
|
||||
cache-shared-key: build-${{ matrix.target }}
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/') }}
|
||||
# main only. A cache saved on refs/tags/X is scoped to that tag: no
|
||||
# other tag, no main run and no PR can restore it, so every release
|
||||
# cycle wrote up to 12 entries of 1-2GB (preview tag plus final tag,
|
||||
# six legs each) that nobody could read, evicting the hot lanes from
|
||||
# the repo-wide 10GB quota. Tag builds still restore the main-scoped
|
||||
# cache, since default-branch caches are readable from every ref.
|
||||
# The one real cost: re-running a failed leg of the same tag no longer
|
||||
# finds that tag's own warm cache and falls back to main's.
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
install-cross-tools: ${{ matrix.cross }}
|
||||
install-test-tools: 'false'
|
||||
|
||||
- name: Download static console assets
|
||||
shell: bash
|
||||
@@ -702,9 +725,14 @@ jobs:
|
||||
needs: [ build-check, build-rustfs ]
|
||||
if: always() && needs.build-check.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Build completion summary
|
||||
shell: bash
|
||||
env:
|
||||
# dispatch input via env: free-form text must not be pasted into the
|
||||
# script for bash to evaluate.
|
||||
INPUT_BUILD_DOCKER: ${{ github.event.inputs.build_docker }}
|
||||
run: |
|
||||
BUILD_TYPE="${{ needs.build-check.outputs.build_type }}"
|
||||
VERSION="${{ needs.build-check.outputs.version }}"
|
||||
@@ -746,7 +774,7 @@ jobs:
|
||||
echo "🐳 Docker Images:"
|
||||
if [[ "$BUILD_TYPE" == "preview" ]]; then
|
||||
echo "⏭️ Preview tags do not publish Docker images"
|
||||
elif [[ "${{ github.event.inputs.build_docker }}" == "false" ]]; then
|
||||
elif [[ "$INPUT_BUILD_DOCKER" == "false" ]]; then
|
||||
echo "⏭️ Docker image build was skipped (binary only build)"
|
||||
elif [[ "$BUILD_STATUS" == "success" ]]; then
|
||||
echo "🔄 Docker images will be built and pushed automatically via workflow_run event"
|
||||
@@ -760,6 +788,7 @@ jobs:
|
||||
needs: [ build-check, build-rustfs ]
|
||||
if: startsWith(github.ref, 'refs/tags/') && (needs.build-check.outputs.build_type == 'preview' || needs.build-check.outputs.build_type == 'release' || needs.build-check.outputs.build_type == 'prerelease')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: write
|
||||
outputs:
|
||||
@@ -769,6 +798,7 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Create GitHub Release
|
||||
@@ -819,12 +849,15 @@ jobs:
|
||||
needs: [ build-check, build-rustfs, create-release ]
|
||||
if: startsWith(github.ref, 'refs/tags/') && (needs.build-check.outputs.build_type == 'preview' || needs.build-check.outputs.build_type == 'release' || needs.build-check.outputs.build_type == 'prerelease')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Download all build artifacts
|
||||
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
|
||||
@@ -910,6 +943,7 @@ jobs:
|
||||
needs: [ build-check, publish-release ]
|
||||
if: startsWith(github.ref, 'refs/tags/') && (needs.build-check.outputs.build_type == 'release' || needs.build-check.outputs.build_type == 'prerelease')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Update latest.json
|
||||
env:
|
||||
@@ -969,6 +1003,7 @@ jobs:
|
||||
needs: [ build-check, create-release, upload-release-assets ]
|
||||
if: startsWith(github.ref, 'refs/tags/') && (needs.build-check.outputs.build_type == 'preview' || needs.build-check.outputs.build_type == 'release' || needs.build-check.outputs.build_type == 'prerelease')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
# Copyright 2026 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.
|
||||
|
||||
# Sole writer of the Rust dependency caches that ci.yml restores.
|
||||
#
|
||||
# Why this is a separate workflow rather than steps inside ci.yml: ci.yml's
|
||||
# concurrency group cancels in-progress runs on main pushes, and merges land far
|
||||
# faster than its 70-minute pipeline. Measured over 15 consecutive main pushes:
|
||||
# 12 cancelled, 2 failed, 0 succeeded. A cancelled run never reaches
|
||||
# Swatinem/rust-cache's post step (cache-on-failure does not cover cancellation),
|
||||
# so the writer lanes were saving nothing and every PR paid a cold restore —
|
||||
# 11.8-20.9 minutes of "Setup Rust environment" against 0.7-3.4 warm.
|
||||
#
|
||||
# Splitting cache writing out of the test pipeline lets ci.yml keep cancelling
|
||||
# superseded runs (which is correct — nobody needs test results for a commit
|
||||
# that is already three merges behind) while the caches still get written.
|
||||
#
|
||||
# The group below deliberately does NOT cancel in progress; see the comment on
|
||||
# it for how that bounds concurrency and why it is scoped by event.
|
||||
#
|
||||
# Each job below owns exactly one shared-key and is the only place that sets
|
||||
# cache-save-if to anything but 'false' for it; every lane in ci.yml reads.
|
||||
# scripts/security/check_cache_save_if.sh keeps the declarations explicit.
|
||||
#
|
||||
# The builds are supersets of what the reading lanes compile, because a reader
|
||||
# restores only what the writer saved. Feature resolution matters here: a lane
|
||||
# built with e2e-test-hooks resolves dependency features differently, which
|
||||
# changes -Cmetadata, so the plain build does not cover it. See
|
||||
# rustfs/backlog#1600.
|
||||
|
||||
name: Cache Warm
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
# Mirrors ci.yml's push paths-ignore: if a commit cannot change what ci.yml
|
||||
# compiles, it cannot change what ci.yml needs restored either.
|
||||
paths-ignore:
|
||||
- "**.md"
|
||||
- "docs/**"
|
||||
- "deploy/**"
|
||||
- "scripts/dev_*.sh"
|
||||
- "scripts/probe.sh"
|
||||
- "LICENSE*"
|
||||
- ".gitignore"
|
||||
- ".dockerignore"
|
||||
- "README*"
|
||||
- "**/*.png"
|
||||
- "**/*.jpg"
|
||||
- "**/*.svg"
|
||||
- ".github/workflows/build.yml"
|
||||
- ".github/workflows/docker.yml"
|
||||
- ".github/workflows/audit.yml"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
emit_timings:
|
||||
description: >-
|
||||
Also emit cargo --timings for the ci-dev build and upload it. Used to
|
||||
decide whether sccache is worth adopting (rustfs/backlog#1601 gate).
|
||||
required: false
|
||||
default: false
|
||||
type: boolean
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Scoped by event. A push run and a dispatch run do not compete: GitHub keeps
|
||||
# one running plus one pending per group, so with a single shared group a
|
||||
# manually dispatched run was displaced as pending by the next merge and
|
||||
# cancelled — observed three times in a row, which made the --timings gate in
|
||||
# rustfs/backlog#1601 effectively impossible to trigger while main was busy.
|
||||
#
|
||||
# Still no cancel-in-progress: a burst of merges collapses into "current run
|
||||
# finishes, newest queued run follows" rather than a pile-up, which is what
|
||||
# bounds this workflow to one self-hosted runner per event type.
|
||||
#
|
||||
# The two paths can now overlap and race to save the same key. That is benign:
|
||||
# the loser finds the key already present and skips, and both builds produce the
|
||||
# same artifacts from the same commit.
|
||||
concurrency:
|
||||
group: cache-warm-${{ github.event_name }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
# Readers: test-and-lint, test-ilm-integration-serial, build-rustfs-debug-binary,
|
||||
# e2e-tests, e2e-full.
|
||||
warm-ci-dev:
|
||||
name: Warm ci-dev
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-dev
|
||||
cache-save-if: 'true'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
# rustfs/backlog#1601 gate. sccache can only cache compilation units whose
|
||||
# --emit includes link, so it covers workspace rlibs and nothing else:
|
||||
# clippy is metadata-only, and the ~100 test binaries, the rustfs bin and
|
||||
# every build script invoke the system linker. Before spending a bucket,
|
||||
# credentials and a supply-chain boundary on it, measure how much of the
|
||||
# build is actually rlib codegen.
|
||||
#
|
||||
# Read from the report: workspace lib codegen as a share of the build, and
|
||||
# s3select-query's own rlib as a share. The plan adopts sccache only above
|
||||
# 50% and 25% respectively; if linking dominates instead, the answer is
|
||||
# mold/lld plus split-debuginfo, which is exactly the part sccache cannot
|
||||
# touch. Off by default — this doubles the ci-dev build.
|
||||
- name: Build ci-dev superset (with --timings)
|
||||
if: inputs.emit_timings
|
||||
env:
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
run: cargo build --workspace --all-targets --timings
|
||||
|
||||
- name: Upload cargo timings report
|
||||
if: inputs.emit_timings
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
||||
with:
|
||||
name: cargo-timings-ci-dev
|
||||
path: target/cargo-timings/
|
||||
retention-days: 30
|
||||
if-no-files-found: error
|
||||
|
||||
# --all-targets covers the test binaries nextest builds, including
|
||||
# e2e_test, which test-and-lint's own run excludes. The second build adds
|
||||
# the e2e-test-hooks feature resolution that build-rustfs-debug-binary uses
|
||||
# and that no lint lane enables.
|
||||
- name: Build ci-dev superset
|
||||
env:
|
||||
# Same limit ci.yml puts on its nextest step: this builds the same
|
||||
# ~100 workspace test binaries, and three concurrent links saturate the
|
||||
# self-hosted runner's overlay I/O and can wedge Cargo (#5394).
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
run: |
|
||||
cargo build --workspace --all-targets
|
||||
cargo build -p rustfs --bins --features e2e-test-hooks
|
||||
|
||||
# Runs before rust-cache's post step, so these are the sizes it is about
|
||||
# to archive. Reported so the cache-all-crates decision stays evidence-led:
|
||||
# registry/src is what that flag prunes, registry/cache is what the pruned
|
||||
# sources are re-unpacked from. See rustfs/backlog#1600.
|
||||
- name: Report cache input sizes
|
||||
if: always()
|
||||
run: |
|
||||
# tee, not a plain redirect: sent only to $GITHUB_STEP_SUMMARY these
|
||||
# numbers are readable in the UI but absent from the job log, and the
|
||||
# REST API exposes the log, not the summary — which made the figures
|
||||
# unreachable for exactly the scripted comparison they exist for.
|
||||
sizes="$(du -sh ~/.cargo/registry/src ~/.cargo/registry/cache \
|
||||
~/.cargo/registry/index ~/.cargo/git target 2>/dev/null || true)"
|
||||
echo "cache-input-sizes-begin"
|
||||
printf '%s\n' "$sizes"
|
||||
echo "cache-input-sizes-end"
|
||||
{
|
||||
echo "### Cache input sizes (ci-dev)"
|
||||
echo '```'
|
||||
printf '%s\n' "$sizes"
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
# Readers: test-and-lint-rio-v2, build-rustfs-debug-binary-rio-v2.
|
||||
warm-ci-feat-rio:
|
||||
name: Warm ci-feat-rio
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-feat-rio
|
||||
cache-save-if: 'true'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Build ci-feat-rio superset
|
||||
run: |
|
||||
cargo build -p rustfs -p rustfs-ecstore --all-targets --features rio-v2
|
||||
cargo build -p rustfs --bins --features rio-v2,e2e-test-hooks
|
||||
|
||||
# Readers: the swift and sftp legs of test-and-lint-protocols. Built in
|
||||
# sequence rather than as `--features swift,sftp`, which is a combination no
|
||||
# lane actually compiles; running both leaves the union in target/.
|
||||
warm-ci-feat-proto:
|
||||
name: Warm ci-feat-proto
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-feat-proto
|
||||
cache-save-if: 'true'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Build ci-feat-proto superset
|
||||
run: |
|
||||
cargo build -p rustfs -p rustfs-protocols --all-targets --features swift
|
||||
cargo build -p rustfs -p rustfs-protocols --all-targets --features sftp
|
||||
|
||||
# Reader: uring-integration. Runs on ubuntu-latest to match it: rust-cache's
|
||||
# key covers runner.os and arch but not the runner label or image, so a cache
|
||||
# written on sm-standard-4 would be restored by the hosted runner as if it
|
||||
# belonged to it.
|
||||
warm-ci-uring:
|
||||
name: Warm ci-uring
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-uring
|
||||
cache-save-if: 'true'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Install build dependencies
|
||||
run: sudo apt-get update && sudo apt-get install -y protobuf-compiler
|
||||
|
||||
- name: Build ci-uring superset
|
||||
run: cargo build -p rustfs-ecstore --all-targets
|
||||
@@ -12,18 +12,24 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Companion to ci.yml for the required "Test and Lint" status check.
|
||||
# Companion to ci.yml for required status checks.
|
||||
#
|
||||
# ci.yml skips docs-only pull requests via paths-ignore, but the branch
|
||||
# ruleset requires a check named "Test and Lint" — without this workflow a
|
||||
# docs-only PR would wait on that check forever. This workflow triggers on
|
||||
# exactly the paths ci.yml ignores and reports an instant success under the
|
||||
# same job name. Mixed PRs trigger both workflows and the real check still
|
||||
# gates: a required check with any failing run blocks the merge.
|
||||
# ci.yml skips docs-only pull requests via paths-ignore, but the branch ruleset
|
||||
# requires a check named "Test and Lint" — without this workflow a docs-only PR
|
||||
# would wait on it forever. This workflow triggers on exactly the paths ci.yml
|
||||
# ignores and reports success under the same job name. Mixed PRs trigger both
|
||||
# workflows and the real check still gates: a required check with any failing
|
||||
# run blocks the merge.
|
||||
# https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/defining-the-mergeability-of-pull-requests/troubleshooting-required-status-checks#handling-skipped-but-required-checks
|
||||
#
|
||||
# "Quick Checks" is mirrored here ahead of the ruleset change that will make it
|
||||
# required too (rustfs/backlog#1599). Until that change lands this job is
|
||||
# inert; mirroring it first is what lets the ruleset change happen without
|
||||
# stranding docs-only PRs on a check nobody reports.
|
||||
#
|
||||
# Keep the paths list below in sync with the pull_request paths-ignore list
|
||||
# in ci.yml.
|
||||
# in ci.yml, and keep the quick-checks steps below byte-identical to the
|
||||
# quick-checks job in ci.yml.
|
||||
|
||||
name: Continuous Integration (docs only)
|
||||
|
||||
@@ -47,17 +53,82 @@ on:
|
||||
- ".github/workflows/build.yml"
|
||||
- ".github/workflows/docker.yml"
|
||||
- ".github/workflows/audit.yml"
|
||||
- "flake.lock"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test-and-lint:
|
||||
name: Test and Lint
|
||||
# Deliberately NOT a bare `echo`. Once "Quick Checks" becomes a required
|
||||
# check, ci.yml gates every expensive job behind it, so a mixed PR reports
|
||||
# two check runs with this name: the real one (45-51s) and this companion.
|
||||
# GitHub has no written contract for how it picks between same-named
|
||||
# required check runs ("latest wins" vs "any failure blocks"), so instead of
|
||||
# relying on ordering we make both runs execute the same commands against
|
||||
# the same merge ref — their conclusions are then necessarily identical and
|
||||
# the choice does not matter. Keep these steps byte-identical to the
|
||||
# quick-checks job in ci.yml (a guard script that asserts this, and the paths
|
||||
# sync below, is tracked in rustfs/backlog#1603).
|
||||
#
|
||||
# For a genuinely docs-only PR this adds no strictness (no code changed, so
|
||||
# fmt and the guards always pass) and costs ~50s of ubuntu-latest.
|
||||
quick-checks:
|
||||
name: Quick Checks
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install ripgrep
|
||||
run: sudo apt-get update && sudo apt-get install -y ripgrep
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
|
||||
with:
|
||||
components: rustfmt
|
||||
|
||||
- name: Check code formatting
|
||||
run: cargo fmt --all --check
|
||||
|
||||
- name: Check unsafe code allowances
|
||||
run: ./scripts/check_unsafe_code_allowances.sh
|
||||
|
||||
- name: Check layered dependencies
|
||||
run: ./scripts/check_layer_dependencies.sh
|
||||
|
||||
- name: Check architecture migration rules
|
||||
run: ./scripts/check_architecture_migration_rules.sh
|
||||
|
||||
- name: Check tokio io-uring feature guard
|
||||
run: ./scripts/check_no_tokio_io_uring.sh
|
||||
|
||||
- name: Check extension schema boundaries
|
||||
run: ./scripts/check_extension_schema_boundaries.sh
|
||||
|
||||
- name: Check body-cache whitelist guard
|
||||
run: ./scripts/check_body_cache_whitelist.sh
|
||||
|
||||
- name: Check no planning docs committed
|
||||
run: ./scripts/check_no_planning_docs.sh
|
||||
|
||||
- name: Check CI paths stay in sync
|
||||
run: ./scripts/check_ci_paths_sync.sh
|
||||
|
||||
- name: Check io_uring lane --lib precondition
|
||||
run: ./scripts/check_uring_lane_lib_only.sh
|
||||
|
||||
test-and-lint:
|
||||
name: Test and Lint
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# Docs-only PRs skip the full code CI, but they are exactly where a
|
||||
# planning-type document could be slipped in (git add -f bypasses
|
||||
|
||||
+214
-63
@@ -33,6 +33,7 @@ on:
|
||||
- ".github/workflows/build.yml"
|
||||
- ".github/workflows/docker.yml"
|
||||
- ".github/workflows/audit.yml"
|
||||
- "flake.lock"
|
||||
pull_request:
|
||||
types: [ opened, synchronize, reopened, closed ]
|
||||
branches: [ main ]
|
||||
@@ -54,6 +55,7 @@ on:
|
||||
- ".github/workflows/build.yml"
|
||||
- ".github/workflows/docker.yml"
|
||||
- ".github/workflows/audit.yml"
|
||||
- "flake.lock"
|
||||
merge_group:
|
||||
types: [ checks_requested ]
|
||||
schedule:
|
||||
@@ -81,6 +83,7 @@ jobs:
|
||||
name: Cancel Closed PR Runs
|
||||
if: github.event_name == 'pull_request' && github.event.action == 'closed'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Explain cancellation run
|
||||
run: echo "PR closed; this run only cancels older runs in the same concurrency group."
|
||||
@@ -89,13 +92,20 @@ jobs:
|
||||
name: Typos
|
||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Typos check with custom config file
|
||||
uses: crate-ci/typos@37bb98842b0d8c4ffebdb75301a13db0267cef89 # master
|
||||
|
||||
# Fast, compile-free checks that fail early so contributors get feedback in
|
||||
# ~1 minute instead of waiting for the full test job.
|
||||
#
|
||||
# These steps are mirrored byte-for-byte in ci-docs-only.yml so that a mixed
|
||||
# PR, which reports two check runs named "Quick Checks", cannot get one red
|
||||
# and one green. Edit both jobs together.
|
||||
quick-checks:
|
||||
name: Quick Checks
|
||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||
@@ -104,6 +114,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install ripgrep
|
||||
run: sudo apt-get update && sudo apt-get install -y ripgrep
|
||||
@@ -137,24 +149,48 @@ jobs:
|
||||
- name: Check no planning docs committed
|
||||
run: ./scripts/check_no_planning_docs.sh
|
||||
|
||||
- name: Check CI paths stay in sync
|
||||
run: ./scripts/check_ci_paths_sync.sh
|
||||
|
||||
- name: Check io_uring lane --lib precondition
|
||||
run: ./scripts/check_uring_lane_lib_only.sh
|
||||
|
||||
test-and-lint:
|
||||
name: Test and Lint
|
||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||
needs: [ quick-checks ]
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 90
|
||||
# Both lines are required. Job-level `permissions` replaces the workflow
|
||||
# block rather than merging with it, so declaring only `actions: write`
|
||||
# would drop `contents: read` and break this job's checkout and the
|
||||
# repo-token the setup action hands to setup-protoc.
|
||||
permissions:
|
||||
contents: read
|
||||
actions: write
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
# This job's token can cancel runs and delete Actions caches. Checkout
|
||||
# otherwise writes it into .git/config, where a PR's own build.rs or
|
||||
# proc-macro could read it back out.
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-test
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
# Every lane in this workflow reads its cache and none writes it.
|
||||
# cache-warm.yml is the sole writer for all four keys: this workflow
|
||||
# cancels superseded runs on main, and a cancelled run never reaches
|
||||
# rust-cache's post step, so writing from here saved nothing (12 of 15
|
||||
# consecutive main-push runs were cancelled). See rustfs/backlog#1600.
|
||||
cache-shared-key: ci-dev
|
||||
cache-save-if: 'false'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Prepare test evidence
|
||||
run: |
|
||||
@@ -169,43 +205,54 @@ jobs:
|
||||
# Clippy runs before the test pass: lint failures are the most common
|
||||
# CI-only breakage and should surface in minutes, not after 20+ minutes
|
||||
# of tests.
|
||||
# Sampled too: clippy is the natural control arm for any CARGO_BUILD_JOBS
|
||||
# experiment, since --all-targets is check-only for workspace members and
|
||||
# never links the ~100 test binaries the limit exists to throttle.
|
||||
- name: Run clippy lints
|
||||
run: cargo clippy --all-targets -- -D warnings
|
||||
run: |
|
||||
./scripts/ci/resource_sampler.sh start clippy
|
||||
trap './scripts/ci/resource_sampler.sh stop' EXIT
|
||||
cargo clippy --all-targets -- -D warnings
|
||||
|
||||
- name: Run nextest tests
|
||||
env:
|
||||
# Three concurrent workspace test links saturate the self-hosted
|
||||
# runner's overlay I/O and can wedge Cargo until the 75m timeout.
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
# #5394 mitigation, now under a measured experiment (backlog#1601).
|
||||
#
|
||||
# 2 was chosen when three concurrent workspace test links were believed
|
||||
# to saturate the runner's overlay I/O and wedge Cargo until the 75m
|
||||
# timeout. cgroup v2 readings from the sampler show the pod actually
|
||||
# has 14 CPUs and 28GB (peak use 2.1GB), so 2 throttles compilation to
|
||||
# a seventh of what is available and memory was never the constraint —
|
||||
# the label name "sm-standard-4" had led everyone, including the
|
||||
# original mitigation, to assume 4 cores.
|
||||
#
|
||||
# Raised to 3 on main pushes and manual dispatches; PRs keep 2 so the
|
||||
# merge path is untouched while the experiment runs.
|
||||
#
|
||||
# Dispatch is included because push alone cannot supply the samples:
|
||||
# this workflow cancels superseded runs on main, and only 4 of the last
|
||||
# 20 push-triggered Test and Lint jobs reached a terminal state — at
|
||||
# that rate ten samples would take roughly fifty merges. The
|
||||
# concurrency group is scoped by event_name, so a dispatched run has
|
||||
# its own group and is not cancelled by merge traffic, which makes the
|
||||
# sample collectable on demand rather than by waiting.
|
||||
#
|
||||
# Baseline over 17 samples at 2:
|
||||
# median nextest/clippy step ratio 1.95, spread 1.85-2.06. The gate-2
|
||||
# criterion is that ratio dropping at least 10% (below ~1.76) with no
|
||||
# 75m timeout and no run showing three consecutive samples of
|
||||
# rustc/collect2/rust-lld in D state. If it does not, the conclusion is
|
||||
# "this limit is not the bottleneck" — fix it back at 2 and record the
|
||||
# experiment, which is a result, not a failure.
|
||||
#
|
||||
# Must stay step-level: rust-cache hashes CARGO/CC/CFLAGS/CXX/CMAKE/RUST
|
||||
# prefixed variables from process.env into the cache key, so promoting
|
||||
# this to job level would rotate every key on this lane.
|
||||
CARGO_BUILD_JOBS: ${{ (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && '3' || '2' }}
|
||||
run: |
|
||||
mkdir -p artifacts/test-and-lint
|
||||
# Evidence sampler for issue #5394: the post-mortem pgrep below runs
|
||||
# only after `timeout` has already TERM'd the whole cargo process
|
||||
# group, so it cannot name a wedged process. Sample system and
|
||||
# process state every 60s instead; the last samples before the
|
||||
# timeout show what was stuck (rustc, linker, build script, memory
|
||||
# pressure, ...). The log rides along in the existing artifact.
|
||||
(
|
||||
while true; do
|
||||
{
|
||||
echo "=== $(date --utc --iso-8601=seconds)"
|
||||
echo "--- load"; cat /proc/loadavg
|
||||
echo "--- psi"; grep -H . /proc/pressure/* 2>/dev/null || true
|
||||
echo "--- mem"; free -m
|
||||
echo "--- disk"; df -h / /home/runner 2>/dev/null || df -h /
|
||||
echo "--- top-rss"
|
||||
ps -eo pid,ppid,stat,etime,rss,pcpu,args --sort=-rss | head -15
|
||||
echo "--- build/test processes"
|
||||
ps -eo pid,ppid,stat,etime,rss,pcpu,args | grep -E '[c]argo|[r]ustc|[n]extest|[c]ollect2|rust-ll[d]|[b]uild-script|deps[/]' || true
|
||||
echo "--- d-state (uninterruptible IO)"
|
||||
ps -eo pid,stat,etime,args | awk 'NR > 1 && $2 ~ /D/' || true
|
||||
echo
|
||||
} >> artifacts/test-and-lint/sampler.log 2>&1 || true
|
||||
sleep 60
|
||||
done
|
||||
) &
|
||||
sampler_pid=$!
|
||||
trap 'kill "${sampler_pid}" 2>/dev/null || true' EXIT
|
||||
./scripts/ci/resource_sampler.sh start nextest
|
||||
trap './scripts/ci/resource_sampler.sh stop' EXIT
|
||||
set +e
|
||||
NEXTEST_HIDE_PROGRESS_BAR=1 timeout --verbose --signal=TERM --kill-after=30s 75m \
|
||||
cargo nextest run --profile ci --all --exclude e2e_test \
|
||||
@@ -277,6 +324,48 @@ jobs:
|
||||
- name: Run rebalance/decommission migration proofs
|
||||
run: ./scripts/check_migration_gate_count.sh
|
||||
|
||||
# Early stop. Once this job has failed the PR cannot merge, so the sibling
|
||||
# lanes are burning runners on a result nobody can act on: on run
|
||||
# 30674613104 three lanes had already failed while Test and Lint and the
|
||||
# rio-v2 variant kept going past 70 minutes.
|
||||
#
|
||||
# Only this job may cancel. The lanes that are NOT required checks
|
||||
# (protocols, ILM, e2e, s3-tests) must never hold that power: a flake in
|
||||
# one of them would turn the required "Test and Lint" into `cancelled`,
|
||||
# which blocks the merge. Today a maintainer can merge with sftp red, and
|
||||
# that has to stay true.
|
||||
#
|
||||
# These steps run last so the `if: always()` artifact upload above still
|
||||
# captures logs and diagnostics before the run goes away.
|
||||
- name: Annotate early-stop reason
|
||||
if: failure() && github.event_name == 'pull_request'
|
||||
run: |
|
||||
echo "## CI early-stop" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "Job \`${GITHUB_JOB}\` (Test and Lint) failed; cancelling run ${GITHUB_RUN_ID} to free runners." >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "Sibling jobs showing **cancelled** were stopped by this job, not by their own failure." >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
# curl rather than `gh`: every existing `gh` call in this repo runs on
|
||||
# ubuntu-latest, and the sm-standard-* images are custom and trimmed (they
|
||||
# ship no C toolchain, see the e2e job below), so `gh` is not known to
|
||||
# exist here.
|
||||
#
|
||||
# Fork PRs are excluded explicitly instead of relying on the error path:
|
||||
# their GITHUB_TOKEN is forced read-only and job-level permissions cannot
|
||||
# raise it, so the call would always 403. Skipping keeps their logs clean.
|
||||
- name: Cancel run on failure (same-repo PR only)
|
||||
if: >-
|
||||
failure() && github.event_name == 'pull_request'
|
||||
&& github.event.pull_request.head.repo.full_name == github.repository
|
||||
continue-on-error: true
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
curl -fsS -X POST \
|
||||
-H "Authorization: Bearer ${GH_TOKEN}" \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "X-GitHub-Api-Version: 2022-11-28" \
|
||||
"${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/cancel" || true
|
||||
|
||||
# Dedicated serial lane for the ILM / lifecycle integration tests. These tests
|
||||
# drive the object layer through process-global singletons (the GLOBAL_ENV
|
||||
# ECStore, the global tier-config manager, background-expiry workers) and bind
|
||||
@@ -290,6 +379,7 @@ jobs:
|
||||
test-ilm-integration-serial:
|
||||
name: ILM Integration (serial)
|
||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||
needs: [ quick-checks ]
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
@@ -297,14 +387,16 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-ilm-serial
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
cache-shared-key: ci-dev
|
||||
cache-save-if: 'false'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
# test_transition_and_restore_flows was re-enabled by rustfs/backlog#1303:
|
||||
# its "missing xl.meta on disk2" was a test-util bug (open_disk hardcoded
|
||||
@@ -327,6 +419,7 @@ jobs:
|
||||
test-and-lint-rio-v2:
|
||||
name: Test and Lint (rio-v2)
|
||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||
needs: [ quick-checks ]
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
@@ -334,14 +427,16 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-test-rio-v2
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
cache-shared-key: ci-feat-rio
|
||||
cache-save-if: 'false'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Run rio-v2 clippy lints
|
||||
run: cargo clippy -p rustfs -p rustfs-ecstore --all-targets --features rio-v2 -- -D warnings
|
||||
@@ -354,10 +449,17 @@ jobs:
|
||||
test-and-lint-protocols:
|
||||
name: "Test and Lint (${{ matrix.features.name }})"
|
||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||
needs: [ quick-checks ]
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
# On a PR, one failing protocol leg is enough to know the PR is not ready,
|
||||
# so stop the sibling leg instead of paying another ~40 minutes for it.
|
||||
# Everywhere else (main pushes, the merge queue, the weekly schedule) keep
|
||||
# the full signal: there we want to know whether swift AND sftp are broken,
|
||||
# not just whichever failed first. This is the only part of the early-stop
|
||||
# work that also covers fork PRs, since it needs no token.
|
||||
fail-fast: ${{ github.event_name == 'pull_request' }}
|
||||
matrix:
|
||||
features:
|
||||
- name: swift
|
||||
@@ -369,14 +471,16 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-test-${{ matrix.features.name }}
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
cache-shared-key: ci-feat-proto
|
||||
cache-save-if: 'false'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Run clippy with ${{ matrix.features.name }}
|
||||
run: |
|
||||
@@ -389,6 +493,7 @@ jobs:
|
||||
build-rustfs-debug-binary:
|
||||
name: Build RustFS Debug Binary
|
||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||
needs: [ quick-checks ]
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
@@ -396,14 +501,16 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-rustfs-debug-binary
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-shared-key: ci-dev
|
||||
cache-save-if: 'false'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Build debug binary
|
||||
run: cargo build -p rustfs --bins --features e2e-test-hooks
|
||||
@@ -419,6 +526,7 @@ jobs:
|
||||
build-rustfs-debug-binary-rio-v2:
|
||||
name: Build RustFS Debug Binary (rio-v2)
|
||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||
needs: [ quick-checks ]
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
@@ -426,14 +534,16 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-rustfs-debug-binary-rio-v2
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-shared-key: ci-feat-rio
|
||||
cache-save-if: 'false'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Build debug binary with rio-v2
|
||||
run: cargo build -p rustfs --bins --features rio-v2,e2e-test-hooks
|
||||
@@ -448,6 +558,14 @@ jobs:
|
||||
|
||||
uring-integration:
|
||||
name: io_uring Integration (real)
|
||||
# The pull_request trigger includes `closed` purely so the concurrency
|
||||
# group cancels in-flight runs of a closed PR; every other job opts out of
|
||||
# that run with this guard (or is skipped through its `needs` chain). This
|
||||
# job had neither, so each closed/merged PR really ran the whole io_uring
|
||||
# suite (measured 4m17s / 7m19s / 7m31s on runs 30678272341 / 30678117601 /
|
||||
# 30662728539) and kept the cancellation run in progress for minutes.
|
||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||
needs: [ quick-checks ]
|
||||
# GitHub-hosted ubuntu-latest runs a recent kernel with io_uring and, unlike
|
||||
# a container, applies no seccomp filter that would block io_uring_setup — so
|
||||
# the probe succeeds and the tests exercise the real UringBackend/FdCache/
|
||||
@@ -458,17 +576,24 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
# Keeps its own key rather than joining ci-dev. rust-cache's key is
|
||||
# built from runner.os/arch plus rustc and lockfile fingerprints — it
|
||||
# does NOT include the runner label or image. ubuntu-latest and
|
||||
# sm-standard-4 are therefore indistinguishable to it, so sharing a key
|
||||
# would let two different system images overwrite each other's
|
||||
# artifacts, and would make a 2-core hosted runner unpack ci-dev's ~3GB
|
||||
# instead of this lane's ~1.3GB. cache-warm.yml warms this key on
|
||||
# ubuntu-latest for the same reason.
|
||||
cache-shared-key: ci-uring
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
|
||||
- name: Install build dependencies
|
||||
run: sudo apt-get update && sudo apt-get install -y protobuf-compiler
|
||||
cache-save-if: 'false'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
# ext4 supports O_DIRECT; the runner's default TMPDIR may sit on tmpfs or
|
||||
# overlayfs, where open(O_DIRECT) returns EINVAL/EOPNOTSUPP and the native
|
||||
@@ -495,7 +620,17 @@ jobs:
|
||||
RUSTFS_IO_URING_READ_ENABLE: "true"
|
||||
RUSTFS_URING_TESTS_MUST_RUN: "1"
|
||||
TMPDIR: /mnt/rustfs-odirect
|
||||
run: cargo test -p rustfs-ecstore uring_ -- --test-threads=1 --nocapture
|
||||
# --lib narrows what gets compiled, not what gets run: every selected
|
||||
# test lives in the lib target. The 7 integration binaries under
|
||||
# crates/ecstore/tests/ each reported "running 0 tests" here, so they
|
||||
# were compiled and linked for nothing.
|
||||
#
|
||||
# The `uring_` filter must stay exactly as it is. libtest matches on
|
||||
# substring, so it also selects names containing `during_` — 6 of the 18
|
||||
# selected tests are such incidental matches. Narrowing the filter to
|
||||
# `io_uring` would silently drop them, which is a coverage change.
|
||||
# scripts/check_uring_lane_lib_only.sh guards the --lib precondition.
|
||||
run: cargo test -p rustfs-ecstore --lib uring_ -- --test-threads=1 --nocapture
|
||||
|
||||
e2e-tests:
|
||||
name: End-to-End Tests
|
||||
@@ -505,6 +640,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# Full setup with dependency caching: the smoke-suite step below
|
||||
# compiles the e2e_test crate, which pulls in most of the workspace.
|
||||
@@ -513,9 +650,9 @@ jobs:
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-e2e
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
cache-shared-key: ci-dev
|
||||
cache-save-if: 'false'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
# Download after the cache restore so the freshly built binary from the
|
||||
# build job always wins over anything restored into target/debug.
|
||||
@@ -589,14 +726,16 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-e2e
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
cache-shared-key: ci-dev
|
||||
cache-save-if: 'false'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
# Download after the cache restore so the freshly built binary from the
|
||||
# build job always wins over anything restored into target/debug.
|
||||
@@ -632,6 +771,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Clean up previous test run
|
||||
run: |
|
||||
@@ -686,6 +827,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Download debug binary
|
||||
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
|
||||
@@ -746,12 +889,20 @@ jobs:
|
||||
# evaluates ILM within ~2s of the due time, well inside the poll window.
|
||||
s3-lifecycle-behavior-tests:
|
||||
name: S3 Lifecycle Behavior Tests
|
||||
needs: [ build-rustfs-debug-binary ]
|
||||
# Also gated on e2e-tests, matching s3-implemented-tests: when the e2e smoke
|
||||
# suite is already red this lane cannot tell us anything new, and it holds a
|
||||
# sm-standard-4 for up to 30 minutes doing so. Both lanes only download the
|
||||
# prebuilt debug binary (no cargo build), and s3-implemented-tests — which
|
||||
# already waits on e2e-tests — finishes later anyway, so a green PR's total
|
||||
# wall clock is unchanged.
|
||||
needs: [ build-rustfs-debug-binary, e2e-tests ]
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Download debug binary
|
||||
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
|
||||
|
||||
@@ -22,11 +22,18 @@ on:
|
||||
issue_comment:
|
||||
types: [created, edited]
|
||||
|
||||
# Least privilege at the top, widened per job below. This workflow runs on
|
||||
# pull_request_target and issue_comment, so it holds full secrets on every fork
|
||||
# PR and on any comment anyone writes — the one place in this repository where a
|
||||
# compromised action would be handed a repo-write token. It does not check out
|
||||
# or execute PR code, so there is no pwn-request path today, but the blast
|
||||
# radius should not depend on that staying true.
|
||||
#
|
||||
# contents: write in particular was never used: the signature records are
|
||||
# written to rustfs/cla through the scoped app token created below, and nothing
|
||||
# here writes to this repository's contents.
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
checks: write
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.event.issue.number || github.ref }}
|
||||
@@ -36,14 +43,26 @@ jobs:
|
||||
cancel-closed-pr-runs:
|
||||
name: Cancel Closed PR Runs
|
||||
if: github.event_name == 'pull_request_target' && github.event.action == 'closed'
|
||||
# Echoes one line; the run exists only so the concurrency group cancels the
|
||||
# in-flight run of a closed PR.
|
||||
permissions: {}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Explain cancellation run
|
||||
run: echo "PR closed; this run only cancels older runs in the same concurrency group."
|
||||
|
||||
cla:
|
||||
if: ${{ (github.event_name != 'issue_comment' || github.event.issue.pull_request) && (github.event_name != 'pull_request_target' || github.event.action != 'closed') }}
|
||||
# checks: write reports the merge-queue check run; pull-requests and issues
|
||||
# let cla-bot comment and label. contents stays read — see the note above.
|
||||
permissions:
|
||||
contents: read
|
||||
checks: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Report CLA result for merge queue
|
||||
if: github.event_name == 'merge_group'
|
||||
|
||||
@@ -62,14 +62,16 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-coverage
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Install cargo-llvm-cov
|
||||
uses: taiki-e/install-action@bffeee26d4db9be238a4ea78d8826604ebcb594d # v2
|
||||
@@ -116,6 +118,8 @@ jobs:
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Open or update failure-tracking issue
|
||||
uses: ./.github/actions/schedule-failure-issue
|
||||
with:
|
||||
|
||||
@@ -85,6 +85,7 @@ jobs:
|
||||
github.event.workflow_run.head_branch != 'main' &&
|
||||
!contains(github.event.workflow_run.head_branch, '-preview'))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
outputs:
|
||||
should_build: ${{ steps.check.outputs.should_build }}
|
||||
should_push: ${{ steps.check.outputs.should_push }}
|
||||
@@ -97,11 +98,18 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
# For workflow_run events, checkout the specific commit that triggered the workflow
|
||||
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
|
||||
|
||||
- name: Check build conditions
|
||||
id: check
|
||||
env:
|
||||
# dispatch inputs via env, not `${{ }}` interpolation: they are
|
||||
# free-form strings and would otherwise be evaluated by bash.
|
||||
INPUT_VERSION: ${{ github.event.inputs.version }}
|
||||
INPUT_PUSH_IMAGES: ${{ github.event.inputs.push_images }}
|
||||
INPUT_FORCE_REBUILD: ${{ github.event.inputs.force_rebuild }}
|
||||
run: |
|
||||
should_build=false
|
||||
should_push=false
|
||||
@@ -202,9 +210,9 @@ jobs:
|
||||
|
||||
elif [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
|
||||
# Manual trigger
|
||||
input_version="${{ github.event.inputs.version }}"
|
||||
input_version="$INPUT_VERSION"
|
||||
version="${input_version}"
|
||||
should_push="${{ github.event.inputs.push_images }}"
|
||||
should_push="$INPUT_PUSH_IMAGES"
|
||||
should_build=true
|
||||
|
||||
# Get short SHA
|
||||
@@ -212,7 +220,7 @@ jobs:
|
||||
|
||||
echo "🎯 Manual Docker build triggered:"
|
||||
echo " 📋 Requested version: $input_version"
|
||||
echo " 🔧 Force rebuild: ${{ github.event.inputs.force_rebuild }}"
|
||||
echo " 🔧 Force rebuild: $INPUT_FORCE_REBUILD"
|
||||
echo " 🚀 Push images: $should_push"
|
||||
|
||||
case "$input_version" in
|
||||
@@ -298,6 +306,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
||||
@@ -333,32 +343,28 @@ jobs:
|
||||
CREATE_LATEST="${{ needs.build-check.outputs.create_latest }}"
|
||||
VARIANT_SUFFIX="${{ matrix.suffix }}"
|
||||
|
||||
# Convert version format for Dockerfile compatibility
|
||||
# Convert version format for Dockerfile compatibility. The former
|
||||
# DOCKER_CHANNEL was "release" down every branch and was passed as a
|
||||
# build-arg no Dockerfile declares, so it is gone.
|
||||
case "$VERSION" in
|
||||
"latest")
|
||||
# For stable latest, use RELEASE=latest + release CHANNEL
|
||||
DOCKER_RELEASE="latest"
|
||||
DOCKER_CHANNEL="release"
|
||||
;;
|
||||
v*)
|
||||
# For versioned releases (v1.0.0), remove 'v' prefix for Dockerfile
|
||||
DOCKER_RELEASE="${VERSION#v}"
|
||||
DOCKER_CHANNEL="release"
|
||||
;;
|
||||
*)
|
||||
# For other versions, pass as-is
|
||||
DOCKER_RELEASE="${VERSION}"
|
||||
DOCKER_CHANNEL="release"
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "docker_release=$DOCKER_RELEASE" >> "$GITHUB_OUTPUT"
|
||||
echo "docker_channel=$DOCKER_CHANNEL" >> "$GITHUB_OUTPUT"
|
||||
|
||||
echo "🐳 Docker build parameters:"
|
||||
echo " - Original version: $VERSION"
|
||||
echo " - Docker RELEASE: $DOCKER_RELEASE"
|
||||
echo " - Docker CHANNEL: $DOCKER_CHANNEL"
|
||||
|
||||
# Generate tags based on build type
|
||||
# Only support release and prerelease builds (no development builds)
|
||||
@@ -412,18 +418,24 @@ jobs:
|
||||
push: ${{ needs.build-check.outputs.should_push == 'true' }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: |
|
||||
type=gha,scope=docker-${{ matrix.variant }}
|
||||
cache-to: |
|
||||
type=gha,mode=max,scope=docker-${{ matrix.variant }}
|
||||
# No layer cache. This build compiles nothing — it downloads a
|
||||
# release zip and runs apk/apt — so the cache could only save the
|
||||
# minute or two those take, while creating a correctness problem: with
|
||||
# RELEASE=latest the binary URL is resolved by curl *inside* a RUN
|
||||
# layer, and the layer key does not include what that resolved to. A
|
||||
# rebuild at the same RELEASE value (dispatch with version=latest, or
|
||||
# a re-run of the same version) would hit the old layer and ship the
|
||||
# previous release's binary. mode=max also consumed the same 10GB
|
||||
# Actions cache quota the Rust lanes are fighting over.
|
||||
#
|
||||
# Only RELEASE is passed: it is the sole build-arg the Dockerfiles
|
||||
# declare besides TARGETARCH. BUILDTIME, VERSION, BUILD_TYPE, REVISION
|
||||
# and CHANNEL were never read by any stage (and BUILDTIME's $(date ...)
|
||||
# was a literal here, not a shell substitution). BUILD_DATE and VCS_REF
|
||||
# are declared by the Dockerfiles but deliberately left unset —
|
||||
# supplying them would change the published image labels.
|
||||
build-args: |
|
||||
BUILDTIME=$(date -u +'%Y-%m-%dT%H:%M:%SZ')
|
||||
VERSION=${{ needs.build-check.outputs.version }}
|
||||
BUILD_TYPE=${{ needs.build-check.outputs.build_type }}
|
||||
REVISION=${{ github.sha }}
|
||||
RELEASE=${{ steps.meta.outputs.docker_release }}
|
||||
CHANNEL=${{ steps.meta.outputs.docker_channel }}
|
||||
BUILDKIT_INLINE_CACHE=1
|
||||
provenance: true
|
||||
sbom: true
|
||||
# Add retry mechanism by splitting the build process
|
||||
@@ -439,6 +451,7 @@ jobs:
|
||||
needs: [ build-check, build-docker ]
|
||||
if: needs.build-check.outputs.should_build == 'true' && needs.build-check.outputs.should_push == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: read
|
||||
security-events: write
|
||||
@@ -493,6 +506,7 @@ jobs:
|
||||
needs: [ build-check, build-docker ]
|
||||
if: always() && needs.build-check.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Docker build completion summary
|
||||
run: |
|
||||
|
||||
@@ -64,14 +64,16 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-e2e-repl
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
# awscurl lets the STS dual-node test actually exercise its path. Without
|
||||
# it the test skips gracefully with a visible log line
|
||||
@@ -124,6 +126,8 @@ jobs:
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Open or update failure-tracking issue
|
||||
uses: ./.github/actions/schedule-failure-issue
|
||||
with:
|
||||
|
||||
@@ -45,6 +45,13 @@
|
||||
# The PR gate (ci.yml s3-implemented-tests) is unaffected: it avoids Docker
|
||||
# via DEPLOY_MODE=binary and defers all pip setup to run.sh's self-bootstrap.
|
||||
|
||||
# DISABLED. This workflow is switched off in the repository's Actions settings
|
||||
# (state: disabled_manually) and does not run on any trigger, including its cron
|
||||
# and workflow_dispatch. That state lives in GitHub's UI and is invisible when
|
||||
# reading this file, which has already misled at least one audit — hence this
|
||||
# banner. Re-enabling is a UI action; anyone doing so should first check that the
|
||||
# workflow still matches the current CI layout. See rustfs/backlog#1603.
|
||||
#
|
||||
name: e2e-s3tests
|
||||
|
||||
on:
|
||||
@@ -135,6 +142,8 @@ jobs:
|
||||
TEST_MODE: ${{ matrix.test-mode }}
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# Provision Python explicitly rather than trusting the runner image to
|
||||
# ship a working pip (ci-1: a bare python3 without pip is what broke the
|
||||
@@ -354,6 +363,8 @@ jobs:
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Open or update failure-tracking issue
|
||||
uses: ./.github/actions/schedule-failure-issue
|
||||
with:
|
||||
|
||||
@@ -12,6 +12,13 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# DISABLED. This workflow is switched off in the repository's Actions settings
|
||||
# (state: disabled_manually) and does not run on any trigger, including its cron
|
||||
# and workflow_dispatch. That state lives in GitHub's UI and is invisible when
|
||||
# reading this file, which has already misled at least one audit — hence this
|
||||
# banner. Re-enabling is a UI action; anyone doing so should first check that the
|
||||
# workflow still matches the current CI layout. See rustfs/backlog#1603.
|
||||
#
|
||||
name: Fuzz
|
||||
|
||||
on:
|
||||
@@ -59,6 +66,7 @@ jobs:
|
||||
name: Cancel Closed PR Runs
|
||||
if: github.event_name == 'pull_request' && github.event.action == 'closed'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Explain cancellation run
|
||||
run: echo "PR closed; this run only cancels older runs in the same concurrency group."
|
||||
@@ -79,13 +87,14 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: nightly
|
||||
cache-shared-key: fuzz-${{ hashFiles('fuzz/Cargo.lock') }}
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' || github.event_name == 'schedule' }}
|
||||
|
||||
- name: Install cargo-fuzz
|
||||
@@ -145,6 +154,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Download prebuilt fuzz binaries
|
||||
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
|
||||
@@ -200,6 +211,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Download prebuilt fuzz binaries
|
||||
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
|
||||
@@ -247,6 +260,8 @@ jobs:
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Open or update failure-tracking issue
|
||||
uses: ./.github/actions/schedule-failure-issue
|
||||
with:
|
||||
|
||||
@@ -32,6 +32,7 @@ permissions:
|
||||
jobs:
|
||||
build-helm-package:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
if: |
|
||||
(github.event_name == 'workflow_dispatch' && !contains(github.event.inputs.version, '-preview')) ||
|
||||
(
|
||||
@@ -49,16 +50,26 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout helm chart repo
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# Both inputs reach the shell through env rather than `${{ }}`
|
||||
# interpolation. A git ref name may contain `$(...)` — anything without a
|
||||
# space is a legal tag — and interpolation pastes it into the script
|
||||
# verbatim, where bash would run it. Reading "$RAW_INPUT" instead makes it
|
||||
# data.
|
||||
- name: Normalize release version
|
||||
id: version
|
||||
env:
|
||||
RAW_INPUT: ${{ github.event.inputs.version }}
|
||||
RAW_BRANCH: ${{ github.event.workflow_run.head_branch }}
|
||||
run: |
|
||||
set -eux
|
||||
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||
RAW="${{ github.event.inputs.version }}"
|
||||
RAW="$RAW_INPUT"
|
||||
else
|
||||
RAW="${{ github.event.workflow_run.head_branch }}"
|
||||
RAW="$RAW_BRANCH"
|
||||
fi
|
||||
|
||||
case "$RAW" in
|
||||
@@ -73,10 +84,13 @@ jobs:
|
||||
./scripts/helm_chart_version.sh "$RAW_TAG"
|
||||
|
||||
- name: Replace chart version and app version
|
||||
env:
|
||||
CHART_VERSION: ${{ steps.version.outputs.chart_version }}
|
||||
APP_VERSION: ${{ steps.version.outputs.app_version }}
|
||||
run: |
|
||||
set -eux
|
||||
sed -i -E 's/^version:.*/version: "${{ steps.version.outputs.chart_version }}"/' helm/rustfs/Chart.yaml
|
||||
sed -i -E 's/^appVersion:.*/appVersion: "${{ steps.version.outputs.app_version }}"/' helm/rustfs/Chart.yaml
|
||||
sed -i -E "s/^version:.*/version: \"${CHART_VERSION}\"/" helm/rustfs/Chart.yaml
|
||||
sed -i -E "s/^appVersion:.*/appVersion: \"${APP_VERSION}\"/" helm/rustfs/Chart.yaml
|
||||
|
||||
- name: Set up Helm
|
||||
uses: azure/setup-helm@b9e51907a09c216f16ebe8536097933489208112 # v4.3.0
|
||||
@@ -101,6 +115,7 @@ jobs:
|
||||
|
||||
publish-helm-package:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
needs: [ build-helm-package ]
|
||||
if: needs.build-helm-package.result == 'success'
|
||||
|
||||
@@ -108,6 +123,8 @@ jobs:
|
||||
- name: Checkout helm package repo
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
# persist-credentials-exempt: this checkout's token IS the push credential —
|
||||
# the job git-pushes to rustfs/helm below. Clearing it breaks chart publishing.
|
||||
repository: rustfs/helm
|
||||
token: ${{ secrets.RUSTFS_HELM_PACKAGE }}
|
||||
|
||||
@@ -123,11 +140,19 @@ jobs:
|
||||
- name: Generate index
|
||||
run: helm repo index . --url https://charts.rustfs.com
|
||||
|
||||
# app_version is derived from the triggering tag name, and this job holds
|
||||
# the cross-repository push token with rustfs/helm already checked out —
|
||||
# the worst place in the repo to paste an attacker-influenced string into
|
||||
# a shell line. Passed through env so bash treats it as data.
|
||||
- name: Push helm package and index file
|
||||
env:
|
||||
GIT_USERNAME: ${{ secrets.USERNAME }}
|
||||
GIT_EMAIL: ${{ secrets.EMAIL_ADDRESS }}
|
||||
APP_VERSION: ${{ needs.build-helm-package.outputs.app_version }}
|
||||
run: |
|
||||
set -eux
|
||||
git config --global user.name "${{ secrets.USERNAME }}"
|
||||
git config --global user.email "${{ secrets.EMAIL_ADDRESS }}"
|
||||
git config --global user.name "${GIT_USERNAME}"
|
||||
git config --global user.email "${GIT_EMAIL}"
|
||||
git add .
|
||||
git commit -m "Update rustfs helm package with ${{ needs.build-helm-package.outputs.app_version }}." || echo "No changes to commit"
|
||||
git commit -m "Update rustfs helm package with ${APP_VERSION}." || echo "No changes to commit"
|
||||
git push origin main
|
||||
|
||||
@@ -12,6 +12,13 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# DISABLED. This workflow is switched off in the repository's Actions settings
|
||||
# (state: disabled_manually) and does not run on any trigger, including its cron
|
||||
# and workflow_dispatch. That state lives in GitHub's UI and is invisible when
|
||||
# reading this file, which has already misled at least one audit — hence this
|
||||
# banner. Re-enabling is a UI action; anyone doing so should first check that the
|
||||
# workflow still matches the current CI layout. See rustfs/backlog#1603.
|
||||
#
|
||||
name: "issue-translator"
|
||||
on:
|
||||
issue_comment:
|
||||
@@ -26,6 +33,7 @@ permissions:
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: usthe/issues-translate-action@b41f55ddc81d7d54bd542a4f289fe28ec081898e # v2.7
|
||||
with:
|
||||
|
||||
@@ -18,11 +18,25 @@
|
||||
# This is NOT a PR gate. The fixtures are real MinIO backend trees generated on
|
||||
# the fly (they are gitignored, never committed), so the job regenerates them
|
||||
# each run with Docker and then runs the `#[ignore]` reader tests in
|
||||
# crates/ecstore/tests/minio_generated_read_test.rs.
|
||||
# rustfs/src/storage/minio_generated_read_test.rs.
|
||||
#
|
||||
# Scope: end-to-end MinIO-to-RustFS SSE interop is NOT implemented yet. Both
|
||||
# envelope parsers reject MinIO's own wrapped-DEK shape — see
|
||||
# `is_data_key_envelope` in crates/kms/src/encryption/dek.rs and the
|
||||
# `deny_unknown_fields` `LocalSseDekEnvelope` in rustfs/src/storage/sse.rs — and
|
||||
# closing that gap is tracked in rustfs/backlog#1638. Treat this job as the
|
||||
# harness for #1638, not as standing evidence that a MinIO migration reads back.
|
||||
#
|
||||
# Runner: GitHub-hosted `ubuntu-latest`. It reliably ships Docker + Python,
|
||||
# unlike the self-hosted fleet, whose pods drift in Docker/pip availability
|
||||
# (see the infra note in e2e-s3tests.yml). Nightly + manual only.
|
||||
# DISABLED. This workflow is switched off in the repository's Actions settings
|
||||
# (state: disabled_manually) and does not run on any trigger, including its cron
|
||||
# and workflow_dispatch. That state lives in GitHub's UI and is invisible when
|
||||
# reading this file, which has already misled at least one audit — hence this
|
||||
# banner. Re-enabling is a UI action; anyone doing so should first check that the
|
||||
# workflow still matches the current CI layout. See rustfs/backlog#1603.
|
||||
#
|
||||
name: minio-interop
|
||||
|
||||
on:
|
||||
@@ -48,23 +62,58 @@ jobs:
|
||||
env:
|
||||
# Fixed 32-byte test KMS key baked into the fixture lab; not a secret.
|
||||
RUSTFS_MINIO_STATIC_KMS_KEY_B64: IyqsU3kMFloCNup4BsZtf/rmfHVcTgznO2F25CkEH1g=
|
||||
# Single definition of "the interop tests", shared by the guard step and
|
||||
# the run step so the two cannot drift apart.
|
||||
#
|
||||
# These used to live in crates/ecstore/tests/minio_generated_read_test.rs
|
||||
# and were selected with `-p rustfs-ecstore -E
|
||||
# 'binary(minio_generated_read_test)'`. #5435 moved them into the `rustfs`
|
||||
# crate as a `#[cfg(test)] mod`, which deleted that test binary; the
|
||||
# selector was never updated and has selected zero interop tests ever
|
||||
# since (cargo-nextest 0.9.140 now rejects it outright: "operator didn't
|
||||
# match any binary names", exit 94).
|
||||
INTEROP_PACKAGE: rustfs
|
||||
INTEROP_FEATURES: rio-v2
|
||||
INTEROP_FILTER: "test(minio_generated_read_test::)"
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-minio-interop
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
|
||||
- name: Generate real MinIO fixtures via Docker
|
||||
run: bash crates/rio-v2/tests/minio_fixture_lab/capture_via_docker.sh
|
||||
|
||||
# `binary(...)` at least dies loudly when nothing matches, but `test(...)`
|
||||
# is a perfectly valid filterset that matches zero tests, so the next
|
||||
# rename or module move would leave this job selecting nothing and
|
||||
# reporting success without executing a single interop assertion. Count
|
||||
# the selection and fail with a reason instead.
|
||||
#
|
||||
# Count only `filter-match.status == "matches"`: the top-level
|
||||
# `test-count` in the JSON is the package total and ignores `-E` entirely.
|
||||
- name: Assert the interop selector still matches tests
|
||||
run: |
|
||||
set -euo pipefail
|
||||
count="$(cargo nextest list --run-ignored all \
|
||||
-p "$INTEROP_PACKAGE" --features "$INTEROP_FEATURES" \
|
||||
-E "$INTEROP_FILTER" --message-format json \
|
||||
| python3 -c 'import json,sys; d=json.load(sys.stdin); print(sum(1 for s in d.get("rust-suites", {}).values() for t in s.get("testcases", {}).values() if t.get("filter-match", {}).get("status") == "matches"))')"
|
||||
echo "interop tests selected: ${count}"
|
||||
if [ "${count}" -eq 0 ]; then
|
||||
echo "::error::Selector '${INTEROP_FILTER}' in package '${INTEROP_PACKAGE}' matched 0 tests. The MinIO interop reader tests have moved or been renamed again; fix the selector instead of letting this job pass without running them. Context: rustfs/backlog#1638."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Run MinIO interop reader tests
|
||||
run: |
|
||||
cargo nextest run --run-ignored ignored-only \
|
||||
-p rustfs-ecstore --features rio-v2 \
|
||||
-E 'binary(minio_generated_read_test)'
|
||||
cargo nextest run --run-ignored ignored-only --no-tests=fail \
|
||||
-p "$INTEROP_PACKAGE" --features "$INTEROP_FEATURES" \
|
||||
-E "$INTEROP_FILTER"
|
||||
|
||||
@@ -45,6 +45,13 @@
|
||||
# docker-capable self-hosted `dind-sm-standard-2` label was the alternative but
|
||||
# has fewer cores and reintroduces fleet-state risk for no reliability gain.
|
||||
|
||||
# DISABLED. This workflow is switched off in the repository's Actions settings
|
||||
# (state: disabled_manually) and does not run on any trigger, including its cron
|
||||
# and workflow_dispatch. That state lives in GitHub's UI and is invisible when
|
||||
# reading this file, which has already misled at least one audit — hence this
|
||||
# banner. Re-enabling is a UI action; anyone doing so should first check that the
|
||||
# workflow still matches the current CI layout. See rustfs/backlog#1603.
|
||||
#
|
||||
name: mint
|
||||
|
||||
on:
|
||||
@@ -118,6 +125,8 @@ jobs:
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Enable buildx
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
||||
@@ -263,6 +272,8 @@ jobs:
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Open or update failure-tracking issue
|
||||
uses: ./.github/actions/schedule-failure-issue
|
||||
with:
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# 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: Nightly GNU Build
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0 * * *"
|
||||
timezone: "Asia/Shanghai"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: nightly-gnu-build-main-${{ github.event_name }}
|
||||
cancel-in-progress: ${{ github.event_name == 'workflow_dispatch' }}
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: 1
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build x86_64 GNU
|
||||
runs-on: sm-standard-2
|
||||
timeout-minutes: 150
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
- name: Checkout main branch
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
ref: main
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
cache-shared-key: build-x86_64-unknown-linux-gnu
|
||||
cache-save-if: 'false'
|
||||
install-build-packaging-tools: 'false'
|
||||
install-test-tools: 'false'
|
||||
|
||||
- name: Build RustFS
|
||||
run: cargo build --release --locked --target x86_64-unknown-linux-gnu -p rustfs --bins
|
||||
@@ -19,9 +19,12 @@ on:
|
||||
schedule:
|
||||
- cron: '0 5 * * 0' # Weekly on Sunday 05:00 UTC (staggered after the midnight ci/build crons)
|
||||
|
||||
# GITHUB_TOKEN only needs to read the repository here: the branch push and the
|
||||
# pull request are both created by update-flake-lock using the
|
||||
# FLAKE_UPDATE_TOKEN PAT below, not by this token. Leaving write on it hands a
|
||||
# repo-write credential to an unattended weekly job that does not use it.
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
@@ -37,6 +40,10 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
# persist-credentials-exempt: update-flake-lock pushes the branch and opens
|
||||
# the PR. It passes FLAKE_UPDATE_TOKEN to create-pull-request itself rather
|
||||
# than reusing .git/config, but that is unverified — exempt until a
|
||||
# workflow_dispatch run confirms it (rustfs/backlog#1602).
|
||||
|
||||
- name: Install Nix
|
||||
uses: DeterminateSystems/determinate-nix-action@629b284231c2a82554b724e357e47fc6020833c8 # v3
|
||||
|
||||
@@ -12,6 +12,13 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# DISABLED. This workflow is switched off in the repository's Actions settings
|
||||
# (state: disabled_manually) and does not run on any trigger, including its cron
|
||||
# and workflow_dispatch. That state lives in GitHub's UI and is invisible when
|
||||
# reading this file, which has already misled at least one audit — hence this
|
||||
# banner. Re-enabling is a UI action; anyone doing so should first check that the
|
||||
# workflow still matches the current CI layout. See rustfs/backlog#1603.
|
||||
#
|
||||
name: Nix CI
|
||||
|
||||
on:
|
||||
@@ -46,6 +53,7 @@ jobs:
|
||||
name: Cancel Closed PR Runs
|
||||
if: github.event_name == 'pull_request' && github.event.action == 'closed'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Explain cancellation run
|
||||
run: echo "PR closed; this run only cancels older runs in the same concurrency group."
|
||||
@@ -63,6 +71,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Nix
|
||||
uses: DeterminateSystems/determinate-nix-action@4eea0b33e3d1f02ecfe37cf16e7204c424009606 # v3.21.0
|
||||
|
||||
@@ -22,6 +22,13 @@
|
||||
# a deliberate correctness cost (e.g. the #4221 fsync durability fix) is
|
||||
# recorded but does not block (rustfs/backlog#935 correction 1).
|
||||
|
||||
# DISABLED. This workflow is switched off in the repository's Actions settings
|
||||
# (state: disabled_manually) and does not run on any trigger, including its cron
|
||||
# and workflow_dispatch. That state lives in GitHub's UI and is invisible when
|
||||
# reading this file, which has already misled at least one audit — hence this
|
||||
# banner. Re-enabling is a UI action; anyone doing so should first check that the
|
||||
# workflow still matches the current CI layout. See rustfs/backlog#1603.
|
||||
#
|
||||
name: Performance A/B
|
||||
|
||||
on:
|
||||
@@ -92,6 +99,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
@@ -99,7 +108,6 @@ jobs:
|
||||
rust-version: stable
|
||||
cache-shared-key: warp-ab-${{ hashFiles('**/Cargo.lock') }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build release rustfs
|
||||
run: cargo build --release --bin rustfs
|
||||
@@ -142,6 +150,7 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0 # baseline is built from origin/main
|
||||
|
||||
- name: Setup Rust environment
|
||||
@@ -150,7 +159,6 @@ jobs:
|
||||
rust-version: stable
|
||||
cache-shared-key: warp-ab-${{ hashFiles('**/Cargo.lock') }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Install warp
|
||||
run: |
|
||||
@@ -162,13 +170,15 @@ jobs:
|
||||
|
||||
- name: Decide exemption
|
||||
id: exempt
|
||||
env:
|
||||
INPUT_ALLOW_REGRESSION: ${{ github.event.inputs.allow_regression }}
|
||||
run: |
|
||||
allow="false"
|
||||
if [[ "${{ github.event_name }}" == "pull_request" ]] \
|
||||
&& ${{ contains(github.event.pull_request.labels.*.name, 'perf-deliberate-tradeoff') }}; then
|
||||
allow="true"
|
||||
fi
|
||||
if [[ "${{ github.event.inputs.allow_regression }}" == "true" ]]; then
|
||||
if [[ "$INPUT_ALLOW_REGRESSION" == "true" ]]; then
|
||||
allow="true"
|
||||
fi
|
||||
echo "allow_regression=$allow" >> "$GITHUB_OUTPUT"
|
||||
@@ -215,8 +225,34 @@ jobs:
|
||||
cp target/release/rustfs baseline-bin/rustfs
|
||||
echo "built=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build baseline on cache miss (different candidate)
|
||||
id: baseline_build
|
||||
if: >-
|
||||
steps.baseline_cache.outputs.cache-hit != 'true' &&
|
||||
steps.commits.outputs.baseline_sha != steps.commits.outputs.candidate_sha
|
||||
run: |
|
||||
set -euo pipefail
|
||||
baseline_root="$RUNNER_TEMP/rustfs-baseline-${{ github.run_id }}"
|
||||
baseline_target="$RUNNER_TEMP/rustfs-baseline-target-${{ github.run_id }}"
|
||||
git worktree add --detach "$baseline_root" "${{ steps.commits.outputs.baseline_sha }}"
|
||||
cargo build --release --manifest-path "$baseline_root/Cargo.toml" --bin rustfs --target-dir "$baseline_target"
|
||||
mkdir -p baseline-bin
|
||||
cp "$baseline_target/release/rustfs" baseline-bin/rustfs
|
||||
git worktree remove --force "$baseline_root"
|
||||
echo "built=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build candidate binary
|
||||
id: candidate_build
|
||||
if: steps.commits.outputs.baseline_sha != steps.commits.outputs.candidate_sha
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cargo build --release --bin rustfs
|
||||
mkdir -p candidate-bin
|
||||
cp target/release/rustfs candidate-bin/rustfs
|
||||
echo "built=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Save self-healed baseline to cache
|
||||
if: steps.selfheal.outputs.built == 'true'
|
||||
if: steps.selfheal.outputs.built == 'true' || steps.baseline_build.outputs.built == 'true'
|
||||
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||
with:
|
||||
path: baseline-bin/rustfs
|
||||
@@ -224,54 +260,58 @@ jobs:
|
||||
|
||||
- name: Run warp A/B and gate
|
||||
id: ab
|
||||
env:
|
||||
INPUT_DURATION: ${{ github.event.inputs.duration }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Budget note: with perf-3's cached baseline the nightly does no source
|
||||
# build on a cache hit, so the wall-clock is dominated by the short warp
|
||||
# matrix — duration/rounds/cooldown are kept small to fit all 24 cells
|
||||
# (6 workloads x 2 phases x 2 drive-sync) rather than dropping cells.
|
||||
# The formal runner executes A1 baseline -> B1 candidate -> B2 candidate
|
||||
# -> A2 baseline for each workload and drive-sync cell. It requires three
|
||||
# rounds per leg to emit tail latency and error-rate evidence.
|
||||
# --health-timeout 180 outlasts the server's own 120s startup-readiness
|
||||
# budget, which the rig's previous 60s health poll undershot (the first
|
||||
# two nightly failures). perf-6 recalibrates these once the noise study
|
||||
# lands.
|
||||
duration="${{ github.event.inputs.duration || '12s' }}"
|
||||
duration="${INPUT_DURATION:-12s}"
|
||||
baseline_sha="${{ steps.commits.outputs.baseline_sha }}"
|
||||
candidate_sha="${{ steps.commits.outputs.candidate_sha }}"
|
||||
baseline_hit="${{ steps.baseline_cache.outputs.cache-hit }}"
|
||||
selfheal_built="${{ steps.selfheal.outputs.built }}"
|
||||
baseline_built="${{ steps.baseline_build.outputs.built }}"
|
||||
candidate_built="${{ steps.candidate_build.outputs.built }}"
|
||||
|
||||
args=(--duration "$duration" --rounds 2 --cooldown 5 --health-timeout 180)
|
||||
args=(--duration "$duration" --rounds 3 --cooldown 5 --health-timeout 180 --baseline-revision "$baseline_sha" --candidate-revision "$candidate_sha")
|
||||
|
||||
if [[ "$baseline_hit" == "true" || "$selfheal_built" == "true" ]]; then
|
||||
if [[ "$baseline_hit" == "true" || "$selfheal_built" == "true" || "$baseline_built" == "true" ]]; then
|
||||
chmod +x baseline-bin/rustfs
|
||||
base_bin="$PWD/baseline-bin/rustfs"
|
||||
args+=(--baseline-bin "$base_bin")
|
||||
if [[ "$baseline_hit" == "true" ]]; then
|
||||
base_src="actions-cache (rustfs-baseline-$baseline_sha)"
|
||||
else
|
||||
elif [[ "$selfheal_built" == "true" ]]; then
|
||||
base_src="source build (cache self-heal, saved as rustfs-baseline-$baseline_sha)"
|
||||
else
|
||||
base_src="isolated origin/main source build (saved as rustfs-baseline-$baseline_sha)"
|
||||
fi
|
||||
if [[ "$candidate_sha" == "$baseline_sha" ]]; then
|
||||
# Nightly on main: the candidate is the same commit as the baseline,
|
||||
# so reuse the one binary for both phases and skip all builds.
|
||||
args+=(--candidate-bin "$base_bin" --skip-build)
|
||||
args+=(--candidate-bin "$base_bin")
|
||||
cand_src="same binary as baseline (same commit)"
|
||||
else
|
||||
elif [[ "$candidate_built" == "true" ]]; then
|
||||
chmod +x candidate-bin/rustfs
|
||||
args+=(--candidate-bin "$PWD/candidate-bin/rustfs")
|
||||
cand_src="source build of the checked-out ref"
|
||||
else
|
||||
echo "::error::candidate binary was not built" >&2
|
||||
exit 2
|
||||
fi
|
||||
else
|
||||
# Cache miss with candidate != baseline (opt-in PR gate only): fall
|
||||
# back to the source double-build. With the post-#4806 LTO profile
|
||||
# this will overrun the job budget and alert; rerun once the push
|
||||
# cache build for origin/main has completed, or wait for perf-7's
|
||||
# merge-base caching.
|
||||
args+=(--baseline-ref origin/main)
|
||||
base_src="source build of origin/main (cache miss)"
|
||||
cand_src="source build of the checked-out ref"
|
||||
echo "::error::baseline binary was not restored or built" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
args+=(--provenance-note "baseline commit: $baseline_sha - $base_src")
|
||||
args+=(--provenance-note "candidate commit: $candidate_sha - $cand_src")
|
||||
echo "baseline binary: $base_src"
|
||||
echo "candidate binary: $cand_src"
|
||||
|
||||
if [[ "${{ steps.exempt.outputs.allow_regression }}" == "true" ]]; then
|
||||
args+=(--allow-regression --exemption-reason "labeled perf-deliberate-tradeoff / dispatch override")
|
||||
@@ -279,7 +319,7 @@ jobs:
|
||||
# Do not let a gate FAIL abort the job here; capture status and surface
|
||||
# it after the PR comment is posted.
|
||||
set +e
|
||||
bash scripts/run_hotpath_warp_ab.sh "${args[@]}"
|
||||
bash scripts/run_hotpath_warp_abba.sh "${args[@]}"
|
||||
echo "status=$?" >> "$GITHUB_OUTPUT"
|
||||
set -e
|
||||
# Locate the newest run dir + gate.md for the summary/comment/artifact
|
||||
@@ -287,10 +327,10 @@ jobs:
|
||||
# holds server-logs/ for diagnosis.
|
||||
# Run dirs are UTC-timestamp names (no special chars); ls is safe here.
|
||||
# shellcheck disable=SC2012
|
||||
run_dir="$(ls -td target/hotpath-ab/*/ 2>/dev/null | head -n1 || true)"
|
||||
run_dir="$(ls -td target/hotpath-abba/*/ 2>/dev/null | head -n1 || true)"
|
||||
echo "run_dir=${run_dir%/}" >> "$GITHUB_OUTPUT"
|
||||
# shellcheck disable=SC2012
|
||||
gate_md="$(ls -t target/hotpath-ab/*/gate.md 2>/dev/null | head -n1 || true)"
|
||||
gate_md="$(ls -t target/hotpath-abba/*/candidate_gate.md 2>/dev/null | head -n1 || true)"
|
||||
echo "gate_md=$gate_md" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Upload A/B results
|
||||
@@ -298,10 +338,10 @@ jobs:
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
||||
with:
|
||||
name: hotpath-warp-ab-${{ github.run_number }}
|
||||
# Includes per-cell median_summary.csv / baseline_compare.csv, gate.md,
|
||||
# Includes per-cell median_summary.csv / baseline_compare.csv, both gates,
|
||||
# and server-logs/ (rustfs.log + startup env per phase) so a failed run
|
||||
# is diagnosable. Short retention: this is churny nightly debug data.
|
||||
path: target/hotpath-ab/
|
||||
path: target/hotpath-abba/
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
@@ -385,6 +425,8 @@ jobs:
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Open or update failure-tracking issue
|
||||
uses: ./.github/actions/schedule-failure-issue
|
||||
with:
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# Copyright 2026 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.
|
||||
|
||||
# Asserts that the self-hosted runners are still ephemeral — one job per pod.
|
||||
#
|
||||
# This repository is public and its pull_request jobs run on those runners,
|
||||
# executing the PR's own build.rs, proc-macros and tests. The only thing keeping
|
||||
# that code from reaching a later job is that each ARC pod handles exactly one
|
||||
# job and is then destroyed. That guarantee lives in the ARC scale-set
|
||||
# configuration, outside this repository, where it can be changed without any PR
|
||||
# — so it is asserted here from the outside, against real run data, instead of
|
||||
# being assumed.
|
||||
#
|
||||
# Monthly rather than per-PR: the property changes only when someone
|
||||
# reconfigures the scale set, and the check costs a few dozen API calls.
|
||||
# See docs/ci/runners.md and rustfs/backlog#1602.
|
||||
|
||||
name: Runner Hygiene
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 6 1 * *" # Monthly, 1st at 06:00 UTC (after the daily audit cron)
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: runner-hygiene
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
check-ephemerality:
|
||||
name: Check runner ephemerality
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# Exit 2 (inconclusive / broken) is deliberately not a pass: a window
|
||||
# where every sm-* job was still queued would otherwise look identical to
|
||||
# a clean bill of health.
|
||||
- name: Assert one job per self-hosted runner
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: ./scripts/ci/check_runner_ephemerality.sh 40
|
||||
|
||||
alert-on-failure:
|
||||
name: Alert on scheduled failure
|
||||
needs: [check-ephemerality]
|
||||
# Same ci-8 mechanism as coverage.yml, audit.yml and the nightly lanes:
|
||||
# scheduled runs file a tracking issue, manual dispatch stays quiet so
|
||||
# debugging never produces a spurious alert.
|
||||
if: always() && github.event_name == 'schedule' && contains(needs.*.result, 'failure')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Open or update failure-tracking issue
|
||||
uses: ./.github/actions/schedule-failure-issue
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -24,6 +24,13 @@
|
||||
# The run itself is expected to end red (the forced failure); only the
|
||||
# alert-on-failure job result matters.
|
||||
|
||||
# DISABLED. This workflow is switched off in the repository's Actions settings
|
||||
# (state: disabled_manually) and does not run on any trigger, including its cron
|
||||
# and workflow_dispatch. That state lives in GitHub's UI and is invisible when
|
||||
# reading this file, which has already misled at least one audit — hence this
|
||||
# banner. Re-enabling is a UI action; anyone doing so should first check that the
|
||||
# workflow still matches the current CI layout. See rustfs/backlog#1603.
|
||||
#
|
||||
name: Schedule Failure Alert Drill
|
||||
|
||||
on:
|
||||
@@ -56,6 +63,8 @@ jobs:
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Open or update failure-tracking issue
|
||||
uses: ./.github/actions/schedule-failure-issue
|
||||
with:
|
||||
|
||||
@@ -12,6 +12,13 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# DISABLED. This workflow is switched off in the repository's Actions settings
|
||||
# (state: disabled_manually) and does not run on any trigger, including its cron
|
||||
# and workflow_dispatch. That state lives in GitHub's UI and is invisible when
|
||||
# reading this file, which has already misled at least one audit — hence this
|
||||
# banner. Re-enabling is a UI action; anyone doing so should first check that the
|
||||
# workflow still matches the current CI layout. See rustfs/backlog#1603.
|
||||
#
|
||||
name: "Mark stale issues"
|
||||
on:
|
||||
schedule:
|
||||
@@ -20,6 +27,7 @@ on:
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/stale@5bef64f19d7facfb25b37b414482c7164d639639 # v9
|
||||
with:
|
||||
|
||||
@@ -15,6 +15,7 @@ concurrency:
|
||||
jobs:
|
||||
update:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: overtrue/repo-visuals-action@72f34d24769ff5d341956da2f23952594ef2f1e2 # v1.3.0
|
||||
with:
|
||||
|
||||
@@ -21,6 +21,22 @@ If repo-level instructions conflict, follow the nearest file and keep behavior a
|
||||
- Avoid redundant file reads, repeated commands, and unnecessary exploratory work once enough context is available.
|
||||
- A good result is a minimal diff with clear assumptions, no over-engineering, and independent verification that survives Adversarial Validation (below).
|
||||
|
||||
## Worktree and Disk Hygiene
|
||||
|
||||
- Unless the requester explicitly says otherwise, treat every new implementation task as isolated work: fetch the latest `origin/main`, confirm the requested change is not already present there, and create a dedicated feature branch and worktree from that exact upstream commit before editing. Do not implement new work directly in the primary checkout or reuse a worktree from another task.
|
||||
- Check available disk space before creating the worktree or starting dependency downloads, builds, tests, coverage, or other artifact-heavy commands. For long-running or artifact-heavy work, re-check disk usage at natural phase boundaries and before broad validation; if remaining space may not safely accommodate the next command, stop and reclaim task-owned artifacts before continuing.
|
||||
- Keep cleanup scoped and safe: remove generated build/test/coverage artifacts and temporary files created by the task when they are no longer needed, and never delete another task's worktree or uncommitted files. Prefer shared dependency caches where supported instead of duplicating large artifacts across worktrees.
|
||||
- At handoff, report the disk-space checks, cleanup performed, and any retained worktree or artifacts with the reason they are still needed.
|
||||
|
||||
## PR Lifecycle Monitoring
|
||||
|
||||
- Creating or updating a PR is not the terminal state. Unless the requester explicitly limits the task to PR creation, monitor the PR through its terminal state: merged, closed, or explicitly handed off because progress requires user or maintainer action.
|
||||
- While the task is active, monitor CI/check runs, review decisions and unresolved threads, mergeability and conflicts, and unexpected head/base changes. Prefer event-driven or bounded waits provided by the current environment over frequent polling; report only state changes, actionable failures, or meaningful prolonged delays.
|
||||
- Investigate every failing check and review comment before changing code. Fix failures attributable to the task, run the verification required for the new diff, push the update, respond to or resolve the corresponding review threads, and resume monitoring. Do not weaken checks, dismiss valid feedback, or retry flaky failures merely to obtain a green result.
|
||||
- Treat opening, green CI, approval, and mergeability as intermediate states. Never merge without the required reviewer approval or explicit authority. If progress depends on credentials, infrastructure, a maintainer decision, or another external action, report the exact blocker and the evidence already collected.
|
||||
- If the current execution environment cannot remain active until the next PR event, use a supported automation, monitor, or thread wakeup when available and within scope. Otherwise leave an explicit handoff containing the PR, current state, next event to observe, and pending cleanup; do not imply that background monitoring exists when none is scheduled.
|
||||
- After observing a merge, verify the commits are preserved on the upstream base, ensure the worktree is clean, remove the dedicated worktree, prune stale worktree metadata, and delete the local task branch when it is no longer in use. For a closed or abandoned PR, preserve any unmerged work unless deletion was explicitly authorized. Do not delete remote branches unless explicitly requested or repository automation owns that cleanup.
|
||||
|
||||
## Autonomy and Approval Boundaries
|
||||
|
||||
- Inquiry tasks (answer, explain, review, diagnose, plan): report findings; do not change files unless a fix is explicitly requested.
|
||||
|
||||
Generated
+152
-36
@@ -290,11 +290,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ar_archive_writer"
|
||||
version = "0.5.2"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4087686b4b0a3427190bae57a1d9a478dbb2d40c5dc1bd6e2b6d797913bdd348"
|
||||
checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6"
|
||||
dependencies = [
|
||||
"object 0.37.3",
|
||||
"object 0.39.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -599,6 +599,16 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "assert-json-diff"
|
||||
version = "2.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "astral-tokio-tar"
|
||||
version = "0.6.4"
|
||||
@@ -943,6 +953,32 @@ dependencies = [
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aws-sdk-kms"
|
||||
version = "1.114.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0b7d906608ee41e7ddea9983577ba82200435644d567d63dc34e822e088b453"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"aws-credential-types",
|
||||
"aws-runtime",
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-http",
|
||||
"aws-smithy-json",
|
||||
"aws-smithy-observability",
|
||||
"aws-smithy-runtime",
|
||||
"aws-smithy-runtime-api",
|
||||
"aws-smithy-schema",
|
||||
"aws-smithy-types",
|
||||
"aws-types",
|
||||
"bytes",
|
||||
"fastrand",
|
||||
"http 0.2.12",
|
||||
"http 1.5.0",
|
||||
"regex-lite",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aws-sdk-s3"
|
||||
version = "1.140.0"
|
||||
@@ -1158,17 +1194,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "635d23afda0a6ab48d666c4d447c4873e8d1e83518a2be2093122397e50b838e"
|
||||
dependencies = [
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-protocol-test",
|
||||
"aws-smithy-runtime-api",
|
||||
"aws-smithy-types",
|
||||
"bytes",
|
||||
"h2",
|
||||
"http 1.5.0",
|
||||
"http-body 1.1.0",
|
||||
"hyper",
|
||||
"hyper-rustls",
|
||||
"hyper-util",
|
||||
"indexmap 2.14.0",
|
||||
"pin-project-lite",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower",
|
||||
@@ -1195,6 +1237,25 @@ dependencies = [
|
||||
"aws-smithy-runtime-api",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-protocol-test"
|
||||
version = "0.64.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f76511a0e223ce78deb6a78b8afebda99cb737cfbc8a58d96dcb190f012dd40a"
|
||||
dependencies = [
|
||||
"assert-json-diff",
|
||||
"aws-smithy-runtime-api",
|
||||
"base64-simd",
|
||||
"cbor-diag",
|
||||
"ciborium",
|
||||
"http 0.2.12",
|
||||
"pretty_assertions",
|
||||
"regex-lite",
|
||||
"roxmltree",
|
||||
"serde_json",
|
||||
"thiserror 2.0.19",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-query"
|
||||
version = "0.62.0"
|
||||
@@ -1528,7 +1589,7 @@ version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array 0.14.7",
|
||||
"generic-array 0.14.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1547,7 +1608,7 @@ version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
|
||||
dependencies = [
|
||||
"generic-array 0.14.7",
|
||||
"generic-array 0.14.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1598,7 +1659,7 @@ version = "3.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dee98b0db6a962de883bf5d20362dee4d7ca0d12fe39a7c6c73c844e1cd7c1f"
|
||||
dependencies = [
|
||||
"darling 0.20.11",
|
||||
"darling 0.23.0",
|
||||
"ident_case",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
@@ -1679,9 +1740,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bytesize"
|
||||
version = "2.4.2"
|
||||
version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d7c8918969267b2932ffd5655509bbbea0833823058c378876953217f5fc50e"
|
||||
checksum = "351a3e803ee3c6eaeee6b00076b767514b37c32a73d326c3ec7abddb7d6c3493"
|
||||
|
||||
[[package]]
|
||||
name = "bytestring"
|
||||
@@ -1758,6 +1819,25 @@ dependencies = [
|
||||
"cipher 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cbor-diag"
|
||||
version = "0.1.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc245b6ecd09b23901a4fbad1ad975701fd5061ceaef6afa93a2d70605a64429"
|
||||
dependencies = [
|
||||
"bs58",
|
||||
"chrono",
|
||||
"data-encoding",
|
||||
"half",
|
||||
"nom 7.1.3",
|
||||
"num-bigint",
|
||||
"num-rational",
|
||||
"num-traits",
|
||||
"separator",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.4.0"
|
||||
@@ -1870,7 +1950,7 @@ version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common 0.1.7",
|
||||
"crypto-common 0.1.6",
|
||||
"inout 0.1.4",
|
||||
]
|
||||
|
||||
@@ -1888,9 +1968,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.4"
|
||||
version = "4.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d91e0c145792ef73a6ad36d27c75ac09f1832222a3c209689d90f534685ee5b7"
|
||||
checksum = "301b56658598e48f3648647ac6fc887be7e7108eddfa4e9b63fcf3ec58c0cadf"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
@@ -1898,9 +1978,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.2"
|
||||
version = "4.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f09628afdcc538b57f3c6341e9c8e9970f18e4a481690a64974d7023bd33548b"
|
||||
checksum = "94a65403d1a1bd28f7dc68eb8506e8874808ee5eecb59298de588e2e1407a078"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -2328,7 +2408,7 @@ version = "0.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
|
||||
dependencies = [
|
||||
"generic-array 0.14.7",
|
||||
"generic-array 0.14.9",
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
@@ -2353,11 +2433,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
|
||||
dependencies = [
|
||||
"generic-array 0.14.7",
|
||||
"generic-array 0.14.9",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
@@ -3554,7 +3634,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer 0.10.4",
|
||||
"const-oid 0.9.6",
|
||||
"crypto-common 0.1.7",
|
||||
"crypto-common 0.1.6",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
@@ -3814,7 +3894,7 @@ dependencies = [
|
||||
"crypto-bigint 0.5.5",
|
||||
"digest 0.10.7",
|
||||
"ff 0.13.1",
|
||||
"generic-array 0.14.7",
|
||||
"generic-array 0.14.9",
|
||||
"group 0.13.0",
|
||||
"hkdf 0.12.4",
|
||||
"pem-rfc7468 0.7.0",
|
||||
@@ -4259,9 +4339,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
version = "0.14.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
@@ -4274,7 +4354,7 @@ version = "1.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab4e5aa225bc56696909483320f0ff9b600f1a971b52e07a17d70f3d9b43254b"
|
||||
dependencies = [
|
||||
"generic-array 0.14.7",
|
||||
"generic-array 0.14.9",
|
||||
"rustversion",
|
||||
"typenum",
|
||||
]
|
||||
@@ -5301,7 +5381,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
||||
dependencies = [
|
||||
"block-padding 0.3.3",
|
||||
"generic-array 0.14.7",
|
||||
"generic-array 0.14.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5835,8 +5915,7 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
[[package]]
|
||||
name = "libmimalloc-sys"
|
||||
version = "0.1.49"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9"
|
||||
source = "git+https://github.com/xonatius/mimalloc_rust.git?rev=1cdadea43e9c5a0f054b65be21200ce580e4eb13#1cdadea43e9c5a0f054b65be21200ce580e4eb13"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cty",
|
||||
@@ -6245,8 +6324,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "mimalloc"
|
||||
version = "0.1.52"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862"
|
||||
source = "git+https://github.com/xonatius/mimalloc_rust.git?rev=1cdadea43e9c5a0f054b65be21200ce580e4eb13#1cdadea43e9c5a0f054b65be21200ce580e4eb13"
|
||||
dependencies = [
|
||||
"libmimalloc-sys",
|
||||
]
|
||||
@@ -6668,6 +6746,17 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-rational"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -6732,7 +6821,7 @@ version = "5.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d"
|
||||
dependencies = [
|
||||
"base64 0.21.7",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"getrandom 0.2.17",
|
||||
"http 1.5.0",
|
||||
@@ -7857,7 +7946,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be769465445e8c1474e9c5dac2018218498557af32d9ed057325ec9a41ae81bf"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"itertools 0.13.0",
|
||||
"itertools 0.14.0",
|
||||
"log",
|
||||
"multimap",
|
||||
"once_cell",
|
||||
@@ -7877,7 +7966,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"itertools 0.13.0",
|
||||
"itertools 0.14.0",
|
||||
"log",
|
||||
"multimap",
|
||||
"petgraph 0.8.3",
|
||||
@@ -7898,7 +7987,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.13.0",
|
||||
"itertools 0.14.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
@@ -7911,7 +8000,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.13.0",
|
||||
"itertools 0.14.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
@@ -8631,6 +8720,15 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.14.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "921904a62e410e37e215c40381b7117f830d9d89ba60ab5236170541dd25646b"
|
||||
dependencies = [
|
||||
"xmlparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rsa"
|
||||
version = "0.9.10"
|
||||
@@ -8724,9 +8822,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "russh"
|
||||
version = "0.62.4"
|
||||
version = "0.62.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8b67b5a0d8068c89dcbe9d95df986af7a851d1f3c604525274c37468e60464f"
|
||||
checksum = "da7c230e0ed9cbeb92fbad6c8848985d6df2a1464c0dc247a021abd666e9005e"
|
||||
dependencies = [
|
||||
"aes 0.9.2",
|
||||
"aws-lc-rs",
|
||||
@@ -9027,6 +9125,7 @@ dependencies = [
|
||||
"url",
|
||||
"urlencoding",
|
||||
"uuid",
|
||||
"zeroize",
|
||||
"zip",
|
||||
"zstd",
|
||||
]
|
||||
@@ -9511,10 +9610,16 @@ dependencies = [
|
||||
"arc-swap",
|
||||
"argon2",
|
||||
"async-trait",
|
||||
"aws-config",
|
||||
"aws-sdk-kms",
|
||||
"aws-smithy-http-client",
|
||||
"aws-smithy-runtime-api",
|
||||
"aws-smithy-types",
|
||||
"base64 0.23.0",
|
||||
"chacha20poly1305",
|
||||
"hex",
|
||||
"hotpath",
|
||||
"http 1.5.0",
|
||||
"insta",
|
||||
"jiff",
|
||||
"md-5 0.11.0",
|
||||
@@ -9523,6 +9628,7 @@ dependencies = [
|
||||
"moka",
|
||||
"rand 0.10.2",
|
||||
"reqwest",
|
||||
"rustfs-s3-types",
|
||||
"rustfs-security-governance",
|
||||
"rustfs-utils",
|
||||
"rustify",
|
||||
@@ -9708,6 +9814,7 @@ dependencies = [
|
||||
"hotpath",
|
||||
"jiff",
|
||||
"libc",
|
||||
"log",
|
||||
"metrics",
|
||||
"num_cpus",
|
||||
"nvml-wrapper",
|
||||
@@ -9743,6 +9850,7 @@ dependencies = [
|
||||
"tracing-error",
|
||||
"tracing-opentelemetry",
|
||||
"tracing-subscriber",
|
||||
"url",
|
||||
"zstd",
|
||||
]
|
||||
|
||||
@@ -9774,6 +9882,7 @@ dependencies = [
|
||||
"time",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -10027,6 +10136,7 @@ dependencies = [
|
||||
"rustfs-data-usage",
|
||||
"rustfs-ecstore",
|
||||
"rustfs-filemeta",
|
||||
"rustfs-lock",
|
||||
"rustfs-storage-api",
|
||||
"rustfs-utils",
|
||||
"s3s",
|
||||
@@ -10607,7 +10717,7 @@ checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
|
||||
dependencies = [
|
||||
"base16ct 0.2.0",
|
||||
"der 0.7.10",
|
||||
"generic-array 0.14.7",
|
||||
"generic-array 0.14.9",
|
||||
"pkcs8 0.10.2",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
@@ -10660,6 +10770,12 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "separator"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f97841a747eef040fcd2e7b3b9a220a7205926e60488e673d9e4926d27772ce5"
|
||||
|
||||
[[package]]
|
||||
name = "seq-macro"
|
||||
version = "0.3.6"
|
||||
@@ -11597,7 +11713,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.3",
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
|
||||
+6
-4
@@ -173,7 +173,7 @@ tower-http = { version = "0.7.0" }
|
||||
# Serialization and Data Formats
|
||||
apache-avro = "0.21.0"
|
||||
bytes = { version = "1.12.1" }
|
||||
bytesize = "2.4.2"
|
||||
bytesize = "2.6.0"
|
||||
byteorder = "1.5.0"
|
||||
flatbuffers = "25.12.19"
|
||||
form_urlencoded = "1.2.2"
|
||||
@@ -227,6 +227,7 @@ atoi = "3.1.0"
|
||||
atomic_enum = "0.3.0"
|
||||
aws-config = { version = "1.10.1" }
|
||||
aws-credential-types = { version = "1.3.0" }
|
||||
aws-sdk-kms = { default-features = false, version = "1.114.0" }
|
||||
aws-sdk-s3 = { default-features = false, version = "1.140.0" }
|
||||
aws-sdk-sts = { default-features = false, version = "1.110.0" }
|
||||
aws-smithy-http-client = { default-features = false, version = "1.2.0" }
|
||||
@@ -235,7 +236,7 @@ aws-smithy-types = { version = "1.6.1" }
|
||||
base64 = "0.23.0"
|
||||
base64-simd = "0.8.0"
|
||||
brotli = "8.0.4"
|
||||
clap = { version = "4.6.4" }
|
||||
clap = { version = "4.6.5" }
|
||||
const-str = { version = "1.1.0" }
|
||||
convert_case = "0.11.0"
|
||||
criterion = { version = "0.8" }
|
||||
@@ -340,14 +341,15 @@ libunftp = { version = "0.23.0" }
|
||||
unftp-core = "0.1.0"
|
||||
suppaftp = { version = "10.0.1" }
|
||||
rcgen = { version = "0.14.8", default-features = false, features = ["aws_lc_rs", "crypto", "pem"] }
|
||||
russh = { version = "0.62.4" }
|
||||
russh = { version = "0.62.5" }
|
||||
russh-sftp = "2.3.0"
|
||||
|
||||
# WebDAV
|
||||
dav-server = "0.11.0"
|
||||
|
||||
# Performance Analysis and Memory Profiling
|
||||
mimalloc = "0.1.52"
|
||||
mimalloc = { version = "0.1.52", git = "https://github.com/xonatius/mimalloc_rust.git", rev = "1cdadea43e9c5a0f054b65be21200ce580e4eb13" }
|
||||
libmimalloc-sys = { version = "0.1.49", git = "https://github.com/xonatius/mimalloc_rust.git", rev = "1cdadea43e9c5a0f054b65be21200ce580e4eb13", features = ["extended"] }
|
||||
hotpath = { version = "0.22.0", default-features = false }
|
||||
# Snapshot testing for output format regression detection
|
||||
insta = { version = "1.48" }
|
||||
|
||||
@@ -47,6 +47,9 @@ consts = "consts"
|
||||
Hashi = "Hashi" # HashiCorp
|
||||
# Accept alternate spelling used in parser/XML comments.
|
||||
unparseable = "unparseable"
|
||||
# Disaster-recovery objectives: recovery time and recovery point.
|
||||
RTO = "RTO"
|
||||
rto = "rto"
|
||||
|
||||
[files]
|
||||
extend-exclude = []
|
||||
|
||||
@@ -230,6 +230,19 @@ pub const ENV_RUSTFS_KMS_ENABLE: &str = "RUSTFS_KMS_ENABLE";
|
||||
/// Default value: false
|
||||
pub const DEFAULT_KMS_ENABLE: bool = false;
|
||||
|
||||
/// Environment variable enabling per-key KMS authorization on the SSE-KMS data path.
|
||||
///
|
||||
/// When enabled, an SSE-KMS write additionally requires `kms:GenerateDataKey` and an
|
||||
/// SSE-KMS read additionally requires `kms:Decrypt` on the resolved key, evaluated as
|
||||
/// the requesting identity. SSE-S3 and SSE-C are unaffected.
|
||||
pub const ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY: &str = "RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY";
|
||||
|
||||
/// Default per-key KMS authorization mode for the SSE-KMS data path.
|
||||
///
|
||||
/// Off for now so deployments whose identity policies only grant s3 actions keep
|
||||
/// working; the default flips to on in a later release.
|
||||
pub const DEFAULT_KMS_ENFORCE_SSE_KEY_POLICY: bool = false;
|
||||
|
||||
/// Environment variable for server KMS backend.
|
||||
pub const ENV_RUSTFS_KMS_BACKEND: &str = "RUSTFS_KMS_BACKEND";
|
||||
|
||||
|
||||
@@ -26,75 +26,16 @@
|
||||
//! Later batches tracked on backlog#1154: config get/set, info, pools status,
|
||||
//! group lifecycle, import/export IAM.
|
||||
|
||||
use crate::common::{RustFSTestEnvironment, init_logging, local_http_client};
|
||||
use crate::common::{RustFSTestEnvironment, admin_ok, admin_request, init_logging};
|
||||
use aws_sdk_s3::config::{Credentials, Region};
|
||||
use aws_sdk_s3::primitives::ByteStream;
|
||||
use aws_sdk_s3::{Client, Config};
|
||||
use http::header::{CONTENT_TYPE, HOST};
|
||||
use reqwest::StatusCode;
|
||||
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
||||
use rustfs_signer::sign_v4;
|
||||
use s3s::Body;
|
||||
use serial_test::serial;
|
||||
use std::error::Error;
|
||||
use tokio::time::{Duration, sleep};
|
||||
|
||||
type TestResult = Result<(), Box<dyn Error + Send + Sync>>;
|
||||
type BoxError = Box<dyn Error + Send + Sync>;
|
||||
|
||||
/// Signs and sends an admin HTTP request with the given credential, returning
|
||||
/// status and body. Native `/rustfs/admin/v3` requests and responses are plain
|
||||
/// JSON (the MinIO-compat encryption applies only to `/minio/admin/v3` paths).
|
||||
async fn admin_request(
|
||||
base_url: &str,
|
||||
method: http::Method,
|
||||
path_and_query: &str,
|
||||
body: Option<String>,
|
||||
access_key: &str,
|
||||
secret_key: &str,
|
||||
) -> Result<(StatusCode, String), BoxError> {
|
||||
let url = format!("{base_url}{path_and_query}");
|
||||
let uri = url.parse::<http::Uri>()?;
|
||||
let authority = uri.authority().ok_or("admin URL missing authority")?.to_string();
|
||||
let mut builder = http::Request::builder()
|
||||
.method(method.clone())
|
||||
.uri(uri)
|
||||
.header(HOST, authority)
|
||||
.header("x-amz-content-sha256", UNSIGNED_PAYLOAD);
|
||||
if body.is_some() {
|
||||
builder = builder.header(CONTENT_TYPE, "application/json");
|
||||
}
|
||||
|
||||
let content_len = body.as_ref().map(|b| b.len() as i64).unwrap_or_default();
|
||||
let signed = sign_v4(builder.body(Body::empty())?, content_len, access_key, secret_key, "", "us-east-1");
|
||||
|
||||
let reqwest_method = reqwest::Method::from_bytes(method.as_str().as_bytes())?;
|
||||
let mut request = local_http_client().request(reqwest_method, &url);
|
||||
for (name, value) in signed.headers() {
|
||||
request = request.header(name, value);
|
||||
}
|
||||
if let Some(body) = body {
|
||||
request = request.body(body);
|
||||
}
|
||||
let response = request.send().await?;
|
||||
let status = response.status();
|
||||
let text = response.text().await.unwrap_or_default();
|
||||
Ok((status, text))
|
||||
}
|
||||
|
||||
/// Root-credential admin request that must succeed; returns the response body.
|
||||
async fn admin_ok(
|
||||
env: &RustFSTestEnvironment,
|
||||
method: http::Method,
|
||||
path_and_query: &str,
|
||||
body: Option<String>,
|
||||
) -> Result<String, BoxError> {
|
||||
let (status, text) = admin_request(&env.url, method.clone(), path_and_query, body, &env.access_key, &env.secret_key).await?;
|
||||
if !status.is_success() {
|
||||
return Err(format!("{method} {path_and_query} failed: {status} {text}").into());
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
fn build_s3_client(url: &str, access_key: &str, secret_key: &str) -> Client {
|
||||
let config = Config::builder()
|
||||
|
||||
@@ -24,7 +24,12 @@
|
||||
use aws_sdk_s3::config::{Credentials, Region};
|
||||
use aws_sdk_s3::{Client, Config};
|
||||
use aws_smithy_http_client::Builder as SmithyHttpClientBuilder;
|
||||
use http::header::{CONTENT_TYPE, HOST};
|
||||
use reqwest::Client as HttpClient;
|
||||
use reqwest::StatusCode;
|
||||
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
||||
use rustfs_signer::sign_v4;
|
||||
use s3s::Body;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs as stdfs;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -75,6 +80,58 @@ pub fn local_http_client() -> HttpClient {
|
||||
.expect("failed to build local reqwest client")
|
||||
}
|
||||
|
||||
/// Signs and sends an admin HTTP request with the given credentials.
|
||||
pub(crate) async fn admin_request(
|
||||
base_url: &str,
|
||||
method: http::Method,
|
||||
path_and_query: &str,
|
||||
body: Option<String>,
|
||||
access_key: &str,
|
||||
secret_key: &str,
|
||||
) -> Result<(StatusCode, String), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let url = format!("{base_url}{path_and_query}");
|
||||
let uri = url.parse::<http::Uri>()?;
|
||||
let authority = uri.authority().ok_or("admin URL missing authority")?.to_string();
|
||||
let mut request = http::Request::builder()
|
||||
.method(method.clone())
|
||||
.uri(uri)
|
||||
.header(HOST, authority)
|
||||
.header("x-amz-content-sha256", UNSIGNED_PAYLOAD);
|
||||
if body.is_some() {
|
||||
request = request.header(CONTENT_TYPE, "application/json");
|
||||
}
|
||||
|
||||
let content_length = i64::try_from(body.as_ref().map_or(0, String::len)).map_err(|_| "admin request body is too large")?;
|
||||
let signed = sign_v4(request.body(Body::empty())?, content_length, access_key, secret_key, "", "us-east-1");
|
||||
|
||||
let mut request = local_http_client().request(method, &url);
|
||||
for (name, value) in signed.headers() {
|
||||
request = request.header(name, value);
|
||||
}
|
||||
if let Some(body) = body {
|
||||
request = request.body(body);
|
||||
}
|
||||
let response = request.send().await?;
|
||||
let status = response.status();
|
||||
let body = response.text().await?;
|
||||
Ok((status, body))
|
||||
}
|
||||
|
||||
/// Sends a root-credential admin request and returns its successful response body.
|
||||
pub(crate) async fn admin_ok(
|
||||
env: &RustFSTestEnvironment,
|
||||
method: http::Method,
|
||||
path_and_query: &str,
|
||||
body: Option<String>,
|
||||
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let (status, response_body) =
|
||||
admin_request(&env.url, method.clone(), path_and_query, body, &env.access_key, &env.secret_key).await?;
|
||||
if !status.is_success() {
|
||||
return Err(format!("{method} {path_and_query} failed: {status} {response_body}").into());
|
||||
}
|
||||
Ok(response_body)
|
||||
}
|
||||
|
||||
/// Resolve the RustFS binary relative to the workspace.
|
||||
pub fn rustfs_binary_path() -> PathBuf {
|
||||
rustfs_binary_path_with_features(requested_rustfs_build_features().as_deref())
|
||||
|
||||
@@ -126,7 +126,55 @@ async fn assert_key_deletion_lifecycle(base_url: &str, access_key: &str, secret_
|
||||
assert_eq!(cancelled["success"], true);
|
||||
assert_eq!(cancelled["key_metadata"]["key_state"], "Enabled");
|
||||
|
||||
let removed = kms_admin_request(
|
||||
// A window outside 7-30 days is refused at the endpoint, whatever the
|
||||
// backend: the bound is enforced once in the service, so no backend can
|
||||
// stretch or skip it (rustfs/backlog#1585).
|
||||
for days in [6, 31] {
|
||||
let refused = kms_admin_request(
|
||||
base_url,
|
||||
http::Method::DELETE,
|
||||
"/rustfs/admin/v3/kms/keys/delete",
|
||||
Some(
|
||||
&serde_json::json!({
|
||||
"key_id": key_id,
|
||||
"pending_window_in_days": days
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
access_key,
|
||||
secret_key,
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.ok_or_else(|| format!("a {days}-day deletion window must be refused"))?;
|
||||
assert!(
|
||||
refused.to_string().contains("400 Bad Request"),
|
||||
"a {days}-day deletion window must report a client error: {refused}"
|
||||
);
|
||||
}
|
||||
|
||||
// Immediate deletion is no longer reachable through the query string, so it
|
||||
// fails before the service gate is even consulted.
|
||||
let refused = kms_admin_request(
|
||||
base_url,
|
||||
http::Method::DELETE,
|
||||
&format!("/rustfs/admin/v3/kms/keys/delete?keyId={key_id}&force_immediate=true"),
|
||||
None,
|
||||
access_key,
|
||||
secret_key,
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.ok_or("immediate KMS key deletion must not be reachable through the query string")?;
|
||||
assert!(
|
||||
refused.to_string().contains("400 Bad Request"),
|
||||
"a query-string immediate deletion must report a client error: {refused}"
|
||||
);
|
||||
|
||||
// A default server refuses to skip the waiting window (rustfs/backlog#1585):
|
||||
// immediate deletion is unrecoverable and takes every object encrypted under
|
||||
// the key with it, so the endpoint must reject it rather than honour it.
|
||||
let refused = kms_admin_request(
|
||||
base_url,
|
||||
http::Method::DELETE,
|
||||
"/rustfs/admin/v3/kms/keys/delete",
|
||||
@@ -140,37 +188,49 @@ async fn assert_key_deletion_lifecycle(base_url: &str, access_key: &str, secret_
|
||||
access_key,
|
||||
secret_key,
|
||||
)
|
||||
.await?;
|
||||
let removed: serde_json::Value = serde_json::from_str(&removed)?;
|
||||
assert_eq!(removed["success"], true);
|
||||
.await
|
||||
.err()
|
||||
.ok_or("immediate KMS key deletion must be refused on a default server")?;
|
||||
assert!(
|
||||
refused.to_string().contains("400 Bad Request"),
|
||||
"refused immediate deletion must report a client error: {refused}"
|
||||
);
|
||||
|
||||
let listed =
|
||||
kms_admin_request(base_url, http::Method::GET, "/rustfs/admin/v3/kms/keys", None, access_key, secret_key).await?;
|
||||
let listed: serde_json::Value = serde_json::from_str(&listed)?;
|
||||
assert_eq!(listed["success"], true);
|
||||
let keys = listed["keys"]
|
||||
.as_array()
|
||||
.ok_or("list KMS keys response omitted keys after deletion")?;
|
||||
if let Some(key) = keys.iter().find(|key| key["key_id"] == key_id) {
|
||||
assert_eq!(key["status"], "PendingDeletion", "a retained force-deleted key must be pending deletion");
|
||||
let removed = kms_admin_request(
|
||||
base_url,
|
||||
http::Method::DELETE,
|
||||
"/rustfs/admin/v3/kms/keys/delete",
|
||||
Some(
|
||||
&serde_json::json!({
|
||||
"key_id": key_id,
|
||||
"force_immediate": true
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
access_key,
|
||||
secret_key,
|
||||
)
|
||||
.await?;
|
||||
let removed: serde_json::Value = serde_json::from_str(&removed)?;
|
||||
assert_eq!(removed["success"], true);
|
||||
}
|
||||
// The refused requests left the key alone, so the window-bounded path still
|
||||
// has something to schedule.
|
||||
let described = kms_admin_request(
|
||||
base_url,
|
||||
http::Method::GET,
|
||||
&format!("/rustfs/admin/v3/kms/keys/{key_id}"),
|
||||
None,
|
||||
access_key,
|
||||
secret_key,
|
||||
)
|
||||
.await?;
|
||||
let described: serde_json::Value = serde_json::from_str(&described)?;
|
||||
assert_eq!(
|
||||
described["key_metadata"]["key_state"], "Enabled",
|
||||
"a refused immediate deletion must leave the key usable"
|
||||
);
|
||||
|
||||
let rescheduled = kms_admin_request(
|
||||
base_url,
|
||||
http::Method::DELETE,
|
||||
"/rustfs/admin/v3/kms/keys/delete",
|
||||
Some(
|
||||
&serde_json::json!({
|
||||
"key_id": key_id,
|
||||
"pending_window_in_days": 7
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
access_key,
|
||||
secret_key,
|
||||
)
|
||||
.await?;
|
||||
let rescheduled: serde_json::Value = serde_json::from_str(&rescheduled)?;
|
||||
assert_eq!(rescheduled["success"], true);
|
||||
assert!(rescheduled["deletion_date"].is_string());
|
||||
|
||||
let listed =
|
||||
kms_admin_request(base_url, http::Method::GET, "/rustfs/admin/v3/kms/keys", None, access_key, secret_key).await?;
|
||||
@@ -179,10 +239,11 @@ async fn assert_key_deletion_lifecycle(base_url: &str, access_key: &str, secret_
|
||||
let keys = listed["keys"]
|
||||
.as_array()
|
||||
.ok_or("final list KMS keys response omitted keys after deletion")?;
|
||||
assert!(
|
||||
keys.iter().all(|key| key["key_id"] != key_id),
|
||||
"force-deleted KMS key must no longer appear in list"
|
||||
);
|
||||
let key = keys
|
||||
.iter()
|
||||
.find(|key| key["key_id"] == key_id)
|
||||
.ok_or("a key awaiting its deletion window must still be listed")?;
|
||||
assert_eq!(key["status"], "PendingDeletion", "a scheduled key must be pending deletion");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,483 @@
|
||||
// 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.
|
||||
|
||||
//! Negative authorization matrix for per-key KMS access control.
|
||||
//!
|
||||
//! Every case here is an end-to-end denial that the pre-`kms` resource server
|
||||
//! allowed, so a regression that reopens one of them fails this file rather than
|
||||
//! only a unit test. The matrix varies one dimension at a time:
|
||||
//!
|
||||
//! - **wrong identity**: a caller holding S3 rights but no `kms` grant at all
|
||||
//! - **wrong key**: a caller scoped to key A naming key B
|
||||
//! - **wrong action**: a caller holding `kms:GenerateDataKey` but not `kms:Decrypt`
|
||||
//! (and, on the admin plane, `kms:DisableKey` but not `kms:RotateKey`)
|
||||
//! - **wrong context**: an explicit `Deny` beating a wildcard `Allow`, and SSE-S3
|
||||
//! staying exempt from `kms` authorization
|
||||
//!
|
||||
//! Each matrix opens with a positive control. Without it a denial proves nothing:
|
||||
//! an identity whose policy has not propagated yet is denied everything.
|
||||
|
||||
use super::common::{LocalKMSTestEnvironment, create_key_with_specific_id};
|
||||
use crate::common::{admin_ok, admin_request, init_logging};
|
||||
use aws_sdk_s3::Client;
|
||||
use aws_sdk_s3::config::{Config, Credentials, Region};
|
||||
use aws_sdk_s3::error::ProvideErrorMetadata;
|
||||
use aws_sdk_s3::primitives::ByteStream;
|
||||
use aws_sdk_s3::types::ServerSideEncryption;
|
||||
use serial_test::serial;
|
||||
use std::time::Duration;
|
||||
use tracing::info;
|
||||
|
||||
type TestResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
|
||||
|
||||
const ALLOWED_KEY: &str = "kms-matrix-allowed-key";
|
||||
const OTHER_KEY: &str = "kms-matrix-other-key";
|
||||
const BUCKET: &str = "kms-authz-matrix";
|
||||
const SECRET: &str = "kms-matrix-secret";
|
||||
const PAYLOAD: &[u8] = b"kms authorization matrix payload";
|
||||
|
||||
/// How long an identity change may take to reach the request path.
|
||||
const IAM_PROPAGATION: Duration = Duration::from_secs(20);
|
||||
|
||||
fn s3_client(url: &str, access_key: &str, secret_key: &str) -> Client {
|
||||
let config = Config::builder()
|
||||
.credentials_provider(Credentials::new(access_key, secret_key, None, None, "kms-authz-matrix"))
|
||||
.region(Region::new("us-east-1"))
|
||||
.endpoint_url(url)
|
||||
.force_path_style(true)
|
||||
.behavior_version_latest()
|
||||
.build();
|
||||
Client::from_conf(config)
|
||||
}
|
||||
|
||||
/// Start a server whose SSE-KMS data path authorizes against the named key.
|
||||
///
|
||||
/// The enforcement switch defaults to off for compatibility, so it has to be set
|
||||
/// explicitly; without it every negative case below would silently pass as an allow.
|
||||
async fn start_enforcing_server(env: &mut LocalKMSTestEnvironment, extra_env: &[(&str, &str)]) -> TestResult {
|
||||
create_key_with_specific_id(&env.kms_keys_dir, ALLOWED_KEY).await?;
|
||||
create_key_with_specific_id(&env.kms_keys_dir, OTHER_KEY).await?;
|
||||
|
||||
let key_dir = env.kms_keys_dir.clone();
|
||||
let args = vec![
|
||||
"--kms-enable",
|
||||
"--kms-backend",
|
||||
"local",
|
||||
"--kms-key-dir",
|
||||
key_dir.as_str(),
|
||||
"--kms-default-key-id",
|
||||
ALLOWED_KEY,
|
||||
];
|
||||
|
||||
let mut envs = vec![("RUSTFS_KMS_ALLOW_INSECURE_DEV_DEFAULTS", "true")];
|
||||
envs.extend_from_slice(extra_env);
|
||||
|
||||
env.base_env.start_rustfs_server_with_env(args, &envs).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create `user` with `policy_document` attached under a canned policy of the same name.
|
||||
async fn provision_user(env: &LocalKMSTestEnvironment, user: &str, policy_document: &str) -> TestResult {
|
||||
admin_ok(
|
||||
&env.base_env,
|
||||
http::Method::PUT,
|
||||
&format!("/rustfs/admin/v3/add-canned-policy?name={user}"),
|
||||
Some(policy_document.to_string()),
|
||||
)
|
||||
.await?;
|
||||
provision_user_with_policy(env, user, user).await
|
||||
}
|
||||
|
||||
/// Create `user` and attach an existing policy (built-in or canned) by name.
|
||||
async fn provision_user_with_policy(env: &LocalKMSTestEnvironment, user: &str, policy_name: &str) -> TestResult {
|
||||
admin_ok(
|
||||
&env.base_env,
|
||||
http::Method::PUT,
|
||||
&format!("/rustfs/admin/v3/add-user?accessKey={user}"),
|
||||
Some(serde_json::json!({ "secretKey": SECRET, "status": "enabled" }).to_string()),
|
||||
)
|
||||
.await?;
|
||||
admin_ok(
|
||||
&env.base_env,
|
||||
http::Method::PUT,
|
||||
&format!("/rustfs/admin/v3/set-user-or-group-policy?policyName={policy_name}&userOrGroup={user}&isGroup=false"),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The S3 half of every data-path policy below: full object access, no KMS grant.
|
||||
fn s3_full_access_statement() -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:*"],
|
||||
"Resource": ["arn:aws:s3:::*"]
|
||||
})
|
||||
}
|
||||
|
||||
fn policy_document(statements: Vec<serde_json::Value>) -> String {
|
||||
serde_json::json!({ "Version": "2012-10-17", "Statement": statements }).to_string()
|
||||
}
|
||||
|
||||
async fn put_sse_kms(client: &Client, key: &str, kms_key_id: &str) -> Result<(), aws_sdk_s3::Error> {
|
||||
client
|
||||
.put_object()
|
||||
.bucket(BUCKET)
|
||||
.key(key)
|
||||
.body(ByteStream::from_static(PAYLOAD))
|
||||
.server_side_encryption(ServerSideEncryption::AwsKms)
|
||||
.ssekms_key_id(kms_key_id)
|
||||
.send()
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(aws_sdk_s3::Error::from)
|
||||
}
|
||||
|
||||
/// Assert the operation failed with `AccessDenied` rather than any other error.
|
||||
///
|
||||
/// A bare `is_err` would also accept `KMSKeyDisabled` or an internal error, which
|
||||
/// would hide both a leak of key state and an outage masquerading as a denial.
|
||||
fn assert_access_denied<T: std::fmt::Debug>(result: Result<T, aws_sdk_s3::Error>, what: &str) {
|
||||
let error = result.expect_err(&format!("{what} must be denied"));
|
||||
assert_eq!(error.code(), Some("AccessDenied"), "{what} must fail with AccessDenied: {error:?}");
|
||||
}
|
||||
|
||||
/// Retry an SSE-KMS write until the identity's policy has reached the request path.
|
||||
async fn wait_for_sse_kms_write(client: &Client, key: &str, kms_key_id: &str) -> TestResult {
|
||||
let deadline = tokio::time::Instant::now() + IAM_PROPAGATION;
|
||||
loop {
|
||||
match put_sse_kms(client, key, kms_key_id).await {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(error) if tokio::time::Instant::now() >= deadline => {
|
||||
return Err(format!("positive control never became authorized: {error:?}").into());
|
||||
}
|
||||
Err(_) => tokio::time::sleep(Duration::from_millis(500)).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Retry an admin call until it stops returning 403, i.e. the policy is live.
|
||||
async fn wait_for_admin_success(
|
||||
env: &LocalKMSTestEnvironment,
|
||||
user: &str,
|
||||
method: http::Method,
|
||||
path: &str,
|
||||
body: Option<String>,
|
||||
) -> TestResult {
|
||||
let deadline = tokio::time::Instant::now() + IAM_PROPAGATION;
|
||||
loop {
|
||||
let (status, response) = admin_request(&env.base_env.url, method.clone(), path, body.clone(), user, SECRET).await?;
|
||||
if status.is_success() {
|
||||
return Ok(());
|
||||
}
|
||||
if tokio::time::Instant::now() >= deadline {
|
||||
return Err(format!("positive control never became authorized: {method} {path} -> {status} {response}").into());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_admin_denied(
|
||||
env: &LocalKMSTestEnvironment,
|
||||
user: &str,
|
||||
method: http::Method,
|
||||
path: &str,
|
||||
body: Option<String>,
|
||||
what: &str,
|
||||
) -> TestResult {
|
||||
let (status, response) = admin_request(&env.base_env.url, method, path, body, user, SECRET).await?;
|
||||
assert_eq!(status.as_u16(), 403, "{what} must be denied, got {status}: {response}");
|
||||
assert!(response.contains("AccessDenied"), "{what} must carry AccessDenied: {response}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn disable_body(key_id: &str) -> String {
|
||||
serde_json::json!({ "key_id": key_id }).to_string()
|
||||
}
|
||||
|
||||
/// Data-path matrix: SSE-KMS writes and reads are authorized against the resolved key.
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn sse_kms_per_key_authorization_negative_matrix() -> TestResult {
|
||||
init_logging();
|
||||
|
||||
let mut env = LocalKMSTestEnvironment::new().await?;
|
||||
start_enforcing_server(&mut env, &[("RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY", "true")]).await?;
|
||||
env.base_env.create_test_bucket(BUCKET).await?;
|
||||
|
||||
// Scoped to ALLOWED_KEY only.
|
||||
provision_user(
|
||||
&env,
|
||||
"kmsmatrixscoped",
|
||||
&policy_document(vec![
|
||||
s3_full_access_statement(),
|
||||
serde_json::json!({
|
||||
"Effect": "Allow",
|
||||
"Action": ["kms:GenerateDataKey", "kms:Decrypt"],
|
||||
"Resource": [format!("arn:aws:kms:::key/{ALLOWED_KEY}")]
|
||||
}),
|
||||
]),
|
||||
)
|
||||
.await?;
|
||||
// S3 rights only: the identity shape that existed before per-key authorization.
|
||||
provision_user(&env, "kmsmatrixs3only", &policy_document(vec![s3_full_access_statement()])).await?;
|
||||
// May wrap a data key but may never unwrap one.
|
||||
provision_user(
|
||||
&env,
|
||||
"kmsmatrixwriter",
|
||||
&policy_document(vec![
|
||||
s3_full_access_statement(),
|
||||
serde_json::json!({
|
||||
"Effect": "Allow",
|
||||
"Action": ["kms:GenerateDataKey"],
|
||||
"Resource": ["arn:aws:kms:::*"]
|
||||
}),
|
||||
]),
|
||||
)
|
||||
.await?;
|
||||
// Wildcard allow, explicit deny on one key.
|
||||
provision_user(
|
||||
&env,
|
||||
"kmsmatrixdenied",
|
||||
&policy_document(vec![
|
||||
s3_full_access_statement(),
|
||||
serde_json::json!({
|
||||
"Effect": "Allow",
|
||||
"Action": ["kms:*"],
|
||||
"Resource": ["arn:aws:kms:::*"]
|
||||
}),
|
||||
serde_json::json!({
|
||||
"Effect": "Deny",
|
||||
"Action": ["kms:*"],
|
||||
"Resource": [format!("arn:aws:kms:::key/{OTHER_KEY}")]
|
||||
}),
|
||||
]),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let scoped = s3_client(&env.base_env.url, "kmsmatrixscoped", SECRET);
|
||||
let s3_only = s3_client(&env.base_env.url, "kmsmatrixs3only", SECRET);
|
||||
let writer = s3_client(&env.base_env.url, "kmsmatrixwriter", SECRET);
|
||||
let denied = s3_client(&env.base_env.url, "kmsmatrixdenied", SECRET);
|
||||
|
||||
// --- positive control -----------------------------------------------------
|
||||
wait_for_sse_kms_write(&scoped, "scoped/allowed", ALLOWED_KEY).await?;
|
||||
let read = scoped.get_object().bucket(BUCKET).key("scoped/allowed").send().await?;
|
||||
assert_eq!(read.body.collect().await?.into_bytes().as_ref(), PAYLOAD);
|
||||
info!("positive control: scoped identity may write and read under its own key");
|
||||
|
||||
// --- wrong key ------------------------------------------------------------
|
||||
assert_access_denied(
|
||||
put_sse_kms(&scoped, "scoped/other", OTHER_KEY).await,
|
||||
"SSE-KMS write under a key outside the identity's scope",
|
||||
);
|
||||
|
||||
// --- wrong identity -------------------------------------------------------
|
||||
assert_access_denied(
|
||||
put_sse_kms(&s3_only, "s3only/allowed", ALLOWED_KEY).await,
|
||||
"SSE-KMS write by an identity holding no kms grant",
|
||||
);
|
||||
// The object the scoped identity wrote is readable by its owner only.
|
||||
assert_access_denied(
|
||||
s3_only
|
||||
.get_object()
|
||||
.bucket(BUCKET)
|
||||
.key("scoped/allowed")
|
||||
.send()
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(aws_sdk_s3::Error::from),
|
||||
"SSE-KMS read by an identity holding no kms grant",
|
||||
);
|
||||
|
||||
// --- wrong action ---------------------------------------------------------
|
||||
wait_for_sse_kms_write(&writer, "writer/allowed", ALLOWED_KEY).await?;
|
||||
assert_access_denied(
|
||||
writer
|
||||
.get_object()
|
||||
.bucket(BUCKET)
|
||||
.key("writer/allowed")
|
||||
.send()
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(aws_sdk_s3::Error::from),
|
||||
"SSE-KMS read by an identity holding kms:GenerateDataKey but not kms:Decrypt",
|
||||
);
|
||||
|
||||
// --- wrong context: explicit Deny beats a wildcard Allow -------------------
|
||||
wait_for_sse_kms_write(&denied, "denied/allowed", ALLOWED_KEY).await?;
|
||||
assert_access_denied(
|
||||
put_sse_kms(&denied, "denied/other", OTHER_KEY).await,
|
||||
"SSE-KMS write under a key covered by an explicit Deny",
|
||||
);
|
||||
|
||||
// --- wrong context: SSE-S3 is out of scope --------------------------------
|
||||
// SSE-S3 wraps its data key with a server-owned key the caller never names, so
|
||||
// it must stay reachable for an identity with no kms grant at all.
|
||||
s3_only
|
||||
.put_object()
|
||||
.bucket(BUCKET)
|
||||
.key("s3only/sse-s3")
|
||||
.body(ByteStream::from_static(PAYLOAD))
|
||||
.server_side_encryption(ServerSideEncryption::Aes256)
|
||||
.send()
|
||||
.await?;
|
||||
let sse_s3_read = s3_only.get_object().bucket(BUCKET).key("s3only/sse-s3").send().await?;
|
||||
assert_eq!(sse_s3_read.body.collect().await?.into_bytes().as_ref(), PAYLOAD);
|
||||
|
||||
// ... and so must an unencrypted object.
|
||||
s3_only
|
||||
.put_object()
|
||||
.bucket(BUCKET)
|
||||
.key("s3only/plain")
|
||||
.body(ByteStream::from_static(PAYLOAD))
|
||||
.send()
|
||||
.await?;
|
||||
s3_only.get_object().bucket(BUCKET).key("s3only/plain").send().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Admin-plane matrix: KMS key endpoints are authorized against the key they name.
|
||||
///
|
||||
/// Runs without the SSE enforcement switch: admin scoping is unconditional, and
|
||||
/// leaving the switch off proves the two planes are independent.
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn kms_admin_per_key_authorization_negative_matrix() -> TestResult {
|
||||
init_logging();
|
||||
|
||||
let mut env = LocalKMSTestEnvironment::new().await?;
|
||||
start_enforcing_server(&mut env, &[]).await?;
|
||||
|
||||
// Built-in role templates, attached by name.
|
||||
provision_user_with_policy(&env, "kmsmatrixkeyadmin", "KMSKeyAdministrator").await?;
|
||||
provision_user_with_policy(&env, "kmsmatrixauditor", "KMSAuditor").await?;
|
||||
// A narrowed copy of the administrator template, scoped to one key.
|
||||
provision_user(
|
||||
&env,
|
||||
"kmsmatrixscopedadmin",
|
||||
&policy_document(vec![serde_json::json!({
|
||||
"Effect": "Allow",
|
||||
"Action": ["kms:DisableKey", "kms:EnableKey"],
|
||||
"Resource": [format!("arn:aws:kms:::key/{ALLOWED_KEY}")]
|
||||
})]),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// --- positive control -----------------------------------------------------
|
||||
wait_for_admin_success(
|
||||
&env,
|
||||
"kmsmatrixkeyadmin",
|
||||
http::Method::POST,
|
||||
"/rustfs/admin/v3/kms/keys/disable",
|
||||
Some(disable_body(OTHER_KEY)),
|
||||
)
|
||||
.await?;
|
||||
admin_request(
|
||||
&env.base_env.url,
|
||||
http::Method::POST,
|
||||
"/rustfs/admin/v3/kms/keys/enable",
|
||||
Some(disable_body(OTHER_KEY)),
|
||||
"kmsmatrixkeyadmin",
|
||||
SECRET,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// --- wrong action: the administrator template withholds service-wide powers -
|
||||
assert_admin_denied(
|
||||
&env,
|
||||
"kmsmatrixkeyadmin",
|
||||
http::Method::GET,
|
||||
"/rustfs/admin/v3/kms/config",
|
||||
None,
|
||||
"KMSKeyAdministrator reading the KMS backend configuration (kms:Configure)",
|
||||
)
|
||||
.await?;
|
||||
assert_admin_denied(
|
||||
&env,
|
||||
"kmsmatrixkeyadmin",
|
||||
http::Method::GET,
|
||||
"/rustfs/admin/v3/kms/backup",
|
||||
None,
|
||||
"KMSKeyAdministrator exporting a backup bundle (kms:Backup)",
|
||||
)
|
||||
.await?;
|
||||
// Separation of duties: managing a key never implies using it.
|
||||
assert_admin_denied(
|
||||
&env,
|
||||
"kmsmatrixkeyadmin",
|
||||
http::Method::POST,
|
||||
"/rustfs/admin/v3/kms/generate-data-key",
|
||||
Some(serde_json::json!({ "key_id": ALLOWED_KEY }).to_string()),
|
||||
"KMSKeyAdministrator generating a data key (kms:GenerateDataKey)",
|
||||
)
|
||||
.await?;
|
||||
|
||||
// --- wrong action: the auditor template is read-only ----------------------
|
||||
wait_for_admin_success(&env, "kmsmatrixauditor", http::Method::GET, "/rustfs/admin/v3/kms/keys", None).await?;
|
||||
assert_admin_denied(
|
||||
&env,
|
||||
"kmsmatrixauditor",
|
||||
http::Method::POST,
|
||||
"/rustfs/admin/v3/kms/keys/disable",
|
||||
Some(disable_body(ALLOWED_KEY)),
|
||||
"KMSAuditor disabling a key (kms:DisableKey)",
|
||||
)
|
||||
.await?;
|
||||
|
||||
// --- wrong key ------------------------------------------------------------
|
||||
wait_for_admin_success(
|
||||
&env,
|
||||
"kmsmatrixscopedadmin",
|
||||
http::Method::POST,
|
||||
"/rustfs/admin/v3/kms/keys/disable",
|
||||
Some(disable_body(ALLOWED_KEY)),
|
||||
)
|
||||
.await?;
|
||||
assert_admin_denied(
|
||||
&env,
|
||||
"kmsmatrixscopedadmin",
|
||||
http::Method::POST,
|
||||
"/rustfs/admin/v3/kms/keys/disable",
|
||||
Some(disable_body(OTHER_KEY)),
|
||||
"key-scoped administrator disabling a key outside its scope",
|
||||
)
|
||||
.await?;
|
||||
// --- wrong action, same key ----------------------------------------------
|
||||
assert_admin_denied(
|
||||
&env,
|
||||
"kmsmatrixscopedadmin",
|
||||
http::Method::POST,
|
||||
"/rustfs/admin/v3/kms/keys/rotate",
|
||||
Some(disable_body(ALLOWED_KEY)),
|
||||
"key-scoped administrator rotating a key it may only enable and disable",
|
||||
)
|
||||
.await?;
|
||||
|
||||
// --- wrong identity -------------------------------------------------------
|
||||
provision_user(&env, "kmsmatrixnokms", &policy_document(vec![s3_full_access_statement()])).await?;
|
||||
assert_admin_denied(
|
||||
&env,
|
||||
"kmsmatrixnokms",
|
||||
http::Method::POST,
|
||||
"/rustfs/admin/v3/kms/keys/disable",
|
||||
Some(disable_body(ALLOWED_KEY)),
|
||||
"identity holding no kms grant disabling a key",
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -417,6 +417,22 @@ async fn test_vault_kms_key_crud(
|
||||
|
||||
info!("✅ Read: Successfully listed keys, found test key");
|
||||
|
||||
// A waiting window outside 7-30 days is refused at the endpoint for this
|
||||
// backend too: the bound is enforced once in the service (rustfs/backlog#1585).
|
||||
for days in [6, 31] {
|
||||
let window_error = crate::common::execute_awscurl(
|
||||
&format!("{base_url}/rustfs/admin/v3/kms/keys/delete?keyId={key_id}&pending_window_in_days={days}"),
|
||||
"DELETE",
|
||||
None,
|
||||
access_key,
|
||||
secret_key,
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.ok_or_else(|| format!("A {days}-day deletion window must be refused"))?;
|
||||
info!("✅ Delete window {} correctly refused: {}", days, window_error);
|
||||
}
|
||||
|
||||
// Delete
|
||||
let delete_response = crate::common::execute_awscurl(
|
||||
&format!("{base_url}/rustfs/admin/v3/kms/keys/delete?keyId={key_id}"),
|
||||
@@ -449,29 +465,32 @@ async fn test_vault_kms_key_crud(
|
||||
|
||||
info!("✅ Delete verification: Key state correctly changed to: {}", key_state);
|
||||
|
||||
// Force Delete - Force immediate deletion for PendingDeletion key
|
||||
let force_delete_response = crate::common::execute_awscurl(
|
||||
// Force Delete - the query string can no longer ask for immediate deletion,
|
||||
// and a default server refuses it in any case (rustfs/backlog#1585):
|
||||
// destroying the key material immediately would take every object encrypted
|
||||
// under the key with it.
|
||||
let force_delete_error = crate::common::execute_awscurl(
|
||||
&format!("{base_url}/rustfs/admin/v3/kms/keys/delete?keyId={key_id}&force_immediate=true"),
|
||||
"DELETE",
|
||||
None,
|
||||
access_key,
|
||||
secret_key,
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
.expect_err("Immediate KMS key deletion must be refused on a default server");
|
||||
info!("✅ Force Delete: correctly refused for key {}: {}", key_id, force_delete_error);
|
||||
|
||||
// Parse and validate the force delete response
|
||||
let force_delete_result: serde_json::Value = serde_json::from_str(&force_delete_response)?;
|
||||
assert_eq!(force_delete_result["success"], true, "Force delete operation must return success=true");
|
||||
info!("✅ Force Delete: Successfully force deleted key: {}", key_id);
|
||||
// The refused request must leave the key exactly as it was: still present,
|
||||
// still pending deletion, still recoverable through cancel-deletion.
|
||||
let describe_after_refusal =
|
||||
crate::common::awscurl_get(&format!("{base_url}/rustfs/admin/v3/kms/keys/{key_id}"), access_key, secret_key).await?;
|
||||
let describe_after_refusal: serde_json::Value = serde_json::from_str(&describe_after_refusal)?;
|
||||
assert_eq!(
|
||||
describe_after_refusal["key_metadata"]["key_state"], "PendingDeletion",
|
||||
"A refused immediate deletion must leave the key pending deletion"
|
||||
);
|
||||
|
||||
// Verify key no longer exists after force deletion (should return error)
|
||||
let describe_force_deleted_result =
|
||||
crate::common::awscurl_get(&format!("{base_url}/rustfs/admin/v3/kms/keys/{key_id}"), access_key, secret_key).await;
|
||||
|
||||
// After force deletion, key should not be found (GET should fail)
|
||||
assert!(describe_force_deleted_result.is_err(), "Force deleted key should not be found");
|
||||
|
||||
info!("✅ Force Delete verification: Key was permanently deleted and is no longer accessible");
|
||||
info!("✅ Force Delete verification: Key survived the refused immediate deletion");
|
||||
|
||||
info!("Vault KMS key CRUD operations completed successfully");
|
||||
Ok(())
|
||||
|
||||
@@ -53,3 +53,6 @@ mod copy_object_version_restore_sse_test;
|
||||
|
||||
#[cfg(test)]
|
||||
mod configured_roundtrip_test;
|
||||
|
||||
#[cfg(test)]
|
||||
mod kms_authorization_negative_matrix_test;
|
||||
|
||||
@@ -15,9 +15,7 @@
|
||||
|
||||
use super::{grpc_lock_client::GrpcLockClient, grpc_lock_server::spawn_lock_server};
|
||||
use rustfs_lock::client::{LockClient, local::LocalClient};
|
||||
use rustfs_lock::{
|
||||
GlobalLockManager, LockError, LockInfo, LockRequest, LockResponse, LockStats, LockType, NamespaceLock, ObjectKey,
|
||||
};
|
||||
use rustfs_lock::{GlobalLockManager, LockInfo, LockRequest, LockResponse, LockStats, LockType, NamespaceLock, ObjectKey};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -35,7 +33,11 @@ struct FailingClient;
|
||||
#[async_trait::async_trait]
|
||||
impl rustfs_lock::LockClient for FailingClient {
|
||||
async fn acquire_lock(&self, _request: &rustfs_lock::LockRequest) -> rustfs_lock::Result<LockResponse> {
|
||||
Err(LockError::internal("simulated gRPC node failure"))
|
||||
// Match RemoteClient's transport-failure response so the coordinator can count this node toward quorum loss.
|
||||
Ok(LockResponse::failure(
|
||||
"Remote lock RPC failed: simulated gRPC node failure",
|
||||
Duration::ZERO,
|
||||
))
|
||||
}
|
||||
|
||||
async fn release(&self, _lock_id: &rustfs_lock::LockId) -> rustfs_lock::Result<bool> {
|
||||
|
||||
@@ -382,7 +382,6 @@ struct ManualTransitionRunReport {
|
||||
skipped_delete_marker: u64,
|
||||
skipped_directory: u64,
|
||||
skipped_replication: u64,
|
||||
skipped_already_transitioned: u64,
|
||||
skipped_already_in_flight: u64,
|
||||
skipped_queue_full: u64,
|
||||
skipped_queue_closed: u64,
|
||||
@@ -408,41 +407,6 @@ fn assert_completed_or_in_flight_partial(state: &str, report: &ManualTransitionR
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_conflict_winner_report(state: &str, report: &ManualTransitionRunReport, expected_objects: u64, context: &str) {
|
||||
assert_completed_or_in_flight_partial(state, report, context);
|
||||
if report.skipped_already_in_flight > 0 {
|
||||
assert!(
|
||||
report.scanned <= expected_objects,
|
||||
"{context}: scanned more objects than the conflict scope contains: {report:#?}"
|
||||
);
|
||||
assert!(
|
||||
report.eligible <= expected_objects,
|
||||
"{context}: marked more objects eligible than the conflict scope contains: {report:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
report.enqueued + report.skipped_already_in_flight,
|
||||
report.eligible,
|
||||
"{context}: partial in-flight accounting must cover every eligible object: {report:#?}"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(report.scanned, expected_objects, "{context}: {report:#?}");
|
||||
assert_eq!(
|
||||
report.eligible + report.skipped_already_transitioned,
|
||||
expected_objects,
|
||||
"{context}: {report:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
report.enqueued + report.skipped_already_in_flight,
|
||||
expected_objects,
|
||||
"{context}: {report:#?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
report.transition_completed, report.enqueued,
|
||||
"{context}: winner must wait for all queued transitions: {report:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ManualTransitionQueueSnapshot {
|
||||
queue_capacity: u64,
|
||||
@@ -1276,8 +1240,15 @@ async fn test_manual_transition_async_scope_conflicts_report_active_job() -> Tes
|
||||
cold_client.create_bucket().bucket(TIER_BUCKET).send().await?;
|
||||
|
||||
let mut hot = RustFSTestEnvironment::new().await?;
|
||||
hot.start_rustfs_server_with_env(vec![], &[("RUSTFS_SCANNER_ENABLED", "false"), ("RUSTFS_SCANNER_CYCLE", "3600")])
|
||||
.await?;
|
||||
hot.start_rustfs_server_with_env(
|
||||
vec![],
|
||||
&[
|
||||
("RUSTFS_SCANNER_ENABLED", "false"),
|
||||
("RUSTFS_SCANNER_CYCLE", "3600"),
|
||||
(MANUAL_TRANSITION_CANCEL_BARRIER_ENV, "1"),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
let hot_client = hot.create_s3_client();
|
||||
add_rustfs_tier(&hot, &cold).await?;
|
||||
|
||||
@@ -1347,20 +1318,21 @@ async fn test_manual_transition_async_scope_conflicts_report_active_job() -> Tes
|
||||
assert_eq!(conflict.cancel_endpoint, status_endpoint);
|
||||
assert!(!conflict.scope_key.is_empty());
|
||||
|
||||
manual_transition_job_cancel(&hot, cancel_endpoint).await?;
|
||||
|
||||
let terminal = wait_for_manual_transition_job_terminal(&hot, status_endpoint, MANUAL_ASYNC_CONFLICT_TERMINAL_TIMEOUT).await?;
|
||||
assert_eq!(terminal.job_id, job_id);
|
||||
assert_eq!(terminal.status, "cancelled", "terminal conflict winner response: {terminal:#?}");
|
||||
assert!(!terminal.report.dry_run);
|
||||
assert_eq!(terminal.report.bucket, MANUAL_ASYNC_CONFLICT_BUCKET);
|
||||
assert_eq!(terminal.report.prefix, accepted.report.prefix);
|
||||
assert_conflict_winner_report(
|
||||
&terminal.status,
|
||||
&terminal.report,
|
||||
MANUAL_ASYNC_CONFLICT_OBJECTS as u64,
|
||||
"terminal conflict winner response",
|
||||
assert!(terminal.report.cancelled, "terminal conflict winner response: {terminal:#?}");
|
||||
assert_eq!(terminal.report.scanned, 0, "terminal conflict winner response: {terminal:#?}");
|
||||
assert_eq!(terminal.report.enqueued, 0, "terminal conflict winner response: {terminal:#?}");
|
||||
assert_eq!(
|
||||
terminal.report.transition_completed, 0,
|
||||
"terminal conflict winner response: {terminal:#?}"
|
||||
);
|
||||
assert_eq!(terminal.report.dry_run_eligible, 0, "terminal conflict winner response: {terminal:#?}");
|
||||
assert_eq!(terminal.report.transition_failed, 0, "terminal conflict winner response: {terminal:#?}");
|
||||
assert_eq!(terminal.report.tier_failure, 0, "terminal conflict winner response: {terminal:#?}");
|
||||
let after_remote_count = cold_tier_object_count(&cold_client).await?;
|
||||
assert!(after_remote_count >= before_remote_count);
|
||||
assert!(after_remote_count <= before_remote_count + MANUAL_ASYNC_CONFLICT_OBJECTS);
|
||||
|
||||
@@ -29,8 +29,9 @@ use aws_sdk_s3::types::{
|
||||
use aws_sdk_s3::{Client, Config};
|
||||
use base64::{Engine, engine::general_purpose::STANDARD as BASE64_STANDARD};
|
||||
use bytes::Bytes;
|
||||
use flate2::read::GzDecoder;
|
||||
use futures::{Stream, StreamExt};
|
||||
use http::header::{CONTENT_TYPE, HOST};
|
||||
use http::header::{CONTENT_ENCODING, CONTENT_TYPE, HOST};
|
||||
use http_body_util::{BodyExt, Full};
|
||||
use hyper::body::Incoming;
|
||||
use hyper::server::conn::http1;
|
||||
@@ -38,6 +39,10 @@ use hyper::service::service_fn;
|
||||
use hyper::{Request, Response};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use local_ip_address::local_ip;
|
||||
use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest;
|
||||
use opentelemetry_proto::tonic::common::v1::{KeyValue, any_value::Value as AnyValue};
|
||||
use opentelemetry_proto::tonic::metrics::v1::{Metric, metric, number_data_point};
|
||||
use prost::Message;
|
||||
use rcgen::{
|
||||
BasicConstraints, CertificateParams, CertifiedIssuer, DnType, ExtendedKeyUsagePurpose, IsCa, KeyPair, KeyUsagePurpose,
|
||||
SanType, generate_simple_self_signed,
|
||||
@@ -56,6 +61,7 @@ use sha2::{Digest, Sha256};
|
||||
use std::collections::BTreeMap;
|
||||
use std::convert::Infallible;
|
||||
use std::error::Error;
|
||||
use std::io::Read;
|
||||
use std::net::IpAddr;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
@@ -64,11 +70,13 @@ use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use time::{Duration as TimeDuration, OffsetDateTime};
|
||||
use tokio::fs;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::watch;
|
||||
use tokio::sync::{Mutex, watch};
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::task::JoinSet;
|
||||
use tokio::time::{Duration, sleep, timeout};
|
||||
|
||||
type TestResult = Result<(), Box<dyn Error + Send + Sync>>;
|
||||
type BacklogMetricPoints = Arc<Mutex<BTreeMap<String, BTreeMap<String, (u64, f64)>>>>;
|
||||
|
||||
/// A replication source server validates the remote target endpoint, and the e2e
|
||||
/// target runs on loopback (127.0.0.1), which RustFS's SSRF egress guard rejects by
|
||||
@@ -107,6 +115,252 @@ const REPL17_KMS_KEY_ID: &str = "repl17-local-key";
|
||||
const REPL17_SSEC_KEY: &str = "01234567890123456789012345678901";
|
||||
const REPLICATION_FAILED_EVENT: &str = "s3:Replication:OperationFailedReplication";
|
||||
const REPLICATION_EVENT_MAX_BUFFER_BYTES: usize = 1024 * 1024;
|
||||
const OTLP_METRICS_BODY_LIMIT: u64 = 4 * 1024 * 1024;
|
||||
const BUCKET_LABEL: &str = "bucket";
|
||||
const TOTAL_FAILED_COUNT_METRIC: &str = "rustfs_bucket_replication_total_failed_count";
|
||||
const CURRENT_BACKLOG_COUNT_METRIC: &str = "rustfs_bucket_replication_current_backlog_count";
|
||||
const CURRENT_BACKLOG_BYTES_METRIC: &str = "rustfs_bucket_replication_current_backlog_bytes";
|
||||
const MRF_PENDING_COUNT_METRIC: &str = "rustfs_bucket_replication_mrf_pending_count";
|
||||
const MRF_PENDING_BYTES_METRIC: &str = "rustfs_bucket_replication_mrf_pending_bytes";
|
||||
|
||||
struct ReplicationBacklogMetricCollector {
|
||||
endpoint: String,
|
||||
values: BacklogMetricPoints,
|
||||
task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl ReplicationBacklogMetricCollector {
|
||||
async fn start() -> Result<Self, Box<dyn Error + Send + Sync>> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let endpoint = format!("http://{}/v1/metrics", listener.local_addr()?);
|
||||
let values = Arc::new(Mutex::new(BTreeMap::new()));
|
||||
let task_values = values.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
loop {
|
||||
let Ok((stream, _)) = listener.accept().await else {
|
||||
break;
|
||||
};
|
||||
let values = task_values.clone();
|
||||
tokio::spawn(async move {
|
||||
let _ = http1::Builder::new()
|
||||
.serve_connection(
|
||||
TokioIo::new(stream),
|
||||
service_fn(move |request| handle_backlog_metric_export(request, values.clone())),
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Self { endpoint, values, task })
|
||||
}
|
||||
|
||||
fn root_endpoint(&self) -> &str {
|
||||
self.endpoint.trim_end_matches("/v1/metrics")
|
||||
}
|
||||
|
||||
async fn bucket_metric_value(&self, metric: &str, bucket: &str) -> f64 {
|
||||
self.values
|
||||
.lock()
|
||||
.await
|
||||
.get(metric)
|
||||
.and_then(|buckets| buckets.get(bucket))
|
||||
.map(|(_, value)| *value)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn wait_for_bucket_metric(
|
||||
&self,
|
||||
metric: &str,
|
||||
bucket: &str,
|
||||
expected: impl Fn(f64) -> bool,
|
||||
description: &str,
|
||||
) -> Result<f64, Box<dyn Error + Send + Sync>> {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
let value = self.bucket_metric_value(metric, bucket).await;
|
||||
if expected(value) {
|
||||
return Ok(value);
|
||||
}
|
||||
if tokio::time::Instant::now() >= deadline {
|
||||
let snapshot = self.values.lock().await.clone();
|
||||
return Err(format!("timed out waiting for {metric} on bucket {bucket} to satisfy {description}; last={value}, snapshot={snapshot:?}").into());
|
||||
}
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ReplicationBacklogMetricCollector {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_backlog_metric_export(
|
||||
request: Request<Incoming>,
|
||||
values: BacklogMetricPoints,
|
||||
) -> Result<Response<Full<Bytes>>, Infallible> {
|
||||
if request.uri().path() != "/v1/metrics" {
|
||||
return Ok(empty_http_response(StatusCode::NOT_FOUND));
|
||||
}
|
||||
|
||||
let gzip = request
|
||||
.headers()
|
||||
.get(CONTENT_ENCODING)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case("gzip"));
|
||||
let Ok(collected) = request.into_body().collect().await else {
|
||||
return Ok(empty_http_response(StatusCode::BAD_REQUEST));
|
||||
};
|
||||
let body = collected.to_bytes();
|
||||
if body.len() as u64 > OTLP_METRICS_BODY_LIMIT {
|
||||
return Ok(empty_http_response(StatusCode::PAYLOAD_TOO_LARGE));
|
||||
}
|
||||
let payload = if gzip {
|
||||
let mut decoder = GzDecoder::new(body.as_ref());
|
||||
let mut decoded = Vec::new();
|
||||
if decoder
|
||||
.by_ref()
|
||||
.take(OTLP_METRICS_BODY_LIMIT + 1)
|
||||
.read_to_end(&mut decoded)
|
||||
.is_err()
|
||||
|| decoded.len() as u64 > OTLP_METRICS_BODY_LIMIT
|
||||
{
|
||||
return Ok(empty_http_response(StatusCode::BAD_REQUEST));
|
||||
}
|
||||
decoded
|
||||
} else {
|
||||
body.to_vec()
|
||||
};
|
||||
|
||||
match ExportMetricsServiceRequest::decode(payload.as_slice()) {
|
||||
Ok(export) => {
|
||||
let mut values = values.lock().await;
|
||||
record_backlog_metrics(&export, &mut values);
|
||||
Ok(empty_http_response(StatusCode::OK))
|
||||
}
|
||||
Err(_) => Ok(empty_http_response(StatusCode::BAD_REQUEST)),
|
||||
}
|
||||
}
|
||||
|
||||
fn empty_http_response(status: StatusCode) -> Response<Full<Bytes>> {
|
||||
Response::builder()
|
||||
.status(status)
|
||||
.body(Full::new(Bytes::new()))
|
||||
.expect("static HTTP response is valid")
|
||||
}
|
||||
|
||||
fn record_backlog_metrics(export: &ExportMetricsServiceRequest, values: &mut BTreeMap<String, BTreeMap<String, (u64, f64)>>) {
|
||||
for resource_metrics in &export.resource_metrics {
|
||||
for scope_metrics in &resource_metrics.scope_metrics {
|
||||
for metric in &scope_metrics.metrics {
|
||||
record_backlog_metric(metric, values);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record_backlog_metric(metric: &Metric, values: &mut BTreeMap<String, BTreeMap<String, (u64, f64)>>) {
|
||||
if ![
|
||||
TOTAL_FAILED_COUNT_METRIC,
|
||||
CURRENT_BACKLOG_COUNT_METRIC,
|
||||
CURRENT_BACKLOG_BYTES_METRIC,
|
||||
MRF_PENDING_COUNT_METRIC,
|
||||
MRF_PENDING_BYTES_METRIC,
|
||||
]
|
||||
.contains(&metric.name.as_str())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let points = match &metric.data {
|
||||
Some(metric::Data::Gauge(gauge)) => gauge.data_points.as_slice(),
|
||||
Some(metric::Data::Sum(sum)) => sum.data_points.as_slice(),
|
||||
_ => return,
|
||||
};
|
||||
for point in points {
|
||||
let Some(bucket) = attribute_string(&point.attributes, BUCKET_LABEL) else {
|
||||
continue;
|
||||
};
|
||||
let Some(value) = number_point_value(point.value.as_ref()) else {
|
||||
continue;
|
||||
};
|
||||
values
|
||||
.entry(metric.name.clone())
|
||||
.or_default()
|
||||
.entry(bucket.to_string())
|
||||
.and_modify(|current| {
|
||||
if point.time_unix_nano >= current.0 {
|
||||
*current = (point.time_unix_nano, value);
|
||||
}
|
||||
})
|
||||
.or_insert((point.time_unix_nano, value));
|
||||
}
|
||||
}
|
||||
|
||||
fn number_point_value(value: Option<&number_data_point::Value>) -> Option<f64> {
|
||||
match value? {
|
||||
number_data_point::Value::AsDouble(value) => Some(*value),
|
||||
number_data_point::Value::AsInt(value) => Some(*value as f64),
|
||||
}
|
||||
}
|
||||
|
||||
fn attribute_string<'a>(attributes: &'a [KeyValue], wanted_key: &str) -> Option<&'a str> {
|
||||
attributes.iter().find_map(|attribute| {
|
||||
if attribute.key != wanted_key {
|
||||
return None;
|
||||
}
|
||||
match attribute.value.as_ref()?.value.as_ref()? {
|
||||
AnyValue::StringValue(value) => Some(value.as_str()),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
struct SlowReplicationTargetGuard {
|
||||
task: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl SlowReplicationTargetGuard {
|
||||
async fn bind(address: &str, response_delay: Duration) -> Result<Self, Box<dyn Error + Send + Sync>> {
|
||||
let listener = TcpListener::bind(address).await?;
|
||||
let task = tokio::spawn(async move {
|
||||
loop {
|
||||
let Ok((stream, _)) = listener.accept().await else {
|
||||
break;
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
let _ = http1::Builder::new()
|
||||
.serve_connection(
|
||||
TokioIo::new(stream),
|
||||
service_fn(move |_request| async move {
|
||||
sleep(response_delay).await;
|
||||
Ok::<_, Infallible>(empty_http_response(StatusCode::SERVICE_UNAVAILABLE))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
});
|
||||
Ok(Self { task: Some(task) })
|
||||
}
|
||||
|
||||
async fn stop(mut self) {
|
||||
if let Some(task) = self.task.take() {
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SlowReplicationTargetGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(task) = self.task.take() {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Deserialize)]
|
||||
struct ReplicationResetStatusResponse {
|
||||
@@ -1253,6 +1507,10 @@ async fn build_sse_replication_pair(
|
||||
("RUSTFS_KMS_KEY_DIR", source_kms_key_dir.as_str()),
|
||||
("RUSTFS_KMS_DEFAULT_KEY_ID", REPL17_KMS_KEY_ID),
|
||||
("RUSTFS_KMS_ALLOW_INSECURE_DEV_DEFAULTS", "true"),
|
||||
// Per-key KMS authorization is on so this contract is pinned in the
|
||||
// configuration replication will eventually ship with: the replication
|
||||
// worker carries no request identity and must stay exempt.
|
||||
("RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY", "true"),
|
||||
]);
|
||||
}
|
||||
source_env.start_rustfs_server_with_env(vec![], &source_process_env).await?;
|
||||
@@ -1265,6 +1523,7 @@ async fn build_sse_replication_pair(
|
||||
("RUSTFS_KMS_KEY_DIR", target_kms_key_dir.as_str()),
|
||||
("RUSTFS_KMS_DEFAULT_KEY_ID", REPL17_KMS_KEY_ID),
|
||||
("RUSTFS_KMS_ALLOW_INSECURE_DEV_DEFAULTS", "true"),
|
||||
("RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY", "true"),
|
||||
]);
|
||||
}
|
||||
target_env
|
||||
@@ -3659,6 +3918,139 @@ async fn test_bucket_replication_recovers_after_target_outage() -> TestResult {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// backlog#1610 - black-box bucket replication backlog observability.
|
||||
///
|
||||
/// The source exports metrics through the same OTLP path production uses. A slow
|
||||
/// loopback target keeps replication workers occupied long enough for the metrics
|
||||
/// runtime to publish non-zero bucket backlog gauges; after the real target
|
||||
/// returns, replication must converge and the exported current/MRF pending gauges
|
||||
/// must settle back to zero even though the historical failed counter remains
|
||||
/// non-zero.
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn test_bucket_replication_backlog_metrics_observe_outage_and_recovery() -> TestResult {
|
||||
init_logging();
|
||||
|
||||
let collector = ReplicationBacklogMetricCollector::start().await?;
|
||||
let mut source_env = RustFSTestEnvironment::new().await?;
|
||||
let metric_root = collector.root_endpoint().to_string();
|
||||
let metric_endpoint = collector.endpoint.clone();
|
||||
let mut source_env_vars: Vec<(&str, &str)> = replication_fast_env().into_iter().collect();
|
||||
source_env_vars.extend_from_slice(LOOPBACK_REPLICATION_TARGET_ENV);
|
||||
source_env_vars.extend_from_slice(FAST_SCANNER_ENV);
|
||||
source_env_vars.extend_from_slice(&[
|
||||
("RUSTFS_OBS_ENDPOINT", metric_root.as_str()),
|
||||
("RUSTFS_OBS_METRIC_ENDPOINT", metric_endpoint.as_str()),
|
||||
("RUSTFS_OBS_METRICS_EXPORT_ENABLED", "true"),
|
||||
("RUSTFS_OBS_TRACES_EXPORT_ENABLED", "false"),
|
||||
("RUSTFS_OBS_LOGS_EXPORT_ENABLED", "false"),
|
||||
("RUSTFS_OBS_METER_INTERVAL", "1"),
|
||||
("RUSTFS_OBS_USE_STDOUT", "false"),
|
||||
("RUSTFS_METRICS_BUCKET_REPLICATION_BANDWIDTH_INTERVAL_SEC", "1"),
|
||||
]);
|
||||
source_env.start_rustfs_server_with_env(vec![], &source_env_vars).await?;
|
||||
|
||||
let mut target_env = RustFSTestEnvironment::new().await?;
|
||||
target_env.start_rustfs_server_without_cleanup(vec![]).await?;
|
||||
|
||||
let source_bucket = "repl-backlog-metrics-src";
|
||||
let target_bucket = "repl-backlog-metrics-dst";
|
||||
let source_client = source_env.create_s3_client();
|
||||
let target_client = target_env.create_s3_client();
|
||||
|
||||
source_client.create_bucket().bucket(source_bucket).send().await?;
|
||||
target_client.create_bucket().bucket(target_bucket).send().await?;
|
||||
enable_bucket_versioning(&source_env, source_bucket).await?;
|
||||
enable_bucket_versioning(&target_env, target_bucket).await?;
|
||||
|
||||
let target_arn = set_replication_target(&source_env, source_bucket, &target_env, target_bucket).await?;
|
||||
put_bucket_replication(&source_env, source_bucket, &target_arn).await?;
|
||||
|
||||
source_client
|
||||
.put_object()
|
||||
.bucket(source_bucket)
|
||||
.key("before-outage.txt")
|
||||
.body(ByteStream::from_static(b"baseline written before backlog metrics outage"))
|
||||
.send()
|
||||
.await?;
|
||||
assert_replication_converged(&source_client, source_bucket, &target_client, target_bucket).await?;
|
||||
|
||||
target_env.stop_server();
|
||||
let slow_target = SlowReplicationTargetGuard::bind(&target_env.address, Duration::from_secs(5)).await?;
|
||||
|
||||
let outage_keys = ["metrics-outage-1.txt", "metrics-outage-2.txt", "metrics-outage-3.txt"];
|
||||
for key in outage_keys {
|
||||
source_client
|
||||
.put_object()
|
||||
.bucket(source_bucket)
|
||||
.key(key)
|
||||
.body(ByteStream::from(
|
||||
format!("written while backlog metrics target was slow: {key}").into_bytes(),
|
||||
))
|
||||
.send()
|
||||
.await?;
|
||||
}
|
||||
|
||||
let current_backlog = collector
|
||||
.wait_for_bucket_metric(
|
||||
CURRENT_BACKLOG_COUNT_METRIC,
|
||||
source_bucket,
|
||||
|value| value >= 1.0,
|
||||
"be at least 1 during outage",
|
||||
)
|
||||
.await?;
|
||||
let current_bytes = collector
|
||||
.wait_for_bucket_metric(
|
||||
CURRENT_BACKLOG_BYTES_METRIC,
|
||||
source_bucket,
|
||||
|value| value > 0.0,
|
||||
"report bytes during outage",
|
||||
)
|
||||
.await?;
|
||||
assert!(
|
||||
current_bytes >= current_backlog,
|
||||
"backlog bytes should be at least the object count while queued; count={current_backlog}, bytes={current_bytes}"
|
||||
);
|
||||
let failed_count = collector
|
||||
.wait_for_bucket_metric(
|
||||
TOTAL_FAILED_COUNT_METRIC,
|
||||
source_bucket,
|
||||
|value| value >= 1.0,
|
||||
"record at least one failed replication attempt during outage",
|
||||
)
|
||||
.await?;
|
||||
|
||||
slow_target.stop().await;
|
||||
target_env.restart_server_preserving_data(vec![], &[]).await?;
|
||||
|
||||
assert_replication_converged(&source_client, source_bucket, &target_client, target_bucket).await?;
|
||||
for metric in [
|
||||
CURRENT_BACKLOG_COUNT_METRIC,
|
||||
CURRENT_BACKLOG_BYTES_METRIC,
|
||||
MRF_PENDING_COUNT_METRIC,
|
||||
MRF_PENDING_BYTES_METRIC,
|
||||
] {
|
||||
collector
|
||||
.wait_for_bucket_metric(metric, source_bucket, |value| value == 0.0, "settle back to zero after recovery")
|
||||
.await?;
|
||||
}
|
||||
let final_failed_count = collector.bucket_metric_value(TOTAL_FAILED_COUNT_METRIC, source_bucket).await;
|
||||
assert!(
|
||||
final_failed_count >= failed_count,
|
||||
"historical failed counter should remain non-zero after recovery while current backlog is zero; before={failed_count}, after={final_failed_count}"
|
||||
);
|
||||
|
||||
let target_state = list_replication_state(&target_client, target_bucket).await?;
|
||||
for key in ["before-outage.txt"].into_iter().chain(outage_keys) {
|
||||
assert!(
|
||||
target_state.iter().any(|entry| entry.key == key && !entry.delete_marker),
|
||||
"target missing object {key} after backlog metrics recovery; state={target_state:?}"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// backlog#1147 repl-5, scenario (b) — failure state survives a source restart
|
||||
/// (mirrors backlog#858 delete-decision re-derivation and #859 no-drop).
|
||||
///
|
||||
|
||||
@@ -12,22 +12,35 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use crate::common::{RustFSTestEnvironment, init_logging, local_http_client};
|
||||
use crate::common::{RustFSTestEnvironment, admin_ok, init_logging};
|
||||
use aws_sdk_sts::config::retry::RetryConfig;
|
||||
use aws_sdk_sts::config::{Credentials, Region};
|
||||
use aws_sdk_sts::error::ProvideErrorMetadata;
|
||||
use aws_sdk_sts::operation::RequestId;
|
||||
use aws_sdk_sts::{Client, Config};
|
||||
use aws_smithy_http_client::Builder as SmithyHttpClientBuilder;
|
||||
use http::header::{CONTENT_TYPE, HOST};
|
||||
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
||||
use rustfs_signer::sign_v4;
|
||||
use s3s::Body;
|
||||
use bytes::Bytes;
|
||||
use http::header::{AUTHORIZATION, CONTENT_TYPE};
|
||||
use http::{Request, Response};
|
||||
use http_body_util::{BodyExt, Full};
|
||||
use hyper::body::Incoming;
|
||||
use hyper::server::conn::http1;
|
||||
use hyper::service::service_fn;
|
||||
use hyper_util::rt::TokioIo;
|
||||
use serde_json::Value;
|
||||
use serial_test::serial;
|
||||
use std::collections::BTreeSet;
|
||||
use std::convert::Infallible;
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::{Notify, mpsc};
|
||||
use tokio::task::{JoinHandle, JoinSet};
|
||||
use tokio::time::{Duration, timeout};
|
||||
|
||||
type BoxError = Box<dyn Error + Send + Sync>;
|
||||
type TestResult = Result<(), BoxError>;
|
||||
const OPA_AUTH_TOKEN: &str = "sts-opa-token";
|
||||
|
||||
fn sts_client(url: &str, access_key: &str, secret_key: &str, session_token: Option<&str>) -> Client {
|
||||
let mut config = Config::builder()
|
||||
@@ -49,32 +62,14 @@ fn sts_client(url: &str, access_key: &str, secret_key: &str, session_token: Opti
|
||||
}
|
||||
|
||||
async fn create_root_service_account(env: &RustFSTestEnvironment) -> Result<(String, String), BoxError> {
|
||||
let path = "/rustfs/admin/v3/add-service-accounts";
|
||||
let url = format!("{}{path}", env.url);
|
||||
let uri = url.parse::<http::Uri>()?;
|
||||
let authority = uri.authority().ok_or("admin URL missing authority")?.to_string();
|
||||
let body = serde_json::json!({ "targetUser": env.access_key.clone() }).to_string();
|
||||
let request = http::Request::builder()
|
||||
.method(http::Method::PUT)
|
||||
.uri(uri)
|
||||
.header(HOST, authority)
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.header("x-amz-content-sha256", UNSIGNED_PAYLOAD)
|
||||
.body(Body::empty())?;
|
||||
let content_length = i64::try_from(body.len()).map_err(|_| "service account request body is too large")?;
|
||||
let signed = sign_v4(request, content_length, &env.access_key, &env.secret_key, "", "us-east-1");
|
||||
let mut request = local_http_client().put(&url);
|
||||
for (name, value) in signed.headers() {
|
||||
request = request.header(name, value);
|
||||
}
|
||||
let response = request.body(body).send().await?;
|
||||
let status = response.status();
|
||||
let body = response.text().await?;
|
||||
if !status.is_success() {
|
||||
return Err(format!("create service account failed: {status} {body}").into());
|
||||
}
|
||||
|
||||
let response: serde_json::Value = serde_json::from_str(&body)?;
|
||||
let body = admin_ok(
|
||||
env,
|
||||
http::Method::PUT,
|
||||
"/rustfs/admin/v3/add-service-accounts",
|
||||
Some(serde_json::json!({ "targetUser": env.access_key.clone() }).to_string()),
|
||||
)
|
||||
.await?;
|
||||
let response: Value = serde_json::from_str(&body)?;
|
||||
let access_key = response["credentials"]["accessKey"]
|
||||
.as_str()
|
||||
.ok_or("service account response should contain credentials.accessKey")?
|
||||
@@ -86,28 +81,237 @@ async fn create_root_service_account(env: &RustFSTestEnvironment) -> Result<(Str
|
||||
Ok((access_key, secret_key))
|
||||
}
|
||||
|
||||
async fn assert_chaining_denied(client: &Client, credential_kind: &str) -> TestResult {
|
||||
async fn create_user_with_policy(
|
||||
env: &RustFSTestEnvironment,
|
||||
user: &str,
|
||||
secret: &str,
|
||||
policy_name: &str,
|
||||
statements: Value,
|
||||
) -> TestResult {
|
||||
create_user(env, user, secret).await?;
|
||||
admin_ok(
|
||||
env,
|
||||
http::Method::PUT,
|
||||
&format!("/rustfs/admin/v3/add-canned-policy?name={policy_name}"),
|
||||
Some(
|
||||
serde_json::json!({
|
||||
"Version": "2012-10-17",
|
||||
"Statement": statements,
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
admin_ok(
|
||||
env,
|
||||
http::Method::POST,
|
||||
"/rustfs/admin/v3/idp/builtin/policy/attach",
|
||||
Some(serde_json::json!({ "policies": [policy_name], "user": user }).to_string()),
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn create_user(env: &RustFSTestEnvironment, user: &str, secret: &str) -> TestResult {
|
||||
admin_ok(
|
||||
env,
|
||||
http::Method::PUT,
|
||||
&format!("/rustfs/admin/v3/add-user?accessKey={user}"),
|
||||
Some(serde_json::json!({ "secretKey": secret, "status": "enabled" }).to_string()),
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn assert_access_denied(client: &Client, context: &str) -> TestResult {
|
||||
let error = client
|
||||
.assume_role()
|
||||
.role_arn("arn:aws:iam::123456789012:role/test")
|
||||
.role_session_name("sts-query-compat-e2e")
|
||||
.send()
|
||||
.await
|
||||
.expect_err("credential chaining must be denied");
|
||||
.expect_err("AssumeRole must be denied");
|
||||
let service_error = error
|
||||
.as_service_error()
|
||||
.ok_or_else(|| format!("{credential_kind} denial should deserialize as an STS service error: {error:?}"))?;
|
||||
.ok_or_else(|| format!("{context} should deserialize as an STS service error: {error:?}"))?;
|
||||
|
||||
assert_eq!(error.raw_response().map(|response| response.status().as_u16()), Some(403));
|
||||
assert_eq!(service_error.code(), Some("AccessDenied"));
|
||||
assert_eq!(service_error.message(), Some("Access Denied"));
|
||||
assert!(
|
||||
error.request_id().is_some_and(|request_id| !request_id.is_empty()),
|
||||
"{credential_kind} denial should include a request ID"
|
||||
"{context} should include a request ID"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_opa_request(
|
||||
request: Request<Incoming>,
|
||||
requests: mpsc::UnboundedSender<Value>,
|
||||
validation_started: mpsc::UnboundedSender<()>,
|
||||
validation_mode: OpaValidationMode,
|
||||
expected_authorization: Option<String>,
|
||||
) -> Result<Response<Full<Bytes>>, Infallible> {
|
||||
if let Some(expected_authorization) = expected_authorization
|
||||
&& request.headers().get(AUTHORIZATION).and_then(|value| value.to_str().ok()) != Some(expected_authorization.as_str())
|
||||
{
|
||||
return Ok(Response::builder()
|
||||
.status(401)
|
||||
.body(Full::new(Bytes::new()))
|
||||
.expect("static OPA unauthorized response must be valid"));
|
||||
}
|
||||
|
||||
let body = match request.into_body().collect().await {
|
||||
Ok(body) => body.to_bytes(),
|
||||
Err(error) => {
|
||||
return Ok(Response::builder()
|
||||
.status(400)
|
||||
.body(Full::new(Bytes::from(error.to_string())))
|
||||
.expect("static OPA error response must be valid"));
|
||||
}
|
||||
};
|
||||
|
||||
let payload = if body.is_empty() {
|
||||
None
|
||||
} else {
|
||||
match serde_json::from_slice::<Value>(&body) {
|
||||
Ok(payload) => Some(payload),
|
||||
Err(error) => {
|
||||
return Ok(Response::builder()
|
||||
.status(400)
|
||||
.body(Full::new(Bytes::from(error.to_string())))
|
||||
.expect("static OPA error response must be valid"));
|
||||
}
|
||||
}
|
||||
};
|
||||
if payload.is_none() {
|
||||
let _ = validation_started.send(());
|
||||
if let OpaValidationMode::DelayedUnavailable(release) = validation_mode {
|
||||
release.notified().await;
|
||||
return Ok(Response::builder()
|
||||
.status(503)
|
||||
.body(Full::new(Bytes::new()))
|
||||
.expect("static OPA unavailable response must be valid"));
|
||||
}
|
||||
}
|
||||
let allow = match payload.as_ref().and_then(|value| value.pointer("/input/identity/account")) {
|
||||
Some(Value::String(account)) if account == "opaallow" => payload
|
||||
.as_ref()
|
||||
.and_then(|value| value.pointer("/input/context/deny_only"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
Some(Value::String(account)) if account == "opadeny" => false,
|
||||
None => true,
|
||||
_ => false,
|
||||
};
|
||||
if let Some(payload) = payload {
|
||||
let _ = requests.send(payload);
|
||||
}
|
||||
let body =
|
||||
serde_json::to_vec(&serde_json::json!({ "result": { "allow": allow } })).expect("static OPA response must serialize");
|
||||
Ok(Response::builder()
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.body(Full::new(Bytes::from(body)))
|
||||
.expect("static OPA response must be valid"))
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum OpaValidationMode {
|
||||
Ready,
|
||||
DelayedUnavailable(Arc<Notify>),
|
||||
}
|
||||
|
||||
struct OpaMock {
|
||||
url: String,
|
||||
requests: mpsc::UnboundedReceiver<Value>,
|
||||
validation_started: mpsc::UnboundedReceiver<()>,
|
||||
validation_release: Option<Arc<Notify>>,
|
||||
task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl OpaMock {
|
||||
async fn start() -> Result<Self, BoxError> {
|
||||
Self::start_with_mode(OpaValidationMode::Ready, Some(OPA_AUTH_TOKEN)).await
|
||||
}
|
||||
|
||||
async fn start_delayed_unavailable() -> Result<Self, BoxError> {
|
||||
let release = Arc::new(Notify::new());
|
||||
Self::start_with_mode(OpaValidationMode::DelayedUnavailable(release), None).await
|
||||
}
|
||||
|
||||
async fn start_with_mode(validation_mode: OpaValidationMode, auth_token: Option<&str>) -> Result<Self, BoxError> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let url = format!("http://{}/v1/data/rustfs/authz/allow", listener.local_addr()?);
|
||||
let (requests_tx, requests) = mpsc::unbounded_channel();
|
||||
let (validation_started_tx, validation_started) = mpsc::unbounded_channel();
|
||||
let expected_authorization = auth_token.map(|token| format!("Bearer {token}"));
|
||||
let validation_release = match &validation_mode {
|
||||
OpaValidationMode::Ready => None,
|
||||
OpaValidationMode::DelayedUnavailable(release) => Some(Arc::clone(release)),
|
||||
};
|
||||
let task = tokio::spawn(async move {
|
||||
let mut connections = JoinSet::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
accepted = listener.accept() => {
|
||||
let Ok((stream, _)) = accepted else { break };
|
||||
let requests = requests_tx.clone();
|
||||
let validation_started = validation_started_tx.clone();
|
||||
let validation_mode = validation_mode.clone();
|
||||
let expected_authorization = expected_authorization.clone();
|
||||
connections.spawn(async move {
|
||||
let handler = service_fn(move |request| {
|
||||
handle_opa_request(
|
||||
request,
|
||||
requests.clone(),
|
||||
validation_started.clone(),
|
||||
validation_mode.clone(),
|
||||
expected_authorization.clone(),
|
||||
)
|
||||
});
|
||||
let _ = http1::Builder::new()
|
||||
.serve_connection(TokioIo::new(stream), handler)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
_ = connections.join_next(), if !connections.is_empty() => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(Self {
|
||||
url,
|
||||
requests,
|
||||
validation_started,
|
||||
validation_release,
|
||||
task,
|
||||
})
|
||||
}
|
||||
|
||||
async fn next_request(&mut self) -> Result<Value, BoxError> {
|
||||
timeout(Duration::from_secs(5), self.requests.recv())
|
||||
.await?
|
||||
.ok_or_else(|| "OPA request channel closed".into())
|
||||
}
|
||||
|
||||
async fn wait_for_validation(&mut self) -> TestResult {
|
||||
timeout(Duration::from_secs(5), self.validation_started.recv())
|
||||
.await?
|
||||
.ok_or_else(|| "OPA validation channel closed".into())
|
||||
}
|
||||
|
||||
fn release_validation(&self) {
|
||||
if let Some(release) = &self.validation_release {
|
||||
release.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OpaMock {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn test_sts_query_responses_are_aws_sdk_compatible() -> TestResult {
|
||||
@@ -155,7 +359,7 @@ async fn test_sts_query_responses_are_aws_sdk_compatible() -> TestResult {
|
||||
"signature rejection should include a request ID"
|
||||
);
|
||||
|
||||
assert_chaining_denied(
|
||||
assert_access_denied(
|
||||
&sts_client(
|
||||
&env.url,
|
||||
temporary.access_key_id(),
|
||||
@@ -167,7 +371,187 @@ async fn test_sts_query_responses_are_aws_sdk_compatible() -> TestResult {
|
||||
.await?;
|
||||
|
||||
let (service_access_key, service_secret_key) = create_root_service_account(&env).await?;
|
||||
assert_chaining_denied(&sts_client(&env.url, &service_access_key, &service_secret_key, None), "service account").await?;
|
||||
assert_access_denied(
|
||||
&sts_client(&env.url, &service_access_key, &service_secret_key, None),
|
||||
"service-account denial",
|
||||
)
|
||||
.await?;
|
||||
|
||||
let implicit_user = "stsimplicit";
|
||||
let explicit_allow_user = "stsallow";
|
||||
let explicit_deny_user = "stsdeny";
|
||||
let policyless_user = "stspolicyless";
|
||||
let secret = "stsAuthzSecret123";
|
||||
create_user(&env, policyless_user, secret).await?;
|
||||
assert_access_denied(&sts_client(&env.url, policyless_user, secret, None), "policyless user").await?;
|
||||
create_user_with_policy(
|
||||
&env,
|
||||
implicit_user,
|
||||
secret,
|
||||
"sts-implicit-policy",
|
||||
serde_json::json!([{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListAllMyBuckets"],
|
||||
"Resource": ["arn:aws:s3:::*"],
|
||||
}]),
|
||||
)
|
||||
.await?;
|
||||
create_user_with_policy(
|
||||
&env,
|
||||
explicit_allow_user,
|
||||
secret,
|
||||
"sts-allow-policy",
|
||||
serde_json::json!([{
|
||||
"Effect": "Allow",
|
||||
"Action": ["sts:AssumeRole"],
|
||||
"Resource": ["arn:aws:s3:::*"],
|
||||
}]),
|
||||
)
|
||||
.await?;
|
||||
create_user_with_policy(
|
||||
&env,
|
||||
explicit_deny_user,
|
||||
secret,
|
||||
"sts-deny-policy",
|
||||
serde_json::json!([
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["sts:AssumeRole"],
|
||||
"Resource": ["arn:aws:s3:::*"],
|
||||
},
|
||||
{
|
||||
"Effect": "Deny",
|
||||
"Action": ["sts:AssumeRole"],
|
||||
"Resource": ["arn:aws:s3:::*"],
|
||||
}
|
||||
]),
|
||||
)
|
||||
.await?;
|
||||
|
||||
for user in [implicit_user, explicit_allow_user] {
|
||||
let output = sts_client(&env.url, user, secret, None)
|
||||
.assume_role()
|
||||
.role_arn("arn:aws:iam::123456789012:role/test")
|
||||
.role_session_name("sts-authz-e2e")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| format!("{user} should be allowed to call AssumeRole: {error:?}"))?;
|
||||
let credentials = output
|
||||
.credentials()
|
||||
.ok_or_else(|| format!("{user} AssumeRole response should contain credentials"))?;
|
||||
assert!(!credentials.access_key_id().is_empty());
|
||||
assert!(!credentials.secret_access_key().is_empty());
|
||||
assert!(!credentials.session_token().is_empty());
|
||||
}
|
||||
assert_access_denied(&sts_client(&env.url, explicit_deny_user, secret, None), "explicit sts:AssumeRole Deny").await?;
|
||||
|
||||
env.stop_server();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn test_sts_assume_role_opa_contract() -> TestResult {
|
||||
init_logging();
|
||||
|
||||
let mut opa = OpaMock::start().await?;
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
env.start_rustfs_server_with_env(
|
||||
vec![],
|
||||
&[
|
||||
("RUSTFS_POLICY_PLUGIN_URL", opa.url.as_str()),
|
||||
("RUSTFS_POLICY_PLUGIN_AUTH_TOKEN", OPA_AUTH_TOKEN),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
|
||||
let secret = "stsOpaSecret123";
|
||||
create_user_with_policy(
|
||||
&env,
|
||||
"opaallow",
|
||||
secret,
|
||||
"sts-opa-local-deny-policy",
|
||||
serde_json::json!([{
|
||||
"Effect": "Deny",
|
||||
"Action": ["sts:AssumeRole"],
|
||||
"Resource": ["arn:aws:s3:::*"],
|
||||
}]),
|
||||
)
|
||||
.await?;
|
||||
create_user_with_policy(
|
||||
&env,
|
||||
"opadeny",
|
||||
secret,
|
||||
"sts-opa-local-allow-policy",
|
||||
serde_json::json!([{
|
||||
"Effect": "Allow",
|
||||
"Action": ["sts:AssumeRole"],
|
||||
"Resource": ["arn:aws:s3:::*"],
|
||||
}]),
|
||||
)
|
||||
.await?;
|
||||
|
||||
sts_client(&env.url, "opaallow", secret, None)
|
||||
.assume_role()
|
||||
.role_arn("arn:aws:iam::123456789012:role/test")
|
||||
.role_session_name("sts-opa-contract")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| format!("OPA allow should override the local explicit Deny: {error:?}"))?;
|
||||
assert_access_denied(
|
||||
&sts_client(&env.url, "opadeny", secret, None),
|
||||
"OPA denial despite local sts:AssumeRole Allow",
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut accounts = BTreeSet::new();
|
||||
for _ in 0..2 {
|
||||
let request = opa.next_request().await?;
|
||||
assert_eq!(request.pointer("/input/action").and_then(Value::as_str), Some("sts:AssumeRole"));
|
||||
assert_eq!(request.pointer("/input/context/deny_only").and_then(Value::as_bool), Some(true));
|
||||
let account = request
|
||||
.pointer("/input/identity/account")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("OPA input should include identity.account")?;
|
||||
accounts.insert(account.to_owned());
|
||||
}
|
||||
assert_eq!(accounts, BTreeSet::from(["opaallow".to_owned(), "opadeny".to_owned()]));
|
||||
|
||||
env.stop_server();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn test_sts_assume_role_fails_closed_while_opa_is_unavailable() -> TestResult {
|
||||
init_logging();
|
||||
|
||||
let mut opa = OpaMock::start_delayed_unavailable().await?;
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
env.start_rustfs_server_with_env(vec![], &[("RUSTFS_POLICY_PLUGIN_URL", opa.url.as_str())])
|
||||
.await?;
|
||||
opa.wait_for_validation().await?;
|
||||
|
||||
let user = "opaunavailable";
|
||||
let secret = "stsOpaUnavailableSecret123";
|
||||
create_user_with_policy(
|
||||
&env,
|
||||
user,
|
||||
secret,
|
||||
"sts-opa-unavailable-local-policy",
|
||||
serde_json::json!([{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListAllMyBuckets"],
|
||||
"Resource": ["arn:aws:s3:::*"],
|
||||
}]),
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert_access_denied(&sts_client(&env.url, user, secret, None), "configured OPA initialization").await?;
|
||||
|
||||
opa.release_validation();
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_access_denied(&sts_client(&env.url, user, secret, None), "configured OPA validation failure").await?;
|
||||
|
||||
env.stop_server();
|
||||
Ok(())
|
||||
|
||||
@@ -172,20 +172,26 @@ pub mod bucket {
|
||||
}
|
||||
|
||||
pub mod replication {
|
||||
pub use crate::bucket::replication::replication_pool::{
|
||||
DurableMrfBacklogSummary, DurableMrfBucketBacklog, DurableMrfTargetBacklog, MrfBacklogObservabilitySummary,
|
||||
MrfBucketBacklogObservability, durable_mrf_backlog_summary_snapshot, durable_mrf_target_backlog_snapshot,
|
||||
mrf_backlog_observability_snapshot,
|
||||
};
|
||||
pub use crate::bucket::replication::{
|
||||
BucketReplicationResyncStatus, BucketStats, DeletedObjectReplicationInfo, DurableMrfBacklog, DynReplicationPool,
|
||||
MrfOpKind, MrfReplicateEntry, MustReplicateOptions, ObjectOpts, REPLICATE_INCOMING_DELETE, ReplicateDecision,
|
||||
ReplicateObjectInfo, ReplicationConfig, ReplicationConfigurationExt, ReplicationDeleteScheduleInput,
|
||||
ReplicationDeleteStateSource, ReplicationHealQueueResult, ReplicationObjectBridge, ReplicationObjectIO,
|
||||
ReplicationOperation, ReplicationPoolTrait, ReplicationPriority, ReplicationQueueAdmission, ReplicationScannerBridge,
|
||||
ReplicationState, ReplicationStats, ReplicationStatusType, ReplicationStorage, ReplicationTargetValidationError,
|
||||
ReplicationType, ResyncOpts, ResyncStatusType, TargetReplicationResyncStatus, VersionPurgeStatusType,
|
||||
delete_replication_state_from_config, delete_replication_version_id, get_global_replication_pool,
|
||||
get_global_replication_stats, init_background_replication, read_durable_mrf_backlog, replication_state_to_filemeta,
|
||||
replication_status_to_filemeta, replication_statuses_map, replication_target_arns, resync_start_conflict_id,
|
||||
should_remove_replication_target, should_schedule_delete_replication, should_use_existing_delete_replication_info,
|
||||
should_use_existing_delete_replication_source, validate_replication_config_target_arns,
|
||||
version_purge_status_to_filemeta,
|
||||
BucketReplicationResyncStatus, BucketStats, DeleteReplicationConfigSnapshot, DeletedObjectReplicationInfo,
|
||||
DurableMrfBacklog, DynReplicationPool, MrfOpKind, MrfReplicateEntry, MustReplicateOptions, ObjectOpts,
|
||||
REPLICATE_INCOMING_DELETE, ReplicateDecision, ReplicateObjectInfo, ReplicationConfig, ReplicationConfigurationExt,
|
||||
ReplicationDeleteScheduleInput, ReplicationDeleteStateSource, ReplicationHealQueueResult, ReplicationObjectBridge,
|
||||
ReplicationObjectIO, ReplicationOperation, ReplicationPoolTrait, ReplicationPriority, ReplicationQueueAdmission,
|
||||
ReplicationScannerBridge, ReplicationState, ReplicationStats, ReplicationStatusType, ReplicationStorage,
|
||||
ReplicationTargetValidationError, ReplicationType, ResyncOpts, ResyncStatusType, RuntimeReplicationTargetBacklog,
|
||||
TargetReplicationResyncStatus, VersionPurgeStatusType, delete_replication_state_from_config,
|
||||
delete_replication_version_id, get_global_replication_pool, get_global_replication_stats,
|
||||
init_background_replication, invalid_replication_config_status_field, read_durable_mrf_backlog,
|
||||
replication_state_to_filemeta, replication_status_to_filemeta, replication_statuses_map, replication_target_arns,
|
||||
resync_start_conflict_id, should_remove_replication_target, should_schedule_delete_replication,
|
||||
should_use_existing_delete_replication_info, should_use_existing_delete_replication_source,
|
||||
unsupported_replication_config_field, validate_replication_config_target_arns, version_purge_status_to_filemeta,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -419,15 +425,15 @@ pub mod rio {
|
||||
|
||||
pub mod rpc {
|
||||
pub use crate::cluster::rpc::{
|
||||
AuthenticatedChannel, LocalPeerS3Client, PEER_RESTDRY_RUN, PEER_RESTSIGNAL, PEER_RESTSUB_SYS, PeerRestClient,
|
||||
PeerS3Client, S3PeerSys, SERVICE_SIGNAL_REFRESH_CONFIG, SERVICE_SIGNAL_RELOAD_DYNAMIC, ScannerBucketListing,
|
||||
ScannerPeerActivity, TONIC_RPC_PREFIX, TonicInterceptor, gen_signature_headers, gen_tonic_replay_scope_headers,
|
||||
gen_tonic_signature_headers, gen_tonic_signature_interceptor, node_service_time_out_client,
|
||||
node_service_time_out_client_no_auth, normalize_tonic_rpc_audience, set_tonic_canonical_body_digest,
|
||||
sign_ns_scanner_capability, sign_tonic_rpc_response_proof, tonic_boot_epoch_challenge, tonic_boot_epoch_response_headers,
|
||||
verify_rpc_signature, verify_tonic_boot_epoch_response, verify_tonic_canonical_body_digest,
|
||||
verify_tonic_mutation_body_digest, verify_tonic_rpc_response_proof, verify_tonic_rpc_signature,
|
||||
verify_tonic_rpc_signature_with_bootstrap,
|
||||
AuthenticatedChannel, KMS_SIGNAL_SUBSYSTEM, LocalPeerS3Client, PEER_RESTDRY_RUN, PEER_RESTSIGNAL, PEER_RESTSUB_SYS,
|
||||
PeerRestClient, PeerS3Client, S3PeerSys, SERVICE_SIGNAL_REFRESH_CONFIG, SERVICE_SIGNAL_RELOAD_DYNAMIC,
|
||||
ScannerBucketListing, ScannerPeerActivity, TONIC_RPC_PREFIX, TonicInterceptor, gen_signature_headers,
|
||||
gen_tonic_replay_scope_headers, gen_tonic_signature_headers, gen_tonic_signature_interceptor,
|
||||
node_service_time_out_client, node_service_time_out_client_no_auth, normalize_tonic_rpc_audience,
|
||||
set_tonic_canonical_body_digest, sign_ns_scanner_capability, sign_tonic_rpc_response_proof, tonic_boot_epoch_challenge,
|
||||
tonic_boot_epoch_response_headers, verify_rpc_signature, verify_tonic_boot_epoch_response,
|
||||
verify_tonic_canonical_body_digest, verify_tonic_mutation_body_digest, verify_tonic_rpc_response_proof,
|
||||
verify_tonic_rpc_signature, verify_tonic_rpc_signature_with_bootstrap,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1995,6 +1995,49 @@ mod tests {
|
||||
use super::*;
|
||||
use rcgen::generate_simple_self_signed;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct RecordingHttpConnector {
|
||||
request_uris: Arc<std::sync::Mutex<Vec<String>>>,
|
||||
}
|
||||
|
||||
impl SmithyHttpConnector for RecordingHttpConnector {
|
||||
fn call(&self, request: HttpRequest) -> HttpConnectorFuture {
|
||||
self.request_uris
|
||||
.lock()
|
||||
.expect("recorded request lock should not be poisoned")
|
||||
.push(request.uri().to_string());
|
||||
HttpConnectorFuture::ready(Ok(HttpResponse::new(
|
||||
aws_smithy_runtime_api::http::StatusCode::try_from(204_u16).expect("204 should be a valid response status"),
|
||||
SdkBody::empty(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
fn recording_target_client() -> (TargetClient, Arc<std::sync::Mutex<Vec<String>>>) {
|
||||
let request_uris = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let connector = SharedHttpConnector::new(RecordingHttpConnector {
|
||||
request_uris: Arc::clone(&request_uris),
|
||||
});
|
||||
let http_client = http_client_fn(move |_settings, _components| connector.clone());
|
||||
let client = s3_client_with_http_client(443, http_client);
|
||||
(
|
||||
TargetClient {
|
||||
endpoint: "https://localhost:443".to_string(),
|
||||
credentials: None,
|
||||
bucket: "target-bucket".to_string(),
|
||||
storage_class: String::new(),
|
||||
disable_proxy: false,
|
||||
arn: "arn:rustfs:replication:us-east-1:target:bucket".to_string(),
|
||||
reset_id: String::new(),
|
||||
secure: true,
|
||||
health_check_duration: Duration::from_secs(5),
|
||||
replicate_sync: false,
|
||||
client: Arc::new(client),
|
||||
},
|
||||
request_uris,
|
||||
)
|
||||
}
|
||||
|
||||
fn spawn_single_request_https_server(cert: &rcgen::CertifiedKey<rcgen::KeyPair>) -> (u16, std::thread::JoinHandle<()>) {
|
||||
use std::io::{Read, Write};
|
||||
|
||||
@@ -2285,6 +2328,32 @@ mod tests {
|
||||
assert_eq!(got.as_deref(), Some(vid.as_str()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remove_object_writes_null_purge_and_omits_marker_creation_version_queries() {
|
||||
let (client, request_uris) = recording_target_client();
|
||||
client
|
||||
.remove_object("target-bucket", "object", Some("null".to_string()), remove_opts(true, false))
|
||||
.await
|
||||
.expect("explicit null version purge should reach the target client");
|
||||
client
|
||||
.remove_object("target-bucket", "object", Some(Uuid::new_v4().to_string()), remove_opts(true, true))
|
||||
.await
|
||||
.expect("delete marker creation should reach the target client");
|
||||
|
||||
let request_uris = request_uris.lock().expect("recorded request lock should not be poisoned");
|
||||
assert_eq!(request_uris.len(), 2);
|
||||
assert!(
|
||||
request_uris[0].contains("versionId=null"),
|
||||
"an explicit null purge must be emitted as a target versionId query: {}",
|
||||
request_uris[0]
|
||||
);
|
||||
assert!(
|
||||
!request_uris[1].contains("versionId="),
|
||||
"delete marker creation must omit the target versionId query: {}",
|
||||
request_uris[1]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn put_object_headers_include_non_empty_source_etag_only() {
|
||||
let mut opts = PutObjectOptions::default();
|
||||
|
||||
@@ -16,6 +16,7 @@ use super::msgp_decode::{read_msgp_ext8_time, skip_msgp_value, write_msgp_time};
|
||||
use super::object_lock::ObjectLockApi;
|
||||
use super::versioning::VersioningApi;
|
||||
use super::{quota::BucketQuota, target::BucketTargets};
|
||||
use crate::bucket::replication::invalid_replication_config_status_field;
|
||||
use crate::bucket::utils::deserialize;
|
||||
use crate::config::com::{read_config, save_config};
|
||||
use crate::disk::BUCKET_META_PREFIX;
|
||||
@@ -25,9 +26,9 @@ use crate::store::ECStore;
|
||||
use byteorder::{BigEndian, ByteOrder, LittleEndian};
|
||||
use rustfs_policy::policy::BucketPolicy;
|
||||
use s3s::dto::{
|
||||
AccelerateConfiguration, BucketLifecycleConfiguration, BucketLoggingStatus, CORSConfiguration, NotificationConfiguration,
|
||||
ObjectLockConfiguration, PublicAccessBlockConfiguration, ReplicationConfiguration, RequestPaymentConfiguration,
|
||||
ServerSideEncryptionConfiguration, Tagging, VersioningConfiguration, WebsiteConfiguration,
|
||||
AccelerateConfiguration, BucketLifecycleConfiguration, BucketLoggingStatus, BucketVersioningStatus, CORSConfiguration,
|
||||
NotificationConfiguration, ObjectLockConfiguration, PublicAccessBlockConfiguration, ReplicationConfiguration,
|
||||
RequestPaymentConfiguration, ServerSideEncryptionConfiguration, Tagging, VersioningConfiguration, WebsiteConfiguration,
|
||||
};
|
||||
use serde::Serializer;
|
||||
use sha2::{Digest, Sha256};
|
||||
@@ -751,11 +752,33 @@ impl BucketMetadata {
|
||||
self.object_lock_config_updated_at = updated;
|
||||
}
|
||||
BUCKET_VERSIONING_CONFIG => {
|
||||
let config = if data.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let config = deserialize::<VersioningConfiguration>(&data)?;
|
||||
if config.status.as_ref().is_some_and(|status| {
|
||||
!matches!(status.as_str(), BucketVersioningStatus::ENABLED | BucketVersioningStatus::SUSPENDED)
|
||||
}) {
|
||||
return Err(Error::other("bucket versioning configuration has an invalid status"));
|
||||
}
|
||||
Some(config)
|
||||
};
|
||||
self.versioning_config_xml = data;
|
||||
self.versioning_config = config;
|
||||
self.versioning_config_updated_at = updated;
|
||||
}
|
||||
BUCKET_REPLICATION_CONFIG => {
|
||||
let config = if data.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let config = deserialize::<ReplicationConfiguration>(&data)?;
|
||||
if let Some(field) = invalid_replication_config_status_field(&config) {
|
||||
return Err(Error::other(format!("replication field {field} has an invalid status")));
|
||||
}
|
||||
Some(config)
|
||||
};
|
||||
self.replication_config_xml = data;
|
||||
self.replication_config = config;
|
||||
self.replication_config_updated_at = updated;
|
||||
}
|
||||
BUCKET_TARGETS_FILE => {
|
||||
@@ -825,7 +848,6 @@ impl BucketMetadata {
|
||||
/// ambient (first) one. [`BucketMetadata::save`] keeps the ambient default.
|
||||
pub async fn save_with_store(&mut self, store: std::sync::Arc<crate::store::ECStore>) -> Result<()> {
|
||||
self.parse_all_configs()?;
|
||||
|
||||
let mut buf: Vec<u8> = vec![0; 4];
|
||||
|
||||
LittleEndian::write_u16(&mut buf[0..2], BUCKET_METADATA_FORMAT);
|
||||
@@ -906,6 +928,7 @@ impl BucketMetadata {
|
||||
"Failed to parse bucket metadata config"
|
||||
);
|
||||
}
|
||||
self.versioning_config = None;
|
||||
if !self.versioning_config_xml.is_empty()
|
||||
&& let Err(e) =
|
||||
deserialize::<VersioningConfiguration>(&self.versioning_config_xml).map(|c| self.versioning_config = Some(c))
|
||||
@@ -960,6 +983,7 @@ impl BucketMetadata {
|
||||
"Failed to parse bucket metadata config"
|
||||
);
|
||||
}
|
||||
self.replication_config = None;
|
||||
if !self.replication_config_xml.is_empty()
|
||||
&& let Err(e) =
|
||||
deserialize::<ReplicationConfiguration>(&self.replication_config_xml).map(|c| self.replication_config = Some(c))
|
||||
@@ -1345,6 +1369,66 @@ mod test {
|
||||
assert!(bm.tagging_config.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_admission_configs_update_parsed_state_atomically() {
|
||||
let mut bm = BucketMetadata::new("test-bucket");
|
||||
let versioning_xml = b"<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>";
|
||||
let replication_xml = b"<ReplicationConfiguration><Role>arn:aws:s3:::target-bucket</Role><Rule><ID>rule1</ID><Status>Enabled</Status><Prefix></Prefix><Destination><Bucket>arn:aws:s3:::target-bucket</Bucket></Destination></Rule></ReplicationConfiguration>";
|
||||
|
||||
bm.update_config(BUCKET_VERSIONING_CONFIG, versioning_xml.to_vec())
|
||||
.expect("valid versioning config should update parsed state");
|
||||
bm.update_config(BUCKET_REPLICATION_CONFIG, replication_xml.to_vec())
|
||||
.expect("valid replication config should update parsed state");
|
||||
|
||||
assert!(bm.versioning_config.as_ref().is_some_and(VersioningConfiguration::enabled));
|
||||
assert_eq!(
|
||||
bm.replication_config.as_ref().map(|config| config.role.as_str()),
|
||||
Some("arn:aws:s3:::target-bucket")
|
||||
);
|
||||
|
||||
assert!(
|
||||
bm.update_config(BUCKET_VERSIONING_CONFIG, b"<VersioningConfiguration>".to_vec())
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
bm.update_config(BUCKET_REPLICATION_CONFIG, b"<ReplicationConfiguration>".to_vec())
|
||||
.is_err()
|
||||
);
|
||||
|
||||
assert_eq!(bm.versioning_config_xml, versioning_xml);
|
||||
assert_eq!(bm.replication_config_xml, replication_xml);
|
||||
assert!(bm.versioning_config.as_ref().is_some_and(VersioningConfiguration::enabled));
|
||||
assert_eq!(
|
||||
bm.replication_config.as_ref().map(|config| config.role.as_str()),
|
||||
Some("arn:aws:s3:::target-bucket")
|
||||
);
|
||||
|
||||
assert!(
|
||||
bm.update_config(
|
||||
BUCKET_VERSIONING_CONFIG,
|
||||
b"<VersioningConfiguration><Status>Enabld</Status></VersioningConfiguration>".to_vec(),
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
bm.update_config(
|
||||
BUCKET_REPLICATION_CONFIG,
|
||||
b"<ReplicationConfiguration><Role>arn:aws:s3:::target-bucket</Role><Rule><ID>rule1</ID><Status>Enabld</Status><Prefix></Prefix><Destination><Bucket>arn:aws:s3:::target-bucket</Bucket></Destination></Rule></ReplicationConfiguration>".to_vec(),
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(bm.versioning_config_xml, versioning_xml);
|
||||
assert_eq!(bm.replication_config_xml, replication_xml);
|
||||
|
||||
bm.versioning_config_xml = b"<VersioningConfiguration>".to_vec();
|
||||
bm.replication_config_xml = b"<ReplicationConfiguration>".to_vec();
|
||||
bm.parse_all_configs()
|
||||
.expect("bulk config parsing reports malformed fields through cleared typed state");
|
||||
|
||||
assert!(bm.versioning_config.is_none());
|
||||
assert!(bm.replication_config.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn marshal_msg_complete_example() {
|
||||
// Create a complete BucketMetadata with various configurations
|
||||
|
||||
@@ -1027,7 +1027,6 @@ impl BucketMetadataSys {
|
||||
/// server's metadata never leaks into the ambient (first) instance.
|
||||
pub(crate) async fn persist_and_set(&self, bm: BucketMetadata) -> Result<()> {
|
||||
let mut bm = bm;
|
||||
|
||||
bm.save_with_store(self.api.clone()).await?;
|
||||
|
||||
self.set(bm.name.clone(), Arc::new(bm)).await;
|
||||
@@ -1221,7 +1220,9 @@ impl BucketMetadataSys {
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(config) = &bm.versioning_config {
|
||||
if !bm.versioning_config_xml.is_empty() && bm.versioning_config.is_none() {
|
||||
Err(Error::other("persisted bucket versioning configuration is invalid"))
|
||||
} else if let Some(config) = &bm.versioning_config {
|
||||
Ok((config.clone(), bm.versioning_config_updated_at))
|
||||
} else {
|
||||
Ok((VersioningConfiguration::default(), bm.versioning_config_updated_at))
|
||||
@@ -1407,7 +1408,9 @@ impl BucketMetadataSys {
|
||||
pub async fn get_replication_config(&self, bucket: &str) -> Result<(ReplicationConfiguration, OffsetDateTime)> {
|
||||
let (bm, _) = self.get_config(bucket).await?;
|
||||
|
||||
if let Some(config) = &bm.replication_config {
|
||||
if !bm.replication_config_xml.is_empty() && bm.replication_config.is_none() {
|
||||
Err(Error::other("persisted bucket replication configuration is invalid"))
|
||||
} else if let Some(config) = &bm.replication_config {
|
||||
Ok((config.clone(), bm.replication_config_updated_at))
|
||||
} else {
|
||||
Err(Error::ConfigNotFound)
|
||||
@@ -1481,6 +1484,28 @@ mod tests {
|
||||
use serial_test::serial;
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[tokio::test]
|
||||
async fn malformed_delete_configs_are_not_treated_as_absent() {
|
||||
let (_dirs, ecstore) = isolated_store_over_temp_disks().await;
|
||||
let sys = BucketMetadataSys::new(ecstore);
|
||||
let bucket = "malformed-delete-config";
|
||||
let mut metadata = BucketMetadata::new(bucket);
|
||||
metadata.versioning_config_xml = b"<VersioningConfiguration>".to_vec();
|
||||
metadata.versioning_config = None;
|
||||
metadata.replication_config_xml = b"<ReplicationConfiguration>".to_vec();
|
||||
metadata.replication_config = None;
|
||||
sys.set(bucket.to_string(), Arc::new(metadata)).await;
|
||||
|
||||
assert!(
|
||||
sys.get_versioning_config(bucket).await.is_err(),
|
||||
"malformed versioning metadata must block destructive requests"
|
||||
);
|
||||
assert!(
|
||||
sys.get_replication_config(bucket).await.is_err(),
|
||||
"malformed replication metadata must not be reported as ConfigNotFound"
|
||||
);
|
||||
}
|
||||
|
||||
/// Concurrent cache misses for one bucket must collapse into a single disk
|
||||
/// load.
|
||||
///
|
||||
|
||||
@@ -45,8 +45,9 @@ mod runtime_boundary;
|
||||
|
||||
pub use datatypes::ResyncStatusType;
|
||||
pub use replication_config_boundary::{
|
||||
ObjectOpts, ReplicationConfigurationExt, ReplicationTargetValidationError, replication_target_arns,
|
||||
should_remove_replication_target, validate_replication_config_target_arns,
|
||||
ObjectOpts, ReplicationConfigurationExt, ReplicationTargetValidationError, invalid_replication_config_status_field,
|
||||
replication_target_arns, should_remove_replication_target, unsupported_replication_config_field,
|
||||
validate_replication_config_target_arns,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use replication_filemeta_boundary::ReplicateTargetDecision;
|
||||
@@ -62,7 +63,7 @@ pub(crate) use replication_filemeta_boundary::{
|
||||
pub(crate) use replication_lifecycle_bridge::{ReplicationLifecycleBridge, ReplicationLifecycleConfig};
|
||||
pub(crate) use replication_migration_bridge::ReplicationMigrationBridge;
|
||||
pub use replication_object_bridge::ReplicationObjectBridge;
|
||||
pub use replication_object_config::ReplicationConfig;
|
||||
pub use replication_object_config::{DeleteReplicationConfigSnapshot, ReplicationConfig};
|
||||
pub use replication_object_decision_boundary::{
|
||||
MustReplicateOptions, ReplicationDeleteScheduleInput, ReplicationDeleteStateSource, delete_replication_state_from_config,
|
||||
delete_replication_version_id, should_schedule_delete_replication, should_use_existing_delete_replication_info,
|
||||
@@ -78,7 +79,7 @@ pub use replication_queue_boundary::{
|
||||
};
|
||||
pub use replication_resync_boundary::{BucketReplicationResyncStatus, ResyncOpts, TargetReplicationResyncStatus};
|
||||
pub use replication_scanner_bridge::ReplicationScannerBridge;
|
||||
pub use replication_state::ReplicationStats;
|
||||
pub use replication_state::{ReplicationStats, RuntimeReplicationTargetBacklog};
|
||||
pub use replication_stats_boundary::BucketStats;
|
||||
pub use replication_storage_boundary::{ReplicationObjectIO, ReplicationStorage};
|
||||
pub(crate) use replication_target_config_bridge::ReplicationTargetConfigBridge;
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
// limitations under the License.
|
||||
|
||||
pub use rustfs_replication::{
|
||||
ObjectOpts, ReplicationConfigurationExt, ReplicationTargetValidationError, replication_target_arns,
|
||||
should_remove_replication_target, validate_replication_config_target_arns,
|
||||
ObjectOpts, ReplicationConfigurationExt, ReplicationRuleExt, ReplicationTargetValidationError,
|
||||
invalid_replication_config_status_field, replication_target_arns, should_remove_replication_target,
|
||||
unsupported_replication_config_field, validate_replication_config_target_arns,
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
pub(crate) use rustfs_filemeta::NULL_VERSION_ID;
|
||||
pub use rustfs_replication::{MrfOpKind, MrfReplicateEntry};
|
||||
pub(crate) use rustfs_replication::{
|
||||
REPLICATE_EXISTING, REPLICATE_EXISTING_DELETE, REPLICATE_HEAL_DELETE, ReplicateTargetDecision, ReplicatedInfos,
|
||||
|
||||
@@ -12,14 +12,19 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use crate::bucket::metadata_sys;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::bucket::{metadata::BucketMetadata, metadata_sys};
|
||||
use crate::disk::{BUCKET_META_PREFIX, RUSTFS_META_BUCKET};
|
||||
use crate::runtime::instance::InstanceContext;
|
||||
use rustfs_utils::path::path_join_buf;
|
||||
use s3s::dto::ReplicationConfiguration;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::replication_error_boundary::{Error, Result};
|
||||
|
||||
pub(crate) type ReplicationInstanceContext = InstanceContext;
|
||||
|
||||
const REPLICATION_DIR: &str = ".replication";
|
||||
const RESYNC_FILE_NAME: &str = "resync.bin";
|
||||
|
||||
@@ -45,6 +50,20 @@ impl ReplicationMetadataStore {
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub(crate) async fn delete_metadata(bucket: &str) -> Result<Arc<BucketMetadata>> {
|
||||
let sys = metadata_sys::get_bucket_metadata_sys()?;
|
||||
let sys = sys.read().await;
|
||||
Ok(sys.get_config(bucket).await?.0)
|
||||
}
|
||||
|
||||
pub(crate) async fn delete_metadata_in(ctx: &ReplicationInstanceContext, bucket: &str) -> Result<Arc<BucketMetadata>> {
|
||||
let sys = ctx
|
||||
.bucket_metadata_sys()
|
||||
.ok_or_else(|| Error::other("request instance bucket metadata system is not initialized"))?;
|
||||
let sys = sys.read().await;
|
||||
Ok(sys.get_config(bucket).await?.0)
|
||||
}
|
||||
|
||||
pub(crate) fn rustfs_meta_bucket() -> &'static str {
|
||||
RUSTFS_META_BUCKET
|
||||
}
|
||||
|
||||
@@ -14,13 +14,19 @@
|
||||
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use super::replication_error_boundary::Result;
|
||||
use super::replication_filemeta_boundary::{ReplicateDecision, ReplicationStatusType, ReplicationType};
|
||||
use super::replication_object_config::{check_replicate_delete, get_must_replicate_options, must_replicate};
|
||||
use super::replication_metadata_boundary::ReplicationInstanceContext;
|
||||
use super::replication_object_config::{
|
||||
DeleteReplicationConfigSnapshot, check_replicate_delete, check_replicate_delete_strict, check_replicate_delete_with_snapshot,
|
||||
get_must_replicate_options, load_delete_replication_config_in, load_delete_request_config_in, must_replicate,
|
||||
};
|
||||
use super::replication_object_decision_boundary::MustReplicateOptions;
|
||||
use super::replication_pool::{schedule_replication, schedule_replication_delete};
|
||||
use super::replication_queue_boundary::DeletedObjectReplicationInfo;
|
||||
use super::replication_storage_boundary::{
|
||||
DeletedObject, ObjectInfo, ObjectOptions, ObjectToDelete, ReplicationStorage, deleted_object_for_replication,
|
||||
DeletedObject, ObjectInfo, ObjectOptions, ObjectToDelete, ReplicationObjectStore, ReplicationStorage,
|
||||
deleted_object_for_replication,
|
||||
};
|
||||
|
||||
pub struct ReplicationObjectBridge;
|
||||
@@ -50,6 +56,49 @@ impl ReplicationObjectBridge {
|
||||
check_replicate_delete(bucket, object, source, opts, get_error).await
|
||||
}
|
||||
|
||||
pub async fn check_delete_strict(
|
||||
bucket: &str,
|
||||
object: &ObjectToDelete,
|
||||
source: &ObjectInfo,
|
||||
opts: &ObjectOptions,
|
||||
get_error: Option<String>,
|
||||
) -> Result<ReplicateDecision> {
|
||||
check_replicate_delete_strict(bucket, object, source, opts, get_error).await
|
||||
}
|
||||
|
||||
pub async fn delete_request_config(api: &ReplicationObjectStore, bucket: &str) -> Result<DeleteReplicationConfigSnapshot> {
|
||||
load_delete_request_config_in(&api.ctx, bucket).await
|
||||
}
|
||||
|
||||
pub(crate) async fn delete_request_config_in(
|
||||
ctx: &ReplicationInstanceContext,
|
||||
bucket: &str,
|
||||
) -> Result<DeleteReplicationConfigSnapshot> {
|
||||
load_delete_request_config_in(ctx, bucket).await
|
||||
}
|
||||
|
||||
pub(crate) async fn delete_config_snapshot_in(
|
||||
ctx: &ReplicationInstanceContext,
|
||||
bucket: &str,
|
||||
opts: &ObjectOptions,
|
||||
) -> Result<DeleteReplicationConfigSnapshot> {
|
||||
load_delete_replication_config_in(ctx, bucket, opts).await
|
||||
}
|
||||
|
||||
pub fn has_active_delete_rule(snapshot: &DeleteReplicationConfigSnapshot, object: &str) -> bool {
|
||||
snapshot.has_active_rule(object)
|
||||
}
|
||||
|
||||
pub fn check_delete_with_snapshot(
|
||||
object: &ObjectToDelete,
|
||||
source: &ObjectInfo,
|
||||
opts: &ObjectOptions,
|
||||
source_error: bool,
|
||||
snapshot: &DeleteReplicationConfigSnapshot,
|
||||
) -> ReplicateDecision {
|
||||
check_replicate_delete_with_snapshot(object, source, opts, source_error, snapshot)
|
||||
}
|
||||
|
||||
pub async fn schedule_object<S: ReplicationStorage>(
|
||||
object: ObjectInfo,
|
||||
storage: Arc<S>,
|
||||
|
||||
@@ -12,23 +12,26 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::{collections::HashMap, fmt, sync::Arc};
|
||||
|
||||
use crate::bucket::metadata::BucketMetadata;
|
||||
use rustfs_utils::http::AMZ_BUCKET_REPLICATION_STATUS;
|
||||
use s3s::dto::ReplicationConfiguration;
|
||||
use s3s::dto::{BucketVersioningStatus, ReplicationConfiguration, ReplicationRuleStatus, VersioningConfiguration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tracing::error;
|
||||
|
||||
use super::replication_config_boundary::{ObjectOpts, ReplicationConfigurationExt as _};
|
||||
use super::replication_config_boundary::{
|
||||
ObjectOpts, ReplicationConfigurationExt as _, ReplicationRuleExt as _, invalid_replication_config_status_field,
|
||||
};
|
||||
use super::replication_error_boundary::Result;
|
||||
use super::replication_filemeta_boundary::{
|
||||
ReplicateDecision, ReplicateTargetDecision, ReplicationStatusType, ReplicationType, ResyncDecision,
|
||||
};
|
||||
use super::replication_logging::{EVENT_RESYNC_CONFIG_LOOKUP_SKIPPED, LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_REPLICATION_RESYNC};
|
||||
use super::replication_metadata_boundary::ReplicationMetadataStore;
|
||||
use super::replication_metadata_boundary::{ReplicationInstanceContext, ReplicationMetadataStore};
|
||||
use super::replication_object_decision_boundary::{
|
||||
MustReplicateOptions, ReplicationDeleteSource, ReplicationResyncTargetObject, delete_replication_missing_source_decision,
|
||||
delete_replication_object_opts, resync_target_for_object,
|
||||
delete_replication_object_opts, heal_uses_delete_replication_path, resync_target_for_object,
|
||||
};
|
||||
use super::replication_storage_boundary::{ObjectInfo, ObjectOptions, ObjectToDelete, object_to_delete_for_replication};
|
||||
use super::replication_target_boundary::{BucketTargets, ReplicationTargetStore};
|
||||
@@ -36,7 +39,197 @@ use super::replication_versioning_boundary::ReplicationVersioningStore;
|
||||
use super::runtime_boundary as runtime_sources;
|
||||
|
||||
pub(crate) async fn get_replication_config(bucket: &str) -> Result<Option<ReplicationConfiguration>> {
|
||||
ReplicationMetadataStore::optional_replication_config(bucket).await
|
||||
let config = ReplicationMetadataStore::optional_replication_config(bucket).await?;
|
||||
validate_delete_replication_config(&VersioningConfiguration::default(), config.as_ref())?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct DeleteReplicationConfigSnapshot {
|
||||
metadata: Option<Arc<BucketMetadata>>,
|
||||
versioning: VersioningConfiguration,
|
||||
}
|
||||
|
||||
impl fmt::Debug for DeleteReplicationConfigSnapshot {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("DeleteReplicationConfigSnapshot")
|
||||
.field("has_replication_config", &self.replication_config().is_some())
|
||||
.field("versioning_status", &self.versioning.status)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl DeleteReplicationConfigSnapshot {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn from_configs_for_test(
|
||||
versioning: VersioningConfiguration,
|
||||
replication: Option<ReplicationConfiguration>,
|
||||
) -> Self {
|
||||
let metadata = replication.map(|config| {
|
||||
let mut metadata = BucketMetadata::new("test-bucket");
|
||||
metadata.replication_config = Some(config);
|
||||
Arc::new(metadata)
|
||||
});
|
||||
Self { metadata, versioning }
|
||||
}
|
||||
|
||||
pub fn versioning_config(&self) -> &VersioningConfiguration {
|
||||
&self.versioning
|
||||
}
|
||||
|
||||
pub fn replication_config(&self) -> Option<&ReplicationConfiguration> {
|
||||
self.metadata
|
||||
.as_ref()
|
||||
.and_then(|metadata| metadata.replication_config.as_ref())
|
||||
}
|
||||
|
||||
pub(crate) fn has_active_rule(&self, object: &str) -> bool {
|
||||
self.replication_config()
|
||||
.is_some_and(|config| config.has_active_rules(object, true))
|
||||
}
|
||||
|
||||
pub(crate) fn active_delete_marker_rules_require_tags(&self, object: &str) -> bool {
|
||||
self.replication_config().is_some_and(|config| {
|
||||
config.rules.iter().any(|rule| {
|
||||
if rule.status == ReplicationRuleStatus::from_static(ReplicationRuleStatus::DISABLED) {
|
||||
return false;
|
||||
}
|
||||
if !object.starts_with(rule.prefix()) {
|
||||
return false;
|
||||
}
|
||||
rule.filter.as_ref().is_some_and(|filter| {
|
||||
filter.tag.is_some()
|
||||
|| filter
|
||||
.and
|
||||
.as_ref()
|
||||
.and_then(|and| and.tags.as_ref())
|
||||
.is_some_and(|tags| !tags.is_empty())
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_delete_replication_config(
|
||||
versioning: &VersioningConfiguration,
|
||||
config: Option<&ReplicationConfiguration>,
|
||||
) -> Result<()> {
|
||||
if versioning
|
||||
.status
|
||||
.as_ref()
|
||||
.is_some_and(|status| !matches!(status.as_str(), BucketVersioningStatus::ENABLED | BucketVersioningStatus::SUSPENDED))
|
||||
{
|
||||
return Err(super::replication_error_boundary::Error::other(
|
||||
"bucket versioning configuration has an invalid status",
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(config) = config {
|
||||
if let Some(field) = invalid_replication_config_status_field(config) {
|
||||
return Err(super::replication_error_boundary::Error::other(format!(
|
||||
"replication field {field} has an invalid status"
|
||||
)));
|
||||
}
|
||||
|
||||
let role = config.role.trim();
|
||||
let mut role_destination = None;
|
||||
for rule in &config.rules {
|
||||
if rule.status.as_str() == ReplicationRuleStatus::ENABLED {
|
||||
let destination = rule.destination.bucket.trim();
|
||||
if role.is_empty() && destination.is_empty() {
|
||||
return Err(super::replication_error_boundary::Error::other(
|
||||
"enabled replication rule has no destination ARN",
|
||||
));
|
||||
}
|
||||
if !role.is_empty() && !destination.is_empty() {
|
||||
match role_destination {
|
||||
Some(existing) if existing != destination => {
|
||||
return Err(super::replication_error_boundary::Error::other(
|
||||
"replication role cannot address multiple active destinations",
|
||||
));
|
||||
}
|
||||
None => role_destination = Some(destination),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn replication_config_from_metadata(metadata: &BucketMetadata) -> Result<Option<&ReplicationConfiguration>> {
|
||||
if !metadata.replication_config_xml.is_empty() && metadata.replication_config.is_none() {
|
||||
return Err(super::replication_error_boundary::Error::other(
|
||||
"persisted bucket replication configuration is invalid",
|
||||
));
|
||||
}
|
||||
Ok(metadata.replication_config.as_ref())
|
||||
}
|
||||
|
||||
fn delete_request_snapshot_from_metadata(metadata: Arc<BucketMetadata>) -> Result<DeleteReplicationConfigSnapshot> {
|
||||
if !metadata.versioning_config_xml.is_empty() && metadata.versioning_config.is_none() {
|
||||
return Err(super::replication_error_boundary::Error::other(
|
||||
"persisted bucket versioning configuration is invalid",
|
||||
));
|
||||
}
|
||||
|
||||
let versioning = metadata.versioning_config.clone().unwrap_or_default();
|
||||
let has_config = {
|
||||
let config = replication_config_from_metadata(&metadata)?;
|
||||
if versioning.status.is_none() && config.is_some() {
|
||||
return Err(super::replication_error_boundary::Error::other(
|
||||
"bucket replication configuration requires versioning",
|
||||
));
|
||||
}
|
||||
validate_delete_replication_config(&versioning, config)?;
|
||||
config.is_some()
|
||||
};
|
||||
Ok(DeleteReplicationConfigSnapshot {
|
||||
metadata: has_config.then_some(metadata),
|
||||
versioning,
|
||||
})
|
||||
}
|
||||
|
||||
fn delete_snapshot_from_metadata(metadata: Arc<BucketMetadata>) -> Result<DeleteReplicationConfigSnapshot> {
|
||||
let has_config = {
|
||||
let config = replication_config_from_metadata(&metadata)?;
|
||||
validate_delete_replication_config(&VersioningConfiguration::default(), config)?;
|
||||
config.is_some()
|
||||
};
|
||||
Ok(DeleteReplicationConfigSnapshot {
|
||||
metadata: has_config.then_some(metadata),
|
||||
versioning: VersioningConfiguration::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn load_delete_request_config_in(
|
||||
ctx: &ReplicationInstanceContext,
|
||||
bucket: &str,
|
||||
) -> Result<DeleteReplicationConfigSnapshot> {
|
||||
delete_request_snapshot_from_metadata(ReplicationMetadataStore::delete_metadata_in(ctx, bucket).await?)
|
||||
}
|
||||
|
||||
pub(crate) async fn load_delete_replication_config(
|
||||
bucket: &str,
|
||||
opts: &ObjectOptions,
|
||||
) -> Result<DeleteReplicationConfigSnapshot> {
|
||||
if opts.replication_request || (!opts.versioned && !opts.version_suspended) {
|
||||
return Ok(DeleteReplicationConfigSnapshot::default());
|
||||
}
|
||||
delete_snapshot_from_metadata(ReplicationMetadataStore::delete_metadata(bucket).await?)
|
||||
}
|
||||
|
||||
pub(crate) async fn load_delete_replication_config_in(
|
||||
ctx: &ReplicationInstanceContext,
|
||||
bucket: &str,
|
||||
opts: &ObjectOptions,
|
||||
) -> Result<DeleteReplicationConfigSnapshot> {
|
||||
if opts.replication_request || (!opts.versioned && !opts.version_suspended) {
|
||||
return Ok(DeleteReplicationConfigSnapshot::default());
|
||||
}
|
||||
delete_snapshot_from_metadata(ReplicationMetadataStore::delete_metadata_in(ctx, bucket).await?)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
@@ -54,10 +247,31 @@ impl ReplicationConfig {
|
||||
self.config.is_none()
|
||||
}
|
||||
|
||||
pub(crate) fn validate(&self) -> Result<()> {
|
||||
validate_delete_replication_config(&VersioningConfiguration::default(), self.config.as_ref())
|
||||
}
|
||||
|
||||
pub fn replicate(&self, obj: &ObjectOpts) -> bool {
|
||||
self.config.as_ref().is_some_and(|config| config.replicate(obj))
|
||||
}
|
||||
|
||||
pub(crate) fn check_delete_for_heal(
|
||||
&self,
|
||||
object: &ObjectToDelete,
|
||||
source: &ObjectInfo,
|
||||
opts: &ObjectOptions,
|
||||
) -> ReplicateDecision {
|
||||
check_replicate_delete_with_config(
|
||||
object,
|
||||
source,
|
||||
opts,
|
||||
false,
|
||||
self.config.as_ref(),
|
||||
source.delete_marker && source.version_purge_status.is_empty(),
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn resync(
|
||||
&self,
|
||||
oi: ObjectInfo,
|
||||
@@ -70,30 +284,34 @@ impl ReplicationConfig {
|
||||
|
||||
let mut dsc = dsc;
|
||||
|
||||
if oi.delete_marker {
|
||||
if heal_uses_delete_replication_path(oi.delete_marker, &oi.version_purge_status) {
|
||||
if !dsc.targets_map.is_empty() {
|
||||
return self.resync_internal(oi, dsc, status);
|
||||
}
|
||||
let opts = ObjectOpts {
|
||||
name: oi.name.clone(),
|
||||
version_id: oi.version_id,
|
||||
delete_marker: true,
|
||||
version_id: if oi.version_purge_status.is_empty() {
|
||||
None
|
||||
} else {
|
||||
oi.version_id
|
||||
},
|
||||
delete_marker: oi.delete_marker,
|
||||
op_type: ReplicationType::Delete,
|
||||
existing_object: true,
|
||||
..Default::default()
|
||||
};
|
||||
let arns = self
|
||||
let targets = self
|
||||
.config
|
||||
.as_ref()
|
||||
.map(|config| config.filter_target_arns(&opts))
|
||||
.map(|config| config.filter_target_replication_decisions(&opts))
|
||||
.unwrap_or_default();
|
||||
|
||||
if arns.is_empty() {
|
||||
if targets.is_empty() {
|
||||
return ResyncDecision::default();
|
||||
}
|
||||
|
||||
for arn in arns {
|
||||
let mut opts = opts.clone();
|
||||
opts.target_arn = arn;
|
||||
|
||||
dsc.set(ReplicateTargetDecision::new(opts.target_arn.clone(), self.replicate(&opts), false));
|
||||
for (arn, replicate) in targets {
|
||||
dsc.set(ReplicateTargetDecision::new(arn, replicate, false));
|
||||
}
|
||||
|
||||
return self.resync_internal(oi, dsc, status);
|
||||
@@ -169,9 +387,10 @@ pub(crate) async fn check_replicate_delete(
|
||||
del_opts: &ObjectOptions,
|
||||
gerr: Option<String>,
|
||||
) -> ReplicateDecision {
|
||||
let rcfg = match get_replication_config(bucket).await {
|
||||
Ok(Some(config)) => config,
|
||||
Ok(None) => return ReplicateDecision::default(),
|
||||
match load_delete_replication_config(bucket, del_opts).await {
|
||||
Ok(snapshot) => {
|
||||
check_replicate_delete_with_config(dobj, oi, del_opts, gerr.is_some(), snapshot.replication_config(), false, false)
|
||||
}
|
||||
Err(err) => {
|
||||
error!(
|
||||
event = EVENT_RESYNC_CONFIG_LOOKUP_SKIPPED,
|
||||
@@ -182,61 +401,110 @@ pub(crate) async fn check_replicate_delete(
|
||||
error = %err,
|
||||
"Failed to look up replication config for delete replication"
|
||||
);
|
||||
return ReplicateDecision::default();
|
||||
ReplicateDecision::default()
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn check_replicate_delete_strict(
|
||||
bucket: &str,
|
||||
dobj: &ObjectToDelete,
|
||||
oi: &ObjectInfo,
|
||||
del_opts: &ObjectOptions,
|
||||
gerr: Option<String>,
|
||||
) -> Result<ReplicateDecision> {
|
||||
let Some(config) = get_replication_config(bucket).await? else {
|
||||
return Ok(ReplicateDecision::default());
|
||||
};
|
||||
let mut decision = check_replicate_delete_with_config(dobj, oi, del_opts, gerr.is_some(), Some(&config), false, false);
|
||||
if gerr.is_some() {
|
||||
return Ok(decision);
|
||||
}
|
||||
|
||||
for target in decision.targets_map.values_mut() {
|
||||
if let Some(client) = ReplicationTargetStore::remote_target_client(bucket, &target.arn).await {
|
||||
target.synchronous = client.replicate_sync;
|
||||
} else {
|
||||
target.replicate = false;
|
||||
target.synchronous = false;
|
||||
}
|
||||
}
|
||||
Ok(decision)
|
||||
}
|
||||
|
||||
pub(crate) fn check_replicate_delete_with_snapshot(
|
||||
dobj: &ObjectToDelete,
|
||||
oi: &ObjectInfo,
|
||||
del_opts: &ObjectOptions,
|
||||
source_error: bool,
|
||||
snapshot: &DeleteReplicationConfigSnapshot,
|
||||
) -> ReplicateDecision {
|
||||
check_replicate_delete_with_config(dobj, oi, del_opts, source_error, snapshot.replication_config(), false, false)
|
||||
}
|
||||
|
||||
fn check_replicate_delete_with_config(
|
||||
dobj: &ObjectToDelete,
|
||||
oi: &ObjectInfo,
|
||||
del_opts: &ObjectOptions,
|
||||
source_error: bool,
|
||||
config: Option<&ReplicationConfiguration>,
|
||||
existing_delete_marker: bool,
|
||||
trust_persisted_replica_status: bool,
|
||||
) -> ReplicateDecision {
|
||||
if del_opts.replication_request {
|
||||
return ReplicateDecision::default();
|
||||
}
|
||||
|
||||
if !del_opts.versioned {
|
||||
if !del_opts.versioned && !del_opts.version_suspended {
|
||||
return ReplicateDecision::default();
|
||||
}
|
||||
|
||||
let Some(rcfg) = config else {
|
||||
return ReplicateDecision::default();
|
||||
};
|
||||
|
||||
let replication_delete = object_to_delete_for_replication(dobj);
|
||||
let opts = delete_replication_object_opts(
|
||||
let missing_source_marker = source_error && dobj.version_id.is_none();
|
||||
let mut opts = delete_replication_object_opts(
|
||||
&replication_delete,
|
||||
&ReplicationDeleteSource {
|
||||
user_defined: oi.user_defined.as_ref(),
|
||||
user_tags: oi.user_tags.as_str(),
|
||||
delete_marker: oi.delete_marker,
|
||||
replication_status: oi.replication_status.clone(),
|
||||
delete_marker: oi.delete_marker || missing_source_marker,
|
||||
replication_status: if trust_persisted_replica_status {
|
||||
oi.replication_status.clone()
|
||||
} else {
|
||||
ReplicationStatusType::Empty
|
||||
},
|
||||
},
|
||||
);
|
||||
if existing_delete_marker {
|
||||
opts.version_id = None;
|
||||
}
|
||||
|
||||
let tgt_arns = rcfg.filter_target_arns(&opts);
|
||||
let target_decisions = rcfg.filter_target_replication_decisions(&opts);
|
||||
let mut dsc = ReplicateDecision::new();
|
||||
|
||||
if tgt_arns.is_empty() {
|
||||
if target_decisions.is_empty() {
|
||||
return dsc;
|
||||
}
|
||||
|
||||
for tgt_arn in tgt_arns {
|
||||
let mut opts = opts.clone();
|
||||
opts.target_arn = tgt_arn.clone();
|
||||
let replicate = rcfg.replicate(&opts);
|
||||
let sync = false;
|
||||
|
||||
if gerr.is_some() {
|
||||
if let Some(replicate) = delete_replication_missing_source_decision(
|
||||
oi.delete_marker,
|
||||
for (tgt_arn, replicate) in target_decisions {
|
||||
let effective_replicate = if source_error {
|
||||
delete_replication_missing_source_decision(
|
||||
oi.delete_marker || missing_source_marker,
|
||||
oi.target_replication_status(&tgt_arn),
|
||||
replicate,
|
||||
&oi.version_purge_status,
|
||||
) {
|
||||
dsc.set(ReplicateTargetDecision::new(tgt_arn, replicate, sync));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let tgt = ReplicationTargetStore::remote_target_client(bucket, &tgt_arn).await;
|
||||
let tgt_dsc = if let Some(tgt) = tgt {
|
||||
ReplicateTargetDecision::new(tgt_arn, replicate, tgt.replicate_sync)
|
||||
)
|
||||
} else {
|
||||
ReplicateTargetDecision::new(tgt_arn, false, false)
|
||||
Some(replicate)
|
||||
};
|
||||
dsc.set(tgt_dsc);
|
||||
let Some(effective_replicate) = effective_replicate else {
|
||||
continue;
|
||||
};
|
||||
|
||||
dsc.set(ReplicateTargetDecision::new(tgt_arn, effective_replicate, false));
|
||||
}
|
||||
|
||||
dsc
|
||||
@@ -299,8 +567,13 @@ pub(crate) async fn must_replicate(bucket: &str, object: &str, mopts: MustReplic
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use s3s::dto::{Destination, ReplicationRule, ReplicationRuleStatus};
|
||||
use s3s::dto::{
|
||||
DeleteMarkerReplication, DeleteMarkerReplicationStatus, DeleteReplication, DeleteReplicationStatus, Destination,
|
||||
ReplicaModifications, ReplicationRule, ReplicationRuleFilter, ReplicationRuleStatus, SourceSelectionCriteria, Tag,
|
||||
};
|
||||
|
||||
use super::super::replication_filemeta_boundary::VersionPurgeStatusType;
|
||||
use super::super::replication_target_boundary::BucketTarget;
|
||||
use super::*;
|
||||
|
||||
fn replication_rule() -> ReplicationRule {
|
||||
@@ -360,4 +633,379 @@ mod tests {
|
||||
assert!(options.is_replication_request());
|
||||
assert_eq!(options.user_tags(), "env=prod");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_snapshot_rejects_enabled_rules_without_a_destination() {
|
||||
let mut rule = replication_rule();
|
||||
rule.destination.bucket.clear();
|
||||
let config = ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![rule],
|
||||
};
|
||||
|
||||
let err = validate_delete_replication_config(&VersioningConfiguration::default(), Some(&config))
|
||||
.expect_err("an enabled rule without a destination must fail closed");
|
||||
|
||||
assert!(err.to_string().contains("destination ARN"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_snapshot_rejects_role_with_multiple_destinations() {
|
||||
let first = replication_rule();
|
||||
let mut second = replication_rule();
|
||||
second.destination.bucket = "arn:aws:s3:::other-target".to_string();
|
||||
let config = ReplicationConfiguration {
|
||||
role: "arn:aws:s3:::role-target".to_string(),
|
||||
rules: vec![first, second],
|
||||
};
|
||||
|
||||
assert!(validate_delete_replication_config(&VersioningConfiguration::default(), Some(&config)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_snapshot_rejects_unknown_status_values() {
|
||||
let invalid_versioning = VersioningConfiguration {
|
||||
status: Some("Enabld".to_string().into()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(validate_delete_replication_config(&invalid_versioning, None).is_err());
|
||||
|
||||
let mut invalid_rule = replication_rule();
|
||||
invalid_rule.status = "Enabld".to_string().into();
|
||||
let config = ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![invalid_rule],
|
||||
};
|
||||
assert!(validate_delete_replication_config(&VersioningConfiguration::default(), Some(&config)).is_err());
|
||||
|
||||
let mut invalid_delete = replication_rule();
|
||||
invalid_delete.delete_replication = Some(DeleteReplication {
|
||||
status: "Enabld".to_string().into(),
|
||||
});
|
||||
let config = ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![invalid_delete],
|
||||
};
|
||||
assert!(validate_delete_replication_config(&VersioningConfiguration::default(), Some(&config)).is_err());
|
||||
|
||||
let mut invalid_delete_marker = replication_rule();
|
||||
invalid_delete_marker.delete_marker_replication = Some(DeleteMarkerReplication {
|
||||
status: Some("Enabld".to_string().into()),
|
||||
});
|
||||
let config = ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![invalid_delete_marker],
|
||||
};
|
||||
assert!(validate_delete_replication_config(&VersioningConfiguration::default(), Some(&config)).is_err());
|
||||
|
||||
let mut invalid_replica_modifications = replication_rule();
|
||||
invalid_replica_modifications.source_selection_criteria = Some(SourceSelectionCriteria {
|
||||
replica_modifications: Some(ReplicaModifications {
|
||||
status: "Enabld".to_string().into(),
|
||||
}),
|
||||
sse_kms_encrypted_objects: None,
|
||||
});
|
||||
let config = ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![invalid_replica_modifications],
|
||||
};
|
||||
assert!(validate_delete_replication_config(&VersioningConfiguration::default(), Some(&config)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_snapshot_borrows_cached_replication_config() {
|
||||
let mut metadata = BucketMetadata::new("bucket");
|
||||
metadata.versioning_config_xml = b"configured".to_vec();
|
||||
metadata.versioning_config = Some(VersioningConfiguration {
|
||||
status: Some(BucketVersioningStatus::from_static(BucketVersioningStatus::ENABLED)),
|
||||
..Default::default()
|
||||
});
|
||||
metadata.replication_config_xml = b"configured".to_vec();
|
||||
metadata.replication_config = Some(ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![replication_rule()],
|
||||
});
|
||||
let metadata = Arc::new(metadata);
|
||||
let cached_config = metadata.replication_config.as_ref().expect("cached config") as *const _;
|
||||
|
||||
let snapshot = delete_request_snapshot_from_metadata(Arc::clone(&metadata)).expect("valid snapshot");
|
||||
|
||||
assert_eq!(snapshot.replication_config().expect("snapshot config") as *const _, cached_config);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_snapshot_debug_redacts_bucket_target_credentials() {
|
||||
let secret = "snapshot-secret-must-not-be-formatted";
|
||||
let mut metadata = BucketMetadata::new("bucket");
|
||||
metadata.bucket_targets_config_json = format!(r#"{{"secretKey":"{secret}"}}"#).into_bytes();
|
||||
let opts = ObjectOptions {
|
||||
delete_replication_config_snapshot: Some(Arc::new(DeleteReplicationConfigSnapshot {
|
||||
metadata: Some(Arc::new(metadata)),
|
||||
versioning: VersioningConfiguration::default(),
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let debug = format!("{opts:?}");
|
||||
assert!(!debug.contains(secret), "delete tracing must not expose replication target credentials");
|
||||
assert!(debug.contains("has_replication_config"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_snapshot_rejects_replication_without_versioning_status() {
|
||||
let mut malformed = BucketMetadata::new("bucket");
|
||||
malformed.replication_config_xml = b"<ReplicationConfiguration>".to_vec();
|
||||
assert!(
|
||||
delete_request_snapshot_from_metadata(Arc::new(malformed)).is_err(),
|
||||
"malformed replication metadata must fail closed even when versioning has no status"
|
||||
);
|
||||
|
||||
let mut inconsistent = BucketMetadata::new("bucket");
|
||||
inconsistent.replication_config = Some(ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![replication_rule()],
|
||||
});
|
||||
assert!(
|
||||
delete_request_snapshot_from_metadata(Arc::new(inconsistent)).is_err(),
|
||||
"replication metadata without an enabled or suspended versioning state must fail closed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_source_marker_creation_is_still_admitted() {
|
||||
let arn = "arn:rustfs:replication:us-east-1:target:bucket";
|
||||
let mut rule = replication_rule();
|
||||
rule.destination.bucket = arn.to_string();
|
||||
rule.delete_marker_replication = Some(DeleteMarkerReplication {
|
||||
status: Some(DeleteMarkerReplicationStatus::from_static(DeleteMarkerReplicationStatus::ENABLED)),
|
||||
});
|
||||
let mut metadata = BucketMetadata::new("bucket");
|
||||
metadata.replication_config = Some(ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![rule],
|
||||
});
|
||||
let snapshot = DeleteReplicationConfigSnapshot {
|
||||
metadata: Some(Arc::new(metadata)),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let decision = check_replicate_delete_with_snapshot(
|
||||
&ObjectToDelete {
|
||||
object_name: "object".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
&ObjectInfo::default(),
|
||||
&ObjectOptions {
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
},
|
||||
true,
|
||||
&snapshot,
|
||||
);
|
||||
|
||||
assert!(decision.replicate_any());
|
||||
assert!(decision.targets_map.get(arn).is_some_and(|target| target.replicate));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_marker_source_read_is_required_only_for_tag_filtered_rules() {
|
||||
let mut prefix_rule = replication_rule();
|
||||
prefix_rule.prefix = Some("logs/".to_string());
|
||||
prefix_rule.delete_marker_replication = Some(DeleteMarkerReplication {
|
||||
status: Some(DeleteMarkerReplicationStatus::from_static(DeleteMarkerReplicationStatus::ENABLED)),
|
||||
});
|
||||
|
||||
let prefix_snapshot = DeleteReplicationConfigSnapshot::from_configs_for_test(
|
||||
VersioningConfiguration {
|
||||
status: Some(BucketVersioningStatus::from_static(BucketVersioningStatus::ENABLED)),
|
||||
..Default::default()
|
||||
},
|
||||
Some(ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![prefix_rule],
|
||||
}),
|
||||
);
|
||||
|
||||
let mut tag_rule = replication_rule();
|
||||
tag_rule.delete_marker_replication = Some(DeleteMarkerReplication {
|
||||
status: Some(DeleteMarkerReplicationStatus::from_static(DeleteMarkerReplicationStatus::ENABLED)),
|
||||
});
|
||||
tag_rule.filter = Some(ReplicationRuleFilter {
|
||||
tag: Some(Tag {
|
||||
key: Some("class".to_string()),
|
||||
value: Some("audit".to_string()),
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
let tag_snapshot = DeleteReplicationConfigSnapshot::from_configs_for_test(
|
||||
VersioningConfiguration {
|
||||
status: Some(BucketVersioningStatus::from_static(BucketVersioningStatus::ENABLED)),
|
||||
..Default::default()
|
||||
},
|
||||
Some(ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![tag_rule],
|
||||
}),
|
||||
);
|
||||
|
||||
assert!(!prefix_snapshot.active_delete_marker_rules_require_tags("logs/2026/app.log"));
|
||||
assert!(tag_snapshot.active_delete_marker_rules_require_tags("logs/2026/app.log"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heal_uses_delete_switch_for_pending_purges_and_marker_switch_for_stored_markers() {
|
||||
let arn = "arn:rustfs:replication:us-east-1:target:bucket";
|
||||
let mut rule = replication_rule();
|
||||
rule.destination.bucket = arn.to_string();
|
||||
rule.delete_replication = Some(DeleteReplication {
|
||||
status: DeleteReplicationStatus::from_static(DeleteReplicationStatus::ENABLED),
|
||||
});
|
||||
rule.delete_marker_replication = Some(DeleteMarkerReplication {
|
||||
status: Some(DeleteMarkerReplicationStatus::from_static(DeleteMarkerReplicationStatus::DISABLED)),
|
||||
});
|
||||
let config = ReplicationConfig::new(
|
||||
Some(ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![rule],
|
||||
}),
|
||||
None,
|
||||
);
|
||||
let object = ObjectToDelete {
|
||||
object_name: "object".to_string(),
|
||||
version_id: Some(uuid::Uuid::new_v4()),
|
||||
..Default::default()
|
||||
};
|
||||
let opts = ObjectOptions {
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let purge = ObjectInfo {
|
||||
version_id: object.version_id,
|
||||
version_purge_status: VersionPurgeStatusType::Pending,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(config.check_delete_for_heal(&object, &purge, &opts).replicate_any());
|
||||
|
||||
let marker = ObjectInfo {
|
||||
delete_marker: true,
|
||||
version_id: object.version_id,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!config.check_delete_for_heal(&object, &marker, &opts).replicate_any());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_delete_does_not_trust_persisted_replica_status() {
|
||||
let mut rule = replication_rule();
|
||||
rule.delete_replication = Some(DeleteReplication {
|
||||
status: DeleteReplicationStatus::from_static(DeleteReplicationStatus::ENABLED),
|
||||
});
|
||||
rule.source_selection_criteria = Some(SourceSelectionCriteria {
|
||||
replica_modifications: Some(ReplicaModifications {
|
||||
status: s3s::dto::ReplicaModificationsStatus::from_static(s3s::dto::ReplicaModificationsStatus::DISABLED),
|
||||
}),
|
||||
sse_kms_encrypted_objects: None,
|
||||
});
|
||||
let replication = ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![rule],
|
||||
};
|
||||
let snapshot = DeleteReplicationConfigSnapshot::from_configs_for_test(
|
||||
VersioningConfiguration {
|
||||
status: Some(BucketVersioningStatus::from_static(BucketVersioningStatus::ENABLED)),
|
||||
..Default::default()
|
||||
},
|
||||
Some(replication.clone()),
|
||||
);
|
||||
let object = ObjectToDelete {
|
||||
object_name: "object".to_string(),
|
||||
version_id: Some(uuid::Uuid::new_v4()),
|
||||
..Default::default()
|
||||
};
|
||||
let source = ObjectInfo {
|
||||
replication_status: ReplicationStatusType::Replica,
|
||||
..Default::default()
|
||||
};
|
||||
let opts = ObjectOptions {
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(
|
||||
check_replicate_delete_with_snapshot(&object, &source, &opts, false, &snapshot).replicate_any(),
|
||||
"an ordinary authenticated delete must not inherit replica identity from object metadata"
|
||||
);
|
||||
assert!(
|
||||
!ReplicationConfig::new(Some(replication), None)
|
||||
.check_delete_for_heal(&object, &source, &opts)
|
||||
.replicate_any(),
|
||||
"heal must still honor the persisted replica identity"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resync_keeps_marker_version_purges_separate_from_marker_creation() {
|
||||
let arn = "arn:rustfs:replication:us-east-1:target:bucket";
|
||||
let mut rule = replication_rule();
|
||||
rule.destination.bucket = arn.to_string();
|
||||
rule.delete_replication = Some(DeleteReplication {
|
||||
status: DeleteReplicationStatus::from_static(DeleteReplicationStatus::ENABLED),
|
||||
});
|
||||
rule.delete_marker_replication = Some(DeleteMarkerReplication {
|
||||
status: Some(DeleteMarkerReplicationStatus::from_static(DeleteMarkerReplicationStatus::DISABLED)),
|
||||
});
|
||||
let config = ReplicationConfig::new(
|
||||
Some(ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![rule],
|
||||
}),
|
||||
Some(BucketTargets {
|
||||
targets: vec![BucketTarget {
|
||||
arn: arn.to_string(),
|
||||
..Default::default()
|
||||
}],
|
||||
}),
|
||||
);
|
||||
let marker = ObjectInfo {
|
||||
name: "object".to_string(),
|
||||
delete_marker: true,
|
||||
version_id: Some(uuid::Uuid::new_v4()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let purge = config
|
||||
.resync(
|
||||
ObjectInfo {
|
||||
version_purge_status: VersionPurgeStatusType::Pending,
|
||||
..marker.clone()
|
||||
},
|
||||
ReplicateDecision::default(),
|
||||
&HashMap::new(),
|
||||
)
|
||||
.await;
|
||||
assert!(purge.targets.get(arn).is_some_and(|target| target.replicate));
|
||||
|
||||
let mut object_purge_decision = ReplicateDecision::default();
|
||||
object_purge_decision.set(ReplicateTargetDecision::new(arn.to_string(), true, false));
|
||||
let object_purge = config
|
||||
.resync(
|
||||
ObjectInfo {
|
||||
name: "object".to_string(),
|
||||
version_id: Some(uuid::Uuid::new_v4()),
|
||||
version_purge_status: VersionPurgeStatusType::Pending,
|
||||
..Default::default()
|
||||
},
|
||||
object_purge_decision,
|
||||
&HashMap::new(),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
object_purge.targets.get(arn).is_some_and(|target| target.replicate),
|
||||
"non-marker PENDING purges must stay on the delete resync path"
|
||||
);
|
||||
|
||||
let stored_marker = config.resync(marker, ReplicateDecision::default(), &HashMap::new()).await;
|
||||
assert!(!stored_marker.targets.contains_key(arn));
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -18,16 +18,16 @@ use super::replication_config_store::ReplicationConfigStore;
|
||||
use super::replication_error_boundary::{Result, is_err_object_not_found, is_err_version_not_found};
|
||||
use super::replication_event_sink::{EventArgs, send_event, send_local_event};
|
||||
use super::replication_filemeta_boundary::{
|
||||
REPLICATE_EXISTING, REPLICATE_EXISTING_DELETE, ReplicateDecision, ReplicateObjectInfo, ReplicatedInfos, ReplicatedTargetInfo,
|
||||
ReplicationAction, ReplicationStatusType, ReplicationType, VersionPurgeStatusType, get_replication_state,
|
||||
parse_replicate_decision, replication_statuses_map, target_reset_header, version_purge_statuses_map,
|
||||
NULL_VERSION_ID, REPLICATE_EXISTING, REPLICATE_EXISTING_DELETE, ReplicateDecision, ReplicateObjectInfo, ReplicatedInfos,
|
||||
ReplicatedTargetInfo, ReplicationAction, ReplicationStatusType, ReplicationType, VersionPurgeStatusType,
|
||||
get_replication_state, parse_replicate_decision, replication_statuses_map, target_reset_header, version_purge_statuses_map,
|
||||
};
|
||||
use super::replication_lock_boundary::ReplicationLockTiming;
|
||||
use super::replication_logging::{EVENT_RESYNC_CONFIG_LOOKUP_SKIPPED, LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_REPLICATION_RESYNC};
|
||||
use super::replication_metadata_boundary::ReplicationMetadataStore;
|
||||
#[cfg(test)]
|
||||
use super::replication_msgp_boundary::ReplicationMsgpCodec;
|
||||
use super::replication_object_config::{ReplicationConfig, check_replicate_delete, get_replication_config, must_replicate};
|
||||
use super::replication_object_config::{ReplicationConfig, get_replication_config, must_replicate};
|
||||
use super::replication_object_decision_boundary::{
|
||||
MustReplicateOptions, ReplicationMultipartPartInput, heal_uses_delete_replication_path,
|
||||
is_retryable_delete_replication_head_error, is_version_delete_replication, replication_etags_match,
|
||||
@@ -642,6 +642,21 @@ impl ReplicationResyncer {
|
||||
};
|
||||
|
||||
let rcfg = ReplicationConfig::new(cfg.clone(), Some(targets));
|
||||
if let Err(err) = rcfg.validate() {
|
||||
error!(
|
||||
event = EVENT_RESYNC_CONFIG_LOOKUP_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
bucket = %opts.bucket,
|
||||
arn = %opts.arn,
|
||||
error = %err,
|
||||
reason = "replication_config_invalid",
|
||||
"Replication resync config is invalid"
|
||||
);
|
||||
self.resync_bucket_mark_status(ResyncStatusType::ResyncFailed, opts.clone(), storage.clone())
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
|
||||
let target_arns = if let Some(cfg) = cfg {
|
||||
cfg.filter_target_arns(&ObjectOpts {
|
||||
@@ -982,7 +997,36 @@ impl ReplicationResyncer {
|
||||
}
|
||||
last_checkpoint = None;
|
||||
|
||||
let roi = get_heal_replicate_object_info(&object, &rcfg).await;
|
||||
let roi = match get_heal_replicate_object_info(&object, &rcfg).await {
|
||||
Ok(roi) => roi,
|
||||
Err(err) => {
|
||||
error!(
|
||||
event = EVENT_RESYNC_CONFIG_LOOKUP_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
bucket = %opts.bucket,
|
||||
arn = %opts.arn,
|
||||
object = %object.name,
|
||||
error = %err,
|
||||
"Failed to classify object for replication resync"
|
||||
);
|
||||
let worker_failed = finish_resync_workers(worker_txs, results_tx, futures, false).await;
|
||||
if worker_failed {
|
||||
error!(
|
||||
event = EVENT_RESYNC_TASK_FAILED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
bucket = %opts.bucket,
|
||||
arn = %opts.arn,
|
||||
reason = "worker_join_failed_after_classification_error",
|
||||
"Replication resync worker cleanup observed task failure"
|
||||
);
|
||||
}
|
||||
self.resync_bucket_mark_status(ResyncStatusType::ResyncFailed, opts.clone(), storage.clone())
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
if !roi.existing_obj_resync.must_resync() {
|
||||
continue;
|
||||
}
|
||||
@@ -1037,18 +1081,25 @@ impl ReplicationResyncer {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_heal_replicate_object_info(oi: &ObjectInfo, rcfg: &ReplicationConfig) -> ReplicateObjectInfo {
|
||||
pub async fn get_heal_replicate_object_info(oi: &ObjectInfo, rcfg: &ReplicationConfig) -> Result<ReplicateObjectInfo> {
|
||||
let mut oi = oi.clone();
|
||||
let mut user_defined = (*oi.user_defined).clone();
|
||||
let delete_path = heal_uses_delete_replication_path(oi.delete_marker, &oi.version_purge_status);
|
||||
let stored_delete_decision = if delete_path && !oi.replication_decision.is_empty() {
|
||||
Some(parse_replicate_decision(&oi.bucket, &oi.replication_decision)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let has_stored_delete_decision = stored_delete_decision.is_some();
|
||||
|
||||
if let Some(rc) = rcfg.config.as_ref()
|
||||
&& !rc.role.is_empty()
|
||||
{
|
||||
if !oi.version_purge_status.is_empty() {
|
||||
if oi.version_purge_status_internal.is_none() && !oi.version_purge_status.is_empty() {
|
||||
oi.version_purge_status_internal = Some(format!("{}={};", rc.role, oi.version_purge_status.as_str()));
|
||||
}
|
||||
|
||||
if !oi.replication_status.is_empty() {
|
||||
if oi.replication_status_internal.is_none() && !oi.replication_status.is_empty() {
|
||||
oi.replication_status_internal = Some(format!("{}={};", rc.role, oi.replication_status.as_str()));
|
||||
}
|
||||
|
||||
@@ -1064,23 +1115,31 @@ pub async fn get_heal_replicate_object_info(oi: &ObjectInfo, rcfg: &ReplicationC
|
||||
}
|
||||
}
|
||||
|
||||
let dsc = if heal_uses_delete_replication_path(oi.delete_marker, &oi.version_purge_status) {
|
||||
check_replicate_delete(
|
||||
oi.bucket.as_str(),
|
||||
&ObjectToDelete {
|
||||
object_name: oi.name.clone(),
|
||||
version_id: oi.version_id,
|
||||
..Default::default()
|
||||
},
|
||||
&oi,
|
||||
&ObjectOptions {
|
||||
versioned: ReplicationVersioningStore::prefix_enabled(&oi.bucket, &oi.name).await,
|
||||
version_suspended: ReplicationVersioningStore::prefix_suspended(&oi.bucket, &oi.name).await,
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
let delete_state = if delete_path && !has_stored_delete_decision {
|
||||
ReplicationVersioningStore::prefix_state(&oi.bucket, &oi.name).await?
|
||||
} else {
|
||||
(false, false)
|
||||
};
|
||||
let dsc = if let Some(decision) = stored_delete_decision {
|
||||
decision
|
||||
} else if delete_path {
|
||||
if !delete_state.0 && !delete_state.1 {
|
||||
ReplicateDecision::default()
|
||||
} else {
|
||||
rcfg.check_delete_for_heal(
|
||||
&ObjectToDelete {
|
||||
object_name: oi.name.clone(),
|
||||
version_id: oi.version_id,
|
||||
..Default::default()
|
||||
},
|
||||
&oi,
|
||||
&ObjectOptions {
|
||||
versioned: delete_state.0,
|
||||
version_suspended: delete_state.1,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
}
|
||||
} else {
|
||||
must_replicate(
|
||||
oi.bucket.as_str(),
|
||||
@@ -1092,12 +1151,16 @@ pub async fn get_heal_replicate_object_info(oi: &ObjectInfo, rcfg: &ReplicationC
|
||||
|
||||
let target_statuses = replication_statuses_map(&oi.replication_status_internal.clone().unwrap_or_default());
|
||||
let target_purge_statuses = version_purge_statuses_map(&oi.version_purge_status_internal.clone().unwrap_or_default());
|
||||
let existing_obj_resync = rcfg.resync(oi.clone(), dsc.clone(), &target_statuses).await;
|
||||
let existing_obj_resync = if delete_path && !has_stored_delete_decision && !delete_state.0 && !delete_state.1 {
|
||||
Default::default()
|
||||
} else {
|
||||
rcfg.resync(oi.clone(), dsc.clone(), &target_statuses).await
|
||||
};
|
||||
let mut replication_state = oi.replication_state();
|
||||
replication_state.replicate_decision_str = dsc.to_string();
|
||||
let actual_size = oi.get_actual_size().unwrap_or_default();
|
||||
|
||||
ReplicateObjectInfo {
|
||||
Ok(ReplicateObjectInfo {
|
||||
name: oi.name.clone(),
|
||||
size: oi.size,
|
||||
actual_size,
|
||||
@@ -1122,7 +1185,7 @@ pub async fn get_heal_replicate_object_info(oi: &ObjectInfo, rcfg: &ReplicationC
|
||||
user_tags: (*oi.user_tags).clone(),
|
||||
checksum: oi.checksum.clone(),
|
||||
retry_count: 0,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn save_resync_status<S: ReplicationObjectIO>(
|
||||
@@ -1151,60 +1214,6 @@ pub async fn replicate_delete<S: ReplicationStorage>(dobj: DeletedObjectReplicat
|
||||
dobj.delete_object.version_id
|
||||
};
|
||||
|
||||
let _rcfg = match get_replication_config(&bucket).await {
|
||||
Ok(Some(config)) => config,
|
||||
Ok(None) => {
|
||||
debug!(
|
||||
event = EVENT_REPLICATION_DELETE_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
bucket = %bucket,
|
||||
reason = "replication_config_missing",
|
||||
"Skipping replication delete because replication config is missing"
|
||||
);
|
||||
send_local_event(EventArgs {
|
||||
event_name: EventName::ObjectReplicationNotTracked.to_string(),
|
||||
bucket_name: bucket.clone(),
|
||||
object: ObjectInfo {
|
||||
bucket: bucket.clone(),
|
||||
name: dobj.delete_object.object_name.clone(),
|
||||
version_id,
|
||||
delete_marker: dobj.delete_object.delete_marker,
|
||||
..Default::default()
|
||||
},
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
Err(err) => {
|
||||
debug!(
|
||||
event = EVENT_REPLICATION_DELETE_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
bucket = %bucket,
|
||||
error = %err,
|
||||
reason = "replication_config_lookup_failed",
|
||||
"Skipping replication delete because replication config lookup failed"
|
||||
);
|
||||
send_local_event(EventArgs {
|
||||
event_name: EventName::ObjectReplicationNotTracked.to_string(),
|
||||
bucket_name: bucket.clone(),
|
||||
object: ObjectInfo {
|
||||
bucket: bucket.clone(),
|
||||
name: dobj.delete_object.object_name.clone(),
|
||||
version_id,
|
||||
delete_marker: dobj.delete_object.delete_marker,
|
||||
..Default::default()
|
||||
},
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if dobj.delete_object.delete_marker
|
||||
&& let Some(delete_marker_version_id) = dobj.delete_object.delete_marker_version_id
|
||||
{
|
||||
@@ -1620,7 +1629,7 @@ async fn replicate_delete_marker_purge_to_targets(bucket: &str, dobj: &DeletedOb
|
||||
.remove_object(
|
||||
&tgt_client.bucket,
|
||||
&dobj.delete_object.object_name,
|
||||
Some(delete_marker_version_id.to_string()),
|
||||
target_delete_version_id(delete_marker_version_id, true),
|
||||
replication_delete_marker_purge_remove_options(dobj.delete_object.delete_marker_mtime),
|
||||
)
|
||||
.await;
|
||||
@@ -1850,6 +1859,14 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
|
||||
}
|
||||
}
|
||||
|
||||
fn target_delete_version_id(version_id: Uuid, version_purge: bool) -> Option<String> {
|
||||
if version_id.is_nil() {
|
||||
version_purge.then(|| NULL_VERSION_ID.to_string())
|
||||
} else {
|
||||
Some(version_id.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn replicate_delete_to_target(dobj: &DeletedObjectReplicationInfo, tgt_client: Arc<TargetClient>) -> ReplicatedTargetInfo {
|
||||
let version_id = if let Some(version_id) = &dobj.delete_object.delete_marker_version_id {
|
||||
version_id.to_owned()
|
||||
@@ -1889,11 +1906,7 @@ async fn replicate_delete_to_target(dobj: &DeletedObjectReplicationInfo, tgt_cli
|
||||
return rinfo;
|
||||
}
|
||||
|
||||
let version_id = if version_id.is_nil() {
|
||||
None
|
||||
} else {
|
||||
Some(version_id.to_string())
|
||||
};
|
||||
let version_id = target_delete_version_id(version_id, is_version_purge);
|
||||
|
||||
if dobj.delete_object.delete_marker && dobj.delete_object.delete_marker_version_id.is_some() {
|
||||
match head_object_with_proxy_stats(
|
||||
@@ -3142,7 +3155,12 @@ async fn replicate_object_with_multipart<S: ReplicationObjectIO>(ctx: MultipartR
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::replication_target_boundary::{BucketTarget, BucketTargets};
|
||||
use super::*;
|
||||
use s3s::dto::{
|
||||
BucketVersioningStatus, DeleteReplication, DeleteReplicationStatus, Destination, ExcludedPrefix, ReplicationRule,
|
||||
ReplicationRuleStatus, VersioningConfiguration,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
@@ -3584,7 +3602,9 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
let rcfg = ReplicationConfig::new(None, None);
|
||||
let roi = get_heal_replicate_object_info(&oi, &rcfg).await;
|
||||
let roi = get_heal_replicate_object_info(&oi, &rcfg)
|
||||
.await
|
||||
.expect("non-delete heal classification should succeed");
|
||||
|
||||
assert_eq!(roi.replication_status, ReplicationStatusType::Failed);
|
||||
assert_eq!(roi.op_type, ReplicationType::Heal);
|
||||
@@ -3609,7 +3629,9 @@ mod tests {
|
||||
};
|
||||
let rcfg = ReplicationConfig::new(None, None);
|
||||
|
||||
let roi = get_heal_replicate_object_info(&oi, &rcfg).await;
|
||||
let roi = get_heal_replicate_object_info(&oi, &rcfg)
|
||||
.await
|
||||
.expect("non-delete heal classification should succeed");
|
||||
|
||||
assert!(roi.ssec);
|
||||
assert_eq!(roi.checksum, Some(checksum));
|
||||
@@ -3625,6 +3647,7 @@ mod tests {
|
||||
version_purge_status: VersionPurgeStatusType::Pending,
|
||||
version_id: Some(Uuid::nil()),
|
||||
mod_time: Some(OffsetDateTime::now_utc()),
|
||||
replication_decision: format!("{role}=true;false;{role};"),
|
||||
..Default::default()
|
||||
};
|
||||
let rcfg = ReplicationConfig::new(
|
||||
@@ -3634,13 +3657,176 @@ mod tests {
|
||||
}),
|
||||
None,
|
||||
);
|
||||
let roi = get_heal_replicate_object_info(&oi, &rcfg).await;
|
||||
let roi = get_heal_replicate_object_info(&oi, &rcfg)
|
||||
.await
|
||||
.expect("stored purge admission should classify without a live versioning lookup");
|
||||
|
||||
assert_eq!(roi.replication_status_internal, None);
|
||||
assert_eq!(roi.version_purge_status_internal.as_deref(), Some(format!("{role}=PENDING;").as_str()));
|
||||
assert_eq!(roi.target_purge_statuses.get(role), Some(&VersionPurgeStatusType::Pending));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn heal_pending_purge_reads_one_versioning_generation() {
|
||||
let bucket = format!("heal-versioning-snapshot-{}", Uuid::new_v4());
|
||||
let object = "archive/object";
|
||||
let arn = "arn:rustfs:replication:us-east-1:target:bucket";
|
||||
ReplicationVersioningStore::install_prefix_state_test_config(
|
||||
&bucket,
|
||||
VersioningConfiguration {
|
||||
status: Some(BucketVersioningStatus::from_static(BucketVersioningStatus::ENABLED)),
|
||||
excluded_prefixes: Some(vec![ExcludedPrefix {
|
||||
prefix: Some("archive/".to_string()),
|
||||
}]),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let rcfg = ReplicationConfig::new(
|
||||
Some(ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![ReplicationRule {
|
||||
delete_marker_replication: None,
|
||||
delete_replication: Some(DeleteReplication {
|
||||
status: DeleteReplicationStatus::from_static(DeleteReplicationStatus::ENABLED),
|
||||
}),
|
||||
destination: Destination {
|
||||
bucket: arn.to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
existing_object_replication: None,
|
||||
filter: None,
|
||||
id: Some("delete".to_string()),
|
||||
prefix: Some(String::new()),
|
||||
priority: Some(1),
|
||||
source_selection_criteria: None,
|
||||
status: ReplicationRuleStatus::from_static(ReplicationRuleStatus::ENABLED),
|
||||
}],
|
||||
}),
|
||||
Some(BucketTargets {
|
||||
targets: vec![BucketTarget {
|
||||
arn: arn.to_string(),
|
||||
..Default::default()
|
||||
}],
|
||||
}),
|
||||
);
|
||||
let oi = ObjectInfo {
|
||||
bucket,
|
||||
name: object.to_string(),
|
||||
version_id: Some(Uuid::nil()),
|
||||
version_purge_status: VersionPurgeStatusType::Pending,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let roi = get_heal_replicate_object_info(&oi, &rcfg)
|
||||
.await
|
||||
.expect("pending null purge classification should succeed");
|
||||
|
||||
assert!(roi.dsc.targets_map.get(arn).is_some_and(|target| target.replicate));
|
||||
assert!(
|
||||
roi.existing_obj_resync
|
||||
.targets
|
||||
.get(arn)
|
||||
.is_some_and(|target| target.replicate)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn heal_pending_purge_preserves_the_persisted_admission_decision() {
|
||||
let admitted_arn = "arn:rustfs:replication:us-east-1:target:admitted";
|
||||
let current_role = "arn:rustfs:replication:us-east-1:target:current";
|
||||
let rcfg = ReplicationConfig::new(
|
||||
Some(ReplicationConfiguration {
|
||||
role: current_role.to_string(),
|
||||
rules: vec![ReplicationRule {
|
||||
delete_marker_replication: None,
|
||||
delete_replication: Some(DeleteReplication {
|
||||
status: DeleteReplicationStatus::from_static(DeleteReplicationStatus::DISABLED),
|
||||
}),
|
||||
destination: Destination {
|
||||
bucket: current_role.to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
existing_object_replication: None,
|
||||
filter: None,
|
||||
id: Some("delete".to_string()),
|
||||
prefix: Some(String::new()),
|
||||
priority: Some(1),
|
||||
source_selection_criteria: None,
|
||||
status: ReplicationRuleStatus::from_static(ReplicationRuleStatus::ENABLED),
|
||||
}],
|
||||
}),
|
||||
Some(BucketTargets {
|
||||
targets: vec![
|
||||
BucketTarget {
|
||||
arn: admitted_arn.to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
BucketTarget {
|
||||
arn: current_role.to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
let oi = ObjectInfo {
|
||||
bucket: "heal-persisted-delete-decision".to_string(),
|
||||
name: "object".to_string(),
|
||||
version_id: Some(Uuid::new_v4()),
|
||||
version_purge_status: VersionPurgeStatusType::Pending,
|
||||
version_purge_status_internal: Some(format!("{admitted_arn}=PENDING;")),
|
||||
replication_decision: format!("{admitted_arn}=true;false;{admitted_arn};"),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let roi = get_heal_replicate_object_info(&oi, &rcfg)
|
||||
.await
|
||||
.expect("persisted delete admission should survive live rule disablement");
|
||||
|
||||
assert_eq!(
|
||||
roi.version_purge_status_internal.as_deref(),
|
||||
Some(format!("{admitted_arn}=PENDING;").as_str())
|
||||
);
|
||||
assert!(roi.dsc.targets_map.get(admitted_arn).is_some_and(|target| target.replicate));
|
||||
assert!(!roi.dsc.targets_map.contains_key(current_role));
|
||||
assert!(
|
||||
roi.existing_obj_resync
|
||||
.targets
|
||||
.get(admitted_arn)
|
||||
.is_some_and(|target| target.replicate)
|
||||
);
|
||||
assert!(!roi.existing_obj_resync.targets.contains_key(current_role));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn heal_rejects_semantically_invalid_replication_config() {
|
||||
let rcfg = ReplicationConfig::new(
|
||||
Some(ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![ReplicationRule {
|
||||
delete_marker_replication: None,
|
||||
delete_replication: None,
|
||||
destination: Destination {
|
||||
bucket: "arn:rustfs:replication:us-east-1:target:bucket".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
existing_object_replication: None,
|
||||
filter: None,
|
||||
id: Some("invalid".to_string()),
|
||||
prefix: Some(String::new()),
|
||||
priority: Some(1),
|
||||
source_selection_criteria: None,
|
||||
status: ReplicationRuleStatus::from_static("Enabld"),
|
||||
}],
|
||||
}),
|
||||
Some(BucketTargets::default()),
|
||||
);
|
||||
let err = rcfg
|
||||
.validate()
|
||||
.expect_err("invalid string-backed statuses must fail before heal classification loop");
|
||||
|
||||
assert!(err.to_string().contains("Rule.Status"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cancel_marks_only_matching_bucket_target_token() {
|
||||
let resyncer = ReplicationResyncer::new().await;
|
||||
@@ -3807,4 +3993,13 @@ mod tests {
|
||||
assert_eq!(resync_status_duration(ResyncStatusType::ResyncStarted, Some(start), end), None);
|
||||
assert_eq!(resync_status_duration(ResyncStatusType::ResyncFailed, None, end), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_delete_version_id_preserves_explicit_null_purges() {
|
||||
let version_id = Uuid::new_v4();
|
||||
|
||||
assert_eq!(target_delete_version_id(version_id, true), Some(version_id.to_string()));
|
||||
assert_eq!(target_delete_version_id(Uuid::nil(), true).as_deref(), Some(NULL_VERSION_ID));
|
||||
assert_eq!(target_delete_version_id(Uuid::nil(), false), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,9 +22,9 @@ use super::replication_stats_boundary::{
|
||||
QueueCache, ReplicationMetricScope, SRMetricsSummary, XferStats,
|
||||
};
|
||||
use super::runtime_boundary as runtime_sources;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::collections::{HashMap, hash_map::Entry};
|
||||
use std::sync::atomic::{AtomicI64, Ordering};
|
||||
use std::sync::{Arc, LazyLock, Mutex as StdMutex, Weak};
|
||||
use std::time::{Duration, SystemTime};
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
use tokio::time::interval;
|
||||
@@ -143,7 +143,7 @@ pub struct ReplicationStats {
|
||||
// Active worker statistics
|
||||
pub workers: Arc<Mutex<ActiveWorkerStat>>,
|
||||
// Queue statistics cache
|
||||
pub q_cache: Arc<Mutex<QueueCache>>,
|
||||
pub q_cache: Arc<StdMutex<QueueCache>>,
|
||||
// Proxy statistics cache
|
||||
pub p_cache: Arc<Mutex<ProxyStatsCache>>,
|
||||
// MRF backlog statistics (simplified)
|
||||
@@ -153,12 +153,89 @@ pub struct ReplicationStats {
|
||||
pub most_recent_stats: Arc<Mutex<HashMap<String, BucketStats>>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RuntimeReplicationTargetBacklog {
|
||||
pub bucket: String,
|
||||
pub target_arn: String,
|
||||
pub count: u64,
|
||||
pub bytes: u64,
|
||||
}
|
||||
|
||||
type TargetQueueKey = (String, String);
|
||||
type TargetQueueCache = HashMap<TargetQueueKey, InQueueMetric>;
|
||||
|
||||
struct TargetQueueCacheSlot {
|
||||
owner: Weak<StdMutex<QueueCache>>,
|
||||
metrics: TargetQueueCache,
|
||||
}
|
||||
|
||||
impl TargetQueueCacheSlot {
|
||||
fn new(owner: &Arc<StdMutex<QueueCache>>) -> Self {
|
||||
Self {
|
||||
owner: Arc::downgrade(owner),
|
||||
metrics: TargetQueueCache::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn belongs_to(&self, owner: &Arc<StdMutex<QueueCache>>) -> bool {
|
||||
self.owner.upgrade().is_some_and(|current| Arc::ptr_eq(¤t, owner))
|
||||
}
|
||||
}
|
||||
|
||||
// Keep runtime target counters outside ReplicationStats to preserve its public struct shape.
|
||||
static TARGET_QUEUE_CACHES: LazyLock<StdMutex<Vec<TargetQueueCacheSlot>>> = LazyLock::new(|| StdMutex::new(Vec::new()));
|
||||
|
||||
fn i64_to_u64_floor_zero(value: i64) -> u64 {
|
||||
u64::try_from(value.max(0)).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn normalized_target_arns(target_arns: &[String]) -> Vec<&str> {
|
||||
let mut target_arns = target_arns
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.filter(|target_arn| !target_arn.is_empty())
|
||||
.collect::<Vec<_>>();
|
||||
target_arns.sort_unstable();
|
||||
target_arns.dedup();
|
||||
target_arns
|
||||
}
|
||||
|
||||
fn target_queue_cache_snapshot(cache: &TargetQueueCache) -> Vec<RuntimeReplicationTargetBacklog> {
|
||||
cache
|
||||
.iter()
|
||||
.filter_map(|((bucket, target_arn), metric)| {
|
||||
let count = i64_to_u64_floor_zero(metric.curr.get_current_count());
|
||||
let bytes = i64_to_u64_floor_zero(metric.curr.get_current_bytes());
|
||||
(count > 0 || bytes > 0).then(|| RuntimeReplicationTargetBacklog {
|
||||
bucket: bucket.clone(),
|
||||
target_arn: target_arn.clone(),
|
||||
count,
|
||||
bytes,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn prune_stale_target_queue_caches(caches: &mut Vec<TargetQueueCacheSlot>) {
|
||||
caches.retain(|slot| slot.owner.strong_count() > 0);
|
||||
}
|
||||
|
||||
fn with_target_queue_caches<T>(f: impl FnOnce(&mut Vec<TargetQueueCacheSlot>) -> T) -> T {
|
||||
match TARGET_QUEUE_CACHES.lock() {
|
||||
Ok(mut caches) => f(&mut caches),
|
||||
Err(poisoned) => {
|
||||
let mut caches = poisoned.into_inner();
|
||||
f(&mut caches)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ReplicationStats {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
sr_stats: Arc::new(SRStats::new()),
|
||||
workers: Arc::new(Mutex::new(ActiveWorkerStat::new())),
|
||||
q_cache: Arc::new(Mutex::new(QueueCache::new())),
|
||||
q_cache: Arc::new(StdMutex::new(QueueCache::new())),
|
||||
p_cache: Arc::new(Mutex::new(ProxyStatsCache::new())),
|
||||
mrf_stats: HashMap::new(),
|
||||
cache: Arc::new(RwLock::new(HashMap::new())),
|
||||
@@ -198,8 +275,9 @@ impl ReplicationStats {
|
||||
let mut interval = interval(Duration::from_secs(2));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
let mut cache = q_cache_clone.lock().await;
|
||||
cache.update();
|
||||
if let Ok(mut cache) = q_cache_clone.lock() {
|
||||
cache.update();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -391,12 +469,13 @@ impl ReplicationStats {
|
||||
drop(cache);
|
||||
|
||||
{
|
||||
let q_cache = self.q_cache.lock().await;
|
||||
for (bucket, queue_stats) in &q_cache.bucket_stats {
|
||||
let bucket_stats = result.entry(bucket.clone()).or_insert_with(BucketReplicationStats::new);
|
||||
bucket_stats.q_stat = queue_stats.snapshot();
|
||||
bucket_stats.mark_node_local_provider_available();
|
||||
bucket_stats.queue_scope = ReplicationMetricScope::NodeLocal;
|
||||
if let Ok(q_cache) = self.q_cache.lock() {
|
||||
for (bucket, queue_stats) in &q_cache.bucket_stats {
|
||||
let bucket_stats = result.entry(bucket.clone()).or_insert_with(BucketReplicationStats::new);
|
||||
bucket_stats.q_stat = queue_stats.snapshot();
|
||||
bucket_stats.mark_node_local_provider_available();
|
||||
bucket_stats.queue_scope = ReplicationMetricScope::NodeLocal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -429,8 +508,11 @@ impl ReplicationStats {
|
||||
let boot_time = SystemTime::UNIX_EPOCH; // simplified implementation
|
||||
let uptime = SystemTime::now().duration_since(boot_time).unwrap_or_default().as_secs() as i64;
|
||||
|
||||
let q_cache = self.q_cache.lock().await;
|
||||
let queued = q_cache.get_site_stats();
|
||||
let queued = self
|
||||
.q_cache
|
||||
.lock()
|
||||
.map(|q_cache| q_cache.get_site_stats())
|
||||
.unwrap_or_default();
|
||||
|
||||
let p_cache = self.p_cache.lock().await;
|
||||
let proxied = p_cache.get_site_stats();
|
||||
@@ -633,8 +715,9 @@ impl ReplicationStats {
|
||||
drop(cache);
|
||||
|
||||
{
|
||||
let q_cache = self.q_cache.lock().await;
|
||||
if let Some(queue_stats) = q_cache.bucket_stats.get(bucket) {
|
||||
if let Ok(q_cache) = self.q_cache.lock()
|
||||
&& let Some(queue_stats) = q_cache.bucket_stats.get(bucket)
|
||||
{
|
||||
replication_stats.q_stat = queue_stats.snapshot();
|
||||
}
|
||||
}
|
||||
@@ -665,31 +748,79 @@ impl ReplicationStats {
|
||||
}
|
||||
|
||||
/// Increase queue statistics
|
||||
pub async fn inc_q(&self, bucket: &str, size: i64, _is_delete_repl: bool, _op_type: ReplicationType) {
|
||||
let mut q_cache = self.q_cache.lock().await;
|
||||
let stats = q_cache
|
||||
.bucket_stats
|
||||
.entry(bucket.to_string())
|
||||
.or_insert_with(InQueueMetric::default);
|
||||
stats.curr.now_bytes.fetch_add(size, Ordering::Relaxed);
|
||||
stats.curr.now_count.fetch_add(1, Ordering::Relaxed);
|
||||
|
||||
q_cache.sr_queue_stats.curr.now_bytes.fetch_add(size, Ordering::Relaxed);
|
||||
q_cache.sr_queue_stats.curr.now_count.fetch_add(1, Ordering::Relaxed);
|
||||
pub fn inc_q(&self, bucket: &str, size: i64, _is_delete_repl: bool, _op_type: ReplicationType) {
|
||||
if let Ok(mut q_cache) = self.q_cache.lock() {
|
||||
q_cache.inc(bucket, size);
|
||||
}
|
||||
}
|
||||
|
||||
/// Decrease queue statistics
|
||||
pub async fn dec_q(&self, bucket: &str, size: i64, _is_del_marker: bool, _op_type: ReplicationType) {
|
||||
let mut q_cache = self.q_cache.lock().await;
|
||||
let stats = q_cache
|
||||
.bucket_stats
|
||||
.entry(bucket.to_string())
|
||||
.or_insert_with(InQueueMetric::default);
|
||||
stats.curr.now_bytes.fetch_sub(size, Ordering::Relaxed);
|
||||
stats.curr.now_count.fetch_sub(1, Ordering::Relaxed);
|
||||
pub fn dec_q(&self, bucket: &str, size: i64, _is_del_marker: bool, _op_type: ReplicationType) {
|
||||
if let Ok(mut q_cache) = self.q_cache.lock() {
|
||||
q_cache.dec(bucket, size);
|
||||
}
|
||||
}
|
||||
|
||||
q_cache.sr_queue_stats.curr.now_bytes.fetch_sub(size, Ordering::Relaxed);
|
||||
q_cache.sr_queue_stats.curr.now_count.fetch_sub(1, Ordering::Relaxed);
|
||||
pub(crate) fn inc_target_q(&self, bucket: &str, target_arns: &[String], size: i64) {
|
||||
let target_arns = normalized_target_arns(target_arns);
|
||||
if target_arns.is_empty() {
|
||||
return;
|
||||
}
|
||||
with_target_queue_caches(|caches| {
|
||||
prune_stale_target_queue_caches(caches);
|
||||
let slot_index = match caches.iter().position(|slot| slot.belongs_to(&self.q_cache)) {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
caches.push(TargetQueueCacheSlot::new(&self.q_cache));
|
||||
caches.len() - 1
|
||||
}
|
||||
};
|
||||
let slot = &mut caches[slot_index];
|
||||
let bucket = bucket.to_string();
|
||||
for target_arn in target_arns {
|
||||
let metric = match slot.metrics.entry((bucket.clone(), target_arn.to_string())) {
|
||||
Entry::Occupied(entry) => entry.into_mut(),
|
||||
Entry::Vacant(entry) => entry.insert(InQueueMetric::default()),
|
||||
};
|
||||
metric.curr.add_current(size, 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn dec_target_q(&self, bucket: &str, target_arns: &[String], size: i64) {
|
||||
let target_arns = normalized_target_arns(target_arns);
|
||||
if target_arns.is_empty() {
|
||||
return;
|
||||
}
|
||||
with_target_queue_caches(|caches| {
|
||||
prune_stale_target_queue_caches(caches);
|
||||
if let Some(slot) = caches.iter_mut().find(|slot| slot.belongs_to(&self.q_cache)) {
|
||||
let bucket = bucket.to_string();
|
||||
for target_arn in target_arns {
|
||||
if let Some(metric) = slot.metrics.get_mut(&(bucket.clone(), target_arn.to_string())) {
|
||||
metric.curr.subtract_current(size, 1);
|
||||
}
|
||||
}
|
||||
slot.metrics
|
||||
.retain(|_, metric| metric.curr.get_current_count() > 0 || metric.curr.get_current_bytes() > 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn runtime_target_backlog_snapshot(&self) -> Vec<RuntimeReplicationTargetBacklog> {
|
||||
let mut snapshot = with_target_queue_caches(|caches| {
|
||||
caches
|
||||
.iter()
|
||||
.find(|slot| slot.belongs_to(&self.q_cache))
|
||||
.map(|slot| target_queue_cache_snapshot(&slot.metrics))
|
||||
.unwrap_or_default()
|
||||
});
|
||||
snapshot.sort_by(|left, right| {
|
||||
left.bucket
|
||||
.cmp(&right.bucket)
|
||||
.then_with(|| left.target_arn.cmp(&right.target_arn))
|
||||
});
|
||||
snapshot
|
||||
}
|
||||
|
||||
/// Increase proxy metrics
|
||||
@@ -715,6 +846,94 @@ impl Default for ReplicationStats {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn runtime_target_backlog_snapshot_tracks_targets() {
|
||||
let stats = ReplicationStats::new();
|
||||
stats.inc_target_q(
|
||||
"photos",
|
||||
&[
|
||||
"arn:rustfs:replication:target-b".to_string(),
|
||||
"arn:rustfs:replication:target-a".to_string(),
|
||||
"arn:rustfs:replication:target-a".to_string(),
|
||||
],
|
||||
1024,
|
||||
);
|
||||
|
||||
let snapshot = stats.runtime_target_backlog_snapshot();
|
||||
|
||||
assert_eq!(
|
||||
snapshot,
|
||||
vec![
|
||||
RuntimeReplicationTargetBacklog {
|
||||
bucket: "photos".to_string(),
|
||||
target_arn: "arn:rustfs:replication:target-a".to_string(),
|
||||
count: 1,
|
||||
bytes: 1024,
|
||||
},
|
||||
RuntimeReplicationTargetBacklog {
|
||||
bucket: "photos".to_string(),
|
||||
target_arn: "arn:rustfs:replication:target-b".to_string(),
|
||||
count: 1,
|
||||
bytes: 1024,
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_target_backlog_ignores_empty_targets() {
|
||||
let stats = ReplicationStats::new();
|
||||
stats.inc_target_q("photos", &["".to_string()], 1024);
|
||||
|
||||
assert!(stats.runtime_target_backlog_snapshot().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_target_backlog_is_scoped_to_stats_instance() {
|
||||
let first = ReplicationStats::new();
|
||||
let second = ReplicationStats::new();
|
||||
first.inc_target_q("photos", &["arn:rustfs:replication:target-a".to_string()], 1024);
|
||||
|
||||
assert!(second.runtime_target_backlog_snapshot().is_empty());
|
||||
assert_eq!(first.runtime_target_backlog_snapshot()[0].count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_target_backlog_decrements_with_saturation() {
|
||||
let stats = ReplicationStats::new();
|
||||
let target_arns = ["arn:rustfs:replication:target-a".to_string()];
|
||||
stats.inc_target_q("photos", &target_arns, 1024);
|
||||
stats.dec_target_q("photos", &target_arns, 2048);
|
||||
|
||||
assert!(stats.runtime_target_backlog_snapshot().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_target_backlog_prunes_stale_sidecar_on_next_access() {
|
||||
{
|
||||
let stats = ReplicationStats::new();
|
||||
stats.inc_target_q("photos", &["arn:rustfs:replication:target-a".to_string()], 1024);
|
||||
assert!(
|
||||
TARGET_QUEUE_CACHES
|
||||
.lock()
|
||||
.expect("target queue cache mutex")
|
||||
.iter()
|
||||
.any(|slot| slot.owner.strong_count() > 0)
|
||||
);
|
||||
}
|
||||
|
||||
let stats = ReplicationStats::new();
|
||||
stats.inc_target_q("photos", &["arn:rustfs:replication:target-b".to_string()], 1024);
|
||||
|
||||
assert!(
|
||||
TARGET_QUEUE_CACHES
|
||||
.lock()
|
||||
.expect("target queue cache mutex")
|
||||
.iter()
|
||||
.all(|slot| slot.owner.strong_count() > 0)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_replication_stats_new() {
|
||||
let stats = ReplicationStats::new();
|
||||
@@ -801,14 +1020,14 @@ mod tests {
|
||||
async fn latest_stats_include_queue_until_drained() {
|
||||
let stats = ReplicationStats::new();
|
||||
|
||||
stats.inc_q("queued-bucket", 4096, false, ReplicationType::Object).await;
|
||||
stats.inc_q("queued-bucket", 4096, false, ReplicationType::Object);
|
||||
let queued = stats.get_latest_replication_stats("queued-bucket").await;
|
||||
assert!(queued.replication_stats.provider_available);
|
||||
assert_eq!(queued.replication_stats.q_stat.curr.count, 1);
|
||||
assert_eq!(queued.replication_stats.q_stat.curr.bytes, 4096);
|
||||
assert_eq!(queued.replication_stats.queue_scope, ReplicationMetricScope::NodeLocal);
|
||||
|
||||
stats.dec_q("queued-bucket", 4096, false, ReplicationType::Object).await;
|
||||
stats.dec_q("queued-bucket", 4096, false, ReplicationType::Object);
|
||||
let drained = stats.get_latest_replication_stats("queued-bucket").await;
|
||||
assert_eq!(drained.replication_stats.q_stat.curr.count, 0);
|
||||
assert_eq!(drained.replication_stats.q_stat.curr.bytes, 0);
|
||||
@@ -911,7 +1130,7 @@ mod tests {
|
||||
for _ in 0..32 {
|
||||
let stats = Arc::clone(&stats);
|
||||
tasks.push(tokio::spawn(async move {
|
||||
stats.inc_q("concurrent-bucket", 7, false, ReplicationType::Object).await;
|
||||
stats.inc_q("concurrent-bucket", 7, false, ReplicationType::Object);
|
||||
}));
|
||||
}
|
||||
for task in tasks {
|
||||
|
||||
@@ -35,6 +35,8 @@ use time::format_description::well_known::Rfc3339;
|
||||
pub(crate) use crate::bucket::bucket_target_sys::{
|
||||
AdvancedPutOptions, PutObjectOptions, PutObjectPartOptions, RemoveObjectOptions, TargetClient,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use crate::bucket::target::BucketTarget;
|
||||
pub(crate) use crate::bucket::target::BucketTargets;
|
||||
|
||||
use super::replication_config_store::ReplicationConfigStore;
|
||||
|
||||
@@ -12,11 +12,28 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use crate::bucket::versioning_sys::BucketVersioningSys;
|
||||
use super::replication_error_boundary::Result;
|
||||
use crate::bucket::{versioning::VersioningApi as _, versioning_sys::BucketVersioningSys};
|
||||
#[cfg(test)]
|
||||
use s3s::dto::VersioningConfiguration;
|
||||
#[cfg(test)]
|
||||
use std::{collections::HashMap, sync::LazyLock, sync::Mutex};
|
||||
|
||||
#[cfg(test)]
|
||||
static PREFIX_STATE_TEST_CONFIGS: LazyLock<Mutex<HashMap<String, VersioningConfiguration>>> =
|
||||
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub(crate) struct ReplicationVersioningStore;
|
||||
|
||||
impl ReplicationVersioningStore {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn install_prefix_state_test_config(bucket: &str, config: VersioningConfiguration) {
|
||||
PREFIX_STATE_TEST_CONFIGS
|
||||
.lock()
|
||||
.expect("replication versioning test config lock should not be poisoned")
|
||||
.insert(bucket.to_string(), config);
|
||||
}
|
||||
|
||||
pub(crate) async fn prefix_enabled(bucket: &str, prefix: &str) -> bool {
|
||||
BucketVersioningSys::prefix_enabled(bucket, prefix).await
|
||||
}
|
||||
@@ -24,4 +41,18 @@ impl ReplicationVersioningStore {
|
||||
pub(crate) async fn prefix_suspended(bucket: &str, prefix: &str) -> bool {
|
||||
BucketVersioningSys::prefix_suspended(bucket, prefix).await
|
||||
}
|
||||
|
||||
pub(crate) async fn prefix_state(bucket: &str, prefix: &str) -> Result<(bool, bool)> {
|
||||
#[cfg(test)]
|
||||
if let Some(config) = PREFIX_STATE_TEST_CONFIGS
|
||||
.lock()
|
||||
.expect("replication versioning test config lock should not be poisoned")
|
||||
.remove(bucket)
|
||||
{
|
||||
return Ok((config.prefix_enabled(prefix), config.prefix_suspended(prefix)));
|
||||
}
|
||||
|
||||
let config = BucketVersioningSys::get(bucket).await?;
|
||||
Ok((config.prefix_enabled(prefix), config.prefix_suspended(prefix)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,9 @@ pub trait VersioningApi {
|
||||
fn enabled(&self) -> bool;
|
||||
fn prefix_enabled(&self, prefix: &str) -> bool;
|
||||
fn prefix_suspended(&self, prefix: &str) -> bool;
|
||||
fn delete_state(&self, prefix: &str) -> (bool, bool) {
|
||||
(self.prefix_enabled(prefix), self.suspended())
|
||||
}
|
||||
fn versioned(&self, prefix: &str) -> bool;
|
||||
fn suspended(&self) -> bool;
|
||||
}
|
||||
@@ -92,3 +95,60 @@ impl VersioningApi for VersioningConfiguration {
|
||||
self.status == Some(BucketVersioningStatus::from_static(BucketVersioningStatus::SUSPENDED))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use s3s::dto::{BucketVersioningStatus, ExcludedPrefix};
|
||||
|
||||
use super::*;
|
||||
|
||||
struct LegacyVersioning;
|
||||
|
||||
impl VersioningApi for LegacyVersioning {
|
||||
fn enabled(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn prefix_enabled(&self, _prefix: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn prefix_suspended(&self, _prefix: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn versioned(&self, _prefix: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn suspended(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_state_has_a_backward_compatible_default() {
|
||||
assert_eq!(LegacyVersioning.delete_state("object"), (false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_state_treats_excluded_prefixes_as_unversioned() {
|
||||
let config = VersioningConfiguration {
|
||||
status: Some(BucketVersioningStatus::from_static(BucketVersioningStatus::ENABLED)),
|
||||
excluded_prefixes: Some(vec![ExcludedPrefix {
|
||||
prefix: Some("archive/".to_string()),
|
||||
}]),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(config.delete_state("archive/object"), (false, false));
|
||||
assert!(config.prefix_suspended("archive/object"));
|
||||
assert_eq!(config.delete_state("live/object"), (true, false));
|
||||
|
||||
let suspended = VersioningConfiguration {
|
||||
status: Some(BucketVersioningStatus::from_static(BucketVersioningStatus::SUSPENDED)),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(suspended.delete_state("archive/object"), (false, true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ pub(crate) use internode_data_transport::TcpHttpInternodeDataTransport;
|
||||
pub use internode_data_transport::build_internode_data_transport_from_env;
|
||||
pub(crate) use peer_rest_client::TierConfigReloadOutcome;
|
||||
pub use peer_rest_client::{
|
||||
PEER_RESTDRY_RUN, PEER_RESTSIGNAL, PEER_RESTSUB_SYS, PeerRestClient, SERVICE_SIGNAL_REFRESH_CONFIG,
|
||||
KMS_SIGNAL_SUBSYSTEM, PEER_RESTDRY_RUN, PEER_RESTSIGNAL, PEER_RESTSUB_SYS, PeerRestClient, SERVICE_SIGNAL_REFRESH_CONFIG,
|
||||
SERVICE_SIGNAL_RELOAD_DYNAMIC, ScannerPeerActivity,
|
||||
};
|
||||
pub(crate) use peer_s3_client::heal_bucket_local_on_disks;
|
||||
|
||||
@@ -45,9 +45,9 @@ use rustfs_protos::proto_gen::node_service::{
|
||||
HealControlRequest, LoadBucketMetadataRequest, LoadGroupRequest, LoadPolicyMappingRequest, LoadPolicyRequest,
|
||||
LoadRebalanceMetaRequest, LoadServiceAccountRequest, LoadTransitionTierConfigRequest, LoadUserRequest,
|
||||
LocalStorageInfoRequest, Mss, ReloadPoolMetaRequest, ReloadSiteReplicationConfigRequest, ScannerActivityRequest,
|
||||
ScannerActivityResponse, ServerInfoRequest, SignalServiceRequest, StartDecommissionRequest, StartProfilingRequest,
|
||||
StopRebalanceRequest, TierMutationAbortRequest, TierMutationCommitRequest, TierMutationControlResponse,
|
||||
TierMutationPeerState, TierMutationPrepareRequest, node_service_client::NodeServiceClient,
|
||||
ScannerActivityResponse, ServerInfoRequest, SignalServiceRequest, SignalServiceResponse, StartDecommissionRequest,
|
||||
StartProfilingRequest, StopRebalanceRequest, TierMutationAbortRequest, TierMutationCommitRequest,
|
||||
TierMutationControlResponse, TierMutationPeerState, TierMutationPrepareRequest, node_service_client::NodeServiceClient,
|
||||
tier_mutation_control_service_client::TierMutationControlServiceClient,
|
||||
};
|
||||
pub use rustfs_protos::{PEER_RESTDRY_RUN, PEER_RESTSIGNAL, PEER_RESTSUB_SYS};
|
||||
@@ -71,6 +71,12 @@ use uuid::Uuid;
|
||||
|
||||
pub const SERVICE_SIGNAL_REFRESH_CONFIG: u64 = 1;
|
||||
pub const SERVICE_SIGNAL_RELOAD_DYNAMIC: u64 = 2;
|
||||
/// Dynamic config subsystem for the cluster-persisted KMS configuration.
|
||||
///
|
||||
/// KMS configuration lives in its own cluster object rather than in the server
|
||||
/// config document, so it is not a `ServerConfig` subsystem; it only shares the
|
||||
/// reload signal transport.
|
||||
pub const KMS_SIGNAL_SUBSYSTEM: &str = "kms";
|
||||
const BACKGROUND_HEAL_STATUS_MAX_MESSAGE_SIZE: usize = 64 * 1024;
|
||||
const HEAL_CONTROL_FINGERPRINT_MAX_SIZE: usize = 256;
|
||||
const HEAL_CONTROL_PAYLOAD_MAX_SIZE: usize = 64 * 1024;
|
||||
@@ -99,8 +105,13 @@ fn decode_bucket_stats_response(response: GetBucketStatsDataResponse) -> Result<
|
||||
}
|
||||
|
||||
fn validate_signal_service_protocol(sig: u64, sub_sys: &str, protocol_version: u32) -> Result<()> {
|
||||
// The version stays pinned to DYNAMIC_CONFIG_PROTOCOL_VERSION rather than
|
||||
// being bumped per subsystem: the comparison is shared, so raising it would
|
||||
// retire peers that already converge scanner and heal config correctly.
|
||||
// Subsystems added after a peer was built are rejected by that peer's own
|
||||
// subsystem allow-list, which surfaces as an explicit failed signal.
|
||||
if sig == SERVICE_SIGNAL_RELOAD_DYNAMIC
|
||||
&& matches!(sub_sys, SCANNER_SUB_SYS | HEAL_SUB_SYS)
|
||||
&& matches!(sub_sys, SCANNER_SUB_SYS | HEAL_SUB_SYS | KMS_SIGNAL_SUBSYSTEM)
|
||||
&& protocol_version < rustfs_protos::DYNAMIC_CONFIG_PROTOCOL_VERSION
|
||||
{
|
||||
return Err(Error::other(format!("peer does not support dynamic {sub_sys} config convergence")));
|
||||
@@ -1500,6 +1511,22 @@ impl PeerRestClient {
|
||||
}
|
||||
|
||||
pub async fn signal_service(&self, sig: u64, sub_sys: &str, dry_run: bool, _exec_at: SystemTime) -> Result<()> {
|
||||
self.signal_service_checked(sig, sub_sys, dry_run).await.map(|_| ())
|
||||
}
|
||||
|
||||
/// Report the KMS configuration fingerprint the peer is currently running.
|
||||
///
|
||||
/// Sent as a dry-run reload signal so the peer answers without swapping its
|
||||
/// own configuration. `None` means the peer has no KMS configuration. The
|
||||
/// fingerprint is advisory and feeds cluster status reporting only, so the
|
||||
/// response is not proof-signed.
|
||||
pub async fn kms_config_fingerprint(&self) -> Result<Option<String>> {
|
||||
self.signal_service_checked(SERVICE_SIGNAL_RELOAD_DYNAMIC, KMS_SIGNAL_SUBSYSTEM, true)
|
||||
.await
|
||||
.map(|response| response.config_fingerprint)
|
||||
}
|
||||
|
||||
async fn signal_service_checked(&self, sig: u64, sub_sys: &str, dry_run: bool) -> Result<SignalServiceResponse> {
|
||||
self.finalize_result(
|
||||
async {
|
||||
let mut client = self.get_client().await?;
|
||||
@@ -1520,7 +1547,7 @@ impl PeerRestClient {
|
||||
return Err(Error::other(""));
|
||||
}
|
||||
validate_signal_service_protocol(sig, sub_sys, response.protocol_version)?;
|
||||
Ok(())
|
||||
Ok(response)
|
||||
}
|
||||
.await,
|
||||
)
|
||||
@@ -2347,6 +2374,19 @@ mod tests {
|
||||
.expect("full refresh compatibility is guarded by its scanner preflight");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_kms_config_requires_versioned_peer_acknowledgement() {
|
||||
let err = validate_signal_service_protocol(SERVICE_SIGNAL_RELOAD_DYNAMIC, KMS_SIGNAL_SUBSYSTEM, 0)
|
||||
.expect_err("an unversioned peer must not claim KMS config convergence");
|
||||
assert!(err.to_string().contains("does not support dynamic"));
|
||||
validate_signal_service_protocol(
|
||||
SERVICE_SIGNAL_RELOAD_DYNAMIC,
|
||||
KMS_SIGNAL_SUBSYSTEM,
|
||||
rustfs_protos::DYNAMIC_CONFIG_PROTOCOL_VERSION,
|
||||
)
|
||||
.expect("a current peer should support dynamic KMS config");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_rest_client_marks_network_like_errors() {
|
||||
assert!(PeerRestClient::is_network_like_error(&Error::other("transport error")));
|
||||
|
||||
@@ -615,7 +615,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for Sets {
|
||||
self.get_disks_by_key(object).delete_object(bucket, object, opts).await
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(self))]
|
||||
#[tracing::instrument(skip(self, objects, opts))]
|
||||
async fn delete_objects(
|
||||
&self,
|
||||
bucket: &str,
|
||||
|
||||
@@ -5078,7 +5078,7 @@ impl LocalDisk {
|
||||
Ok((buf, mtime))
|
||||
}
|
||||
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "LocalDisk")]
|
||||
async fn read_metadata_with_dmtime(&self, file_path: impl AsRef<Path>) -> Result<(Vec<u8>, Option<OffsetDateTime>)> {
|
||||
check_path_length(file_path.as_ref().to_string_lossy().as_ref())?;
|
||||
|
||||
@@ -5121,7 +5121,7 @@ impl LocalDisk {
|
||||
Ok((data, modtime))
|
||||
}
|
||||
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "LocalDisk")]
|
||||
async fn read_all_data(&self, volume: &str, volume_dir: impl AsRef<Path>, file_path: impl AsRef<Path>) -> Result<Vec<u8>> {
|
||||
// TODO: timeout support
|
||||
let (data, _) = self.read_all_data_with_dmtime(volume, volume_dir, file_path).await?;
|
||||
@@ -6641,6 +6641,49 @@ impl LocalDisk {
|
||||
let xl_path = object_dir.join(STORAGE_FORMAT_FILE);
|
||||
restore_delete_rollback_after_error(object_dir, &xl_path, Some(rollback_dir), volume, object, stage, err).await
|
||||
}
|
||||
|
||||
/// Execute every deferred data-dir deletion pending on `volume` right now,
|
||||
/// even while snapshot leases are still held. Bucket deletion requires it:
|
||||
/// a streaming reader defers the physical cleanup of an already-deleted
|
||||
/// version, and a non-force `delete_volume` would otherwise fail closed
|
||||
/// with `VolumeNotEmpty` on those remnants even though the bucket is
|
||||
/// logically empty. The still-active readers keep their open descriptors;
|
||||
/// only path-based reopens observe the removal.
|
||||
async fn settle_pending_snapshot_deletes(&self, volume: &str) {
|
||||
let pending: Vec<(SnapshotLeaseKey, DeleteOptions)> = {
|
||||
let mut registry = self.snapshot_leases.lock().await;
|
||||
registry
|
||||
.entries
|
||||
.iter_mut()
|
||||
.filter(|(key, entry)| key.volume == volume && !entry.deleting && entry.pending_delete.is_some())
|
||||
.map(|(key, entry)| {
|
||||
entry.deleting = true;
|
||||
(key.clone(), entry.pending_delete.clone().expect("filtered on Some"))
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
|
||||
for (key, opts) in pending {
|
||||
let result = self.delete_unleased(&key.volume, &key.path, &opts).await;
|
||||
let mut registry = self.snapshot_leases.lock().await;
|
||||
match result {
|
||||
Ok(()) => {
|
||||
registry.entries.remove(&key);
|
||||
}
|
||||
Err(err) => {
|
||||
if let Some(entry) = registry.entries.get_mut(&key) {
|
||||
entry.deleting = false;
|
||||
}
|
||||
warn!(
|
||||
volume = %key.volume,
|
||||
path = %key.path,
|
||||
error = %err,
|
||||
"failed to settle deferred data-dir deletion before volume removal"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
@@ -9122,6 +9165,14 @@ impl DiskAPI for LocalDisk {
|
||||
let p = self.get_bucket_path(volume)?;
|
||||
let _volume_mutation_guard = os::disk_volume_mutation_lock(&self.root, volume).write_owned().await;
|
||||
|
||||
// A streaming reader's snapshot lease defers the physical cleanup of
|
||||
// data dirs whose version delete already committed. Those remnants are
|
||||
// logically deleted, so run the parked cleanups now instead of letting
|
||||
// the non-force removal below fail closed on them (the s3-tests SSE-C
|
||||
// teardown races exactly this way: DeleteObjects, then DeleteBucket
|
||||
// while an abandoned GET body still pins the lease).
|
||||
self.settle_pending_snapshot_deletes(volume).await;
|
||||
|
||||
// Non-force removes empty directory remnants children-first with
|
||||
// non-recursive rmdir calls. A file that exists during the scan, or
|
||||
// appears before its parent is removed, fails closed with
|
||||
@@ -15981,6 +16032,74 @@ mod test {
|
||||
assert!(matches!(disk.read_all(volume, &first_part).await, Err(DiskError::FileNotFound)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_volume_settles_lease_deferred_cleanup() {
|
||||
use tempfile::tempdir;
|
||||
|
||||
let root_dir = tempdir().expect("temp dir should be created");
|
||||
let endpoint = Endpoint::try_from(root_dir.path().to_string_lossy().as_ref()).expect("endpoint should parse");
|
||||
let disk = LocalDisk::new(&endpoint, false).await.expect("local disk should be created");
|
||||
let volume = "snapshot-lease-bucket-delete";
|
||||
let object = "multipart_enc";
|
||||
let version_id = Uuid::new_v4();
|
||||
let data_dir = Uuid::new_v4();
|
||||
let rollback_dir = Uuid::new_v4();
|
||||
let data_path = path_join_buf(&[object, &data_dir.to_string()]);
|
||||
let part = path_join_buf(&[&data_path, "part.1"]);
|
||||
ensure_test_volume(&disk, volume).await;
|
||||
disk.write_all(volume, &part, Bytes::from_static(b"payload"))
|
||||
.await
|
||||
.expect("shard should be written");
|
||||
let fi = test_file_info(object, version_id, Some(data_dir), None);
|
||||
disk.write_all(volume, &path_join_buf(&[object, STORAGE_FORMAT_FILE]), test_meta(fi.clone()).into())
|
||||
.await
|
||||
.expect("metadata should be written");
|
||||
|
||||
// An abandoned streaming GET pins the data dir with a snapshot lease.
|
||||
let snapshot = disk
|
||||
.acquire_snapshot_lease(volume, &data_path)
|
||||
.await
|
||||
.expect("snapshot lease should be acquired");
|
||||
disk.delete_version(
|
||||
volume,
|
||||
object,
|
||||
fi.clone(),
|
||||
false,
|
||||
DeleteOptions {
|
||||
old_data_dir: Some(rollback_dir),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("version delete should commit metadata");
|
||||
disk.delete(
|
||||
volume,
|
||||
&format!("{object}/{rollback_dir}"),
|
||||
DeleteOptions {
|
||||
recursive: true,
|
||||
immediate: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("version delete should schedule physical cleanup");
|
||||
|
||||
// The bucket is logically empty; a non-force volume delete must settle
|
||||
// the deferred data-dir cleanup instead of failing with VolumeNotEmpty.
|
||||
disk.delete_volume(volume, false)
|
||||
.await
|
||||
.expect("bucket delete must not observe lease-deferred remnants");
|
||||
assert!(matches!(
|
||||
disk.read_all(volume, &part).await,
|
||||
Err(DiskError::FileNotFound | DiskError::VolumeNotFound)
|
||||
));
|
||||
|
||||
// The late lease release finds nothing pending and stays idempotent.
|
||||
disk.release_snapshot_lease(volume, &data_path, snapshot)
|
||||
.await
|
||||
.expect("releasing the lease after bucket deletion should be a no-op");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_delete_cleanup_intent_survives_local_disk_restart() {
|
||||
use tempfile::tempdir;
|
||||
|
||||
@@ -103,7 +103,7 @@ where
|
||||
/// or `out` is larger than one shard. On error `out`'s contents are
|
||||
/// unspecified but never contain bytes that failed the hash check — the copy
|
||||
/// happens only after verification.
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "BitrotReader")]
|
||||
pub async fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
|
||||
let want = out.len();
|
||||
self.begin_read(want)?;
|
||||
@@ -303,7 +303,7 @@ where
|
||||
|
||||
/// Write a (hash+data) block. Returns the number of data bytes written.
|
||||
/// Returns an error if called after a short write or if data exceeds shard_size.
|
||||
#[hotpath::measure(label = "BitrotWriter::write")]
|
||||
#[hotpath::measure(label = "BitrotWriter::write", impl_type = "BitrotWriter")]
|
||||
pub async fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
if buf.is_empty() {
|
||||
return Ok(0);
|
||||
|
||||
@@ -691,7 +691,7 @@ impl<R> ParallelReader<R>
|
||||
where
|
||||
R: crate::erasure::coding::ShardSource,
|
||||
{
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "ParallelReader")]
|
||||
pub async fn read(&mut self) -> (Vec<Option<Vec<u8>>>, Vec<Option<Error>>) {
|
||||
// On the reconstruction-verifying GET path, read every live shard reader
|
||||
// in lockstep so all readers advance one block per stripe and stay
|
||||
@@ -1505,7 +1505,7 @@ where
|
||||
}
|
||||
|
||||
impl Erasure {
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub async fn decode<W, R>(
|
||||
&self,
|
||||
writer: &mut W,
|
||||
@@ -1645,15 +1645,28 @@ impl Erasure {
|
||||
}
|
||||
Err(e) => {
|
||||
record_get_stage_duration_if_enabled(GET_OBJECT_PATH_LEGACY_DUPLEX, GET_STAGE_EMIT, emit_stage_start);
|
||||
error!(
|
||||
block_offset,
|
||||
block_length,
|
||||
bytes_written = *written,
|
||||
stage = GET_STAGE_EMIT,
|
||||
reason = classify_io_error(&e).as_str(),
|
||||
error = ?e,
|
||||
"Erasure decode failed to emit reconstructed data"
|
||||
);
|
||||
let reason = classify_io_error(&e);
|
||||
if reason == GetObjectFailureReason::DownstreamClosed {
|
||||
debug!(
|
||||
block_offset,
|
||||
block_length,
|
||||
bytes_written = *written,
|
||||
stage = GET_STAGE_EMIT,
|
||||
reason = reason.as_str(),
|
||||
error = ?e,
|
||||
"Erasure decode stopped after downstream closed"
|
||||
);
|
||||
} else {
|
||||
error!(
|
||||
block_offset,
|
||||
block_length,
|
||||
bytes_written = *written,
|
||||
stage = GET_STAGE_EMIT,
|
||||
reason = reason.as_str(),
|
||||
error = ?e,
|
||||
"Erasure decode failed to emit reconstructed data"
|
||||
);
|
||||
}
|
||||
*ret_err = Some(e);
|
||||
return StripeFlow::Stop;
|
||||
}
|
||||
@@ -1945,7 +1958,7 @@ mod tests {
|
||||
use std::io::Cursor;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use std::task::{Context, Poll};
|
||||
@@ -2120,6 +2133,59 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
struct DownstreamClosedWriter;
|
||||
|
||||
impl AsyncWrite for DownstreamClosedWriter {
|
||||
fn poll_write(self: Pin<&mut Self>, _cx: &mut Context<'_>, _buf: &[u8]) -> Poll<io::Result<usize>> {
|
||||
Poll::Ready(Err(crate::diagnostics::get::mark_get_object_downstream_closed(io::Error::new(
|
||||
ErrorKind::BrokenPipe,
|
||||
"injected downstream close",
|
||||
))))
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct CapturedLogs(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
struct CapturedLogWriter(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl CapturedLogs {
|
||||
fn contents(&self) -> String {
|
||||
String::from_utf8(self.0.lock().expect("captured logs mutex should not be poisoned").clone())
|
||||
.expect("captured logs should be valid UTF-8")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Write for CapturedLogWriter {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.0
|
||||
.lock()
|
||||
.expect("captured logs mutex should not be poisoned")
|
||||
.extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CapturedLogs {
|
||||
type Writer = CapturedLogWriter;
|
||||
|
||||
fn make_writer(&'a self) -> Self::Writer {
|
||||
CapturedLogWriter(Arc::clone(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parallel_reader_constructor_variants_preserve_read_cost_and_verification_flags() {
|
||||
let erasure = Erasure::new(2, 1, 64);
|
||||
@@ -2215,6 +2281,47 @@ mod tests {
|
||||
assert_eq!(err.to_string(), "injected emit failure");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn erasure_decode_logs_reconstructed_downstream_close_at_debug() {
|
||||
let logs = CapturedLogs::default();
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_max_level(tracing::Level::DEBUG)
|
||||
.with_writer(logs.clone())
|
||||
.with_ansi(false)
|
||||
.without_time()
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
|
||||
let erasure = Erasure::new(2, 1, 64);
|
||||
let data: Vec<u8> = (0..64).collect();
|
||||
let shard_size = erasure.shard_size();
|
||||
let encoded = erasure.encode_data(&data).expect("test data should encode");
|
||||
let readers = vec![
|
||||
None,
|
||||
Some(BitrotReader::new(
|
||||
Cursor::new(encoded[1].to_vec()),
|
||||
shard_size,
|
||||
HashAlgorithm::None,
|
||||
false,
|
||||
)),
|
||||
Some(BitrotReader::new(
|
||||
Cursor::new(encoded[2].to_vec()),
|
||||
shard_size,
|
||||
HashAlgorithm::None,
|
||||
false,
|
||||
)),
|
||||
];
|
||||
|
||||
let mut writer = DownstreamClosedWriter;
|
||||
let (written, err) = erasure.decode(&mut writer, readers, 0, data.len(), data.len()).await;
|
||||
|
||||
assert_eq!(written, 0);
|
||||
assert_eq!(err.expect("downstream close must still terminate the GET").kind(), ErrorKind::BrokenPipe);
|
||||
let captured = logs.contents();
|
||||
assert!(captured.contains("Erasure decode stopped after downstream closed"));
|
||||
assert!(!captured.contains("Erasure decode failed to emit reconstructed data"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_erasure_decode_rejects_reader_count_and_range_overflow() {
|
||||
let erasure = Erasure::new(2, 1, 64);
|
||||
|
||||
@@ -28,8 +28,11 @@ use std::vec;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::runtime::RuntimeFlavor;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::{JoinError, JoinHandle};
|
||||
use tracing::error;
|
||||
|
||||
/// Queue-capacity input for encoded blocks awaiting shard writers; it is not a
|
||||
/// per-PUT or process-RSS memory limit.
|
||||
const ENV_RUSTFS_ERASURE_ENCODE_MAX_INFLIGHT_BYTES: &str = "RUSTFS_ERASURE_ENCODE_MAX_INFLIGHT_BYTES";
|
||||
const ENV_RUSTFS_ERASURE_ENCODE_BATCH_BLOCKS: &str = "RUSTFS_ERASURE_ENCODE_BATCH_BLOCKS";
|
||||
const ENV_RUSTFS_ERASURE_ENCODE_BYTESMUT_INGEST: &str = "RUSTFS_ERASURE_ENCODE_BYTESMUT_INGEST";
|
||||
@@ -87,6 +90,33 @@ fn use_bytesmut_ingest() -> bool {
|
||||
rustfs_utils::get_env_bool(ENV_RUSTFS_ERASURE_ENCODE_BYTESMUT_INGEST, DEFAULT_RUSTFS_ERASURE_ENCODE_BYTESMUT_INGEST)
|
||||
})
|
||||
}
|
||||
|
||||
/// Keeps the encoder producer scoped to its parent future. Tokio detaches a
|
||||
/// task when its `JoinHandle` is dropped, so the producer must be aborted when
|
||||
/// an upload is cancelled before the encode pipeline finishes.
|
||||
struct AbortOnDropTask<T>(JoinHandle<T>);
|
||||
|
||||
impl<T> AbortOnDropTask<T> {
|
||||
fn new(task: JoinHandle<T>) -> Self {
|
||||
Self(task)
|
||||
}
|
||||
|
||||
async fn abort_and_wait(&mut self) {
|
||||
self.0.abort();
|
||||
let _ = (&mut self.0).await;
|
||||
}
|
||||
|
||||
async fn join(&mut self) -> Result<T, JoinError> {
|
||||
(&mut self.0).await
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for AbortOnDropTask<T> {
|
||||
fn drop(&mut self) {
|
||||
self.0.abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// Read up to `limit` bytes into `buf`'s uninitialized spare capacity, appending after its
|
||||
/// current length, and distinguish a clean EOF from a short read.
|
||||
///
|
||||
@@ -133,22 +163,65 @@ fn queued_block_bytes(block: &[Bytes]) -> usize {
|
||||
block.iter().map(Bytes::len).sum()
|
||||
}
|
||||
|
||||
async fn drain_queued_inflight_bytes(rx: &mut mpsc::Receiver<Vec<Bytes>>) {
|
||||
while let Some(block) = rx.recv().await {
|
||||
rustfs_io_metrics::remove_ec_encode_inflight_bytes(queued_block_bytes(&block));
|
||||
/// Owns an encoded queue entry's gauge contribution until its consumer takes it.
|
||||
struct QueuedInflightBytes {
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl QueuedInflightBytes {
|
||||
fn new(bytes: usize) -> Self {
|
||||
rustfs_io_metrics::add_ec_encode_inflight_bytes(bytes);
|
||||
Self { bytes }
|
||||
}
|
||||
|
||||
fn settle(&mut self) {
|
||||
let bytes = std::mem::take(&mut self.bytes);
|
||||
if bytes != 0 {
|
||||
rustfs_io_metrics::remove_ec_encode_inflight_bytes(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for QueuedInflightBytes {
|
||||
fn drop(&mut self) {
|
||||
self.settle();
|
||||
}
|
||||
}
|
||||
|
||||
/// Couples an encoded block with its queue gauge contribution. Keeping the
|
||||
/// guard in the queue entry also covers Tokio sends that complete through a
|
||||
/// permit after the receiver has closed.
|
||||
struct InflightEntry<T> {
|
||||
entry: T,
|
||||
accounting: QueuedInflightBytes,
|
||||
}
|
||||
|
||||
impl<T> InflightEntry<T> {
|
||||
fn new(entry: T, bytes: usize) -> Self {
|
||||
Self {
|
||||
entry,
|
||||
accounting: QueuedInflightBytes::new(bytes),
|
||||
}
|
||||
}
|
||||
|
||||
fn into_inner(mut self) -> T {
|
||||
self.accounting.settle();
|
||||
self.entry
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_queued<T>(
|
||||
sender: &mpsc::Sender<InflightEntry<T>>,
|
||||
entry: T,
|
||||
bytes: usize,
|
||||
) -> Result<(), mpsc::error::SendError<InflightEntry<T>>> {
|
||||
sender.send(InflightEntry::new(entry, bytes)).await
|
||||
}
|
||||
|
||||
fn queued_batch_bytes(batch: &[Vec<Bytes>]) -> usize {
|
||||
batch.iter().map(|block| queued_block_bytes(block)).sum()
|
||||
}
|
||||
|
||||
async fn drain_queued_batched_inflight_bytes(rx: &mut mpsc::Receiver<Vec<Vec<Bytes>>>) {
|
||||
while let Some(batch) = rx.recv().await {
|
||||
rustfs_io_metrics::remove_ec_encode_inflight_bytes(queued_batch_bytes(&batch));
|
||||
}
|
||||
}
|
||||
|
||||
fn dominant_error_summary_label(summary: &WriteQuorumFailureSummary) -> &'static str {
|
||||
summary.dominant_error_label
|
||||
}
|
||||
@@ -504,7 +577,7 @@ impl Erasure {
|
||||
Ok((reader, total))
|
||||
}
|
||||
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub async fn encode<R>(
|
||||
self: Arc<Self>,
|
||||
reader: R,
|
||||
@@ -540,13 +613,14 @@ impl Erasure {
|
||||
));
|
||||
}
|
||||
|
||||
// Bound queued encoded blocks by memory budget to avoid per-request spikes.
|
||||
// Bound queued encoded blocks by a queue budget; this does not bound
|
||||
// reader, encoder, writer, allocator, or process-RSS memory.
|
||||
let expanded_block_bytes = self.shard_size().saturating_mul(self.total_shard_count());
|
||||
let max_inflight_bytes = erasure_encode_max_inflight_bytes();
|
||||
let inflight_blocks = encode_channel_capacity(expanded_block_bytes, max_inflight_bytes);
|
||||
let (tx, mut rx) = mpsc::channel::<Vec<Bytes>>(inflight_blocks);
|
||||
let (tx, mut rx) = mpsc::channel::<InflightEntry<Vec<Bytes>>>(inflight_blocks);
|
||||
|
||||
let task = tokio::spawn(async move {
|
||||
let mut task = AbortOnDropTask::new(tokio::spawn(async move {
|
||||
let block_size = self.block_size;
|
||||
let mut total = 0;
|
||||
if use_bytesmut_ingest {
|
||||
@@ -567,10 +641,9 @@ impl Erasure {
|
||||
let res = self.clone().encode_block_bytes_mut(encode_buf, n).await?;
|
||||
buf = BytesMut::with_capacity(ingest_capacity);
|
||||
let queued_bytes = queued_block_bytes(&res);
|
||||
rustfs_io_metrics::add_ec_encode_inflight_bytes(queued_bytes);
|
||||
let _producer_stage = rustfs_io_metrics::track_ec_encode_producer_bytes(queued_bytes);
|
||||
let send_wait_stage_start = stage_timer_if_enabled();
|
||||
if let Err(err) = tx.send(res).await {
|
||||
rustfs_io_metrics::remove_ec_encode_inflight_bytes(queued_bytes);
|
||||
if let Err(err) = send_queued(&tx, res, queued_bytes).await {
|
||||
return Err(std::io::Error::other(format!("Failed to send encoded data : {err}")));
|
||||
}
|
||||
record_internal_stage_if_enabled("erasure_encode_send_wait", send_wait_stage_start);
|
||||
@@ -598,10 +671,9 @@ impl Erasure {
|
||||
let (res, returned_buf) = self.clone().encode_block(encode_buf, n).await?;
|
||||
buf = returned_buf;
|
||||
let queued_bytes = queued_block_bytes(&res);
|
||||
rustfs_io_metrics::add_ec_encode_inflight_bytes(queued_bytes);
|
||||
let _producer_stage = rustfs_io_metrics::track_ec_encode_producer_bytes(queued_bytes);
|
||||
let send_wait_stage_start = stage_timer_if_enabled();
|
||||
if let Err(err) = tx.send(res).await {
|
||||
rustfs_io_metrics::remove_ec_encode_inflight_bytes(queued_bytes);
|
||||
if let Err(err) = send_queued(&tx, res, queued_bytes).await {
|
||||
return Err(std::io::Error::other(format!("Failed to send encoded data : {err}")));
|
||||
}
|
||||
record_internal_stage_if_enabled("erasure_encode_send_wait", send_wait_stage_start);
|
||||
@@ -626,7 +698,7 @@ impl Erasure {
|
||||
}
|
||||
|
||||
Ok((reader, total))
|
||||
});
|
||||
}));
|
||||
|
||||
let mut writers = MultiWriter::new(writers, quorum);
|
||||
|
||||
@@ -638,11 +710,11 @@ impl Erasure {
|
||||
break;
|
||||
};
|
||||
record_internal_stage_if_enabled("erasure_encode_recv_wait", recv_wait_stage_start);
|
||||
let block = block.into_inner();
|
||||
if block.is_empty() {
|
||||
break;
|
||||
}
|
||||
let queued_bytes = queued_block_bytes(&block);
|
||||
rustfs_io_metrics::remove_ec_encode_inflight_bytes(queued_bytes);
|
||||
let _writer_stage = rustfs_io_metrics::track_ec_encode_writer_bytes(queued_block_bytes(&block));
|
||||
let write_stage_start = stage_timer_if_enabled();
|
||||
if let Err(err) = writers.write(block).await {
|
||||
write_err = Some(err);
|
||||
@@ -652,9 +724,8 @@ impl Erasure {
|
||||
}
|
||||
|
||||
if let Some(err) = write_err {
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
drain_queued_inflight_bytes(&mut rx).await;
|
||||
task.abort_and_wait().await;
|
||||
drop(rx);
|
||||
let shutdown_stage_start = stage_timer_if_enabled();
|
||||
if let Err(shutdown_err) = writers.shutdown().await {
|
||||
error!("failed to shutdown erasure writers after write error: {:?}", shutdown_err);
|
||||
@@ -663,14 +734,14 @@ impl Erasure {
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let (reader, total) = task.await??;
|
||||
let (reader, total) = task.join().await??;
|
||||
let shutdown_stage_start = stage_timer_if_enabled();
|
||||
writers.shutdown().await?;
|
||||
record_internal_stage_if_enabled("erasure_encode_shutdown", shutdown_stage_start);
|
||||
Ok((reader, total))
|
||||
}
|
||||
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub async fn encode_batched<R>(
|
||||
self: Arc<Self>,
|
||||
mut reader: R,
|
||||
@@ -692,14 +763,15 @@ impl Erasure {
|
||||
let inflight_blocks = encode_channel_capacity(expanded_block_bytes, max_inflight_bytes);
|
||||
let batch_blocks = encode_batch_block_count().min(inflight_blocks);
|
||||
let channel_capacity = inflight_blocks.div_ceil(batch_blocks).max(1);
|
||||
let (tx, mut rx) = mpsc::channel::<Vec<Vec<Bytes>>>(channel_capacity);
|
||||
let (tx, mut rx) = mpsc::channel::<InflightEntry<Vec<Vec<Bytes>>>>(channel_capacity);
|
||||
|
||||
let task = tokio::spawn(async move {
|
||||
let mut task = AbortOnDropTask::new(tokio::spawn(async move {
|
||||
let block_size = self.block_size;
|
||||
let mut total = 0;
|
||||
let mut buf = vec![0u8; block_size];
|
||||
let mut pending_batch = Vec::with_capacity(batch_blocks);
|
||||
let mut pending_batch_bytes = 0usize;
|
||||
let mut pending_batch_stage = None;
|
||||
loop {
|
||||
match rustfs_utils::read_full_or_eof(&mut reader, &mut buf).await {
|
||||
Ok(Some(n)) => {
|
||||
@@ -711,15 +783,16 @@ impl Erasure {
|
||||
let queued_bytes = queued_block_bytes(&res);
|
||||
pending_batch_bytes = pending_batch_bytes.saturating_add(queued_bytes);
|
||||
pending_batch.push(res);
|
||||
drop(pending_batch_stage.take());
|
||||
pending_batch_stage = Some(rustfs_io_metrics::track_ec_encode_producer_bytes(pending_batch_bytes));
|
||||
|
||||
if pending_batch.len() >= batch_blocks {
|
||||
rustfs_io_metrics::add_ec_encode_inflight_bytes(pending_batch_bytes);
|
||||
let send_wait_stage_start = stage_timer_if_enabled();
|
||||
if let Err(err) = tx.send(pending_batch).await {
|
||||
rustfs_io_metrics::remove_ec_encode_inflight_bytes(pending_batch_bytes);
|
||||
if let Err(err) = send_queued(&tx, pending_batch, pending_batch_bytes).await {
|
||||
return Err(std::io::Error::other(format!("Failed to send encoded data : {err}")));
|
||||
}
|
||||
record_internal_stage_if_enabled("erasure_encode_batched_send_wait", send_wait_stage_start);
|
||||
drop(pending_batch_stage.take());
|
||||
pending_batch = Vec::with_capacity(batch_blocks);
|
||||
pending_batch_bytes = 0;
|
||||
}
|
||||
@@ -742,17 +815,16 @@ impl Erasure {
|
||||
}
|
||||
|
||||
if !pending_batch.is_empty() {
|
||||
rustfs_io_metrics::add_ec_encode_inflight_bytes(pending_batch_bytes);
|
||||
let send_wait_stage_start = stage_timer_if_enabled();
|
||||
if let Err(err) = tx.send(pending_batch).await {
|
||||
rustfs_io_metrics::remove_ec_encode_inflight_bytes(pending_batch_bytes);
|
||||
if let Err(err) = send_queued(&tx, pending_batch, pending_batch_bytes).await {
|
||||
return Err(std::io::Error::other(format!("Failed to send encoded data : {err}")));
|
||||
}
|
||||
record_internal_stage_if_enabled("erasure_encode_batched_send_wait", send_wait_stage_start);
|
||||
drop(pending_batch_stage);
|
||||
}
|
||||
|
||||
Ok((reader, total))
|
||||
});
|
||||
}));
|
||||
|
||||
let mut writers = MultiWriter::new(writers, quorum);
|
||||
let mut write_err = None;
|
||||
@@ -763,7 +835,8 @@ impl Erasure {
|
||||
break;
|
||||
};
|
||||
record_internal_stage_if_enabled("erasure_encode_batched_recv_wait", recv_wait_stage_start);
|
||||
rustfs_io_metrics::remove_ec_encode_inflight_bytes(queued_batch_bytes(&batch));
|
||||
let batch = batch.into_inner();
|
||||
let _writer_stage = rustfs_io_metrics::track_ec_encode_writer_bytes(queued_batch_bytes(&batch));
|
||||
let write_stage_start = stage_timer_if_enabled();
|
||||
for block in batch {
|
||||
if let Err(err) = writers.write(block).await {
|
||||
@@ -778,9 +851,8 @@ impl Erasure {
|
||||
}
|
||||
|
||||
if let Some(err) = write_err {
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
drain_queued_batched_inflight_bytes(&mut rx).await;
|
||||
task.abort_and_wait().await;
|
||||
drop(rx);
|
||||
let shutdown_stage_start = stage_timer_if_enabled();
|
||||
if let Err(shutdown_err) = writers.shutdown().await {
|
||||
error!("failed to shutdown erasure writers after write error: {:?}", shutdown_err);
|
||||
@@ -789,7 +861,7 @@ impl Erasure {
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let (reader, total) = task.await??;
|
||||
let (reader, total) = task.join().await??;
|
||||
let shutdown_stage_start = stage_timer_if_enabled();
|
||||
writers.shutdown().await?;
|
||||
record_internal_stage_if_enabled("erasure_encode_batched_shutdown", shutdown_stage_start);
|
||||
@@ -798,7 +870,7 @@ impl Erasure {
|
||||
|
||||
/// Fast path for small inline objects: skip tokio::spawn + mpsc channel.
|
||||
/// Reads all data, encodes directly, writes shards sequentially.
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub async fn encode_inline_small<R>(
|
||||
self: Arc<Self>,
|
||||
reader: R,
|
||||
@@ -813,7 +885,7 @@ impl Erasure {
|
||||
|
||||
/// Fast path for single-block non-inline objects: avoids the producer/consumer
|
||||
/// pipeline in `encode()` while keeping the same writer/quorum/shutdown semantics.
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub async fn encode_single_block_non_inline<R>(
|
||||
self: Arc<Self>,
|
||||
reader: R,
|
||||
@@ -839,7 +911,104 @@ mod tests {
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncWrite, AsyncWriteExt};
|
||||
use tokio::io::{AsyncWrite, AsyncWriteExt, ReadBuf};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
struct PendingReader {
|
||||
entered: Option<oneshot::Sender<()>>,
|
||||
dropped: Option<oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
impl PendingReader {
|
||||
fn new() -> (Self, oneshot::Receiver<()>, oneshot::Receiver<()>) {
|
||||
let (entered_tx, entered_rx) = oneshot::channel();
|
||||
let (dropped_tx, dropped_rx) = oneshot::channel();
|
||||
(
|
||||
Self {
|
||||
entered: Some(entered_tx),
|
||||
dropped: Some(dropped_tx),
|
||||
},
|
||||
entered_rx,
|
||||
dropped_rx,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for PendingReader {
|
||||
fn poll_read(mut self: Pin<&mut Self>, _cx: &mut Context<'_>, _buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
if let Some(entered) = self.entered.take() {
|
||||
let _ = entered.send(());
|
||||
}
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PendingReader {
|
||||
fn drop(&mut self) {
|
||||
if let Some(dropped) = self.dropped.take() {
|
||||
let _ = dropped.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BlocksThenPendingReader {
|
||||
blocks_remaining: usize,
|
||||
block: Vec<u8>,
|
||||
blocked: Option<oneshot::Sender<()>>,
|
||||
dropped: Option<oneshot::Sender<()>>,
|
||||
final_block: Option<oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
impl BlocksThenPendingReader {
|
||||
fn new(
|
||||
blocks_remaining: usize,
|
||||
block_size: usize,
|
||||
) -> (Self, oneshot::Receiver<()>, oneshot::Receiver<()>, oneshot::Receiver<()>) {
|
||||
let (blocked_tx, blocked_rx) = oneshot::channel();
|
||||
let (dropped_tx, dropped_rx) = oneshot::channel();
|
||||
let (final_block_tx, final_block_rx) = oneshot::channel();
|
||||
(
|
||||
Self {
|
||||
blocks_remaining,
|
||||
block: vec![0x5a; block_size],
|
||||
blocked: Some(blocked_tx),
|
||||
dropped: Some(dropped_tx),
|
||||
final_block: Some(final_block_tx),
|
||||
},
|
||||
blocked_rx,
|
||||
dropped_rx,
|
||||
final_block_rx,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for BlocksThenPendingReader {
|
||||
fn poll_read(mut self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
if self.blocks_remaining == 0 {
|
||||
if let Some(blocked) = self.blocked.take() {
|
||||
let _ = blocked.send(());
|
||||
}
|
||||
return Poll::Pending;
|
||||
}
|
||||
|
||||
if self.blocks_remaining == 1
|
||||
&& let Some(final_block) = self.final_block.take()
|
||||
{
|
||||
let _ = final_block.send(());
|
||||
}
|
||||
self.blocks_remaining -= 1;
|
||||
buf.put_slice(&self.block);
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BlocksThenPendingReader {
|
||||
fn drop(&mut self) {
|
||||
if let Some(dropped) = self.dropped.take() {
|
||||
let _ = dropped.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn erasure_with_zero_block_size() -> Erasure {
|
||||
let mut erasure = Erasure::default();
|
||||
@@ -897,6 +1066,54 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
struct FailAfterReaderBlocksWriter {
|
||||
reader_blocked: oneshot::Receiver<()>,
|
||||
writes: Arc<std::sync::atomic::AtomicUsize>,
|
||||
}
|
||||
|
||||
impl AsyncWrite for FailAfterReaderBlocksWriter {
|
||||
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, _buf: &[u8]) -> Poll<std::io::Result<usize>> {
|
||||
match Pin::new(&mut self.reader_blocked).poll(cx) {
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(_) => {
|
||||
self.writes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
Poll::Ready(Err(std::io::Error::other("injected write failure after producer blocks")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
struct StallOnWriteWithSignal {
|
||||
entered: Option<oneshot::Sender<()>>,
|
||||
writes: Arc<std::sync::atomic::AtomicUsize>,
|
||||
}
|
||||
|
||||
impl AsyncWrite for StallOnWriteWithSignal {
|
||||
fn poll_write(mut self: Pin<&mut Self>, _cx: &mut Context<'_>, _buf: &[u8]) -> Poll<std::io::Result<usize>> {
|
||||
self.writes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
if let Some(entered) = self.entered.take() {
|
||||
let _ = entered.send(());
|
||||
}
|
||||
Poll::Pending
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct ShortWriteWriter;
|
||||
|
||||
@@ -1046,6 +1263,262 @@ mod tests {
|
||||
BitrotWriterWrapper::new(CustomWriter::new_tokio_writer(writer), shard_size, HashAlgorithm::None)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum EncodePipeline {
|
||||
Vec,
|
||||
BytesMut,
|
||||
Batched,
|
||||
}
|
||||
|
||||
async fn aborting_encode_drops_blocked_producer(pipeline: EncodePipeline) {
|
||||
const BLOCK_SIZE: usize = 16;
|
||||
|
||||
let gauge_baseline = rustfs_io_metrics::current_ec_encode_inflight_bytes();
|
||||
let committed = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut writers = vec![Some(bitrot_writer(DeferredCommitWriter::new(committed.clone()), BLOCK_SIZE))];
|
||||
let (reader, entered, dropped) = PendingReader::new();
|
||||
let erasure = Arc::new(Erasure::new(1, 0, BLOCK_SIZE));
|
||||
|
||||
let encode = match pipeline {
|
||||
EncodePipeline::Vec => {
|
||||
tokio::spawn(async move { erasure.encode_with_ingest_mode(reader, &mut writers, 1, false).await })
|
||||
}
|
||||
EncodePipeline::BytesMut => {
|
||||
tokio::spawn(async move { erasure.encode_with_ingest_mode(reader, &mut writers, 1, true).await })
|
||||
}
|
||||
EncodePipeline::Batched => tokio::spawn(async move { erasure.encode_batched(reader, &mut writers, 1).await }),
|
||||
};
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(1), entered)
|
||||
.await
|
||||
.expect("producer should enter the blocked reader before cancellation")
|
||||
.expect("blocked reader should signal entry");
|
||||
encode.abort();
|
||||
assert!(matches!(encode.await, Err(err) if err.is_cancelled()), "encode task should be cancelled");
|
||||
tokio::time::timeout(Duration::from_secs(1), dropped)
|
||||
.await
|
||||
.expect("cancelling encode should drop the producer reader")
|
||||
.expect("blocked reader should signal producer drop");
|
||||
assert!(
|
||||
committed.lock().expect("committed buffer should be lockable").is_empty(),
|
||||
"cancelling before the first encoded block must not make data visible"
|
||||
);
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_inflight_bytes(),
|
||||
gauge_baseline,
|
||||
"cancelling the encode pipeline must preserve the inflight queue gauge"
|
||||
);
|
||||
}
|
||||
|
||||
async fn writer_error_aborts_blocked_producer(pipeline: EncodePipeline) {
|
||||
let gauge_baseline = rustfs_io_metrics::current_ec_encode_inflight_bytes();
|
||||
let producer_baseline = rustfs_io_metrics::current_ec_encode_producer_bytes();
|
||||
let writer_baseline = rustfs_io_metrics::current_ec_encode_writer_bytes();
|
||||
let producer_peak_before = rustfs_io_metrics::current_ec_encode_producer_bytes_peak();
|
||||
let writer_peak_before = rustfs_io_metrics::current_ec_encode_writer_bytes_peak();
|
||||
let block_size = match pipeline {
|
||||
EncodePipeline::Batched => usize::try_from(producer_peak_before.max(writer_peak_before).saturating_add(1))
|
||||
.expect("stage peak fits the test address space"),
|
||||
EncodePipeline::Vec | EncodePipeline::BytesMut => 16,
|
||||
};
|
||||
rustfs_io_metrics::set_put_stage_metrics_enabled(true);
|
||||
let erasure = Arc::new(Erasure::new(1, 0, block_size));
|
||||
let batch_blocks = encode_batch_block_count().min(encode_channel_capacity(
|
||||
erasure.shard_size().saturating_mul(erasure.total_shard_count()),
|
||||
erasure_encode_max_inflight_bytes(),
|
||||
));
|
||||
let blocks_before_pending = match pipeline {
|
||||
EncodePipeline::Batched => batch_blocks,
|
||||
EncodePipeline::Vec | EncodePipeline::BytesMut => 1,
|
||||
};
|
||||
let (reader, reader_blocked, reader_dropped, _final_block) =
|
||||
BlocksThenPendingReader::new(blocks_before_pending, block_size);
|
||||
let writes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let mut writers = vec![Some(bitrot_writer(
|
||||
FailAfterReaderBlocksWriter {
|
||||
reader_blocked,
|
||||
writes: writes.clone(),
|
||||
},
|
||||
block_size,
|
||||
))];
|
||||
|
||||
let result = match pipeline {
|
||||
EncodePipeline::Vec => erasure.encode_with_ingest_mode(reader, &mut writers, 1, false).await,
|
||||
EncodePipeline::BytesMut => erasure.encode_with_ingest_mode(reader, &mut writers, 1, true).await,
|
||||
EncodePipeline::Batched => erasure.encode_batched(reader, &mut writers, 1).await,
|
||||
};
|
||||
|
||||
let err = match result {
|
||||
Ok(_) => panic!("writer quorum failure should fail the encode pipeline"),
|
||||
Err(err) => err,
|
||||
};
|
||||
assert!(err.to_string().contains("Failed to write data"));
|
||||
tokio::time::timeout(Duration::from_secs(1), reader_dropped)
|
||||
.await
|
||||
.expect("writer failure should abort the blocked producer")
|
||||
.expect("blocked producer should signal reader drop");
|
||||
assert_eq!(
|
||||
writes.load(std::sync::atomic::Ordering::SeqCst),
|
||||
1,
|
||||
"writer failure must stop the pipeline before any additional shard write"
|
||||
);
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_inflight_bytes(),
|
||||
gauge_baseline,
|
||||
"writer failure must settle all queued and pending encoded bytes"
|
||||
);
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_producer_bytes(),
|
||||
producer_baseline,
|
||||
"writer failure must settle producer stage bytes for every ingest pipeline"
|
||||
);
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_writer_bytes(),
|
||||
writer_baseline,
|
||||
"writer failure must settle writer stage bytes for every ingest pipeline"
|
||||
);
|
||||
if matches!(pipeline, EncodePipeline::Batched) {
|
||||
let expected_batch_bytes = u64::try_from(block_size)
|
||||
.expect("block size fits the stage gauge")
|
||||
.checked_mul(u64::try_from(batch_blocks).expect("batch block count fits the stage gauge"))
|
||||
.expect("test batch payload fits the stage gauge");
|
||||
assert!(
|
||||
rustfs_io_metrics::current_ec_encode_producer_bytes_peak() >= producer_peak_before.max(expected_batch_bytes),
|
||||
"batched producer must expose its full pending batch before writer failure"
|
||||
);
|
||||
assert!(
|
||||
rustfs_io_metrics::current_ec_encode_writer_bytes_peak() >= writer_peak_before.max(expected_batch_bytes),
|
||||
"batched writer must expose its full batch before writer failure"
|
||||
);
|
||||
}
|
||||
rustfs_io_metrics::set_put_stage_metrics_enabled(false);
|
||||
}
|
||||
|
||||
async fn aborting_full_queue_settles_pending_send() {
|
||||
const BLOCK_SIZE: usize = 16;
|
||||
|
||||
let gauge_baseline = rustfs_io_metrics::current_ec_encode_inflight_bytes();
|
||||
let producer_baseline = rustfs_io_metrics::current_ec_encode_producer_bytes();
|
||||
let writer_baseline = rustfs_io_metrics::current_ec_encode_writer_bytes();
|
||||
rustfs_io_metrics::set_put_stage_metrics_enabled(true);
|
||||
let erasure = Arc::new(Erasure::new(1, 0, BLOCK_SIZE));
|
||||
let inflight_blocks = encode_channel_capacity(
|
||||
erasure.shard_size().saturating_mul(erasure.total_shard_count()),
|
||||
erasure_encode_max_inflight_bytes(),
|
||||
);
|
||||
let (reader, _reader_blocked, reader_dropped, final_block) =
|
||||
BlocksThenPendingReader::new(inflight_blocks + 2, BLOCK_SIZE);
|
||||
let (writer_entered_tx, writer_entered) = oneshot::channel();
|
||||
let writes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let mut writers = vec![Some(bitrot_writer(
|
||||
StallOnWriteWithSignal {
|
||||
entered: Some(writer_entered_tx),
|
||||
writes: writes.clone(),
|
||||
},
|
||||
BLOCK_SIZE,
|
||||
))];
|
||||
let erasure_for_task = erasure.clone();
|
||||
let encode = tokio::spawn(async move { erasure_for_task.encode_with_ingest_mode(reader, &mut writers, 1, false).await });
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(1), writer_entered)
|
||||
.await
|
||||
.expect("consumer should start the first writer call")
|
||||
.expect("stalling writer should signal entry");
|
||||
tokio::time::timeout(Duration::from_secs(1), final_block)
|
||||
.await
|
||||
.expect("producer should supply the block whose send fills the queue")
|
||||
.expect("reader should signal final block");
|
||||
|
||||
let expected_queued_bytes =
|
||||
u64::try_from((inflight_blocks + 1) * BLOCK_SIZE).expect("queued byte count should fit the gauge");
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while rustfs_io_metrics::current_ec_encode_inflight_bytes() < gauge_baseline + expected_queued_bytes {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("producer should account for the pending send after the queue fills");
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while rustfs_io_metrics::current_ec_encode_producer_bytes() == producer_baseline
|
||||
|| rustfs_io_metrics::current_ec_encode_writer_bytes() == writer_baseline
|
||||
{
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("full queue must retain producer and writer stage ownership before cancellation");
|
||||
|
||||
encode.abort();
|
||||
assert!(matches!(encode.await, Err(err) if err.is_cancelled()), "encode task should be cancelled");
|
||||
tokio::time::timeout(Duration::from_secs(1), reader_dropped)
|
||||
.await
|
||||
.expect("cancelling a full queue should abort its producer")
|
||||
.expect("full-queue producer should signal reader drop");
|
||||
assert_eq!(
|
||||
writes.load(std::sync::atomic::Ordering::SeqCst),
|
||||
1,
|
||||
"cancellation must not resume the stalled writer"
|
||||
);
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_inflight_bytes(),
|
||||
gauge_baseline,
|
||||
"cancelling a full queue must settle queued and pending bytes"
|
||||
);
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_producer_bytes(),
|
||||
producer_baseline,
|
||||
"cancelling a full queue must settle the pending producer stage"
|
||||
);
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_writer_bytes(),
|
||||
writer_baseline,
|
||||
"cancelling a full queue must settle the stalled writer stage"
|
||||
);
|
||||
rustfs_io_metrics::set_put_stage_metrics_enabled(false);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn cancelling_vec_encode_drops_blocked_producer() {
|
||||
aborting_encode_drops_blocked_producer(EncodePipeline::Vec).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn cancelling_bytesmut_encode_drops_blocked_producer() {
|
||||
aborting_encode_drops_blocked_producer(EncodePipeline::BytesMut).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn cancelling_batched_encode_drops_blocked_producer() {
|
||||
aborting_encode_drops_blocked_producer(EncodePipeline::Batched).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn vec_writer_error_aborts_blocked_producer() {
|
||||
writer_error_aborts_blocked_producer(EncodePipeline::Vec).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn bytesmut_writer_error_aborts_blocked_producer() {
|
||||
writer_error_aborts_blocked_producer(EncodePipeline::BytesMut).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn batched_writer_error_aborts_blocked_producer() {
|
||||
writer_error_aborts_blocked_producer(EncodePipeline::Batched).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn cancelling_full_queue_settles_pending_send() {
|
||||
aborting_full_queue_settles_pending_send().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn helper_writers_cover_flush_and_shutdown_paths() {
|
||||
let mut failing_write = FailingWriteWriter;
|
||||
@@ -1329,25 +1802,99 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn drain_queued_inflight_bytes_consumes_pending_blocks() {
|
||||
let (tx, mut rx) = mpsc::channel(2);
|
||||
tx.send(vec![Bytes::from_static(b"queued")]).await.unwrap();
|
||||
drop(tx);
|
||||
#[serial_test::serial]
|
||||
async fn queued_inflight_bytes_are_settled_on_all_queue_exit_paths() {
|
||||
let baseline = rustfs_io_metrics::current_ec_encode_inflight_bytes();
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
let queued = vec![Bytes::from_static(b"queued")];
|
||||
let queued_bytes = queued_block_bytes(&queued);
|
||||
|
||||
drain_queued_inflight_bytes(&mut rx).await;
|
||||
send_queued(&tx, queued, queued_bytes)
|
||||
.await
|
||||
.expect("first queue entry should fit");
|
||||
|
||||
assert!(rx.recv().await.is_none());
|
||||
let blocked = vec![Bytes::from_static(b"blocked")];
|
||||
let blocked_bytes = queued_block_bytes(&blocked);
|
||||
{
|
||||
let pending_send = send_queued(&tx, blocked, blocked_bytes);
|
||||
tokio::pin!(pending_send);
|
||||
assert!(
|
||||
futures::poll!(pending_send.as_mut()).is_pending(),
|
||||
"full queue must suspend producer send"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_inflight_bytes(),
|
||||
baseline + u64::try_from(queued_bytes).expect("queue bytes fit the gauge"),
|
||||
"dropping a pending producer send must compensate its bytes"
|
||||
);
|
||||
|
||||
drop(rx);
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_inflight_bytes(),
|
||||
baseline,
|
||||
"dropping the receiver must settle every buffered entry"
|
||||
);
|
||||
|
||||
let rejected = vec![Bytes::from_static(b"rejected")];
|
||||
let rejected_bytes = queued_block_bytes(&rejected);
|
||||
assert!(
|
||||
send_queued(&tx, rejected, rejected_bytes).await.is_err(),
|
||||
"closed receiver must reject a new send"
|
||||
);
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_inflight_bytes(),
|
||||
baseline,
|
||||
"failed sends must compensate their bytes"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn drain_queued_batched_inflight_bytes_consumes_pending_batches() {
|
||||
let (tx, mut rx) = mpsc::channel(2);
|
||||
tx.send(vec![vec![Bytes::from_static(b"queued")]]).await.unwrap();
|
||||
drop(tx);
|
||||
#[serial_test::serial]
|
||||
async fn queued_batch_entry_settles_bytes_before_handoff() {
|
||||
let baseline = rustfs_io_metrics::current_ec_encode_inflight_bytes();
|
||||
let (tx, rx) = mpsc::channel(2);
|
||||
let mut rx = rx;
|
||||
let batch = vec![vec![Bytes::from_static(b"queued")], vec![Bytes::from_static(b"batch")]];
|
||||
let batch_bytes = queued_batch_bytes(&batch);
|
||||
|
||||
drain_queued_batched_inflight_bytes(&mut rx).await;
|
||||
send_queued(&tx, batch, batch_bytes).await.expect("batch should be queued");
|
||||
let batch = rx.recv().await.expect("queued batch should be received").into_inner();
|
||||
assert_eq!(batch_bytes, queued_batch_bytes(&batch));
|
||||
|
||||
assert!(rx.recv().await.is_none());
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_inflight_bytes(),
|
||||
baseline,
|
||||
"receiving a batch must settle all contained block bytes before shard writes"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn queued_entry_settles_when_a_closed_receiver_accepts_an_outstanding_permit() {
|
||||
let baseline = rustfs_io_metrics::current_ec_encode_inflight_bytes();
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
let permit = tx
|
||||
.clone()
|
||||
.reserve_owned()
|
||||
.await
|
||||
.expect("open receiver should reserve queue capacity");
|
||||
rx.close();
|
||||
assert!(
|
||||
matches!(rx.try_recv(), Err(mpsc::error::TryRecvError::Empty)),
|
||||
"an outstanding permit must leave the closed queue observably empty"
|
||||
);
|
||||
|
||||
let block = vec![Bytes::from_static(b"late-permit")];
|
||||
let block_bytes = queued_block_bytes(&block);
|
||||
permit.send(InflightEntry::new(block, block_bytes));
|
||||
drop(rx);
|
||||
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_inflight_bytes(),
|
||||
baseline,
|
||||
"a queue entry sent through an outstanding permit must settle when Tokio drops it"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1394,6 +1941,61 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn bytesmut_streaming_encode_observes_all_payload_stage_peaks() {
|
||||
let queue_baseline = rustfs_io_metrics::current_ec_encode_inflight_bytes();
|
||||
let producer_peak_before = rustfs_io_metrics::current_ec_encode_producer_bytes_peak();
|
||||
let queue_peak_before = rustfs_io_metrics::current_ec_encode_queue_bytes_peak();
|
||||
let writer_peak_before = rustfs_io_metrics::current_ec_encode_writer_bytes_peak();
|
||||
let prior_peak = producer_peak_before.max(queue_peak_before).max(writer_peak_before);
|
||||
let block_size = usize::try_from(prior_peak.saturating_add(1)).expect("stage peak fits the test address space");
|
||||
let erasure = Arc::new(Erasure::new(1, 0, block_size));
|
||||
let encoded_block_bytes = erasure.shard_size() * erasure.total_shard_count();
|
||||
let committed = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut writers = vec![Some(bitrot_writer(DeferredCommitWriter::new(committed.clone()), block_size))];
|
||||
let reader = tokio::io::BufReader::new(Cursor::new(vec![0x5a; block_size * 2]));
|
||||
|
||||
rustfs_io_metrics::set_put_stage_metrics_enabled(true);
|
||||
let result = erasure.encode_with_ingest_mode(reader, &mut writers, 1, true).await;
|
||||
rustfs_io_metrics::set_put_stage_metrics_enabled(false);
|
||||
|
||||
let (_reader, written) = result.expect("bytesmut streaming encode should complete");
|
||||
assert_eq!(written, block_size * 2);
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_inflight_bytes(),
|
||||
queue_baseline,
|
||||
"completed streaming encode must not retain queue bytes"
|
||||
);
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_producer_bytes(),
|
||||
0,
|
||||
"completed streaming encode must not retain producer bytes"
|
||||
);
|
||||
assert_eq!(
|
||||
rustfs_io_metrics::current_ec_encode_writer_bytes(),
|
||||
0,
|
||||
"completed streaming encode must not retain writer bytes"
|
||||
);
|
||||
let expected_peak = u64::try_from(encoded_block_bytes).expect("encoded block bytes fit the gauge");
|
||||
assert!(
|
||||
rustfs_io_metrics::current_ec_encode_producer_bytes_peak() >= producer_peak_before.max(expected_peak),
|
||||
"producer peak must observe encoded bytes before queue hand-off"
|
||||
);
|
||||
assert!(
|
||||
rustfs_io_metrics::current_ec_encode_queue_bytes_peak() >= queue_peak_before.max(expected_peak),
|
||||
"queue peak must observe encoded bytes pending shard writers"
|
||||
);
|
||||
assert!(
|
||||
rustfs_io_metrics::current_ec_encode_writer_bytes_peak() >= writer_peak_before.max(expected_peak),
|
||||
"writer peak must observe encoded bytes after queue hand-off"
|
||||
);
|
||||
assert!(
|
||||
!committed.lock().expect("committed buffer should be lockable").is_empty(),
|
||||
"stage peak observation must not change writer commit behavior"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn encode_streaming_write_quorum_failure_aborts_and_reports_error() {
|
||||
const DATA_SHARDS: usize = 2;
|
||||
|
||||
@@ -640,7 +640,7 @@ impl Erasure {
|
||||
/// # Returns
|
||||
/// A vector of encoded shards as `Bytes`.
|
||||
#[tracing::instrument(level = "debug", skip_all, fields(data_len=data.len()))]
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub fn encode_data(&self, data: &[u8]) -> io::Result<Vec<Bytes>> {
|
||||
let shard_size_fn = if self.uses_legacy {
|
||||
calc_shard_size_legacy
|
||||
@@ -688,7 +688,7 @@ impl Erasure {
|
||||
|
||||
/// Encode owned data, avoiding a copy when the caller already has a heap buffer.
|
||||
/// Falls back to copying into a new buffer if zero-copy conversion fails.
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub fn encode_data_owned(&self, data: Vec<u8>) -> io::Result<Vec<Bytes>> {
|
||||
let shard_size_fn = if self.uses_legacy {
|
||||
calc_shard_size_legacy
|
||||
@@ -752,7 +752,7 @@ impl Erasure {
|
||||
/// block), the `resize(need_total_size)` below stays within capacity for every
|
||||
/// `data_len <= block_size` — both shard-size formulas are monotone in
|
||||
/// `data_len` — so this function never reallocates the buffer.
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub fn encode_data_bytes_mut(&self, mut data_buffer: BytesMut, data_len: usize) -> io::Result<Vec<Bytes>> {
|
||||
let shard_size_fn = if self.uses_legacy {
|
||||
calc_shard_size_legacy
|
||||
@@ -805,7 +805,7 @@ impl Erasure {
|
||||
///
|
||||
/// # Returns
|
||||
/// Ok if reconstruction succeeds, error otherwise.
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub fn decode_data(&self, shards: &mut [Option<Vec<u8>>]) -> io::Result<()> {
|
||||
if self.parity_shards > 0 {
|
||||
if self.uses_legacy {
|
||||
@@ -825,7 +825,7 @@ impl Erasure {
|
||||
}
|
||||
|
||||
/// Decode and reconstruct missing data shards, then regenerate parity shards.
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub fn decode_data_and_parity(&self, shards: &mut [Option<Vec<u8>>]) -> io::Result<()> {
|
||||
if self.parity_shards > 0 {
|
||||
if self.uses_legacy {
|
||||
|
||||
@@ -19,6 +19,8 @@ use crate::diagnostics::get::{
|
||||
GET_STAGE_READER_MMAP_PATH_RESOLVE, GET_STAGE_READER_OPEN_MMAP_COPY_FALLBACK, GET_STAGE_READER_OPEN_MMAP_COPY_SUCCESS,
|
||||
GET_STAGE_READER_OPEN_STREAM, GET_STAGE_READER_STREAM_FIRST_READ, record_get_stage_duration_if_enabled,
|
||||
};
|
||||
#[cfg(feature = "hotpath")]
|
||||
use crate::disk::FileWriter;
|
||||
use crate::disk::{self, DiskAPI as _, DiskStore, FileReader, MmapCopyStageMetrics, error::DiskError};
|
||||
use crate::erasure::coding::{BitrotReader, BitrotWriterWrapper, CustomWriter};
|
||||
use bytes::Bytes;
|
||||
@@ -36,6 +38,11 @@ use std::time::Instant;
|
||||
use tokio::io::{AsyncRead, ReadBuf};
|
||||
use tracing::debug;
|
||||
|
||||
#[cfg(all(test, feature = "hotpath"))]
|
||||
tokio::task_local! {
|
||||
static FORCE_MMAP_COPY_FAILURE_FOR_TEST: ();
|
||||
}
|
||||
|
||||
/// A shard source for the bitrot reader.
|
||||
///
|
||||
/// `InMemory` keeps the `Bytes` concrete instead of erasing it behind
|
||||
@@ -360,10 +367,21 @@ async fn open_disk_reader(
|
||||
mmap_copy_stage: GET_STAGE_READER_MMAP_COPY_BUFFER,
|
||||
direct_read_copy_stage: GET_STAGE_READER_MMAP_DIRECT_READ_COPY,
|
||||
});
|
||||
match disk
|
||||
.read_file_mmap_copy_with_metrics(bucket, path, offset, length, mmap_metrics)
|
||||
.await
|
||||
{
|
||||
let mmap_result = {
|
||||
#[cfg(all(test, feature = "hotpath"))]
|
||||
if FORCE_MMAP_COPY_FAILURE_FOR_TEST.try_with(|_| ()).is_ok() {
|
||||
Err(DiskError::other("forced mmap-copy failure for test"))
|
||||
} else {
|
||||
disk.read_file_mmap_copy_with_metrics(bucket, path, offset, length, mmap_metrics)
|
||||
.await
|
||||
}
|
||||
#[cfg(not(all(test, feature = "hotpath")))]
|
||||
{
|
||||
disk.read_file_mmap_copy_with_metrics(bucket, path, offset, length, mmap_metrics)
|
||||
.await
|
||||
}
|
||||
};
|
||||
match mmap_result {
|
||||
Ok(bytes) => {
|
||||
let duration_ms = zero_copy_start.elapsed().as_secs_f64() * 1000.0;
|
||||
|
||||
@@ -398,7 +416,11 @@ async fn open_disk_reader(
|
||||
}
|
||||
|
||||
return match stream_result {
|
||||
Ok(reader) => Ok(wrap_first_read_metrics(reader, metrics_path)),
|
||||
Ok(reader) => {
|
||||
#[cfg(feature = "hotpath")]
|
||||
let reader = instrument_raw_shard_reader(reader, disk.is_local());
|
||||
Ok(wrap_first_read_metrics(reader, metrics_path))
|
||||
}
|
||||
Err(_) => Err(err),
|
||||
};
|
||||
}
|
||||
@@ -407,6 +429,8 @@ async fn open_disk_reader(
|
||||
|
||||
let stream_start = stage_metrics_enabled.then(Instant::now);
|
||||
let reader = disk.read_file_stream(bucket, path, offset, length).await?;
|
||||
#[cfg(feature = "hotpath")]
|
||||
let reader = instrument_raw_shard_reader(reader, disk.is_local());
|
||||
if let Some(metrics_path) = metrics_path {
|
||||
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READER_OPEN_STREAM, stream_start);
|
||||
}
|
||||
@@ -427,6 +451,37 @@ fn wrap_first_read_metrics(reader: FileReader, metrics_path: Option<&'static str
|
||||
ShardReader::Stream(reader)
|
||||
}
|
||||
|
||||
// The labels are deliberately fixed: object keys, disk paths, and remote hosts
|
||||
// are all high-cardinality or sensitive and belong nowhere in a profiling report.
|
||||
#[cfg(feature = "hotpath")]
|
||||
const RAW_SHARD_READ_LOCAL_LABEL: &str = "EC raw shard read local";
|
||||
#[cfg(feature = "hotpath")]
|
||||
const RAW_SHARD_READ_REMOTE_LABEL: &str = "EC raw shard read remote";
|
||||
#[cfg(feature = "hotpath")]
|
||||
const RAW_SHARD_WRITE_LOCAL_LABEL: &str = "EC raw shard write local";
|
||||
#[cfg(feature = "hotpath")]
|
||||
const RAW_SHARD_WRITE_REMOTE_LABEL: &str = "EC raw shard write remote";
|
||||
|
||||
#[cfg(feature = "hotpath")]
|
||||
fn instrument_raw_shard_reader(reader: FileReader, is_local: bool) -> FileReader {
|
||||
// `io!` aggregates by call site, so the local and remote branches must remain distinct.
|
||||
if is_local {
|
||||
Box::new(hotpath::io!(reader, label = RAW_SHARD_READ_LOCAL_LABEL))
|
||||
} else {
|
||||
Box::new(hotpath::io!(reader, label = RAW_SHARD_READ_REMOTE_LABEL))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "hotpath")]
|
||||
fn instrument_raw_shard_writer(writer: FileWriter, is_local: bool) -> FileWriter {
|
||||
// `io!` aggregates by call site, so the local and remote branches must remain distinct.
|
||||
if is_local {
|
||||
Box::new(hotpath::io!(writer, label = RAW_SHARD_WRITE_LOCAL_LABEL))
|
||||
} else {
|
||||
Box::new(hotpath::io!(writer, label = RAW_SHARD_WRITE_REMOTE_LABEL))
|
||||
}
|
||||
}
|
||||
|
||||
fn bitrot_encoded_range(offset: usize, length: usize, shard_size: usize, checksum_algo: HashAlgorithm) -> (usize, usize) {
|
||||
(
|
||||
offset.div_ceil(shard_size) * checksum_algo.size() + offset,
|
||||
@@ -686,6 +741,8 @@ pub async fn create_bitrot_writer(
|
||||
};
|
||||
|
||||
let file = disk.create_file("", volume, path, length).await?;
|
||||
#[cfg(feature = "hotpath")]
|
||||
let file = instrument_raw_shard_writer(file, disk.is_local());
|
||||
CustomWriter::new_tokio_writer(file)
|
||||
} else {
|
||||
return Err(DiskError::DiskNotFound);
|
||||
@@ -698,6 +755,194 @@ pub async fn create_bitrot_writer(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(feature = "hotpath")]
|
||||
use crate::cluster::rpc::RemoteDisk;
|
||||
#[cfg(feature = "hotpath")]
|
||||
use crate::cluster::rpc::internode_data_transport::{
|
||||
InternodeDataTransport, InternodeDataTransportCapabilities, ReadStreamRequest, WalkDirStreamRequest, WriteStreamRequest,
|
||||
};
|
||||
#[cfg(feature = "hotpath")]
|
||||
use crate::disk::{Disk, DiskOption, error::Result};
|
||||
|
||||
#[cfg(feature = "hotpath")]
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct TestRemoteDataTransport {
|
||||
bytes: Arc<Mutex<Vec<u8>>>,
|
||||
write_error: Option<io::ErrorKind>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "hotpath")]
|
||||
impl TestRemoteDataTransport {
|
||||
fn with_write_error(kind: io::ErrorKind) -> Self {
|
||||
Self {
|
||||
bytes: Arc::default(),
|
||||
write_error: Some(kind),
|
||||
}
|
||||
}
|
||||
|
||||
fn bytes(&self) -> Vec<u8> {
|
||||
self.bytes
|
||||
.lock()
|
||||
.expect("test remote transport bytes lock should not be poisoned")
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "hotpath")]
|
||||
#[derive(Debug)]
|
||||
struct TestRemoteWriter {
|
||||
bytes: Arc<Mutex<Vec<u8>>>,
|
||||
write_error: Option<io::ErrorKind>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "hotpath")]
|
||||
impl tokio::io::AsyncWrite for TestRemoteWriter {
|
||||
fn poll_write(self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
|
||||
if let Some(kind) = self.write_error {
|
||||
return Poll::Ready(Err(io::Error::from(kind)));
|
||||
}
|
||||
self.bytes
|
||||
.lock()
|
||||
.expect("test remote transport bytes lock should not be poisoned")
|
||||
.extend_from_slice(buf);
|
||||
Poll::Ready(Ok(buf.len()))
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "hotpath")]
|
||||
#[async_trait::async_trait]
|
||||
impl InternodeDataTransport for TestRemoteDataTransport {
|
||||
async fn open_read(&self, _request: ReadStreamRequest) -> Result<FileReader> {
|
||||
Ok(Box::new(Cursor::new(self.bytes())))
|
||||
}
|
||||
|
||||
async fn open_write(&self, _request: WriteStreamRequest) -> Result<FileWriter> {
|
||||
Ok(Box::new(TestRemoteWriter {
|
||||
bytes: Arc::clone(&self.bytes),
|
||||
write_error: self.write_error,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn open_walk_dir(&self, _request: WalkDirStreamRequest) -> Result<FileReader> {
|
||||
panic!("open_walk_dir must not be used by the raw shard I/O test")
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"bitrot-test-remote"
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> InternodeDataTransportCapabilities {
|
||||
InternodeDataTransportCapabilities::tcp_http()
|
||||
}
|
||||
}
|
||||
|
||||
async fn local_test_disk() -> (DiskStore, tempfile::TempDir) {
|
||||
use crate::disk::endpoint::Endpoint;
|
||||
use crate::disk::{DiskOption, new_disk};
|
||||
|
||||
let dir = tempfile::tempdir().expect("tempdir should be created");
|
||||
let mut endpoint =
|
||||
Endpoint::try_from(dir.path().to_str().expect("tempdir path should be utf8")).expect("endpoint should parse");
|
||||
endpoint.set_pool_index(0);
|
||||
endpoint.set_set_index(0);
|
||||
endpoint.set_disk_index(0);
|
||||
let disk = new_disk(
|
||||
&endpoint,
|
||||
&DiskOption {
|
||||
cleanup: false,
|
||||
health_check: false,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("local disk should be created");
|
||||
|
||||
(disk, dir)
|
||||
}
|
||||
|
||||
#[cfg(feature = "hotpath")]
|
||||
async fn remote_test_disk(transport: TestRemoteDataTransport) -> (DiskStore, TestRemoteDataTransport) {
|
||||
use crate::disk::endpoint::Endpoint;
|
||||
|
||||
let endpoint = Endpoint {
|
||||
url: url::Url::parse("http://remote-node:9000/data/rustfs0").expect("test remote endpoint should parse"),
|
||||
is_local: false,
|
||||
pool_idx: 0,
|
||||
set_idx: 0,
|
||||
disk_idx: 0,
|
||||
};
|
||||
let remote = RemoteDisk::new(
|
||||
&endpoint,
|
||||
&DiskOption {
|
||||
cleanup: false,
|
||||
health_check: false,
|
||||
},
|
||||
Arc::new(transport.clone()),
|
||||
)
|
||||
.await
|
||||
.expect("test remote disk should be created");
|
||||
|
||||
(Arc::new(Disk::Remote(Box::new(remote))), transport)
|
||||
}
|
||||
|
||||
async fn round_trip_disk_bitrot(disk: &DiskStore, bucket: &str, path: &str, payload: &[u8], shard_size: usize) -> Vec<u8> {
|
||||
disk.make_volume(bucket).await.expect("volume should be created");
|
||||
let mut writer = create_bitrot_writer(
|
||||
false,
|
||||
Some(disk),
|
||||
bucket,
|
||||
path,
|
||||
i64::try_from(payload.len()).expect("test payload length should fit i64"),
|
||||
shard_size,
|
||||
HashAlgorithm::None,
|
||||
)
|
||||
.await
|
||||
.expect("disk bitrot writer should open the raw shard file");
|
||||
for chunk in payload.chunks(shard_size) {
|
||||
writer
|
||||
.write(chunk)
|
||||
.await
|
||||
.expect("disk bitrot writer should preserve each shard block");
|
||||
}
|
||||
writer.shutdown().await.expect("disk bitrot writer should close cleanly");
|
||||
|
||||
let mut reader = create_bitrot_reader(
|
||||
None,
|
||||
Some(disk),
|
||||
bucket,
|
||||
path,
|
||||
0,
|
||||
payload.len(),
|
||||
shard_size,
|
||||
HashAlgorithm::None,
|
||||
false,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.expect("disk bitrot reader should open the raw shard file")
|
||||
.expect("disk bitrot reader should exist");
|
||||
let mut actual = Vec::with_capacity(payload.len());
|
||||
while actual.len() < payload.len() {
|
||||
let remaining = payload.len() - actual.len();
|
||||
let mut chunk = vec![0; remaining.min(shard_size)];
|
||||
let read = reader
|
||||
.read(&mut chunk)
|
||||
.await
|
||||
.expect("disk bitrot reader should return the complete shard body");
|
||||
assert!(read > 0, "disk bitrot reader must not end before the expected shard body is complete");
|
||||
actual.extend_from_slice(&chunk[..read]);
|
||||
}
|
||||
|
||||
actual
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_mmap_read_enabled_accepts_legacy_zero_copy_alias() {
|
||||
temp_env::with_vars(
|
||||
@@ -724,6 +969,214 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "hotpath")]
|
||||
#[test]
|
||||
fn raw_shard_io_wrappers_report_fixed_labels_and_preserve_bytes() {
|
||||
const CHILD_ENV: &str = "RUSTFS_HOTPATH_RAW_SHARD_IO_TEST_CHILD";
|
||||
if std::env::var_os(CHILD_ENV).is_none() {
|
||||
let status = std::process::Command::new(std::env::current_exe().expect("test executable path should be available"))
|
||||
.arg("--exact")
|
||||
.arg("io_support::bitrot::tests::raw_shard_io_wrappers_report_fixed_labels_and_preserve_bytes")
|
||||
.arg("--nocapture")
|
||||
.env(CHILD_ENV, "1")
|
||||
.status()
|
||||
.expect("isolated HotPath I/O test process should start");
|
||||
assert!(status.success(), "isolated HotPath I/O test process should pass");
|
||||
return;
|
||||
}
|
||||
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("test runtime should be created")
|
||||
.block_on(raw_shard_io_wrappers_report_fixed_labels_and_preserve_bytes_in_isolated_process());
|
||||
}
|
||||
|
||||
#[cfg(feature = "hotpath")]
|
||||
async fn raw_shard_io_wrappers_report_fixed_labels_and_preserve_bytes_in_isolated_process() {
|
||||
use hotpath::{Format, HotpathGuardBuilder, Section};
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
let report_dir = tempfile::tempdir().expect("report tempdir should be created");
|
||||
let report_path = report_dir.path().join("hotpath-io.json");
|
||||
let guard = HotpathGuardBuilder::new("raw_shard_io_test")
|
||||
.format(Format::Json)
|
||||
.output_path(&report_path)
|
||||
.sections(vec![Section::Io])
|
||||
.build();
|
||||
|
||||
let (disk, _dir) = local_test_disk().await;
|
||||
let bucket = "test-bucket";
|
||||
let path = "obj/hotpath-part.1";
|
||||
let payload = b"local shard bytes";
|
||||
let shard_size = 4;
|
||||
let local_read = round_trip_disk_bitrot(&disk, bucket, path, payload, shard_size).await;
|
||||
assert_eq!(local_read, payload, "local raw shard I/O instrumentation must not alter stored bytes");
|
||||
|
||||
let fallback_path = "obj/hotpath-mmap-fallback-part.1";
|
||||
let fallback_payload = b"mmap fallback shard bytes";
|
||||
disk.write_all("test-bucket", fallback_path, Bytes::from_static(fallback_payload))
|
||||
.await
|
||||
.expect("fallback shard file should be written");
|
||||
let mut fallback_reader = FORCE_MMAP_COPY_FAILURE_FOR_TEST
|
||||
.scope((), open_disk_reader(&disk, bucket, fallback_path, 0, fallback_payload.len(), true, None))
|
||||
.await
|
||||
.expect("mmap-copy failure should fall back to a raw shard stream");
|
||||
assert!(
|
||||
matches!(fallback_reader, ShardReader::Stream(_)),
|
||||
"forced mmap-copy failure must use the streaming fallback"
|
||||
);
|
||||
let mut fallback_read = Vec::new();
|
||||
fallback_reader
|
||||
.read_to_end(&mut fallback_read)
|
||||
.await
|
||||
.expect("mmap-copy fallback stream should preserve bytes");
|
||||
assert_eq!(fallback_read, fallback_payload);
|
||||
|
||||
let (remote_disk, remote_transport) = remote_test_disk(TestRemoteDataTransport::default()).await;
|
||||
let remote_payload = b"remote shard bytes";
|
||||
let mut remote_writer = create_bitrot_writer(
|
||||
false,
|
||||
Some(&remote_disk),
|
||||
bucket,
|
||||
"obj/hotpath-remote-part.1",
|
||||
i64::try_from(remote_payload.len()).expect("remote payload length should fit i64"),
|
||||
shard_size,
|
||||
HashAlgorithm::None,
|
||||
)
|
||||
.await
|
||||
.expect("remote bitrot writer should use the production raw writer path");
|
||||
for chunk in remote_payload.chunks(shard_size) {
|
||||
remote_writer
|
||||
.write(chunk)
|
||||
.await
|
||||
.expect("remote bitrot writer should preserve bytes");
|
||||
}
|
||||
remote_writer
|
||||
.shutdown()
|
||||
.await
|
||||
.expect("remote bitrot writer should close cleanly");
|
||||
assert_eq!(remote_transport.bytes(), remote_payload);
|
||||
|
||||
let mut reader = create_bitrot_reader(
|
||||
None,
|
||||
Some(&remote_disk),
|
||||
bucket,
|
||||
"obj/hotpath-remote-part.1",
|
||||
0,
|
||||
remote_payload.len(),
|
||||
shard_size,
|
||||
HashAlgorithm::None,
|
||||
false,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.expect("remote bitrot reader should use the production raw reader path")
|
||||
.expect("remote bitrot reader should exist");
|
||||
let mut remote_read = Vec::with_capacity(remote_payload.len());
|
||||
while remote_read.len() < remote_payload.len() {
|
||||
let remaining = remote_payload.len() - remote_read.len();
|
||||
let mut chunk = vec![0; remaining.min(shard_size)];
|
||||
let read = reader
|
||||
.read(&mut chunk)
|
||||
.await
|
||||
.expect("remote bitrot reader should preserve bytes");
|
||||
assert!(read > 0, "remote bitrot reader must not end before the expected shard body is complete");
|
||||
remote_read.extend_from_slice(&chunk[..read]);
|
||||
}
|
||||
assert_eq!(remote_read, remote_payload);
|
||||
|
||||
let (failing_remote_disk, _) = remote_test_disk(TestRemoteDataTransport::with_write_error(io::ErrorKind::Other)).await;
|
||||
let mut failing_writer = create_bitrot_writer(
|
||||
false,
|
||||
Some(&failing_remote_disk),
|
||||
bucket,
|
||||
"obj/hotpath-remote-write-error-part.1",
|
||||
4,
|
||||
shard_size,
|
||||
HashAlgorithm::None,
|
||||
)
|
||||
.await
|
||||
.expect("failing remote bitrot writer should open before its first write");
|
||||
let write_error = failing_writer
|
||||
.write(b"fail")
|
||||
.await
|
||||
.expect_err("raw shard writer failures must remain visible through the bitrot writer");
|
||||
assert_eq!(write_error.kind(), io::ErrorKind::Other);
|
||||
|
||||
let (would_block_remote_disk, _) =
|
||||
remote_test_disk(TestRemoteDataTransport::with_write_error(io::ErrorKind::WouldBlock)).await;
|
||||
let mut would_block_writer = create_bitrot_writer(
|
||||
false,
|
||||
Some(&would_block_remote_disk),
|
||||
bucket,
|
||||
"obj/hotpath-remote-write-would-block-part.1",
|
||||
4,
|
||||
shard_size,
|
||||
HashAlgorithm::None,
|
||||
)
|
||||
.await
|
||||
.expect("would-block remote bitrot writer should open before its first write");
|
||||
let would_block = would_block_writer
|
||||
.write(b"wait")
|
||||
.await
|
||||
.expect_err("would-block must remain visible to the caller");
|
||||
assert_eq!(would_block.kind(), io::ErrorKind::WouldBlock);
|
||||
|
||||
drop(guard);
|
||||
let report = std::fs::read_to_string(&report_path).expect("HotPath I/O report should be written");
|
||||
let report: serde_json::Value = serde_json::from_str(&report).expect("HotPath I/O report should be valid JSON");
|
||||
let entries = report["io"]["data"]
|
||||
.as_array()
|
||||
.expect("HotPath I/O report should include data rows");
|
||||
let io_bytes = |label: &str, direction: &str| {
|
||||
let byte_count: u64 = entries
|
||||
.iter()
|
||||
.filter(|entry| entry["label"].as_str().is_some_and(|entry_label| entry_label == label))
|
||||
.filter_map(|entry| entry[direction]["bytes"].as_u64())
|
||||
.sum();
|
||||
assert!(byte_count > 0, "report must include fixed label {label}");
|
||||
byte_count
|
||||
};
|
||||
let io_errors = |label: &str, direction: &str| {
|
||||
entries
|
||||
.iter()
|
||||
.filter(|entry| entry["label"].as_str().is_some_and(|entry_label| entry_label == label))
|
||||
.filter_map(|entry| entry[direction]["errors"].as_u64())
|
||||
.sum::<u64>()
|
||||
};
|
||||
let payload_len = u64::try_from(payload.len()).expect("test payload length should fit u64");
|
||||
assert_eq!(
|
||||
io_bytes(RAW_SHARD_READ_LOCAL_LABEL, "read"),
|
||||
payload_len + u64::try_from(fallback_payload.len()).expect("fallback payload length should fit u64")
|
||||
);
|
||||
assert_eq!(io_bytes(RAW_SHARD_WRITE_LOCAL_LABEL, "write"), payload_len);
|
||||
assert_eq!(
|
||||
io_bytes(RAW_SHARD_READ_REMOTE_LABEL, "read"),
|
||||
u64::try_from(remote_payload.len()).expect("remote payload length should fit u64")
|
||||
);
|
||||
assert_eq!(
|
||||
io_bytes(RAW_SHARD_WRITE_REMOTE_LABEL, "write"),
|
||||
u64::try_from(remote_payload.len()).expect("remote payload length should fit u64")
|
||||
);
|
||||
assert_eq!(
|
||||
io_errors(RAW_SHARD_WRITE_REMOTE_LABEL, "write"),
|
||||
1,
|
||||
"the wrapper must record the real remote writer failure without changing it, while excluding WouldBlock"
|
||||
);
|
||||
for label in [
|
||||
RAW_SHARD_READ_LOCAL_LABEL,
|
||||
RAW_SHARD_READ_REMOTE_LABEL,
|
||||
RAW_SHARD_WRITE_LOCAL_LABEL,
|
||||
RAW_SHARD_WRITE_REMOTE_LABEL,
|
||||
] {
|
||||
assert!(
|
||||
!label.contains(['/', ':', '?', '@']),
|
||||
"raw shard I/O labels must not carry a path, host, query, or credential delimiter: {label}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_mmap_read_max_length_defaults_and_env_override() {
|
||||
temp_env::with_var(ENV_OBJECT_MMAP_READ_MAX_LENGTH, None::<&str>, || {
|
||||
@@ -741,25 +1194,9 @@ mod tests {
|
||||
// be materialized in memory by the mmap-copy path; over-cap reads stream.
|
||||
#[tokio::test]
|
||||
async fn open_disk_reader_streams_when_length_exceeds_mmap_cap() {
|
||||
use crate::disk::endpoint::Endpoint;
|
||||
use crate::disk::{DiskOption, new_disk};
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
let dir = tempfile::tempdir().expect("tempdir should be created");
|
||||
let mut endpoint =
|
||||
Endpoint::try_from(dir.path().to_str().expect("tempdir path should be utf8")).expect("endpoint should parse");
|
||||
endpoint.set_pool_index(0);
|
||||
endpoint.set_set_index(0);
|
||||
endpoint.set_disk_index(0);
|
||||
let disk = new_disk(
|
||||
&endpoint,
|
||||
&DiskOption {
|
||||
cleanup: false,
|
||||
health_check: false,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("local disk should be created");
|
||||
let (disk, _dir) = local_test_disk().await;
|
||||
|
||||
let payload = vec![7u8; 4096];
|
||||
disk.make_volume("test-bucket").await.expect("volume should be created");
|
||||
@@ -814,6 +1251,17 @@ mod tests {
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disk_bitrot_reader_and_writer_preserve_full_shard_body() {
|
||||
let (disk, _dir) = local_test_disk().await;
|
||||
let bucket = "test-bucket";
|
||||
let path = "obj/wrapped-part.1";
|
||||
let payload = b"wrapped shard body";
|
||||
let actual = round_trip_disk_bitrot(&disk, bucket, path, payload, 4).await;
|
||||
|
||||
assert_eq!(actual, payload, "raw shard I/O instrumentation must not alter stored bytes");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_create_bitrot_reader_with_inline_data() {
|
||||
let test_data = b"hello world test data";
|
||||
|
||||
@@ -22,6 +22,8 @@ use rustfs_config::{
|
||||
ENV_STARTUP_TOPOLOGY_WAIT_MODE, ENV_STARTUP_TOPOLOGY_WAIT_TIMEOUT, ENV_UNSAFE_BYPASS_DISK_CHECK,
|
||||
};
|
||||
use rustfs_utils::{XHost, check_local_server_addr, get_env_opt_str, get_host_ip, is_local_host};
|
||||
#[cfg(test)]
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet, HashMap, HashSet, hash_map::Entry},
|
||||
future::Future,
|
||||
@@ -598,6 +600,58 @@ const DNS_RETRY_JITTER_PERCENT: u64 = 20;
|
||||
/// wait does not flood the log with one line per backoff tick.
|
||||
const TOPOLOGY_WARN_THROTTLE: Duration = Duration::from_secs(30);
|
||||
|
||||
#[cfg(test)]
|
||||
static FORCED_LOCAL_HOST_RESOLUTION_TIMEOUTS: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
|
||||
|
||||
#[cfg(test)]
|
||||
struct LocalHostResolutionTimeoutGuard {
|
||||
hosts: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl Drop for LocalHostResolutionTimeoutGuard {
|
||||
fn drop(&mut self) {
|
||||
let mut forced_hosts = FORCED_LOCAL_HOST_RESOLUTION_TIMEOUTS
|
||||
.lock()
|
||||
.expect("local-host test resolver mutex poisoned");
|
||||
for host in &self.hosts {
|
||||
forced_hosts.remove(host);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn force_local_host_resolution_timeout_for_test(hosts: &[&str]) -> LocalHostResolutionTimeoutGuard {
|
||||
let hosts = hosts.iter().map(|host| (*host).to_string()).collect::<Vec<_>>();
|
||||
let mut forced_hosts = FORCED_LOCAL_HOST_RESOLUTION_TIMEOUTS
|
||||
.lock()
|
||||
.expect("local-host test resolver mutex poisoned");
|
||||
forced_hosts.extend(hosts.iter().cloned());
|
||||
LocalHostResolutionTimeoutGuard { hosts }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn local_host_resolution_timeout_forced(host: &Host<&str>) -> bool {
|
||||
let host = match host {
|
||||
Host::Domain(domain) => (*domain).to_string(),
|
||||
Host::Ipv4(ip) => ip.to_string(),
|
||||
Host::Ipv6(ip) => ip.to_string(),
|
||||
};
|
||||
FORCED_LOCAL_HOST_RESOLUTION_TIMEOUTS
|
||||
.lock()
|
||||
.expect("local-host test resolver mutex poisoned")
|
||||
.contains(&host)
|
||||
}
|
||||
|
||||
fn endpoint_is_local_host(host: Host<&str>, port: u16, local_port: u16) -> Result<bool> {
|
||||
#[cfg(test)]
|
||||
if local_host_resolution_timeout_forced(&host) {
|
||||
return Err(Error::new(ErrorKind::TimedOut, "resolver timeout"));
|
||||
}
|
||||
|
||||
is_local_host(host, port, local_port)
|
||||
}
|
||||
|
||||
struct DnsRetryDeadline {
|
||||
started: Instant,
|
||||
timeout: Duration,
|
||||
@@ -694,7 +748,7 @@ async fn resolve_local_host_with_retry(
|
||||
retry_dns_operation(
|
||||
|| {
|
||||
let host = host.clone();
|
||||
async move { is_local_host(host, port, local_port) }
|
||||
async move { endpoint_is_local_host(host, port, local_port) }
|
||||
},
|
||||
async_sleep,
|
||||
dns_retry_deadline,
|
||||
@@ -2231,6 +2285,9 @@ mod test {
|
||||
#[serial]
|
||||
#[tokio::test]
|
||||
async fn create_server_endpoints_bounds_kubernetes_alias_dns_fallback() {
|
||||
let _resolution_timeout =
|
||||
force_local_host_resolution_timeout_for_test(&["unrelated-0.example.invalid", "unrelated-1.example.invalid"]);
|
||||
|
||||
async_with_vars(
|
||||
[
|
||||
(ENV_LOCAL_ENDPOINT_HOST, None),
|
||||
|
||||
@@ -17,8 +17,8 @@
|
||||
|
||||
use crate::bucket::metadata_sys::get_versioning_config;
|
||||
use crate::bucket::replication::{
|
||||
ReplicateDecision, ReplicationState, ReplicationStatusType, VersionPurgeStatusType, replication_status_from_filemeta,
|
||||
replication_statuses_map, version_purge_status_from_filemeta, version_purge_statuses_map,
|
||||
DeleteReplicationConfigSnapshot, ReplicateDecision, ReplicationState, ReplicationStatusType, VersionPurgeStatusType,
|
||||
replication_status_from_filemeta, replication_statuses_map, version_purge_status_from_filemeta, version_purge_statuses_map,
|
||||
};
|
||||
use crate::bucket::versioning::VersioningApi as _;
|
||||
use crate::config::storageclass;
|
||||
|
||||
@@ -20,6 +20,47 @@ use crate::storage_api_contracts::{
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct DeleteLockFence {
|
||||
signals: Arc<Vec<Arc<rustfs_lock::distributed_lock::LockLostSignal>>>,
|
||||
#[cfg(test)]
|
||||
forced_lost: bool,
|
||||
}
|
||||
|
||||
impl Debug for DeleteLockFence {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DeleteLockFence")
|
||||
.field("signal_count", &self.signals.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl DeleteLockFence {
|
||||
pub(crate) fn new(signals: Vec<Arc<rustfs_lock::distributed_lock::LockLostSignal>>) -> Self {
|
||||
Self {
|
||||
signals: Arc::new(signals),
|
||||
#[cfg(test)]
|
||||
forced_lost: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_lock_lost(&self) -> bool {
|
||||
#[cfg(test)]
|
||||
if self.forced_lost {
|
||||
return true;
|
||||
}
|
||||
self.signals.iter().any(|signal| signal.is_lost())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn lost_for_test() -> Self {
|
||||
Self {
|
||||
signals: Arc::default(),
|
||||
forced_lost: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct ObjectOptions {
|
||||
// Use the maximum parity (N/2), used when saving server configuration files
|
||||
@@ -54,8 +95,11 @@ pub struct ObjectOptions {
|
||||
pub http_preconditions: Option<HTTPPreconditions>,
|
||||
|
||||
pub delete_replication: Option<ReplicationState>,
|
||||
pub delete_replication_config_snapshot: Option<Arc<DeleteReplicationConfigSnapshot>>,
|
||||
pub delete_lock_fence: Option<DeleteLockFence>,
|
||||
pub replication_request: bool,
|
||||
pub delete_marker: bool,
|
||||
pub synthetic_version_id: bool,
|
||||
|
||||
pub transition: TransitionOptions,
|
||||
pub expiration: ExpirationOptions,
|
||||
|
||||
@@ -337,6 +337,15 @@ pub struct NotificationPeerErr {
|
||||
pub err: Option<Error>,
|
||||
}
|
||||
|
||||
/// One peer's answer to a KMS configuration fingerprint probe.
|
||||
pub struct PeerKmsConfigFingerprint {
|
||||
pub host: String,
|
||||
/// `None` when the peer has no KMS configuration of its own, or could not
|
||||
/// be asked at all, in which case `err` carries the reason.
|
||||
pub fingerprint: Option<String>,
|
||||
pub err: Option<Error>,
|
||||
}
|
||||
|
||||
fn notification_peer_result<T>(host: String, result: Result<T>) -> NotificationPeerErr {
|
||||
NotificationPeerErr { host, err: result.err() }
|
||||
}
|
||||
@@ -518,6 +527,47 @@ impl NotificationSys {
|
||||
self.signal_dynamic_config(sub_sys, false).await
|
||||
}
|
||||
|
||||
/// Ask every peer to re-read the cluster-persisted KMS configuration.
|
||||
///
|
||||
/// Best-effort by contract: the caller has already switched locally, so a
|
||||
/// peer that fails is reported rather than rolled back. Peers built before
|
||||
/// the KMS subsystem existed reject the signal with an explicit error.
|
||||
pub async fn reload_kms_config(&self) -> Vec<NotificationPeerErr> {
|
||||
self.reload_dynamic_config(crate::cluster::rpc::KMS_SIGNAL_SUBSYSTEM).await
|
||||
}
|
||||
|
||||
/// Collect the KMS configuration fingerprint each peer is running.
|
||||
///
|
||||
/// A peer whose build predates the KMS subsystem rejects the probe, so it
|
||||
/// is reported as an error rather than silently agreeing with this node.
|
||||
pub async fn kms_config_fingerprints(&self) -> Vec<PeerKmsConfigFingerprint> {
|
||||
let mut futures = Vec::with_capacity(self.peer_clients.len());
|
||||
for client in self.peer_clients.iter() {
|
||||
futures.push(async move {
|
||||
let Some(client) = client else {
|
||||
return PeerKmsConfigFingerprint {
|
||||
host: String::new(),
|
||||
fingerprint: None,
|
||||
err: Some(Error::other("peer is not reachable")),
|
||||
};
|
||||
};
|
||||
match client.kms_config_fingerprint().await {
|
||||
Ok(fingerprint) => PeerKmsConfigFingerprint {
|
||||
host: client.host.to_string(),
|
||||
fingerprint,
|
||||
err: None,
|
||||
},
|
||||
Err(e) => PeerKmsConfigFingerprint {
|
||||
host: client.host.to_string(),
|
||||
fingerprint: None,
|
||||
err: Some(e),
|
||||
},
|
||||
}
|
||||
});
|
||||
}
|
||||
join_all(futures).await
|
||||
}
|
||||
|
||||
pub async fn refresh_config_snapshot(&self) -> Vec<NotificationPeerErr> {
|
||||
let mut futures = Vec::with_capacity(self.peer_clients.len());
|
||||
for client in self.peer_clients.iter() {
|
||||
|
||||
@@ -35,14 +35,17 @@ use crate::bucket::lifecycle::{
|
||||
save_transition_transaction_record,
|
||||
},
|
||||
};
|
||||
use crate::bucket::replication::{DeleteReplicationConfigSnapshot, VersionPurgeStatusType, version_purge_status_to_filemeta};
|
||||
use crate::diagnostics::get::GetObjectFailureReason;
|
||||
use crate::disk::OldCurrentSize;
|
||||
use crate::error::is_err_invalid_upload_id;
|
||||
use crate::object_api::DeleteLockFence;
|
||||
use crate::object_api::{GetObjectBodySource, get_object_body_cache_hook_suppressed};
|
||||
use crate::services::tier::tier::{TierConfigMgr, TierOperationLease};
|
||||
use crate::store::ECStore;
|
||||
use futures::FutureExt as _;
|
||||
use http::HeaderValue;
|
||||
use rustfs_utils::path::decode_dir_object;
|
||||
use std::future::Future;
|
||||
|
||||
fn erasure_from_file_info(fi: &FileInfo, uses_legacy: bool) -> Result<coding::Erasure> {
|
||||
@@ -3111,25 +3114,24 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
quorum_result
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(self))]
|
||||
#[tracing::instrument(skip(self, objects, opts))]
|
||||
async fn delete_objects(
|
||||
&self,
|
||||
bucket: &str,
|
||||
objects: Vec<ObjectToDelete>,
|
||||
opts: ObjectOptions,
|
||||
) -> (Vec<DeletedObject>, Vec<Option<Error>>) {
|
||||
let mut del_objects = vec![DeletedObject::default(); objects.len()];
|
||||
let delete_config_snapshot = opts
|
||||
.delete_replication_config_snapshot
|
||||
.clone()
|
||||
.unwrap_or_else(|| Arc::new(DeleteReplicationConfigSnapshot::default()));
|
||||
|
||||
for object in &objects {
|
||||
self.invalidate_get_object_metadata_cache(bucket, &object.object_name).await;
|
||||
}
|
||||
|
||||
// Default return value
|
||||
let mut del_objects = vec![DeletedObject::default(); objects.len()];
|
||||
|
||||
let mut del_errs = Vec::with_capacity(objects.len());
|
||||
|
||||
for _ in 0..objects.len() {
|
||||
del_errs.push(None)
|
||||
}
|
||||
let mut del_errs = (0..objects.len()).map(|_| None).collect::<Vec<_>>();
|
||||
|
||||
// Acquire locks in batch mode (best effort, matching previous behavior)
|
||||
let mut batch = rustfs_lock::BatchLockRequest::new(self.locker_owner.as_str()).with_all_or_nothing(false);
|
||||
@@ -3195,14 +3197,8 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
}
|
||||
}
|
||||
|
||||
let ver_cfg = BucketVersioningSys::get_in(&self.ctx, bucket).await.unwrap_or_default();
|
||||
|
||||
// backlog#929 (HP-8): the per-object stat below exists solely to feed
|
||||
// check_object_lock_delete (#4297). Resolve the bucket lock
|
||||
// configuration once (in-memory cache) and skip the whole stat fanout
|
||||
// for buckets without Object Lock; unknown metadata fails closed and
|
||||
// keeps the stat, so the #4297 protection is preserved verbatim for
|
||||
// every object-lock-enabled bucket.
|
||||
// Resolve Object Lock once; replication still reads each matching
|
||||
// object's tags below while the batch write lock is held.
|
||||
let object_lock_checks_required =
|
||||
object_lock_delete_check_required(metadata_sys::get_in(&self.ctx, bucket).await.ok().as_deref());
|
||||
|
||||
@@ -3213,31 +3209,75 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
continue;
|
||||
}
|
||||
|
||||
let replication_object_name = decode_dir_object(&dobj.object_name);
|
||||
let explicit_null_version = is_explicit_null_version(dobj.version_id);
|
||||
let version_id = delete_file_info_version_id(dobj.version_id);
|
||||
if object_lock_checks_required {
|
||||
let check_opts = ObjectOptions {
|
||||
version_id: version_id.map(|version_id| version_id.to_string()),
|
||||
versioned: ver_cfg.prefix_enabled(dobj.object_name.as_str()),
|
||||
version_suspended: ver_cfg.suspended(),
|
||||
object_lock_delete: opts.object_lock_delete.clone(),
|
||||
no_lock: true,
|
||||
..Default::default()
|
||||
};
|
||||
let (versioned, version_suspended) = delete_config_snapshot
|
||||
.versioning_config()
|
||||
.delete_state(replication_object_name.as_str());
|
||||
let check_opts = ObjectOptions {
|
||||
version_id: version_id.map(|version_id| version_id.to_string()),
|
||||
versioned,
|
||||
version_suspended,
|
||||
object_lock_delete: opts.object_lock_delete.clone(),
|
||||
no_lock: true,
|
||||
..Default::default()
|
||||
};
|
||||
let replicate_delete = delete_config_snapshot.has_active_rule(&replication_object_name);
|
||||
let marker_delete = dobj.version_id.is_none() || dobj.synthetic_version_id;
|
||||
let replication_needs_source = replicate_delete
|
||||
&& (!marker_delete || delete_config_snapshot.active_delete_marker_rules_require_tags(&replication_object_name));
|
||||
let (goi, gerr) = if object_lock_checks_required || replication_needs_source {
|
||||
let (goi, _write_quorum, gerr) = self.get_object_info_and_quorum(bucket, &dobj.object_name, &check_opts).await;
|
||||
if gerr.is_none()
|
||||
&& let Err(err) = check_object_lock_delete(bucket, &dobj.object_name, &goi, &check_opts).await
|
||||
{
|
||||
del_errs[i] = Some(err);
|
||||
continue;
|
||||
}
|
||||
(goi, gerr)
|
||||
} else {
|
||||
(ObjectInfo::default(), None)
|
||||
};
|
||||
let source_missing = gerr
|
||||
.as_ref()
|
||||
.is_some_and(|err| is_err_object_not_found(err) || is_err_version_not_found(err));
|
||||
if let Some(err) = gerr.as_ref()
|
||||
&& !source_missing
|
||||
{
|
||||
del_errs[i] = Some(err.clone());
|
||||
continue;
|
||||
}
|
||||
if object_lock_checks_required
|
||||
&& !source_missing
|
||||
&& let Err(err) = check_object_lock_delete(bucket, &dobj.object_name, &goi, &check_opts).await
|
||||
{
|
||||
del_errs[i] = Some(err);
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut admitted = dobj.clone();
|
||||
admitted.object_name = replication_object_name;
|
||||
if admitted.synthetic_version_id {
|
||||
admitted.version_id = None;
|
||||
}
|
||||
if replicate_delete {
|
||||
let dsc = ReplicationObjectBridge::check_delete_with_snapshot(
|
||||
&admitted,
|
||||
&goi,
|
||||
&check_opts,
|
||||
source_missing,
|
||||
&delete_config_snapshot,
|
||||
);
|
||||
if dsc.replicate_any() {
|
||||
if admitted.version_id.is_some() {
|
||||
admitted.version_purge_status = Some(version_purge_status_to_filemeta(VersionPurgeStatusType::Pending));
|
||||
admitted.version_purge_statuses = dsc.pending_status();
|
||||
} else {
|
||||
admitted.delete_marker_replication_status = dsc.pending_status();
|
||||
}
|
||||
admitted.replicate_decision_str = Some(dsc.to_string());
|
||||
}
|
||||
}
|
||||
let mut vr = FileInfo {
|
||||
name: dobj.object_name.clone(),
|
||||
version_id,
|
||||
idx: i,
|
||||
replication_state_internal: Some(dobj.replication_state()),
|
||||
replication_state_internal: Some(admitted.replication_state()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -3247,14 +3287,11 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
// del_objects[i].object_name.clone_from(&vr.name);
|
||||
// del_objects[i].version_id = vr.version_id.map(|v| v.to_string());
|
||||
|
||||
if dobj.version_id.is_none() {
|
||||
let (suspended, versioned) = (ver_cfg.suspended(), ver_cfg.prefix_enabled(dobj.object_name.as_str()));
|
||||
if suspended || versioned {
|
||||
vr.mod_time = Some(OffsetDateTime::now_utc());
|
||||
vr.deleted = true;
|
||||
if versioned {
|
||||
vr.version_id = Some(Uuid::new_v4());
|
||||
}
|
||||
if dobj.version_id.is_none() && (version_suspended || versioned) {
|
||||
vr.mod_time = Some(OffsetDateTime::now_utc());
|
||||
vr.deleted = true;
|
||||
if versioned {
|
||||
vr.version_id = Some(Uuid::new_v4());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3312,6 +3349,24 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
vers.push(fi_vers);
|
||||
}
|
||||
|
||||
if opts.delete_lock_fence.as_ref().is_some_and(DeleteLockFence::is_lock_lost) {
|
||||
if dist_erasure {
|
||||
self.release_dist_delete_object_locks_batch(dist_batch_lock_ids).await;
|
||||
}
|
||||
for (index, object) in objects.iter().enumerate() {
|
||||
if del_errs[index].is_none() {
|
||||
del_errs[index] = Some(Error::NamespaceLockQuorumUnavailable {
|
||||
mode: "delete_objects_commit",
|
||||
bucket: bucket.to_string(),
|
||||
object: decode_dir_object(&object.object_name),
|
||||
required: 1,
|
||||
achieved: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
return (del_objects, del_errs);
|
||||
}
|
||||
|
||||
let rollback_dir = Uuid::new_v4();
|
||||
|
||||
let disks = self.disks.read().await;
|
||||
@@ -3490,6 +3545,16 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
|
||||
#[tracing::instrument(skip(self))]
|
||||
async fn delete_object(&self, bucket: &str, object: &str, mut opts: ObjectOptions) -> Result<ObjectInfo> {
|
||||
let preserve_delete_replication_state = should_preserve_delete_replication_state(&opts);
|
||||
let delete_config_snapshot = if opts.delete_prefix || opts.transition.expire_restored || preserve_delete_replication_state
|
||||
{
|
||||
None
|
||||
} else if let Some(snapshot) = opts.delete_replication_config_snapshot.clone() {
|
||||
Some(snapshot)
|
||||
} else {
|
||||
Some(Arc::new(DeleteReplicationConfigSnapshot::default()))
|
||||
};
|
||||
|
||||
self.invalidate_get_object_metadata_cache(bucket, object).await;
|
||||
|
||||
// Guard lock for single object delete
|
||||
@@ -3580,18 +3645,20 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
}
|
||||
|
||||
let otd = ObjectToDelete {
|
||||
object_name: object.to_string(),
|
||||
version_id: opts
|
||||
.version_id
|
||||
.clone()
|
||||
.map(|v| Uuid::parse_str(v.as_str()).ok().unwrap_or_default()),
|
||||
object_name: decode_dir_object(object),
|
||||
version_id: if opts.synthetic_version_id {
|
||||
None
|
||||
} else {
|
||||
opts.version_id.as_deref().map(Uuid::parse_str).transpose()?
|
||||
},
|
||||
synthetic_version_id: opts.synthetic_version_id,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let dsc = if should_preserve_delete_replication_state(&opts) {
|
||||
ReplicateDecision::default()
|
||||
let dsc = if let Some(snapshot) = delete_config_snapshot {
|
||||
ReplicationObjectBridge::check_delete_with_snapshot(&otd, &goi, &opts, gerr.is_some(), &snapshot)
|
||||
} else {
|
||||
ReplicationObjectBridge::check_delete(bucket, &otd, &goi, &opts, gerr.map(|e| e.to_string())).await
|
||||
ReplicateDecision::default()
|
||||
};
|
||||
|
||||
if dsc.replicate_any() {
|
||||
@@ -3649,6 +3716,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
self.record_capacity_scope_if_needed(opts.capacity_scope_token, &disks);
|
||||
|
||||
let mut oi = ObjectInfo::from_file_info(&fi, bucket, object, opts.versioned || opts.version_suspended);
|
||||
oi.user_tags = Arc::clone(&goi.user_tags);
|
||||
oi.replication_decision = goi.replication_decision;
|
||||
self.invalidate_get_object_metadata_cache(bucket, object).await;
|
||||
return Ok(oi);
|
||||
@@ -3680,6 +3748,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
|
||||
let mut obj_info = ObjectInfo::from_file_info(&dfi, bucket, object, opts.versioned || opts.version_suspended);
|
||||
obj_info.size = goi.size;
|
||||
obj_info.user_tags = Arc::clone(&goi.user_tags);
|
||||
self.invalidate_get_object_metadata_cache(bucket, object).await;
|
||||
Ok(obj_info)
|
||||
}
|
||||
@@ -7801,6 +7870,56 @@ mod object_tagging_namespace_lock_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_delete_returns_tags_read_under_the_delete_lock() {
|
||||
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
|
||||
let bucket = "delete-locked-tags";
|
||||
let object = "object";
|
||||
for disk in &disk_stores {
|
||||
disk.make_volume(bucket).await.expect("bucket volume should be created");
|
||||
}
|
||||
let mut reader = PutObjReader::from_vec(b"body".to_vec());
|
||||
let uploaded = set_disks
|
||||
.put_object(
|
||||
bucket,
|
||||
object,
|
||||
&mut reader,
|
||||
&ObjectOptions {
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("versioned object should be written");
|
||||
let version_id = uploaded.version_id.expect("versioned PUT should return an ID").to_string();
|
||||
let version_opts = ObjectOptions {
|
||||
versioned: true,
|
||||
version_id: Some(version_id),
|
||||
delete_replication_config_snapshot: Some(Arc::new(DeleteReplicationConfigSnapshot::default())),
|
||||
..Default::default()
|
||||
};
|
||||
set_disks
|
||||
.put_object_tags(bucket, object, "generation=stale", &version_opts)
|
||||
.await
|
||||
.expect("initial tags should be written");
|
||||
let advisory = set_disks
|
||||
.get_object_info(bucket, object, &version_opts)
|
||||
.await
|
||||
.expect("advisory pre-read should succeed");
|
||||
set_disks
|
||||
.put_object_tags(bucket, object, "generation=locked", &version_opts)
|
||||
.await
|
||||
.expect("concurrent tag update should commit before delete");
|
||||
|
||||
let deleted = set_disks
|
||||
.delete_object(bucket, object, version_opts)
|
||||
.await
|
||||
.expect("version delete should succeed");
|
||||
|
||||
assert_eq!(advisory.user_tags.as_str(), "generation=stale");
|
||||
assert_eq!(deleted.user_tags.as_str(), "generation=locked");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn tagging_serializes_with_put_and_delete_for_versioned_and_unversioned_objects() {
|
||||
@@ -7815,6 +7934,7 @@ mod object_tagging_namespace_lock_tests {
|
||||
|
||||
let object_opts = ObjectOptions {
|
||||
versioned,
|
||||
delete_replication_config_snapshot: Some(Arc::new(DeleteReplicationConfigSnapshot::default())),
|
||||
..Default::default()
|
||||
};
|
||||
let original_body = b"original body".to_vec();
|
||||
@@ -8014,6 +8134,276 @@ mod delete_objects_lock_gating_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_objects_derives_per_object_versioning_from_the_request_snapshot() {
|
||||
use s3s::dto::{BucketVersioningStatus, ExcludedPrefix, VersioningConfiguration};
|
||||
|
||||
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
|
||||
let bucket = "batch-versioning-snapshot-bucket";
|
||||
for disk in &disk_stores {
|
||||
disk.make_volume(bucket).await.expect("bucket volume should be created");
|
||||
}
|
||||
|
||||
put_plain_object(&set_disks, bucket, "marker-object").await;
|
||||
put_plain_object(&set_disks, bucket, "archive/unversioned-object").await;
|
||||
let snapshot = Arc::new(DeleteReplicationConfigSnapshot::from_configs_for_test(
|
||||
VersioningConfiguration {
|
||||
status: Some(BucketVersioningStatus::from_static(BucketVersioningStatus::ENABLED)),
|
||||
excluded_prefixes: Some(vec![ExcludedPrefix {
|
||||
prefix: Some("archive/".to_string()),
|
||||
}]),
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
));
|
||||
let objects = vec![
|
||||
ObjectToDelete {
|
||||
object_name: "marker-object".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
ObjectToDelete {
|
||||
object_name: "archive/unversioned-object".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
|
||||
let (deleted, errors) = set_disks
|
||||
.delete_objects(
|
||||
bucket,
|
||||
objects,
|
||||
ObjectOptions {
|
||||
versioned: true,
|
||||
delete_replication_config_snapshot: Some(snapshot),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
errors.iter().all(Option::is_none),
|
||||
"snapshot-backed batch delete should succeed: {errors:?}"
|
||||
);
|
||||
assert!(deleted[0].delete_marker);
|
||||
assert!(deleted[0].delete_marker_version_id.is_some());
|
||||
assert!(!deleted[1].delete_marker);
|
||||
set_disks
|
||||
.get_object_info(bucket, "archive/unversioned-object", &ObjectOptions::default())
|
||||
.await
|
||||
.expect_err("the snapshot-excluded object should be removed without a delete marker");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn batch_version_delete_uses_tags_read_under_the_delete_lock() {
|
||||
use rustfs_utils::http::headers::AMZ_OBJECT_TAGGING;
|
||||
use s3s::dto::{
|
||||
BucketVersioningStatus, DeleteReplication, DeleteReplicationStatus, Destination, ReplicationConfiguration,
|
||||
ReplicationRule, ReplicationRuleFilter, ReplicationRuleStatus, Tag, VersioningConfiguration,
|
||||
};
|
||||
|
||||
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
|
||||
let bucket = "batch-delete-locked-tags";
|
||||
let object = "object";
|
||||
let arn = "arn:rustfs:replication:us-east-1:target:bucket";
|
||||
for disk in &disk_stores {
|
||||
disk.make_volume(bucket).await.expect("bucket volume should be created");
|
||||
}
|
||||
let mut reader = PutObjReader::from_vec(b"body".to_vec());
|
||||
let uploaded = set_disks
|
||||
.put_object(
|
||||
bucket,
|
||||
object,
|
||||
&mut reader,
|
||||
&ObjectOptions {
|
||||
versioned: true,
|
||||
user_defined: HashMap::from([(AMZ_OBJECT_TAGGING.to_string(), "generation=stale".to_string())]),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("versioned object should be written");
|
||||
let version_id = uploaded.version_id.expect("versioned PUT should return an ID");
|
||||
let version_opts = ObjectOptions {
|
||||
versioned: true,
|
||||
version_id: Some(version_id.to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
set_disks
|
||||
.put_object_tags(bucket, object, "generation=locked", &version_opts)
|
||||
.await
|
||||
.expect("tag update should commit before the batch delete");
|
||||
|
||||
let snapshot = Arc::new(DeleteReplicationConfigSnapshot::from_configs_for_test(
|
||||
VersioningConfiguration {
|
||||
status: Some(BucketVersioningStatus::from_static(BucketVersioningStatus::ENABLED)),
|
||||
..Default::default()
|
||||
},
|
||||
Some(ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![ReplicationRule {
|
||||
delete_marker_replication: None,
|
||||
delete_replication: Some(DeleteReplication {
|
||||
status: DeleteReplicationStatus::from_static(DeleteReplicationStatus::ENABLED),
|
||||
}),
|
||||
destination: Destination {
|
||||
bucket: arn.to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
existing_object_replication: None,
|
||||
filter: Some(ReplicationRuleFilter {
|
||||
tag: Some(Tag {
|
||||
key: Some("generation".to_string()),
|
||||
value: Some("locked".to_string()),
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
id: Some("delete".to_string()),
|
||||
prefix: Some(String::new()),
|
||||
priority: Some(1),
|
||||
source_selection_criteria: None,
|
||||
status: ReplicationRuleStatus::from_static(ReplicationRuleStatus::ENABLED),
|
||||
}],
|
||||
}),
|
||||
));
|
||||
let (deleted, errors) = set_disks
|
||||
.delete_objects(
|
||||
bucket,
|
||||
vec![ObjectToDelete {
|
||||
object_name: object.to_string(),
|
||||
version_id: Some(version_id),
|
||||
..Default::default()
|
||||
}],
|
||||
ObjectOptions {
|
||||
versioned: true,
|
||||
delete_replication_config_snapshot: Some(snapshot),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(errors.iter().all(Option::is_none), "batch version delete should succeed: {errors:?}");
|
||||
let state = deleted[0]
|
||||
.replication_state
|
||||
.as_ref()
|
||||
.expect("locked decision should be persisted");
|
||||
assert_eq!(
|
||||
state.version_purge_status_internal.as_deref(),
|
||||
Some("arn:rustfs:replication:us-east-1:target:bucket=PENDING;")
|
||||
);
|
||||
assert!(state.replicate_decision_str.contains(arn));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn synthetic_directory_delete_uses_decoded_prefix_and_marker_switch() {
|
||||
use s3s::dto::{
|
||||
BucketVersioningStatus, DeleteMarkerReplication, DeleteMarkerReplicationStatus, DeleteReplication,
|
||||
DeleteReplicationStatus, Destination, ReplicationConfiguration, ReplicationRule, ReplicationRuleFilter,
|
||||
ReplicationRuleStatus, VersioningConfiguration,
|
||||
};
|
||||
|
||||
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
|
||||
let bucket = "batch-directory-replication";
|
||||
let object = encode_dir_object("photos/");
|
||||
let arn = "arn:rustfs:replication:us-east-1:target:bucket";
|
||||
for disk in &disk_stores {
|
||||
disk.make_volume(bucket).await.expect("bucket volume should be created");
|
||||
}
|
||||
put_plain_object(&set_disks, bucket, &object).await;
|
||||
|
||||
let snapshot = Arc::new(DeleteReplicationConfigSnapshot::from_configs_for_test(
|
||||
VersioningConfiguration {
|
||||
status: Some(BucketVersioningStatus::from_static(BucketVersioningStatus::ENABLED)),
|
||||
..Default::default()
|
||||
},
|
||||
Some(ReplicationConfiguration {
|
||||
role: String::new(),
|
||||
rules: vec![ReplicationRule {
|
||||
delete_marker_replication: Some(DeleteMarkerReplication {
|
||||
status: Some(DeleteMarkerReplicationStatus::from_static(DeleteMarkerReplicationStatus::ENABLED)),
|
||||
}),
|
||||
delete_replication: Some(DeleteReplication {
|
||||
status: DeleteReplicationStatus::from_static(DeleteReplicationStatus::DISABLED),
|
||||
}),
|
||||
destination: Destination {
|
||||
bucket: arn.to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
existing_object_replication: None,
|
||||
filter: Some(ReplicationRuleFilter {
|
||||
prefix: Some("photos/".to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
id: Some("directory-marker".to_string()),
|
||||
prefix: None,
|
||||
priority: Some(1),
|
||||
source_selection_criteria: None,
|
||||
status: ReplicationRuleStatus::from_static(ReplicationRuleStatus::ENABLED),
|
||||
}],
|
||||
}),
|
||||
));
|
||||
|
||||
let (deleted, errors) = set_disks
|
||||
.delete_objects(
|
||||
bucket,
|
||||
vec![ObjectToDelete {
|
||||
object_name: object,
|
||||
version_id: Some(Uuid::nil()),
|
||||
synthetic_version_id: true,
|
||||
..Default::default()
|
||||
}],
|
||||
ObjectOptions {
|
||||
versioned: true,
|
||||
delete_replication_config_snapshot: Some(snapshot),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(errors[0].is_none(), "directory delete should succeed: {:?}", errors[0]);
|
||||
let state = deleted[0]
|
||||
.replication_state
|
||||
.as_ref()
|
||||
.expect("marker replication decision should be persisted");
|
||||
assert_eq!(state.replication_status_internal.as_deref(), Some(format!("{arn}=PENDING;").as_str()));
|
||||
assert!(state.version_purge_status_internal.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_objects_aborts_before_disk_mutation_after_outer_lock_loss() {
|
||||
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
|
||||
let bucket = "batch-lost-outer-lock";
|
||||
let object = "object";
|
||||
for disk in &disk_stores {
|
||||
disk.make_volume(bucket).await.expect("bucket volume should be created");
|
||||
}
|
||||
put_plain_object(&set_disks, bucket, object).await;
|
||||
|
||||
let (_deleted, errors) = set_disks
|
||||
.delete_objects(
|
||||
bucket,
|
||||
vec![ObjectToDelete {
|
||||
object_name: object.to_string(),
|
||||
..Default::default()
|
||||
}],
|
||||
ObjectOptions {
|
||||
no_lock: true,
|
||||
delete_lock_fence: Some(DeleteLockFence::lost_for_test()),
|
||||
delete_replication_config_snapshot: Some(Arc::new(DeleteReplicationConfigSnapshot::default())),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
matches!(errors[0], Some(Error::NamespaceLockQuorumUnavailable { .. })),
|
||||
"lost outer lock must fail the batch before disk mutation: {:?}",
|
||||
errors[0]
|
||||
);
|
||||
set_disks
|
||||
.get_object_info(bucket, object, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("object must survive a lost-lock batch");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_objects_blocks_locked_object_and_deletes_the_rest() {
|
||||
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
|
||||
|
||||
@@ -199,7 +199,7 @@ impl SetDisks {
|
||||
);
|
||||
}
|
||||
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "SetDisks")]
|
||||
pub async fn read_version_optimized(
|
||||
&self,
|
||||
bucket: &str,
|
||||
@@ -238,7 +238,7 @@ impl SetDisks {
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug", skip(self))]
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "SetDisks")]
|
||||
pub(super) async fn get_object_fileinfo(
|
||||
&self,
|
||||
bucket: &str,
|
||||
@@ -410,7 +410,7 @@ impl SetDisks {
|
||||
Ok((fi, parts_metadata, op_online_disks))
|
||||
}
|
||||
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "SetDisks")]
|
||||
pub(super) async fn get_object_info_and_quorum(
|
||||
&self,
|
||||
bucket: &str,
|
||||
@@ -605,7 +605,7 @@ impl SetDisks {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "SetDisks")]
|
||||
pub(super) async fn get_object_with_fileinfo<W>(
|
||||
// &self,
|
||||
bucket: &str,
|
||||
@@ -1140,7 +1140,7 @@ impl SetDisks {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "SetDisks")]
|
||||
pub(super) async fn get_object_decode_reader_with_fileinfo(
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
@@ -1296,7 +1296,7 @@ impl SetDisks {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "SetDisks")]
|
||||
async fn build_codec_streaming_part_reader(
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
|
||||
@@ -4861,10 +4861,7 @@ async fn poll_merge_head(rx: &CancellationToken, in_channels: &mut [Receiver<Met
|
||||
|
||||
async fn send_or_cancel(rx: &CancellationToken, out_channel: &Sender<MetaCacheEntry>, entry: MetaCacheEntry) -> Result<bool> {
|
||||
tokio::select! {
|
||||
result = out_channel.send(entry) => {
|
||||
result.map_err(Error::other)?;
|
||||
Ok(true)
|
||||
}
|
||||
result = out_channel.send(entry) => Ok(result.is_ok()),
|
||||
_ = rx.cancelled() => Ok(false),
|
||||
}
|
||||
}
|
||||
@@ -9858,6 +9855,28 @@ mod test {
|
||||
assert_eq!(results, vec!["obj-a", "obj-b"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn merge_entry_channels_treats_dropped_output_receiver_as_completion() {
|
||||
let (tx_a, rx_a) = mpsc::channel(4);
|
||||
let (tx_b, rx_b) = mpsc::channel(4);
|
||||
let (out_tx, out_rx) = mpsc::channel(1);
|
||||
|
||||
tx_a.send(test_meta_entry("obj-a")).await.unwrap();
|
||||
tx_b.send(test_meta_entry("obj-b")).await.unwrap();
|
||||
drop(tx_a);
|
||||
drop(tx_b);
|
||||
drop(out_rx);
|
||||
|
||||
let result = timeout(
|
||||
Duration::from_secs(1),
|
||||
merge_entry_channels(CancellationToken::new(), vec![rx_a, rx_b], out_tx, 1),
|
||||
)
|
||||
.await
|
||||
.expect("merge should stop promptly when its consumer disconnects");
|
||||
|
||||
assert!(result.is_ok(), "consumer disconnect must not surface as a merge worker error");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn walk_ascending_versions_contract_reverses_newest_first_metadata() {
|
||||
// Documents the invariant the walk `versions_sort` handling relies on:
|
||||
|
||||
@@ -519,7 +519,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for ECStore {
|
||||
result
|
||||
}
|
||||
|
||||
#[instrument(skip(self))]
|
||||
#[instrument(skip(self, objects, opts))]
|
||||
async fn delete_objects(
|
||||
&self,
|
||||
bucket: &str,
|
||||
|
||||
@@ -238,7 +238,7 @@ impl ECStore {
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data))]
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "ECStore")]
|
||||
pub(super) async fn handle_put_object_part(
|
||||
&self,
|
||||
bucket: &str,
|
||||
|
||||
@@ -13,7 +13,9 @@
|
||||
// limitations under the License.
|
||||
|
||||
use super::*;
|
||||
use crate::bucket::replication::ReplicationObjectBridge;
|
||||
use crate::disk::OldCurrentSize;
|
||||
use crate::object_api::DeleteLockFence;
|
||||
use crate::set_disk::{
|
||||
get_lock_acquire_timeout, get_object_lock_diag_slow_acquire_threshold, get_object_lock_diag_slow_hold_threshold,
|
||||
is_lock_optimization_enabled, is_object_lock_diag_enabled,
|
||||
@@ -156,6 +158,13 @@ impl ObjectLockDiagGuard {
|
||||
acquired_at: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn lock_lost_signal(&self) -> Option<Arc<rustfs_lock::distributed_lock::LockLostSignal>> {
|
||||
match &self.guard {
|
||||
rustfs_lock::NamespaceLockGuard::Standard(guard) => Some(guard.lock_lost()),
|
||||
rustfs_lock::NamespaceLockGuard::Fast(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Opaque write-lock guard for the RestoreObject accept path; see
|
||||
@@ -594,6 +603,9 @@ impl ECStore {
|
||||
guards.push(self.acquire_object_write_lock("delete_objects", bucket, object).await?);
|
||||
}
|
||||
opts.no_lock = true;
|
||||
opts.delete_lock_fence = Some(DeleteLockFence::new(
|
||||
guards.iter().filter_map(ObjectLockDiagGuard::lock_lost_signal).collect(),
|
||||
));
|
||||
|
||||
Ok(guards)
|
||||
}
|
||||
@@ -815,7 +827,7 @@ impl ECStore {
|
||||
}
|
||||
|
||||
#[instrument(level = "debug", skip(self))]
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "ECStore")]
|
||||
pub(super) async fn handle_get_object_reader(
|
||||
&self,
|
||||
bucket: &str,
|
||||
@@ -849,7 +861,7 @@ impl ECStore {
|
||||
}
|
||||
|
||||
#[instrument(level = "debug", skip(self, data))]
|
||||
#[hotpath::measure]
|
||||
#[hotpath::measure(impl_type = "ECStore")]
|
||||
pub(super) async fn handle_put_object(
|
||||
&self,
|
||||
bucket: &str,
|
||||
@@ -1222,7 +1234,7 @@ impl ECStore {
|
||||
Err(StorageError::ObjectNotFound(bucket.to_owned(), object.to_owned()))
|
||||
}
|
||||
|
||||
#[instrument(skip(self))]
|
||||
#[instrument(skip(self, objects, opts))]
|
||||
pub(super) async fn handle_delete_objects(
|
||||
&self,
|
||||
bucket: &str,
|
||||
@@ -1248,6 +1260,17 @@ impl ECStore {
|
||||
}
|
||||
|
||||
let mut opts = opts;
|
||||
if opts.delete_replication_config_snapshot.is_none() {
|
||||
match ReplicationObjectBridge::delete_request_config_in(&self.ctx, bucket).await {
|
||||
Ok(snapshot) => opts.delete_replication_config_snapshot = Some(Arc::new(snapshot)),
|
||||
Err(err) => {
|
||||
let message = err.to_string();
|
||||
let errors = (0..objects.len()).map(|_| Some(Error::other(message.clone()))).collect();
|
||||
return (del_objects, errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _object_lock_guards = match self.acquire_delete_objects_write_locks(bucket, &objects, &mut opts).await {
|
||||
Ok(guards) => guards,
|
||||
Err(err) => return return_batch_delete_lock_error(objects.as_slice(), err),
|
||||
@@ -2540,6 +2563,7 @@ mod tests {
|
||||
|
||||
assert_eq!(guards.len(), 2, "duplicate object names should share one namespace lock");
|
||||
assert!(opts.no_lock, "set layer should not reacquire locks already held by ECStore");
|
||||
assert!(opts.delete_lock_fence.is_some(), "set layer must receive the outer write-lock loss fence");
|
||||
|
||||
let alpha_lock = store
|
||||
.handle_new_ns_lock("bucket", "alpha")
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
// 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.
|
||||
|
||||
const STORE_MULTIPART: &str = include_str!("../src/store/multipart.rs");
|
||||
const STORE_OBJECT: &str = include_str!("../src/store/object.rs");
|
||||
const ERASURE: &str = include_str!("../src/erasure/coding/erasure.rs");
|
||||
const DECODE: &str = include_str!("../src/erasure/coding/decode.rs");
|
||||
const ENCODE: &str = include_str!("../src/erasure/coding/encode.rs");
|
||||
const LOCAL_DISK: &str = include_str!("../src/disk/local.rs");
|
||||
const BITROT: &str = include_str!("../src/erasure/coding/bitrot.rs");
|
||||
const SET_DISK_READ: &str = include_str!("../src/set_disk/read.rs");
|
||||
|
||||
fn assert_measured_as(source: &str, impl_type: &str, function: &str) {
|
||||
let attribute = format!("#[hotpath::measure(impl_type = \"{impl_type}\")]\n");
|
||||
let function_start = format!("fn {function}");
|
||||
let mut remaining = source;
|
||||
|
||||
while let Some(attribute_offset) = remaining.find(&attribute) {
|
||||
let measured_source = &remaining[attribute_offset + attribute.len()..];
|
||||
if measured_source.find(&function_start).is_some_and(|offset| offset < 256) {
|
||||
return;
|
||||
}
|
||||
remaining = measured_source;
|
||||
}
|
||||
|
||||
panic!("missing HotPath impl_type={impl_type} for {function}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inherent_hotpath_measurements_have_cpu_attribution_types() {
|
||||
assert_measured_as(STORE_MULTIPART, "ECStore", "handle_put_object_part");
|
||||
for function in ["handle_get_object_reader", "handle_put_object"] {
|
||||
assert_measured_as(STORE_OBJECT, "ECStore", function);
|
||||
}
|
||||
for function in [
|
||||
"encode_data",
|
||||
"encode_data_owned",
|
||||
"encode_data_bytes_mut",
|
||||
"decode_data",
|
||||
"decode_data_and_parity",
|
||||
] {
|
||||
assert_measured_as(ERASURE, "Erasure", function);
|
||||
}
|
||||
assert_measured_as(DECODE, "ParallelReader", "read");
|
||||
assert_measured_as(DECODE, "Erasure", "decode");
|
||||
for function in [
|
||||
"encode",
|
||||
"encode_batched",
|
||||
"encode_inline_small",
|
||||
"encode_single_block_non_inline",
|
||||
] {
|
||||
assert_measured_as(ENCODE, "Erasure", function);
|
||||
}
|
||||
for function in ["read_metadata_with_dmtime", "read_all_data"] {
|
||||
assert_measured_as(LOCAL_DISK, "LocalDisk", function);
|
||||
}
|
||||
assert_measured_as(BITROT, "BitrotReader", "read");
|
||||
assert!(
|
||||
BITROT.contains("#[hotpath::measure(label = \"BitrotWriter::write\", impl_type = \"BitrotWriter\")]"),
|
||||
"BitrotWriter::write must retain its stable label and CPU impl_type",
|
||||
);
|
||||
for function in [
|
||||
"read_version_optimized",
|
||||
"get_object_fileinfo",
|
||||
"get_object_info_and_quorum",
|
||||
"get_object_with_fileinfo",
|
||||
"get_object_decode_reader_with_fileinfo",
|
||||
"build_codec_streaming_part_reader",
|
||||
] {
|
||||
assert_measured_as(SET_DISK_READ, "SetDisks", function);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_hotpath_measurements_remain_untyped() {
|
||||
assert!(
|
||||
BITROT.contains("#[hotpath::measure]\npub async fn bitrot_verify"),
|
||||
"bitrot_verify is a module function and must not claim an impl type",
|
||||
);
|
||||
assert!(
|
||||
SET_DISK_READ.contains("#[hotpath::measure]\nasync fn setup_multipart_part_readers"),
|
||||
"setup_multipart_part_readers is a module function and must not claim an impl type",
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,8 @@
|
||||
mod storage_api;
|
||||
|
||||
use s3s::dto::ReplicationConfiguration;
|
||||
use std::future::Future;
|
||||
use storage_api::contract_compat::{Error, ObjectInfo, ObjectOptions, ObjectToDelete};
|
||||
use storage_api::replication_compat::{
|
||||
BucketStats, DeletedObjectReplicationInfo, DynReplicationPool, ObjectOpts, REPLICATE_INCOMING_DELETE, ReplicateDecision,
|
||||
ReplicationConfigurationExt, ReplicationDeleteScheduleInput, ReplicationDeleteStateSource, ReplicationObjectBridge,
|
||||
@@ -34,6 +36,8 @@ fn type_name_unsized<T: ?Sized>() -> &'static str {
|
||||
|
||||
fn assert_replication_config_ext<T: ReplicationConfigurationExt>() {}
|
||||
|
||||
fn assert_strict_delete_future<F: Future<Output = Result<ReplicateDecision, Error>>>(_: &F) {}
|
||||
|
||||
#[test]
|
||||
fn replication_facade_exports_config_extension_contract() {
|
||||
assert_replication_config_ext::<ReplicationConfiguration>();
|
||||
@@ -58,6 +62,13 @@ fn replication_facade_exports_runtime_and_dto_types() {
|
||||
assert!(type_name::<DeletedObjectReplicationInfo>().contains("DeletedObjectReplicationInfo"));
|
||||
assert!(type_name::<ReplicationObjectBridge>().contains("ReplicationObjectBridge"));
|
||||
assert!(type_name_unsized::<DynReplicationPool>().contains("ReplicationPoolTrait"));
|
||||
|
||||
let object = ObjectToDelete::default();
|
||||
let source = ObjectInfo::default();
|
||||
let opts = ObjectOptions::default();
|
||||
let future = ReplicationObjectBridge::check_delete_strict("bucket", &object, &source, &opts, None);
|
||||
assert_strict_delete_future(&future);
|
||||
assert!(!std::any::type_name_of_val(&future).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+239
-30
@@ -41,7 +41,7 @@ use rustfs_policy::policy::Args;
|
||||
use rustfs_policy::policy::opa;
|
||||
use rustfs_policy::policy::{Policy, PolicyDoc, iam_policy_claim_name_sa, policy_needs_existing_object_tag_for_args};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use time::OffsetDateTime;
|
||||
@@ -61,10 +61,51 @@ const VERIFIED_FEDERATED_POLICY_CLAIM: &str = "x-rustfs-internal-federated-polic
|
||||
const FEDERATED_POLICY_BOUNDARY_CLAIM: &str = "x-rustfs-internal-federated-boundary";
|
||||
pub(crate) const SITE_REPLICATOR_CLAIM: &str = "site-replicator";
|
||||
|
||||
static POLICY_PLUGIN_CLIENT: OnceLock<Arc<RwLock<Option<rustfs_policy::policy::opa::AuthZPlugin>>>> = OnceLock::new();
|
||||
#[derive(Clone)]
|
||||
enum PolicyPluginState {
|
||||
Disabled,
|
||||
Initializing,
|
||||
Ready(opa::AuthZPlugin),
|
||||
Failed,
|
||||
}
|
||||
|
||||
fn get_policy_plugin_client() -> Arc<RwLock<Option<rustfs_policy::policy::opa::AuthZPlugin>>> {
|
||||
POLICY_PLUGIN_CLIENT.get_or_init(|| Arc::new(RwLock::new(None))).clone()
|
||||
static POLICY_PLUGIN_STATE: OnceLock<Arc<RwLock<PolicyPluginState>>> = OnceLock::new();
|
||||
|
||||
fn get_policy_plugin_state() -> Arc<RwLock<PolicyPluginState>> {
|
||||
POLICY_PLUGIN_STATE
|
||||
.get_or_init(|| {
|
||||
let configured = opa::is_configured();
|
||||
let state = Arc::new(RwLock::new(if configured {
|
||||
PolicyPluginState::Initializing
|
||||
} else {
|
||||
PolicyPluginState::Disabled
|
||||
}));
|
||||
if configured {
|
||||
let state = Arc::clone(&state);
|
||||
tokio::spawn(async move {
|
||||
let next_state = match opa::lookup_config().await {
|
||||
Ok(conf) if conf.enable() => {
|
||||
info!("OPA plugin enabled");
|
||||
PolicyPluginState::Ready(opa::AuthZPlugin::new(conf))
|
||||
}
|
||||
Ok(_) => PolicyPluginState::Failed,
|
||||
Err(e) => {
|
||||
error!(
|
||||
component = "iam",
|
||||
subsystem = "policy_plugin",
|
||||
result = "configuration_load_failed",
|
||||
error_kind = e.kind(),
|
||||
"OPA plugin configuration load failed"
|
||||
);
|
||||
PolicyPluginState::Failed
|
||||
}
|
||||
};
|
||||
*state.write().await = next_state;
|
||||
});
|
||||
}
|
||||
state
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub struct IamSys<T> {
|
||||
@@ -173,19 +214,7 @@ impl<T: Store> IamSys<T> {
|
||||
/// # Returns
|
||||
/// A new instance of IamSys
|
||||
pub fn new(store: Arc<IamCache<T>>) -> Self {
|
||||
tokio::spawn(async move {
|
||||
match opa::lookup_config().await {
|
||||
Ok(conf) => {
|
||||
if conf.enable() {
|
||||
Self::set_policy_plugin_client(opa::AuthZPlugin::new(conf)).await;
|
||||
info!("OPA plugin enabled");
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Error loading OPA configuration err:{}", e);
|
||||
}
|
||||
};
|
||||
});
|
||||
get_policy_plugin_state();
|
||||
|
||||
Self {
|
||||
store,
|
||||
@@ -206,15 +235,22 @@ impl<T: Store> IamSys<T> {
|
||||
}
|
||||
|
||||
pub async fn set_policy_plugin_client(client: rustfs_policy::policy::opa::AuthZPlugin) {
|
||||
let policy_plugin_client = get_policy_plugin_client();
|
||||
let mut guard = policy_plugin_client.write().await;
|
||||
*guard = Some(client);
|
||||
let policy_plugin_state = get_policy_plugin_state();
|
||||
let mut guard = policy_plugin_state.write().await;
|
||||
*guard = PolicyPluginState::Ready(client);
|
||||
}
|
||||
|
||||
pub async fn get_policy_plugin_client() -> Option<rustfs_policy::policy::opa::AuthZPlugin> {
|
||||
let policy_plugin_client = get_policy_plugin_client();
|
||||
let guard = policy_plugin_client.read().await;
|
||||
guard.clone()
|
||||
let policy_plugin_state = get_policy_plugin_state();
|
||||
let guard = policy_plugin_state.read().await;
|
||||
match &*guard {
|
||||
PolicyPluginState::Ready(client) => Some(client.clone()),
|
||||
PolicyPluginState::Disabled | PolicyPluginState::Initializing | PolicyPluginState::Failed => None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn policy_plugin_state() -> PolicyPluginState {
|
||||
get_policy_plugin_state().read().await.clone()
|
||||
}
|
||||
|
||||
pub async fn load_group(&self, name: &str) -> Result<()> {
|
||||
@@ -1060,11 +1096,20 @@ impl<T: Store> IamSys<T> {
|
||||
};
|
||||
}
|
||||
|
||||
if Self::get_policy_plugin_client().await.is_some() {
|
||||
return PreparedIamAuth {
|
||||
needs_existing_object_tag: false,
|
||||
mode: PreparedIamMode::Opa,
|
||||
};
|
||||
match Self::policy_plugin_state().await {
|
||||
PolicyPluginState::Ready(_) => {
|
||||
return PreparedIamAuth {
|
||||
needs_existing_object_tag: false,
|
||||
mode: PreparedIamMode::Opa,
|
||||
};
|
||||
}
|
||||
PolicyPluginState::Initializing | PolicyPluginState::Failed => {
|
||||
return PreparedIamAuth {
|
||||
needs_existing_object_tag: false,
|
||||
mode: PreparedIamMode::Deny,
|
||||
};
|
||||
}
|
||||
PolicyPluginState::Disabled => {}
|
||||
}
|
||||
|
||||
let Ok((is_svc, parent_user)) = self.is_service_account(args.account).await else {
|
||||
@@ -1163,7 +1208,22 @@ impl<T: Store> IamSys<T> {
|
||||
};
|
||||
}
|
||||
|
||||
let combined_policy = self.get_combined_policy(&policies).await;
|
||||
let (resolved_policies, combined_policy) = self.store.merge_policies(&policies.join(",")).await;
|
||||
if args.deny_only {
|
||||
let resolved_policy_names: HashSet<&str> = resolved_policies
|
||||
.split(',')
|
||||
.filter(|policy_name| !policy_name.trim().is_empty())
|
||||
.collect();
|
||||
if policies
|
||||
.iter()
|
||||
.any(|policy_name| !resolved_policy_names.contains(policy_name.as_str()))
|
||||
{
|
||||
return PreparedIamAuth {
|
||||
needs_existing_object_tag: false,
|
||||
mode: PreparedIamMode::Deny,
|
||||
};
|
||||
}
|
||||
}
|
||||
PreparedIamAuth {
|
||||
needs_existing_object_tag: policy_needs_existing_object_tag_for_args(&combined_policy, args).await,
|
||||
mode: PreparedIamMode::Regular { combined_policy },
|
||||
@@ -1703,7 +1763,7 @@ mod tests {
|
||||
fn deprecated_list_polices_api_is_available() {
|
||||
let _ = IamSys::<StsTestMockStore>::list_polices;
|
||||
}
|
||||
use rustfs_policy::policy::action::{Action, AdminAction, S3Action};
|
||||
use rustfs_policy::policy::action::{Action, AdminAction, S3Action, StsAction};
|
||||
use rustfs_policy::policy::policy_uses_existing_object_tag_conditions;
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
@@ -3309,6 +3369,155 @@ mod tests {
|
||||
assert!(!iam_sys.eval_prepared(&prepared, &args).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn regular_deny_only_rejects_unresolved_mapped_policy() {
|
||||
let iam_sys = test_iam_sys().await;
|
||||
let user = "regular-unresolved-policy";
|
||||
let identity = UserIdentity::from(Credentials {
|
||||
access_key: user.to_string(),
|
||||
secret_key: "longenoughsecret".to_string(),
|
||||
status: ACCOUNT_ON.to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
iam_sys.store.cache.with_write_lock(|cache| {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
cache.add_or_update_user(user, &identity, now);
|
||||
cache.add_or_update_user_policy(user, &MappedPolicy::new("readwrite,missing-policy"), now);
|
||||
});
|
||||
|
||||
let groups = None;
|
||||
let claims = HashMap::new();
|
||||
let conditions = HashMap::new();
|
||||
let args = Args {
|
||||
account: user,
|
||||
groups: &groups,
|
||||
action: Action::StsAction(StsAction::AssumeRoleAction),
|
||||
bucket: "",
|
||||
conditions: &conditions,
|
||||
is_owner: false,
|
||||
object: "",
|
||||
claims: &claims,
|
||||
deny_only: true,
|
||||
};
|
||||
|
||||
let prepared = iam_sys.prepare_regular_auth(&args).await;
|
||||
assert!(matches!(prepared.mode, PreparedIamMode::Deny));
|
||||
assert!(
|
||||
!iam_sys.eval_prepared(&prepared, &args).await,
|
||||
"deny-only evaluation must fail closed when a mapped policy document is unresolved"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn regular_full_evaluation_keeps_resolved_part_of_partial_mapping() {
|
||||
let iam_sys = test_iam_sys().await;
|
||||
let user = "regular-partial-policy";
|
||||
let identity = UserIdentity::from(Credentials {
|
||||
access_key: user.to_string(),
|
||||
secret_key: "longenoughsecret".to_string(),
|
||||
status: ACCOUNT_ON.to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
iam_sys.store.cache.with_write_lock(|cache| {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
cache.add_or_update_user(user, &identity, now);
|
||||
cache.add_or_update_user_policy(user, &MappedPolicy::new("readwrite,missing-policy"), now);
|
||||
});
|
||||
|
||||
let groups = None;
|
||||
let claims = HashMap::new();
|
||||
let conditions = HashMap::new();
|
||||
let args = Args {
|
||||
account: user,
|
||||
groups: &groups,
|
||||
action: Action::S3Action(S3Action::GetObjectAction),
|
||||
bucket: "bucket",
|
||||
conditions: &conditions,
|
||||
is_owner: false,
|
||||
object: "object",
|
||||
claims: &claims,
|
||||
deny_only: false,
|
||||
};
|
||||
|
||||
let prepared = iam_sys.prepare_regular_auth(&args).await;
|
||||
assert!(matches!(prepared.mode, PreparedIamMode::Regular { .. }));
|
||||
assert!(
|
||||
iam_sys.eval_prepared(&prepared, &args).await,
|
||||
"full evaluation must preserve the historical partial-resolution behavior"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn regular_deny_only_honors_group_derived_explicit_deny() {
|
||||
let iam_sys = test_iam_sys().await;
|
||||
let deny_policy =
|
||||
Policy::parse_config(br#"{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":["sts:AssumeRole"]}]}"#)
|
||||
.expect("group deny policy should parse");
|
||||
let now = OffsetDateTime::now_utc();
|
||||
iam_sys
|
||||
.store
|
||||
.cache
|
||||
.add_or_update_policy_doc("deny-assume-role", &PolicyDoc::new(deny_policy), now);
|
||||
iam_sys
|
||||
.store
|
||||
.cache
|
||||
.add_or_update_group_policy("testgroup", &MappedPolicy::new("deny-assume-role"), now);
|
||||
|
||||
let groups = Some(vec!["testgroup".to_string()]);
|
||||
let claims = HashMap::new();
|
||||
let conditions = HashMap::new();
|
||||
let args = Args {
|
||||
account: "sts-fallback-test-parent",
|
||||
groups: &groups,
|
||||
action: Action::StsAction(StsAction::AssumeRoleAction),
|
||||
bucket: "",
|
||||
conditions: &conditions,
|
||||
is_owner: false,
|
||||
object: "",
|
||||
claims: &claims,
|
||||
deny_only: true,
|
||||
};
|
||||
|
||||
let prepared = iam_sys.prepare_regular_auth(&args).await;
|
||||
assert!(matches!(prepared.mode, PreparedIamMode::Regular { .. }));
|
||||
assert!(
|
||||
!iam_sys.eval_prepared(&prepared, &args).await,
|
||||
"group-derived explicit Deny must remain authoritative"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn regular_deny_only_rejects_unresolved_group_mapping() {
|
||||
let iam_sys = test_iam_sys().await;
|
||||
iam_sys.store.cache.add_or_update_group_policy(
|
||||
"testgroup",
|
||||
&MappedPolicy::new("readwrite,missing-policy"),
|
||||
OffsetDateTime::now_utc(),
|
||||
);
|
||||
|
||||
let groups = Some(vec!["testgroup".to_string()]);
|
||||
let claims = HashMap::new();
|
||||
let conditions = HashMap::new();
|
||||
let args = Args {
|
||||
account: "sts-fallback-test-parent",
|
||||
groups: &groups,
|
||||
action: Action::StsAction(StsAction::AssumeRoleAction),
|
||||
bucket: "",
|
||||
conditions: &conditions,
|
||||
is_owner: false,
|
||||
object: "",
|
||||
claims: &claims,
|
||||
deny_only: true,
|
||||
};
|
||||
|
||||
let prepared = iam_sys.prepare_regular_auth(&args).await;
|
||||
assert!(matches!(prepared.mode, PreparedIamMode::Deny));
|
||||
assert!(
|
||||
!iam_sys.eval_prepared(&prepared, &args).await,
|
||||
"deny-only evaluation must fail closed for an unresolved group-derived mapping"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_sts_claim_policy_ignores_unsafe_and_missing_policy_names() {
|
||||
let store = StsTestMockStore::new(true);
|
||||
|
||||
@@ -49,7 +49,10 @@
|
||||
#[macro_use]
|
||||
extern crate metrics;
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
/// Global switch for detailed per-stage PUT metrics (path label, stage durations).
|
||||
/// When `false`, `record_put_object_path` and `record_put_object_stage_duration`
|
||||
@@ -269,6 +272,12 @@ pub use collector::MetricsCollector;
|
||||
pub use performance::PerformanceMetrics;
|
||||
|
||||
static EC_ENCODE_INFLIGHT_BYTES: AtomicU64 = AtomicU64::new(0);
|
||||
static EC_ENCODE_PRODUCER_BYTES_CURRENT: AtomicU64 = AtomicU64::new(0);
|
||||
static EC_ENCODE_PRODUCER_BYTES_PEAK: AtomicU64 = AtomicU64::new(0);
|
||||
static EC_ENCODE_QUEUE_BYTES_PEAK: AtomicU64 = AtomicU64::new(0);
|
||||
static EC_ENCODE_WRITER_BYTES_CURRENT: AtomicU64 = AtomicU64::new(0);
|
||||
static EC_ENCODE_WRITER_BYTES_PEAK: AtomicU64 = AtomicU64::new(0);
|
||||
static EC_ENCODE_PEAK_PUBLISH_LOCK: Mutex<()> = Mutex::new(());
|
||||
static GET_OBJECT_BUFFERED_BYTES: AtomicU64 = AtomicU64::new(0);
|
||||
const SHARD_READ_COST_LOCAL: &str = "local";
|
||||
const SHARD_READ_COST_REMOTE: &str = "remote";
|
||||
@@ -313,6 +322,49 @@ fn saturating_sub_atomic(counter: &AtomicU64, bytes: u64) -> u64 {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn update_peak_atomic(counter: &AtomicU64, value: u64) -> Option<u64> {
|
||||
let mut peak = counter.load(Ordering::Relaxed);
|
||||
loop {
|
||||
if value <= peak {
|
||||
return None;
|
||||
}
|
||||
match counter.compare_exchange_weak(peak, value, Ordering::Relaxed, Ordering::Relaxed) {
|
||||
Ok(_) => return Some(value),
|
||||
Err(actual) => peak = actual,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum EcEncodePeakMetric {
|
||||
Producer,
|
||||
Queue,
|
||||
Writer,
|
||||
}
|
||||
|
||||
fn publish_ec_encode_peak_with(counter: &AtomicU64, value: u64, before_publish_lock: impl FnOnce(), set_gauge: impl FnOnce(f64)) {
|
||||
if update_peak_atomic(counter, value).is_none() {
|
||||
return;
|
||||
}
|
||||
before_publish_lock();
|
||||
let _guard = EC_ENCODE_PEAK_PUBLISH_LOCK.lock().unwrap_or_else(|error| error.into_inner());
|
||||
set_gauge(counter.load(Ordering::Relaxed) as f64);
|
||||
}
|
||||
|
||||
fn publish_ec_encode_peak(counter: &AtomicU64, metric: EcEncodePeakMetric, value: u64) {
|
||||
publish_ec_encode_peak_with(
|
||||
counter,
|
||||
value,
|
||||
|| {},
|
||||
|peak| match metric {
|
||||
EcEncodePeakMetric::Producer => gauge_set_cached!("rustfs_ec_encode_producer_bytes_peak", peak),
|
||||
EcEncodePeakMetric::Queue => gauge_set_cached!("rustfs_ec_encode_queue_bytes_peak", peak),
|
||||
EcEncodePeakMetric::Writer => gauge_set_cached!("rustfs_ec_encode_writer_bytes_peak", peak),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn usize_to_f64(value: usize) -> f64 {
|
||||
value as f64
|
||||
@@ -2195,18 +2247,25 @@ pub fn record_allocator_memory_observation(backend: &'static str, observation: A
|
||||
}
|
||||
}
|
||||
|
||||
/// Track encoded bytes currently queued between erasure encode and disk writers.
|
||||
/// Track encoded bytes in the queue hand-off between erasure encode and disk writers.
|
||||
///
|
||||
/// This is queue occupancy, not a per-request or process-RSS memory limit. The
|
||||
/// erasure encoder settles it on failed/cancelled sends, receiver drop, and
|
||||
/// consumer hand-off before shard writes begin.
|
||||
#[inline(always)]
|
||||
pub fn add_ec_encode_inflight_bytes(bytes: usize) {
|
||||
let next = EC_ENCODE_INFLIGHT_BYTES.fetch_add(bytes as u64, Ordering::Relaxed) + bytes as u64;
|
||||
gauge!("rustfs_ec_encode_inflight_bytes_current").set(next as f64);
|
||||
gauge_set_cached!("rustfs_ec_encode_inflight_bytes_current", next as f64);
|
||||
if put_stage_metrics_enabled() {
|
||||
publish_ec_encode_peak(&EC_ENCODE_QUEUE_BYTES_PEAK, EcEncodePeakMetric::Queue, next);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove encoded bytes from the tracked erasure encode in-flight gauge.
|
||||
#[inline(always)]
|
||||
pub fn remove_ec_encode_inflight_bytes(bytes: usize) {
|
||||
let next = saturating_sub_atomic(&EC_ENCODE_INFLIGHT_BYTES, bytes as u64);
|
||||
gauge!("rustfs_ec_encode_inflight_bytes_current").set(next as f64);
|
||||
gauge_set_cached!("rustfs_ec_encode_inflight_bytes_current", next as f64);
|
||||
}
|
||||
|
||||
/// Return the current tracked EC encode in-flight bytes.
|
||||
@@ -2215,6 +2274,109 @@ pub fn current_ec_encode_inflight_bytes() -> u64 {
|
||||
EC_ENCODE_INFLIGHT_BYTES.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Tracks encoded payload bytes held before queue hand-off or during shard writes.
|
||||
///
|
||||
/// Each guard contributes to a process-wide stage total until it is dropped. The
|
||||
/// reported peak therefore includes concurrent PUTs, but excludes reader,
|
||||
/// allocator, and transport buffers; it is not a per-PUT or process-RSS limit.
|
||||
pub struct EcEncodePayloadStageGuard {
|
||||
counter: &'static AtomicU64,
|
||||
bytes: u64,
|
||||
enabled: bool,
|
||||
current_metric: EcEncodePeakMetric,
|
||||
}
|
||||
|
||||
impl Drop for EcEncodePayloadStageGuard {
|
||||
fn drop(&mut self) {
|
||||
if !self.enabled {
|
||||
return;
|
||||
}
|
||||
let next = saturating_sub_atomic(self.counter, self.bytes);
|
||||
match self.current_metric {
|
||||
EcEncodePeakMetric::Producer => gauge_set_cached!("rustfs_ec_encode_producer_bytes_current", next as f64),
|
||||
EcEncodePeakMetric::Queue => unreachable!("queue bytes use their own ownership guard"),
|
||||
EcEncodePeakMetric::Writer => gauge_set_cached!("rustfs_ec_encode_writer_bytes_current", next as f64),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn track_ec_encode_payload_stage(
|
||||
bytes: usize,
|
||||
counter: &'static AtomicU64,
|
||||
peak: &'static AtomicU64,
|
||||
metric: EcEncodePeakMetric,
|
||||
) -> EcEncodePayloadStageGuard {
|
||||
let enabled = put_stage_metrics_enabled();
|
||||
let bytes = bytes as u64;
|
||||
if enabled {
|
||||
let next = counter.fetch_add(bytes, Ordering::Relaxed) + bytes;
|
||||
match metric {
|
||||
EcEncodePeakMetric::Producer => gauge_set_cached!("rustfs_ec_encode_producer_bytes_current", next as f64),
|
||||
EcEncodePeakMetric::Queue => unreachable!("queue bytes use their own ownership guard"),
|
||||
EcEncodePeakMetric::Writer => gauge_set_cached!("rustfs_ec_encode_writer_bytes_current", next as f64),
|
||||
}
|
||||
publish_ec_encode_peak(peak, metric, next);
|
||||
}
|
||||
EcEncodePayloadStageGuard {
|
||||
counter,
|
||||
bytes,
|
||||
enabled,
|
||||
current_metric: metric,
|
||||
}
|
||||
}
|
||||
|
||||
/// Track encoded producer payload bytes until queue hand-off completes.
|
||||
#[inline(always)]
|
||||
pub fn track_ec_encode_producer_bytes(bytes: usize) -> EcEncodePayloadStageGuard {
|
||||
track_ec_encode_payload_stage(
|
||||
bytes,
|
||||
&EC_ENCODE_PRODUCER_BYTES_CURRENT,
|
||||
&EC_ENCODE_PRODUCER_BYTES_PEAK,
|
||||
EcEncodePeakMetric::Producer,
|
||||
)
|
||||
}
|
||||
|
||||
/// Track encoded payload bytes while shard writers own the batch.
|
||||
#[inline(always)]
|
||||
pub fn track_ec_encode_writer_bytes(bytes: usize) -> EcEncodePayloadStageGuard {
|
||||
track_ec_encode_payload_stage(
|
||||
bytes,
|
||||
&EC_ENCODE_WRITER_BYTES_CURRENT,
|
||||
&EC_ENCODE_WRITER_BYTES_PEAK,
|
||||
EcEncodePeakMetric::Writer,
|
||||
)
|
||||
}
|
||||
|
||||
/// Return the process-lifetime high-water mark of encoded producer payload bytes.
|
||||
#[inline(always)]
|
||||
pub fn current_ec_encode_producer_bytes_peak() -> u64 {
|
||||
EC_ENCODE_PRODUCER_BYTES_PEAK.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Return the current process-wide encoded producer payload bytes.
|
||||
#[inline(always)]
|
||||
pub fn current_ec_encode_producer_bytes() -> u64 {
|
||||
EC_ENCODE_PRODUCER_BYTES_CURRENT.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Return the process-lifetime high-water mark of encoded queue payload bytes.
|
||||
#[inline(always)]
|
||||
pub fn current_ec_encode_queue_bytes_peak() -> u64 {
|
||||
EC_ENCODE_QUEUE_BYTES_PEAK.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Return the process-lifetime high-water mark of encoded writer payload bytes.
|
||||
#[inline(always)]
|
||||
pub fn current_ec_encode_writer_bytes_peak() -> u64 {
|
||||
EC_ENCODE_WRITER_BYTES_PEAK.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Return the current process-wide encoded writer payload bytes.
|
||||
#[inline(always)]
|
||||
pub fn current_ec_encode_writer_bytes() -> u64 {
|
||||
EC_ENCODE_WRITER_BYTES_CURRENT.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Track whole-object buffering on the GET path.
|
||||
#[inline(always)]
|
||||
pub fn track_get_object_buffered_bytes(bytes: usize) -> Option<MemoryGaugeGuard> {
|
||||
@@ -2381,7 +2543,9 @@ pub fn record_io_latency_p99(latency_ms: f64) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Mutex;
|
||||
use metrics_util::MetricKind;
|
||||
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
|
||||
use std::sync::{Arc, Barrier, Mutex};
|
||||
|
||||
// Serialize tests that mutate the process-global PUT_STAGE_METRICS_ENABLED flag.
|
||||
static METRICS_FLAG_LOCK: Mutex<()> = Mutex::new(());
|
||||
@@ -2834,6 +2998,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_ec_encode_inflight_bytes_tracking() {
|
||||
let _guard = METRICS_FLAG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
set_put_stage_metrics_enabled(true);
|
||||
let queue_peak_before = current_ec_encode_queue_bytes_peak();
|
||||
EC_ENCODE_INFLIGHT_BYTES.store(0, Ordering::Relaxed);
|
||||
add_ec_encode_inflight_bytes(1024);
|
||||
add_ec_encode_inflight_bytes(2048);
|
||||
@@ -2841,6 +3008,188 @@ mod tests {
|
||||
remove_ec_encode_inflight_bytes(2048);
|
||||
remove_ec_encode_inflight_bytes(4096);
|
||||
assert_eq!(current_ec_encode_inflight_bytes(), 0);
|
||||
assert!(
|
||||
current_ec_encode_queue_bytes_peak() >= queue_peak_before.max(3072),
|
||||
"queue peak must retain the largest observed queue occupancy"
|
||||
);
|
||||
set_put_stage_metrics_enabled(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ec_encode_producer_and_writer_stage_guards_aggregate_and_settle() {
|
||||
let _guard = METRICS_FLAG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
set_put_stage_metrics_enabled(true);
|
||||
|
||||
let producer_bytes = 1024;
|
||||
let producer_first = track_ec_encode_producer_bytes(producer_bytes);
|
||||
let producer_second = track_ec_encode_producer_bytes(producer_bytes);
|
||||
assert_eq!(current_ec_encode_producer_bytes(), 2048);
|
||||
assert!(
|
||||
current_ec_encode_producer_bytes_peak() >= 2048,
|
||||
"producer peak must include simultaneous stage ownership"
|
||||
);
|
||||
drop((producer_first, producer_second));
|
||||
assert_eq!(current_ec_encode_producer_bytes(), 0);
|
||||
|
||||
let writer_bytes = 2048;
|
||||
let writer_first = track_ec_encode_writer_bytes(writer_bytes);
|
||||
let writer_second = track_ec_encode_writer_bytes(writer_bytes);
|
||||
assert_eq!(current_ec_encode_writer_bytes(), 4096);
|
||||
assert!(
|
||||
current_ec_encode_writer_bytes_peak() >= 4096,
|
||||
"writer peak must include simultaneous stage ownership"
|
||||
);
|
||||
drop((writer_first, writer_second));
|
||||
assert_eq!(current_ec_encode_writer_bytes(), 0);
|
||||
|
||||
set_put_stage_metrics_enabled(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ec_encode_payload_stage_guards_are_noop_when_disabled() {
|
||||
let _guard = METRICS_FLAG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
set_put_stage_metrics_enabled(false);
|
||||
|
||||
let producer_current_before = current_ec_encode_producer_bytes();
|
||||
let producer_peak_before = current_ec_encode_producer_bytes_peak();
|
||||
let writer_current_before = current_ec_encode_writer_bytes();
|
||||
let writer_peak_before = current_ec_encode_writer_bytes_peak();
|
||||
|
||||
let producer = track_ec_encode_producer_bytes(1024);
|
||||
let writer = track_ec_encode_writer_bytes(2048);
|
||||
assert_eq!(current_ec_encode_producer_bytes(), producer_current_before);
|
||||
assert_eq!(current_ec_encode_producer_bytes_peak(), producer_peak_before);
|
||||
assert_eq!(current_ec_encode_writer_bytes(), writer_current_before);
|
||||
assert_eq!(current_ec_encode_writer_bytes_peak(), writer_peak_before);
|
||||
|
||||
drop((producer, writer));
|
||||
assert_eq!(current_ec_encode_producer_bytes(), producer_current_before);
|
||||
assert_eq!(current_ec_encode_producer_bytes_peak(), producer_peak_before);
|
||||
assert_eq!(current_ec_encode_writer_bytes(), writer_current_before);
|
||||
assert_eq!(current_ec_encode_writer_bytes_peak(), writer_peak_before);
|
||||
}
|
||||
|
||||
fn assert_concurrent_ec_encode_stage_guards_aggregate_and_settle(
|
||||
track: fn(usize) -> EcEncodePayloadStageGuard,
|
||||
current: fn() -> u64,
|
||||
peak: fn() -> u64,
|
||||
) {
|
||||
const WORKERS: usize = 4;
|
||||
const STAGE_BYTES: usize = 1536;
|
||||
|
||||
let current_before = current();
|
||||
let peak_before = peak();
|
||||
let entered = Arc::new(Barrier::new(WORKERS + 1));
|
||||
let release = Arc::new(Barrier::new(WORKERS + 1));
|
||||
let mut workers = Vec::with_capacity(WORKERS);
|
||||
|
||||
for _ in 0..WORKERS {
|
||||
let entered = Arc::clone(&entered);
|
||||
let release = Arc::clone(&release);
|
||||
workers.push(std::thread::spawn(move || {
|
||||
let stage = track(STAGE_BYTES);
|
||||
entered.wait();
|
||||
release.wait();
|
||||
drop(stage);
|
||||
}));
|
||||
}
|
||||
|
||||
entered.wait();
|
||||
let expected_delta = u64::try_from(WORKERS).expect("worker count should fit in u64")
|
||||
* u64::try_from(STAGE_BYTES).expect("stage bytes should fit in u64");
|
||||
assert_eq!(current(), current_before + expected_delta);
|
||||
assert!(
|
||||
peak() >= peak_before.max(current_before + expected_delta),
|
||||
"stage peak must expose process-wide concurrent ownership"
|
||||
);
|
||||
|
||||
release.wait();
|
||||
for worker in workers {
|
||||
worker.join().expect("stage worker should not panic");
|
||||
}
|
||||
assert_eq!(current(), current_before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ec_encode_payload_stage_guards_track_concurrent_ownership() {
|
||||
let _guard = METRICS_FLAG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
set_put_stage_metrics_enabled(true);
|
||||
|
||||
assert_concurrent_ec_encode_stage_guards_aggregate_and_settle(
|
||||
track_ec_encode_producer_bytes,
|
||||
current_ec_encode_producer_bytes,
|
||||
current_ec_encode_producer_bytes_peak,
|
||||
);
|
||||
assert_concurrent_ec_encode_stage_guards_aggregate_and_settle(
|
||||
track_ec_encode_writer_bytes,
|
||||
current_ec_encode_writer_bytes,
|
||||
current_ec_encode_writer_bytes_peak,
|
||||
);
|
||||
|
||||
set_put_stage_metrics_enabled(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ec_encode_producer_peak_exports_the_high_water_mark() {
|
||||
let _guard = METRICS_FLAG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
assert_eq!(current_ec_encode_producer_bytes(), 0, "test must start without producer stage ownership");
|
||||
let previous_peak = EC_ENCODE_PRODUCER_BYTES_PEAK.swap(0, Ordering::Relaxed);
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
set_put_stage_metrics_enabled(true);
|
||||
let first = track_ec_encode_producer_bytes(1024);
|
||||
let second = track_ec_encode_producer_bytes(2048);
|
||||
drop((first, second));
|
||||
set_put_stage_metrics_enabled(false);
|
||||
});
|
||||
|
||||
let exported_peak = snapshotter
|
||||
.snapshot()
|
||||
.into_vec()
|
||||
.into_iter()
|
||||
.find_map(|(composite, _, _, value)| {
|
||||
(composite.kind() == MetricKind::Gauge && composite.key().name() == "rustfs_ec_encode_producer_bytes_peak")
|
||||
.then_some(value)
|
||||
});
|
||||
assert!(
|
||||
matches!(exported_peak, Some(DebugValue::Gauge(value)) if value.0 == 3072.0),
|
||||
"exported producer peak must retain the aggregate high-water mark"
|
||||
);
|
||||
EC_ENCODE_PRODUCER_BYTES_PEAK.fetch_max(previous_peak, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ec_encode_peak_publish_does_not_regress_after_out_of_order_cas() {
|
||||
let _guard = METRICS_FLAG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let peak = Arc::new(AtomicU64::new(0));
|
||||
let exported = Arc::new(AtomicU64::new(0));
|
||||
let first_ready = Arc::new(Barrier::new(2));
|
||||
let release_first = Arc::new(Barrier::new(2));
|
||||
let first_peak = Arc::clone(&peak);
|
||||
let first_exported = Arc::clone(&exported);
|
||||
let first_ready_for_thread = Arc::clone(&first_ready);
|
||||
let release_first_for_thread = Arc::clone(&release_first);
|
||||
|
||||
let first = std::thread::spawn(move || {
|
||||
publish_ec_encode_peak_with(
|
||||
&first_peak,
|
||||
10,
|
||||
|| {
|
||||
first_ready_for_thread.wait();
|
||||
release_first_for_thread.wait();
|
||||
},
|
||||
|value| first_exported.store(value as u64, Ordering::Relaxed),
|
||||
);
|
||||
});
|
||||
first_ready.wait();
|
||||
publish_ec_encode_peak_with(&peak, 20, || {}, |value| exported.store(value as u64, Ordering::Relaxed));
|
||||
release_first.wait();
|
||||
first.join().expect("first publisher should not panic");
|
||||
|
||||
assert_eq!(peak.load(Ordering::Relaxed), 20);
|
||||
assert_eq!(exported.load(Ordering::Relaxed), 20, "late publisher must reload the high-water mark");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -64,6 +64,10 @@ md-5 = { workspace = true }
|
||||
arc-swap = { workspace = true }
|
||||
rustfs-utils = { workspace = true }
|
||||
rustfs-security-governance = { workspace = true }
|
||||
# `EventName` for KMS audit records. A leaf crate with no rustfs dependencies,
|
||||
# so the audit sink can live outside this crate without a second, drifting
|
||||
# copy of the event vocabulary.
|
||||
rustfs-s3-types = { workspace = true }
|
||||
|
||||
# HTTP client for Vault
|
||||
reqwest = { workspace = true }
|
||||
@@ -73,6 +77,16 @@ vaultrs = { workspace = true }
|
||||
rustify = { workspace = true }
|
||||
tokio-util = { workspace = true }
|
||||
|
||||
# AWS KMS backend. Credentials come from the standard aws-config provider chain
|
||||
# (environment, shared profile, IMDS/container roles); this crate never handles
|
||||
# AWS credential material itself.
|
||||
aws-config = { workspace = true }
|
||||
aws-sdk-kms = { workspace = true, default-features = false, features = ["default-https-client", "rt-tokio"] }
|
||||
# SdkError variants and raw HTTP status are needed to classify AWS failures for
|
||||
# the operation policy's retry decisions.
|
||||
aws-smithy-runtime-api = { workspace = true, features = ["http-1x"] }
|
||||
aws-smithy-types = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow = { workspace = true }
|
||||
# Debugging recorder for asserting emitted metrics in tests.
|
||||
@@ -82,6 +96,9 @@ tempfile = { workspace = true }
|
||||
temp-env = { workspace = true }
|
||||
# "net" backs the scripted loopback Vault used by the policy wiring tests.
|
||||
tokio = { workspace = true, features = ["net", "test-util"] }
|
||||
# Replays canned AWS KMS HTTP exchanges so the AWS backend tests stay offline.
|
||||
aws-smithy-http-client = { workspace = true, default-features = false, features = ["test-util"] }
|
||||
http = { workspace = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
// 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.
|
||||
|
||||
//! Operator entry point for the KMS disaster-recovery drill.
|
||||
//!
|
||||
//! Runs one rehearsal inside a scratch workspace and writes the evidence
|
||||
//! bundle. Everything it touches lives under that workspace: it never reads,
|
||||
//! writes, or restores into a running deployment's key directory. See
|
||||
//! `docs/operations/kms-disaster-recovery-drill.md` for the procedure and for
|
||||
//! how to size the dataset so the measured recovery time transfers.
|
||||
//!
|
||||
//! Exit status is the verdict: 0 when every check held, 1 otherwise, so a
|
||||
//! scheduled drill fails its job instead of quietly filing a bad report.
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
|
||||
use rustfs_kms::backup::{BackupKek, DrillDataset, DrillDisaster, DrillRequest, DrillVerdict, run_local_drill};
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
const ENV_WORKSPACE: &str = "RUSTFS_KMS_DRILL_WORKSPACE";
|
||||
const ENV_DRILL_ID: &str = "RUSTFS_KMS_DRILL_ID";
|
||||
const ENV_DISASTER: &str = "RUSTFS_KMS_DRILL_DISASTER";
|
||||
const ENV_DEPLOYMENT: &str = "RUSTFS_KMS_DRILL_DEPLOYMENT";
|
||||
const ENV_MASTER_KEY: &str = "RUSTFS_KMS_DRILL_MASTER_KEY";
|
||||
const ENV_KEYS: &str = "RUSTFS_KMS_DRILL_KEYS";
|
||||
const ENV_OBJECTS_PER_KEY: &str = "RUSTFS_KMS_DRILL_OBJECTS_PER_KEY";
|
||||
const ENV_OBJECT_BYTES: &str = "RUSTFS_KMS_DRILL_OBJECT_BYTES";
|
||||
const ENV_EVIDENCE: &str = "RUSTFS_KMS_DRILL_EVIDENCE";
|
||||
const ENV_FILE_PERMISSIONS: &str = "RUSTFS_KMS_DRILL_FILE_PERMISSIONS";
|
||||
|
||||
// Deliberately the same names the admin backup API reads: drilling with the
|
||||
// KEK the real backups are sealed under is what proves that KEK is still
|
||||
// retrievable, which is the part of a recovery no bundle can attest to.
|
||||
const ENV_KEK: &str = "RUSTFS_KMS_BACKUP_KEK";
|
||||
const ENV_KEK_ID: &str = "RUSTFS_KMS_BACKUP_KEK_ID";
|
||||
const ENV_KEK_VERSION: &str = "RUSTFS_KMS_BACKUP_KEK_VERSION";
|
||||
|
||||
fn usage() -> String {
|
||||
format!(
|
||||
"KMS disaster-recovery drill.\n\
|
||||
\n\
|
||||
Required:\n \
|
||||
{ENV_WORKSPACE} absolute path to a scratch directory the drill owns\n \
|
||||
{ENV_MASTER_KEY} at-rest master key for the throwaway rehearsal deployment\n \
|
||||
{ENV_KEK} base64 of the 32-byte backup KEK\n \
|
||||
{ENV_KEK_ID} identifier recorded in the bundle manifest\n\
|
||||
\n\
|
||||
Optional:\n \
|
||||
{ENV_KEK_VERSION} backup KEK version (default 1)\n \
|
||||
{ENV_DRILL_ID} drill identifier and key-id prefix (default kms-dr-drill)\n \
|
||||
{ENV_DEPLOYMENT} deployment identity recorded in the bundle (default kms-dr-drill)\n \
|
||||
{ENV_DISASTER} key-directory-lost | master-key-salt-lost | key-record-corrupted\n \
|
||||
{ENV_KEYS} master keys to rehearse with (default 4)\n \
|
||||
{ENV_OBJECTS_PER_KEY} objects sealed per key (default 2)\n \
|
||||
{ENV_OBJECT_BYTES} plaintext bytes per object (default 4096)\n \
|
||||
{ENV_FILE_PERMISSIONS} octal key-file mode (default 600)\n \
|
||||
{ENV_EVIDENCE} evidence output path (default <workspace>/evidence.json)"
|
||||
)
|
||||
}
|
||||
|
||||
fn required(name: &str) -> Result<String, String> {
|
||||
std::env::var(name)
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.ok_or_else(|| format!("{name} is required\n\n{}", usage()))
|
||||
}
|
||||
|
||||
fn optional_usize(name: &str, default: usize) -> Result<usize, String> {
|
||||
match std::env::var(name) {
|
||||
Ok(value) => value
|
||||
.trim()
|
||||
.parse()
|
||||
.map_err(|_| format!("{name} must be an unsigned integer")),
|
||||
Err(_) => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
fn disaster_from_env() -> Result<DrillDisaster, String> {
|
||||
match std::env::var(ENV_DISASTER).ok().as_deref().map(str::trim) {
|
||||
None | Some("") | Some("key-directory-lost") => Ok(DrillDisaster::KeyDirectoryLost),
|
||||
Some("master-key-salt-lost") => Ok(DrillDisaster::MasterKeySaltLost),
|
||||
Some("key-record-corrupted") => Ok(DrillDisaster::KeyRecordCorrupted),
|
||||
Some(other) => Err(format!(
|
||||
"{ENV_DISASTER}={other:?} is not a known disaster; use key-directory-lost, master-key-salt-lost, or key-record-corrupted"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn kek_from_env() -> Result<BackupKek, String> {
|
||||
let raw = Zeroizing::new(required(ENV_KEK)?);
|
||||
let decoded = Zeroizing::new(BASE64.decode(raw.trim()).map_err(|_| format!("{ENV_KEK} must be base64"))?);
|
||||
if decoded.len() != 32 {
|
||||
return Err(format!("{ENV_KEK} must decode to exactly 32 bytes"));
|
||||
}
|
||||
let mut material = [0u8; 32];
|
||||
material.copy_from_slice(&decoded);
|
||||
let version = optional_usize(ENV_KEK_VERSION, 1)?;
|
||||
let version = u32::try_from(version).map_err(|_| format!("{ENV_KEK_VERSION} is out of range"))?;
|
||||
BackupKek::new(required(ENV_KEK_ID)?, version, material).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
async fn run() -> Result<DrillVerdict, String> {
|
||||
let workspace = PathBuf::from(required(ENV_WORKSPACE)?);
|
||||
if !workspace.is_absolute() {
|
||||
return Err(format!("{ENV_WORKSPACE} must be an absolute path"));
|
||||
}
|
||||
let drill_id = std::env::var(ENV_DRILL_ID)
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.unwrap_or_else(|| "kms-dr-drill".to_string());
|
||||
let file_permissions = match std::env::var(ENV_FILE_PERMISSIONS) {
|
||||
Ok(value) => Some(u32::from_str_radix(value.trim(), 8).map_err(|_| format!("{ENV_FILE_PERMISSIONS} must be octal"))?),
|
||||
Err(_) => Some(0o600),
|
||||
};
|
||||
|
||||
let request = DrillRequest {
|
||||
deployment_identity: std::env::var(ENV_DEPLOYMENT)
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.unwrap_or_else(|| drill_id.clone()),
|
||||
drill_id,
|
||||
workspace: workspace.clone(),
|
||||
rustfs_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
// A drill always restores into a target that has observed nothing, so
|
||||
// any generation is monotonic; the number is recorded as evidence of
|
||||
// which snapshot the rehearsal covered.
|
||||
snapshot_generation: 1,
|
||||
dataset: DrillDataset {
|
||||
keys: optional_usize(ENV_KEYS, 4)?,
|
||||
objects_per_key: optional_usize(ENV_OBJECTS_PER_KEY, 2)?,
|
||||
object_bytes: optional_usize(ENV_OBJECT_BYTES, 4096)?,
|
||||
},
|
||||
disaster: disaster_from_env()?,
|
||||
master_key: required(ENV_MASTER_KEY)?,
|
||||
file_permissions,
|
||||
};
|
||||
|
||||
let kek = kek_from_env()?;
|
||||
let evidence = run_local_drill(&kek, &request).await.map_err(|error| error.to_string())?;
|
||||
|
||||
let evidence_path = std::env::var(ENV_EVIDENCE)
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.map_or_else(|| workspace.join("evidence.json"), PathBuf::from);
|
||||
let encoded = evidence.encode().map_err(|error| error.to_string())?;
|
||||
std::fs::write(&evidence_path, &encoded).map_err(|error| format!("cannot write {}: {error}", evidence_path.display()))?;
|
||||
|
||||
eprintln!("verdict: {:?}", evidence.verdict);
|
||||
eprintln!("disaster: {:?}", evidence.disaster);
|
||||
eprintln!(
|
||||
"objects: {}/{} historical objects decrypted after the restore",
|
||||
evidence.envelope_probes.iter().filter(|probe| probe.verified).count(),
|
||||
evidence.envelope_probes.len()
|
||||
);
|
||||
eprintln!("rpo: {} ms of work past the snapshot fence was lost", evidence.rpo.rpo_window_millis);
|
||||
eprintln!("rto: {} ms of recovery work", evidence.rto_millis);
|
||||
for finding in &evidence.findings {
|
||||
eprintln!("finding: {finding}");
|
||||
}
|
||||
eprintln!("evidence: {}", evidence_path.display());
|
||||
|
||||
Ok(evidence.verdict)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExitCode {
|
||||
match run().await {
|
||||
Ok(DrillVerdict::Passed) => ExitCode::SUCCESS,
|
||||
Ok(DrillVerdict::Failed) => ExitCode::FAILURE,
|
||||
Err(message) => {
|
||||
eprintln!("{message}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -227,10 +227,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
// Step 12: Check cache statistics
|
||||
println!("12. Checking cache statistics...");
|
||||
if let Some((hits, misses)) = encryption_service.cache_stats().await {
|
||||
if let Some(stats) = encryption_service.cache_stats().await {
|
||||
println!(" ✓ Cache statistics:");
|
||||
println!(" - Cache hits: {}", hits);
|
||||
println!(" - Cache misses: {}\n", misses);
|
||||
println!(" - Cached entries: {}", stats.entries);
|
||||
println!(" - Cache hits: {}", stats.hits);
|
||||
println!(" - Cache misses: {}", stats.misses);
|
||||
println!(" - Entries evicted: {}\n", stats.evictions);
|
||||
} else {
|
||||
println!(" - Cache is disabled\n");
|
||||
}
|
||||
|
||||
@@ -263,10 +263,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
// Step 12: Check cache statistics
|
||||
println!("12. Checking cache statistics...");
|
||||
if let Some((hits, misses)) = encryption_service.cache_stats().await {
|
||||
if let Some(stats) = encryption_service.cache_stats().await {
|
||||
println!(" ✓ Cache statistics:");
|
||||
println!(" - Cache hits: {}", hits);
|
||||
println!(" - Cache misses: {}\n", misses);
|
||||
println!(" - Cached entries: {}", stats.entries);
|
||||
println!(" - Cache hits: {}", stats.hits);
|
||||
println!(" - Cache misses: {}", stats.misses);
|
||||
println!(" - Entries evicted: {}\n", stats.evictions);
|
||||
} else {
|
||||
println!(" - Cache is disabled\n");
|
||||
}
|
||||
|
||||
+238
-19
@@ -15,9 +15,10 @@
|
||||
//! API types for KMS dynamic configuration
|
||||
|
||||
use crate::config::{
|
||||
BackendConfig, CacheConfig, DEFAULT_VAULT_TRANSIT_METADATA_KEY_PREFIX, DEFAULT_VAULT_TRANSIT_METADATA_KV_MOUNT, KmsBackend,
|
||||
KmsConfig, LocalConfig, StaticConfig, TlsConfig, VaultAuthMethod, VaultConfig, VaultTransitConfig, redacted_secret,
|
||||
redacted_secret_option,
|
||||
AwsKmsConfig, BackendConfig, CacheConfig, DEFAULT_CACHE_TTL, DEFAULT_MAX_CACHED_KEYS,
|
||||
DEFAULT_VAULT_TRANSIT_METADATA_KEY_PREFIX, DEFAULT_VAULT_TRANSIT_METADATA_KV_MOUNT, KmsBackend, KmsConfig, LocalConfig,
|
||||
StaticConfig, TlsConfig, VaultAuthMethod, VaultConfig, VaultTransitConfig, allow_immediate_deletion_from_env,
|
||||
redacted_secret, redacted_secret_option,
|
||||
};
|
||||
use crate::service_manager::KmsServiceStatus;
|
||||
use crate::types::{KeyMetadata, KeyUsage};
|
||||
@@ -165,6 +166,47 @@ pub struct ConfigureStaticKmsRequest {
|
||||
pub allow_insecure_dev_defaults: Option<bool>,
|
||||
}
|
||||
|
||||
/// Request to configure KMS with the AWS KMS backend.
|
||||
///
|
||||
/// Accepts no credential material by design: every node resolves AWS
|
||||
/// credentials through the standard `aws-config` provider chain, so nothing
|
||||
/// secret is submitted here, persisted with the cluster configuration, or
|
||||
/// echoed back by the status API.
|
||||
///
|
||||
/// Keys are not created by this path. The backend refuses caller-named key
|
||||
/// creation because AWS assigns identifiers itself, so `default_key_id` must
|
||||
/// name a key that already exists in AWS, by key id or ARN.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ConfigureAwsKmsRequest {
|
||||
/// AWS region hosting the keys.
|
||||
///
|
||||
/// Mandatory here, unlike the environment-variable path: this
|
||||
/// configuration is persisted once and replayed on every node, so leaving
|
||||
/// the region to each node's ambient provider chain would let nodes
|
||||
/// silently address different regions — and therefore different keys —
|
||||
/// while reporting the same configuration.
|
||||
pub region: String,
|
||||
/// Endpoint override for local emulators and private endpoints. Unset in
|
||||
/// production, where the SDK derives the regional endpoint; a plaintext
|
||||
/// endpoint stays gated behind the development opt-in.
|
||||
pub endpoint_url: Option<String>,
|
||||
/// Default master key ID for auto-encryption, as an AWS key id or ARN
|
||||
pub default_key_id: Option<String>,
|
||||
/// Operation timeout in seconds
|
||||
pub timeout_seconds: Option<u64>,
|
||||
/// Number of retry attempts
|
||||
pub retry_attempts: Option<u32>,
|
||||
/// Enable caching
|
||||
pub enable_cache: Option<bool>,
|
||||
/// Maximum number of keys to cache
|
||||
pub max_cached_keys: Option<usize>,
|
||||
/// Cache TTL in seconds
|
||||
pub cache_ttl_seconds: Option<u64>,
|
||||
/// Allow development-only insecure defaults
|
||||
pub allow_insecure_dev_defaults: Option<bool>,
|
||||
}
|
||||
|
||||
impl Drop for ConfigureStaticKmsRequest {
|
||||
fn drop(&mut self) {
|
||||
use zeroize::Zeroize;
|
||||
@@ -211,6 +253,9 @@ pub enum ConfigureKmsRequest {
|
||||
/// Configure with Static single-key backend
|
||||
#[serde(rename = "Static", alias = "static")]
|
||||
Static(ConfigureStaticKmsRequest),
|
||||
/// Configure with the AWS KMS backend
|
||||
#[serde(rename = "AWS", alias = "AwsKms", alias = "aws", alias = "aws-kms", alias = "aws_kms")]
|
||||
Aws(ConfigureAwsKmsRequest),
|
||||
}
|
||||
|
||||
/// KMS configuration response
|
||||
@@ -418,14 +463,26 @@ pub enum BackendSummary {
|
||||
/// Configured key identifier
|
||||
key_id: String,
|
||||
},
|
||||
/// AWS KMS backend summary
|
||||
Aws {
|
||||
/// Configured region, when pinned instead of resolved by the AWS chain
|
||||
region: Option<String>,
|
||||
/// Endpoint override, when set for an emulator or private endpoint
|
||||
endpoint_url: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<&KmsConfig> for KmsConfigSummary {
|
||||
fn from(config: &KmsConfig) -> Self {
|
||||
// Report the lifetime the cache was built with, not the raw configured
|
||||
// value: an oversized `ttl` is clamped rather than rejected, and this
|
||||
// response is what operators check the cache against.
|
||||
let cache_ttl_seconds = config.cache_config.effective_ttl().as_secs();
|
||||
|
||||
let cache_summary = if config.enable_cache {
|
||||
Some(CacheSummary {
|
||||
max_keys: config.cache_config.max_keys,
|
||||
ttl_seconds: config.cache_config.ttl.as_secs(),
|
||||
ttl_seconds: cache_ttl_seconds,
|
||||
enable_metrics: config.cache_config.enable_metrics,
|
||||
})
|
||||
} else {
|
||||
@@ -467,6 +524,10 @@ impl From<&KmsConfig> for KmsConfigSummary {
|
||||
BackendConfig::Static(static_config) => BackendSummary::Static {
|
||||
key_id: static_config.key_id.clone(),
|
||||
},
|
||||
BackendConfig::Aws(aws_config) => BackendSummary::Aws {
|
||||
region: aws_config.region.clone(),
|
||||
endpoint_url: aws_config.endpoint_url.clone(),
|
||||
},
|
||||
};
|
||||
|
||||
Self {
|
||||
@@ -476,7 +537,7 @@ impl From<&KmsConfig> for KmsConfigSummary {
|
||||
retry_attempts: config.retry_attempts,
|
||||
enable_cache: config.enable_cache,
|
||||
max_cached_keys: config.cache_config.max_keys,
|
||||
cache_ttl_seconds: config.cache_config.ttl.as_secs(),
|
||||
cache_ttl_seconds,
|
||||
cache_summary,
|
||||
backend_summary,
|
||||
}
|
||||
@@ -495,13 +556,17 @@ impl ConfigureLocalKmsRequest {
|
||||
file_permissions: self.file_permissions,
|
||||
}),
|
||||
allow_insecure_dev_defaults: self.allow_insecure_dev_defaults.unwrap_or(false),
|
||||
// Read from server configuration, never from the request body: the
|
||||
// gate must mean the same thing whether KMS was configured at
|
||||
// startup or through this endpoint.
|
||||
allow_immediate_deletion: allow_immediate_deletion_from_env(),
|
||||
timeout: Duration::from_secs(self.timeout_seconds.unwrap_or(30)),
|
||||
retry_attempts: self.retry_attempts.unwrap_or(3),
|
||||
enable_cache: self.enable_cache.unwrap_or(true),
|
||||
cache_config: CacheConfig {
|
||||
max_keys: self.max_cached_keys.unwrap_or(1000),
|
||||
ttl: Duration::from_secs(self.cache_ttl_seconds.unwrap_or(3600)),
|
||||
enable_metrics: true,
|
||||
max_keys: self.max_cached_keys.unwrap_or(DEFAULT_MAX_CACHED_KEYS),
|
||||
ttl: self.cache_ttl_seconds.map_or(DEFAULT_CACHE_TTL, Duration::from_secs),
|
||||
..CacheConfig::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -532,13 +597,17 @@ impl ConfigureVaultKmsRequest {
|
||||
},
|
||||
})),
|
||||
allow_insecure_dev_defaults: self.allow_insecure_dev_defaults.unwrap_or(false),
|
||||
// Read from server configuration, never from the request body: the
|
||||
// gate must mean the same thing whether KMS was configured at
|
||||
// startup or through this endpoint.
|
||||
allow_immediate_deletion: allow_immediate_deletion_from_env(),
|
||||
timeout: Duration::from_secs(self.timeout_seconds.unwrap_or(30)),
|
||||
retry_attempts: self.retry_attempts.unwrap_or(3),
|
||||
enable_cache: self.enable_cache.unwrap_or(true),
|
||||
cache_config: CacheConfig {
|
||||
max_keys: self.max_cached_keys.unwrap_or(1000),
|
||||
ttl: Duration::from_secs(self.cache_ttl_seconds.unwrap_or(3600)),
|
||||
enable_metrics: true,
|
||||
max_keys: self.max_cached_keys.unwrap_or(DEFAULT_MAX_CACHED_KEYS),
|
||||
ttl: self.cache_ttl_seconds.map_or(DEFAULT_CACHE_TTL, Duration::from_secs),
|
||||
..CacheConfig::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -569,13 +638,17 @@ impl ConfigureVaultTransitKmsRequest {
|
||||
},
|
||||
})),
|
||||
allow_insecure_dev_defaults: self.allow_insecure_dev_defaults.unwrap_or(false),
|
||||
// Read from server configuration, never from the request body: the
|
||||
// gate must mean the same thing whether KMS was configured at
|
||||
// startup or through this endpoint.
|
||||
allow_immediate_deletion: allow_immediate_deletion_from_env(),
|
||||
timeout: Duration::from_secs(self.timeout_seconds.unwrap_or(30)),
|
||||
retry_attempts: self.retry_attempts.unwrap_or(3),
|
||||
enable_cache: self.enable_cache.unwrap_or(true),
|
||||
cache_config: CacheConfig {
|
||||
max_keys: self.max_cached_keys.unwrap_or(1000),
|
||||
ttl: Duration::from_secs(self.cache_ttl_seconds.unwrap_or(3600)),
|
||||
enable_metrics: true,
|
||||
max_keys: self.max_cached_keys.unwrap_or(DEFAULT_MAX_CACHED_KEYS),
|
||||
ttl: self.cache_ttl_seconds.map_or(DEFAULT_CACHE_TTL, Duration::from_secs),
|
||||
..CacheConfig::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -592,13 +665,44 @@ impl ConfigureStaticKmsRequest {
|
||||
secret_key: self.secret_key.clone(),
|
||||
}),
|
||||
allow_insecure_dev_defaults: self.allow_insecure_dev_defaults.unwrap_or(false),
|
||||
// Read from server configuration, never from the request body: the
|
||||
// gate must mean the same thing whether KMS was configured at
|
||||
// startup or through this endpoint.
|
||||
allow_immediate_deletion: allow_immediate_deletion_from_env(),
|
||||
timeout: Duration::from_secs(self.timeout_seconds.unwrap_or(30)),
|
||||
retry_attempts: self.retry_attempts.unwrap_or(3),
|
||||
enable_cache: self.enable_cache.unwrap_or(true),
|
||||
cache_config: CacheConfig {
|
||||
max_keys: self.max_cached_keys.unwrap_or(1000),
|
||||
ttl: Duration::from_secs(self.cache_ttl_seconds.unwrap_or(3600)),
|
||||
enable_metrics: true,
|
||||
max_keys: self.max_cached_keys.unwrap_or(DEFAULT_MAX_CACHED_KEYS),
|
||||
ttl: self.cache_ttl_seconds.map_or(DEFAULT_CACHE_TTL, Duration::from_secs),
|
||||
..CacheConfig::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigureAwsKmsRequest {
|
||||
/// Convert to KmsConfig
|
||||
pub fn to_kms_config(&self) -> KmsConfig {
|
||||
KmsConfig {
|
||||
backend: KmsBackend::Aws,
|
||||
default_key_id: self.default_key_id.clone(),
|
||||
backend_config: BackendConfig::Aws(Box::new(AwsKmsConfig {
|
||||
region: Some(self.region.clone()),
|
||||
endpoint_url: self.endpoint_url.clone(),
|
||||
})),
|
||||
allow_insecure_dev_defaults: self.allow_insecure_dev_defaults.unwrap_or(false),
|
||||
// Read from server configuration, never from the request body: the
|
||||
// gate must mean the same thing whether KMS was configured at
|
||||
// startup or through this endpoint.
|
||||
allow_immediate_deletion: allow_immediate_deletion_from_env(),
|
||||
timeout: Duration::from_secs(self.timeout_seconds.unwrap_or(30)),
|
||||
retry_attempts: self.retry_attempts.unwrap_or(3),
|
||||
enable_cache: self.enable_cache.unwrap_or(true),
|
||||
cache_config: CacheConfig {
|
||||
max_keys: self.max_cached_keys.unwrap_or(DEFAULT_MAX_CACHED_KEYS),
|
||||
ttl: self.cache_ttl_seconds.map_or(DEFAULT_CACHE_TTL, Duration::from_secs),
|
||||
..CacheConfig::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -612,6 +716,7 @@ impl ConfigureKmsRequest {
|
||||
ConfigureKmsRequest::VaultKv2(req) => req.to_kms_config(),
|
||||
ConfigureKmsRequest::VaultTransit(req) => req.to_kms_config(),
|
||||
ConfigureKmsRequest::Static(req) => req.to_kms_config(),
|
||||
ConfigureKmsRequest::Aws(req) => req.to_kms_config(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -797,6 +902,108 @@ mod tests {
|
||||
assert!(request.to_kms_config().validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_aws_configure_request_accepts_type_aliases() {
|
||||
for backend_type in ["AWS", "AwsKms", "aws", "aws-kms", "aws_kms"] {
|
||||
let raw = serde_json::json!({
|
||||
"backend_type": backend_type,
|
||||
"region": "eu-central-1",
|
||||
"default_key_id": "arn:aws:kms:eu-central-1:111122223333:key/1234abcd"
|
||||
});
|
||||
|
||||
let request: ConfigureKmsRequest = serde_json::from_value(raw).unwrap_or_else(|e| panic!("{backend_type}: {e}"));
|
||||
let config = request.to_kms_config();
|
||||
assert_eq!(config.backend, KmsBackend::Aws, "backend_type={backend_type}");
|
||||
let aws = config.aws_kms_config().expect("aws backend config");
|
||||
assert_eq!(aws.region.as_deref(), Some("eu-central-1"));
|
||||
assert_eq!(aws.endpoint_url, None);
|
||||
assert!(config.validate().is_ok(), "backend_type={backend_type}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A cluster-persisted AWS configuration must pin its own region: a
|
||||
/// request that leaves it to each node's ambient provider chain is refused
|
||||
/// rather than accepted into a configuration every node interprets
|
||||
/// differently.
|
||||
#[test]
|
||||
fn test_aws_configure_request_requires_an_explicit_region() {
|
||||
let missing = serde_json::json!({
|
||||
"backend_type": "AWS",
|
||||
"default_key_id": "arn:aws:kms:eu-central-1:111122223333:key/1234abcd"
|
||||
});
|
||||
let err = serde_json::from_value::<ConfigureKmsRequest>(missing).expect_err("a region-less AWS request must be refused");
|
||||
assert!(err.to_string().contains("region"), "{err}");
|
||||
|
||||
let empty = serde_json::json!({ "backend_type": "AWS", "region": "" });
|
||||
let request: ConfigureKmsRequest = serde_json::from_value(empty).expect("an empty region deserializes");
|
||||
assert!(request.to_kms_config().validate().is_err(), "an empty region must not validate");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_aws_configure_request_rejects_plaintext_endpoint_without_opt_in() {
|
||||
let raw = serde_json::json!({
|
||||
"backend_type": "AWS",
|
||||
"region": "us-east-1",
|
||||
"endpoint_url": "http://localhost:4566"
|
||||
});
|
||||
let request: ConfigureKmsRequest = serde_json::from_value(raw).expect("aws request should deserialize");
|
||||
assert!(request.to_kms_config().validate().is_err());
|
||||
|
||||
let opt_in = serde_json::json!({
|
||||
"backend_type": "AWS",
|
||||
"region": "us-east-1",
|
||||
"endpoint_url": "http://localhost:4566",
|
||||
"allow_insecure_dev_defaults": true
|
||||
});
|
||||
let request: ConfigureKmsRequest = serde_json::from_value(opt_in).expect("aws request should deserialize");
|
||||
assert!(request.to_kms_config().validate().is_ok());
|
||||
}
|
||||
|
||||
/// The AWS summary carries only non-credential settings, because the
|
||||
/// backend never holds AWS credential material to begin with.
|
||||
#[test]
|
||||
fn test_aws_status_summary_reports_only_non_credential_settings() {
|
||||
let config = ConfigureAwsKmsRequest {
|
||||
region: "us-east-1".to_string(),
|
||||
endpoint_url: None,
|
||||
default_key_id: Some("arn:aws:kms:us-east-1:111122223333:key/1234abcd".to_string()),
|
||||
timeout_seconds: None,
|
||||
retry_attempts: None,
|
||||
enable_cache: None,
|
||||
max_cached_keys: None,
|
||||
cache_ttl_seconds: None,
|
||||
allow_insecure_dev_defaults: None,
|
||||
}
|
||||
.to_kms_config();
|
||||
|
||||
let summary = KmsConfigSummary::from(&config);
|
||||
assert_eq!(summary.backend_type, KmsBackend::Aws);
|
||||
match &summary.backend_summary {
|
||||
BackendSummary::Aws { region, endpoint_url } => {
|
||||
assert_eq!(region.as_deref(), Some("us-east-1"));
|
||||
assert_eq!(endpoint_url.as_deref(), None);
|
||||
}
|
||||
other => panic!("expected aws summary, got {other:?}"),
|
||||
}
|
||||
|
||||
let response = KmsStatusResponse {
|
||||
status: KmsServiceStatus::Running,
|
||||
backend_type: Some(config.backend),
|
||||
healthy: Some(true),
|
||||
config_summary: Some(summary),
|
||||
};
|
||||
let rendered = format!(
|
||||
"{}\n{response:?}",
|
||||
serde_json::to_string(&response).expect("kms status response should serialize")
|
||||
);
|
||||
for credential_field in ["access_key", "secret_key", "session_token", "has_stored_credentials"] {
|
||||
assert!(
|
||||
!rendered.contains(credential_field),
|
||||
"aws status output must not describe credential material: {rendered}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_configure_request_rejects_unknown_fields() {
|
||||
let raw = serde_json::json!({
|
||||
@@ -821,6 +1028,17 @@ mod tests {
|
||||
|
||||
let err = serde_json::from_value::<ConfigureKmsRequest>(raw).expect_err("unknown auth field should fail");
|
||||
assert!(err.to_string().contains("unknown field"));
|
||||
|
||||
// AWS credentials belong to the provider chain: a request that tries to
|
||||
// smuggle them in must be refused, not silently ignored.
|
||||
let raw = serde_json::json!({
|
||||
"backend_type": "AWS",
|
||||
"region": "us-east-1",
|
||||
"secret_access_key": "AKIA-not-accepted-here"
|
||||
});
|
||||
|
||||
let err = serde_json::from_value::<ConfigureKmsRequest>(raw).expect_err("unknown aws field should fail");
|
||||
assert!(err.to_string().contains("unknown field"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -847,6 +1065,7 @@ mod tests {
|
||||
tls: None,
|
||||
})),
|
||||
allow_insecure_dev_defaults: true,
|
||||
allow_immediate_deletion: false,
|
||||
timeout: Duration::from_secs(30),
|
||||
retry_attempts: 3,
|
||||
enable_cache: true,
|
||||
@@ -858,8 +1077,8 @@ mod tests {
|
||||
assert_eq!(summary.backend_type, KmsBackend::VaultTransit);
|
||||
assert_eq!(summary.timeout_seconds, 30);
|
||||
assert_eq!(summary.retry_attempts, 3);
|
||||
assert_eq!(summary.max_cached_keys, 1000);
|
||||
assert_eq!(summary.cache_ttl_seconds, 3600);
|
||||
assert_eq!(summary.max_cached_keys, DEFAULT_MAX_CACHED_KEYS);
|
||||
assert_eq!(summary.cache_ttl_seconds, DEFAULT_CACHE_TTL.as_secs());
|
||||
|
||||
match summary.backend_summary {
|
||||
BackendSummary::VaultTransit {
|
||||
|
||||
@@ -0,0 +1,425 @@
|
||||
// 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.
|
||||
|
||||
//! Audit contract for KMS management operations.
|
||||
//!
|
||||
//! [`KmsManager`](crate::manager::KmsManager) builds a [`KmsAuditRecord`] for
|
||||
//! every management operation it serves and hands it to the installed
|
||||
//! [`KmsAuditSink`]. No sink is installed by default, so a deployment that
|
||||
//! does not consume KMS audit records pays nothing beyond the `Option` check.
|
||||
//!
|
||||
//! The record is deliberately a KMS-side type rather than an audit-crate
|
||||
//! entry: keeping the dependency edge out of this crate lets the server map
|
||||
//! records onto its existing audit pipeline (and its delivery semantics)
|
||||
//! without KMS having to know that pipeline exists.
|
||||
//!
|
||||
//! # Redaction
|
||||
//!
|
||||
//! A record has no field that can hold key material, and every value that
|
||||
//! originates from a caller passes through [`redact_encryption_context`]
|
||||
//! before it is stored. Adding a field here means re-checking that invariant.
|
||||
|
||||
use crate::error::KmsError;
|
||||
use crate::types::OperationContext;
|
||||
use rustfs_s3_types::EventName;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::time::Duration;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Encryption-context keys that describe *where* an object lives rather than
|
||||
/// anything secret about it. Their values are recorded verbatim; every other
|
||||
/// key is reduced to a digest.
|
||||
const ENCRYPTION_CONTEXT_ALLOWLIST: [&str; 5] = ["bucket", "object", "object_key", "algorithm", "sse_type"];
|
||||
|
||||
/// Prefix marking a value that was replaced by a digest of itself.
|
||||
const DIGEST_PREFIX: &str = "sha256:";
|
||||
|
||||
/// Hex characters of the digest that are kept. Enough to correlate repeated
|
||||
/// values across records without being reversible in practice.
|
||||
const DIGEST_LEN: usize = 16;
|
||||
|
||||
/// A KMS management operation that produces an audit record.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum KmsAuditOperation {
|
||||
/// Creation of a new master key.
|
||||
CreateKey,
|
||||
/// Metadata lookup for a single key.
|
||||
DescribeKey,
|
||||
/// Enumeration of keys.
|
||||
ListKeys,
|
||||
/// Scheduling a key for deletion after the pending window.
|
||||
ScheduleKeyDeletion,
|
||||
/// Cancelling a previously scheduled deletion.
|
||||
CancelKeyDeletion,
|
||||
/// Returning a disabled key to service.
|
||||
EnableKey,
|
||||
/// Taking a key out of service without destroying it.
|
||||
DisableKey,
|
||||
/// Rotating a key to a new version.
|
||||
RotateKey,
|
||||
/// Irreversible removal of key material once the pending window expired.
|
||||
DeleteKey,
|
||||
}
|
||||
|
||||
impl KmsAuditOperation {
|
||||
/// Stable operation name for audit consumers.
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
KmsAuditOperation::CreateKey => "CreateKey",
|
||||
KmsAuditOperation::DescribeKey => "DescribeKey",
|
||||
KmsAuditOperation::ListKeys => "ListKeys",
|
||||
KmsAuditOperation::ScheduleKeyDeletion => "ScheduleKeyDeletion",
|
||||
KmsAuditOperation::CancelKeyDeletion => "CancelKeyDeletion",
|
||||
KmsAuditOperation::EnableKey => "EnableKey",
|
||||
KmsAuditOperation::DisableKey => "DisableKey",
|
||||
KmsAuditOperation::RotateKey => "RotateKey",
|
||||
KmsAuditOperation::DeleteKey => "DeleteKey",
|
||||
}
|
||||
}
|
||||
|
||||
/// Notification/audit event name carried by records for this operation.
|
||||
pub fn event_name(&self) -> EventName {
|
||||
match self {
|
||||
KmsAuditOperation::CreateKey => EventName::KmsKeyCreated,
|
||||
KmsAuditOperation::DescribeKey | KmsAuditOperation::ListKeys => EventName::KmsKeyAccessed,
|
||||
KmsAuditOperation::ScheduleKeyDeletion => EventName::KmsKeyDeletionScheduled,
|
||||
KmsAuditOperation::CancelKeyDeletion => EventName::KmsKeyDeletionCancelled,
|
||||
KmsAuditOperation::EnableKey => EventName::KmsKeyEnabled,
|
||||
KmsAuditOperation::DisableKey => EventName::KmsKeyDisabled,
|
||||
KmsAuditOperation::RotateKey => EventName::KmsKeyRotated,
|
||||
KmsAuditOperation::DeleteKey => EventName::KmsKeyDeleted,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the audited operation completed.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum KmsAuditOutcome {
|
||||
/// The operation completed and its effect is durable.
|
||||
Success,
|
||||
/// The operation failed; `error_class` carries the reason category.
|
||||
Failure,
|
||||
}
|
||||
|
||||
impl KmsAuditOutcome {
|
||||
/// Stable outcome name for audit consumers.
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
KmsAuditOutcome::Success => "success",
|
||||
KmsAuditOutcome::Failure => "failure",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Coarse, stable classification of a failed KMS operation.
|
||||
///
|
||||
/// Audit consumers alert on these, so the strings are a wire contract: add
|
||||
/// new classes rather than renaming existing ones.
|
||||
pub fn error_class(error: &KmsError) -> &'static str {
|
||||
match error {
|
||||
KmsError::ConfigurationError { .. } => "configuration",
|
||||
KmsError::KeyNotFound { .. } => "key_not_found",
|
||||
KmsError::InvalidKey { .. } => "invalid_key",
|
||||
KmsError::CryptographicError { .. } => "cryptographic",
|
||||
KmsError::BackendError { .. } => "backend",
|
||||
KmsError::AccessDenied { .. } => "access_denied",
|
||||
KmsError::KeyAlreadyExists { .. } => "key_already_exists",
|
||||
KmsError::InvalidOperation { .. } => "invalid_operation",
|
||||
KmsError::InternalError { .. } => "internal",
|
||||
KmsError::SerializationError { .. } => "serialization",
|
||||
KmsError::IoError { .. } => "io",
|
||||
KmsError::CacheError { .. } => "cache",
|
||||
KmsError::ValidationError { .. } => "validation",
|
||||
KmsError::UnsupportedAlgorithm { .. } => "unsupported_algorithm",
|
||||
KmsError::InvalidKeySize { .. } => "invalid_key_size",
|
||||
KmsError::ContextMismatch { .. } => "context_mismatch",
|
||||
KmsError::OperationTimedOut { .. } => "timeout",
|
||||
KmsError::OperationCancelled { .. } => "cancelled",
|
||||
KmsError::MaterialMissing { .. } => "material_missing",
|
||||
KmsError::MaterialCorrupt { .. } => "material_corrupt",
|
||||
KmsError::MaterialAuthenticationFailed { .. } => "material_authentication_failed",
|
||||
KmsError::UnsupportedFormatVersion { .. } => "unsupported_format_version",
|
||||
KmsError::KeyVersionNotFound { .. } => "key_version_not_found",
|
||||
KmsError::Backup(_) => "backup",
|
||||
KmsError::UnsupportedCapability { .. } => "unsupported_capability",
|
||||
KmsError::CredentialsUnavailable { .. } => "credentials_unavailable",
|
||||
KmsError::BaselineVersionLost { .. } => "baseline_version_lost",
|
||||
KmsError::KeyStillReferenced { .. } => "key_still_referenced",
|
||||
}
|
||||
}
|
||||
|
||||
/// One audited KMS management operation.
|
||||
///
|
||||
/// Everything an audit consumer needs to answer "who did what to which key,
|
||||
/// against which backend, and did it work" — and nothing that could carry key
|
||||
/// material. See the module docs for the redaction rules.
|
||||
///
|
||||
/// Tenant attribution is intentionally absent: multi-tenancy is not modelled
|
||||
/// yet, and an invented tenant value is worse than a missing one. It will
|
||||
/// arrive as an entry in [`Self::context`] once tenancy lands.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct KmsAuditRecord {
|
||||
/// Correlates every record emitted for one logical request.
|
||||
pub operation_id: Uuid,
|
||||
/// The audited operation.
|
||||
pub operation: KmsAuditOperation,
|
||||
/// Event name published to audit consumers.
|
||||
pub event: EventName,
|
||||
/// Authenticated identity that requested the operation, or
|
||||
/// [`OperationContext::INTERNAL_PRINCIPAL`] for server-initiated work.
|
||||
pub principal: String,
|
||||
/// Client address, when the caller supplied one.
|
||||
pub source_ip: Option<String>,
|
||||
/// Client user agent, when the caller supplied one.
|
||||
pub user_agent: Option<String>,
|
||||
/// Key the operation acted on. `None` for operations that span keys, such
|
||||
/// as listing.
|
||||
pub key_id: Option<String>,
|
||||
/// Key version the operation resolved to, when the result identifies one.
|
||||
/// Operations on a key as a whole leave this unset.
|
||||
pub key_version: Option<u32>,
|
||||
/// Whether the operation succeeded.
|
||||
pub outcome: KmsAuditOutcome,
|
||||
/// Failure category; `None` on success. See [`error_class`].
|
||||
pub error_class: Option<&'static str>,
|
||||
/// Backend that served the operation, e.g. `local` or `vault-transit`.
|
||||
pub backend: &'static str,
|
||||
/// Wall-clock time spent in the audited operation.
|
||||
pub latency: Duration,
|
||||
/// Retries performed above the audit point. `None` means the number is
|
||||
/// not observable here: backend-internal retries are accounted for by the
|
||||
/// `rustfs_kms_backend_operation_attempts` metric instead of being
|
||||
/// duplicated (and possibly contradicted) in the audit trail.
|
||||
pub retry_count: Option<u32>,
|
||||
/// Server-supplied correlation values carried by the operation context.
|
||||
/// Also the reserved slot for tenant attribution.
|
||||
pub context: BTreeMap<String, String>,
|
||||
/// Caller-supplied encryption context, after [`redact_encryption_context`].
|
||||
pub encryption_context: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl KmsAuditRecord {
|
||||
/// Start a record for `operation` performed under `context`.
|
||||
///
|
||||
/// The outcome defaults to failure so that a record which somehow escapes
|
||||
/// without [`Self::with_result`] under-reports success rather than
|
||||
/// inventing it.
|
||||
pub fn new(operation: KmsAuditOperation, context: &OperationContext, backend: &'static str) -> Self {
|
||||
Self {
|
||||
operation_id: context.operation_id,
|
||||
operation,
|
||||
event: operation.event_name(),
|
||||
principal: context.principal.clone(),
|
||||
source_ip: context.source_ip.clone(),
|
||||
user_agent: context.user_agent.clone(),
|
||||
key_id: None,
|
||||
key_version: None,
|
||||
outcome: KmsAuditOutcome::Failure,
|
||||
error_class: None,
|
||||
backend,
|
||||
latency: Duration::ZERO,
|
||||
retry_count: None,
|
||||
context: context
|
||||
.additional_context
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), v.clone()))
|
||||
.collect(),
|
||||
encryption_context: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Attach the key the operation acted on.
|
||||
pub fn with_key_id(mut self, key_id: Option<impl Into<String>>) -> Self {
|
||||
self.key_id = key_id.map(Into::into);
|
||||
self
|
||||
}
|
||||
|
||||
/// Attach the key version the operation resolved to.
|
||||
pub fn with_key_version(mut self, key_version: Option<u32>) -> Self {
|
||||
self.key_version = key_version;
|
||||
self
|
||||
}
|
||||
|
||||
/// Attach the measured duration of the operation.
|
||||
pub fn with_latency(mut self, latency: Duration) -> Self {
|
||||
self.latency = latency;
|
||||
self
|
||||
}
|
||||
|
||||
/// Derive outcome and error class from the operation result.
|
||||
pub fn with_result<T>(mut self, result: &crate::error::Result<T>) -> Self {
|
||||
match result {
|
||||
Ok(_) => {
|
||||
self.outcome = KmsAuditOutcome::Success;
|
||||
self.error_class = None;
|
||||
}
|
||||
Err(error) => {
|
||||
self.outcome = KmsAuditOutcome::Failure;
|
||||
self.error_class = Some(error_class(error));
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Attach the caller-supplied encryption context, redacted.
|
||||
///
|
||||
/// Redaction happens here rather than at the call site so no caller can
|
||||
/// place a raw context value into a record by accident.
|
||||
pub fn with_encryption_context(mut self, encryption_context: &HashMap<String, String>) -> Self {
|
||||
self.encryption_context = redact_encryption_context(encryption_context);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Reduce a caller-supplied encryption context to something safe to persist.
|
||||
///
|
||||
/// Keys naming the object's location are kept verbatim because they are the
|
||||
/// reason the context is audited at all. Every other value is replaced by a
|
||||
/// truncated digest, which still correlates repeated values across records
|
||||
/// but does not reproduce whatever the caller put there.
|
||||
pub fn redact_encryption_context(encryption_context: &HashMap<String, String>) -> BTreeMap<String, String> {
|
||||
encryption_context
|
||||
.iter()
|
||||
.map(|(key, value)| {
|
||||
let recorded = if ENCRYPTION_CONTEXT_ALLOWLIST.contains(&key.as_str()) {
|
||||
value.clone()
|
||||
} else {
|
||||
digest_value(value)
|
||||
};
|
||||
(key.clone(), recorded)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn digest_value(value: &str) -> String {
|
||||
let digest = hex::encode(Sha256::digest(value.as_bytes()));
|
||||
format!("{DIGEST_PREFIX}{}", &digest[..DIGEST_LEN])
|
||||
}
|
||||
|
||||
/// Receives KMS audit records.
|
||||
///
|
||||
/// Implementations must not block: they are called on the task that served
|
||||
/// the KMS operation. Delivery failures are the sink's problem — the KMS
|
||||
/// operation has already completed by the time a record is emitted, and its
|
||||
/// result is never changed by what the sink does.
|
||||
pub trait KmsAuditSink: Send + Sync {
|
||||
/// Handle one audit record.
|
||||
fn emit(&self, record: KmsAuditRecord);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_operation_maps_to_a_kms_event() {
|
||||
let operations = [
|
||||
KmsAuditOperation::CreateKey,
|
||||
KmsAuditOperation::DescribeKey,
|
||||
KmsAuditOperation::ListKeys,
|
||||
KmsAuditOperation::ScheduleKeyDeletion,
|
||||
KmsAuditOperation::CancelKeyDeletion,
|
||||
KmsAuditOperation::EnableKey,
|
||||
KmsAuditOperation::DisableKey,
|
||||
KmsAuditOperation::RotateKey,
|
||||
KmsAuditOperation::DeleteKey,
|
||||
];
|
||||
|
||||
for operation in operations {
|
||||
let event = operation.event_name();
|
||||
assert!(event.is_kms(), "{} must map to a KMS event, got {event}", operation.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_defaults_to_failure_until_a_result_is_attached() {
|
||||
let context = OperationContext::new("tester".to_string());
|
||||
let record = KmsAuditRecord::new(KmsAuditOperation::CreateKey, &context, "local");
|
||||
|
||||
assert_eq!(record.outcome, KmsAuditOutcome::Failure);
|
||||
assert!(record.error_class.is_none());
|
||||
|
||||
let ok: crate::error::Result<()> = Ok(());
|
||||
assert_eq!(record.clone().with_result(&ok).outcome, KmsAuditOutcome::Success);
|
||||
|
||||
let denied: crate::error::Result<()> = Err(KmsError::access_denied("nope"));
|
||||
let failed = record.with_result(&denied);
|
||||
assert_eq!(failed.outcome, KmsAuditOutcome::Failure);
|
||||
assert_eq!(failed.error_class, Some("access_denied"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_carries_the_full_operation_context() {
|
||||
let context = OperationContext::new("arn:aws:iam::user/alice".to_string())
|
||||
.with_source_ip("10.0.0.7".to_string())
|
||||
.with_user_agent("aws-cli/2".to_string())
|
||||
.with_context("requestID".to_string(), "req-1".to_string());
|
||||
|
||||
let record = KmsAuditRecord::new(KmsAuditOperation::RotateKey, &context, "vault-transit")
|
||||
.with_key_id(Some("key-1"))
|
||||
.with_key_version(Some(3))
|
||||
.with_latency(Duration::from_millis(12));
|
||||
|
||||
assert_eq!(record.operation_id, context.operation_id);
|
||||
assert_eq!(record.principal, "arn:aws:iam::user/alice");
|
||||
assert_eq!(record.source_ip.as_deref(), Some("10.0.0.7"));
|
||||
assert_eq!(record.user_agent.as_deref(), Some("aws-cli/2"));
|
||||
assert_eq!(record.key_id.as_deref(), Some("key-1"));
|
||||
assert_eq!(record.key_version, Some(3));
|
||||
assert_eq!(record.backend, "vault-transit");
|
||||
assert_eq!(record.latency, Duration::from_millis(12));
|
||||
assert_eq!(record.event, EventName::KmsKeyRotated);
|
||||
assert_eq!(record.context.get("requestID").map(String::as_str), Some("req-1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encryption_context_keeps_only_allowlisted_values_verbatim() {
|
||||
let secret = "eyJhbGciOiJIUzI1NiJ9.super-secret-grant-token";
|
||||
let context = HashMap::from([
|
||||
("bucket".to_string(), "photos".to_string()),
|
||||
("object_key".to_string(), "2026/cat.png".to_string()),
|
||||
("algorithm".to_string(), "AES256".to_string()),
|
||||
("grant_token".to_string(), secret.to_string()),
|
||||
("customer_reference".to_string(), "acct-4711".to_string()),
|
||||
]);
|
||||
|
||||
let redacted = redact_encryption_context(&context);
|
||||
|
||||
assert_eq!(redacted.get("bucket").map(String::as_str), Some("photos"));
|
||||
assert_eq!(redacted.get("object_key").map(String::as_str), Some("2026/cat.png"));
|
||||
assert_eq!(redacted.get("algorithm").map(String::as_str), Some("AES256"));
|
||||
|
||||
for key in ["grant_token", "customer_reference"] {
|
||||
let value = redacted.get(key).expect("non-allowlisted key should be kept as a digest");
|
||||
assert!(value.starts_with(DIGEST_PREFIX), "{key} should be digested, got {value}");
|
||||
}
|
||||
|
||||
let rendered = format!("{redacted:?}");
|
||||
assert!(!rendered.contains(secret), "redacted context must not reproduce the raw value");
|
||||
assert!(!rendered.contains("acct-4711"), "redacted context must not reproduce the raw value");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_values_digest_identically_across_records() {
|
||||
// Correlation is the reason a digest is preferable to a fixed
|
||||
// placeholder; assert it actually holds.
|
||||
let first = redact_encryption_context(&HashMap::from([("tenant".to_string(), "alpha".to_string())]));
|
||||
let second = redact_encryption_context(&HashMap::from([("tenant".to_string(), "alpha".to_string())]));
|
||||
let other = redact_encryption_context(&HashMap::from([("tenant".to_string(), "beta".to_string())]));
|
||||
|
||||
assert_eq!(first.get("tenant"), second.get("tenant"));
|
||||
assert_ne!(first.get("tenant"), other.get("tenant"));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -108,6 +108,7 @@ fn schedule_request(key_id: &str) -> DeleteKeyRequest {
|
||||
key_id: key_id.to_string(),
|
||||
pending_window_in_days: Some(7),
|
||||
force_immediate: None,
|
||||
confirm_key_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,10 @@
|
||||
|
||||
//! Local file-based KMS backend implementation
|
||||
|
||||
use crate::backends::{BackendCapabilities, ExpiredKeyRemoval, KmsBackend, StateGatedOperation, ensure_key_status_permits};
|
||||
use crate::backends::{
|
||||
BackendCapabilities, ExpiredKeyRemoval, KmsBackend, StateGatedOperation, ensure_key_status_permits,
|
||||
ensure_tag_keys_are_mutable, paginate_keys,
|
||||
};
|
||||
use crate::config::KmsConfig;
|
||||
use crate::config::LocalConfig;
|
||||
use crate::encryption::{AesDekCrypto, DataKeyEnvelope, DekCrypto, generate_key_material};
|
||||
@@ -1211,6 +1214,32 @@ impl LocalKmsClient {
|
||||
Ok(master_key.into())
|
||||
}
|
||||
|
||||
/// Every key identifier in the key directory, sorted.
|
||||
///
|
||||
/// `read_dir` order is arbitrary and may differ between calls over the same
|
||||
/// directory, so it cannot carry a pagination cursor. Sorting gives the key
|
||||
/// set a stable total order that a marker can point into.
|
||||
async fn sorted_key_ids(&self) -> Result<Vec<String>> {
|
||||
let mut key_ids = Vec::new();
|
||||
let mut entries = fs::read_dir(&self.config.key_dir).await?;
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
let path = entry.path();
|
||||
if path.extension().is_some_and(|ext| ext == "key")
|
||||
&& let Some(key_id) = path.file_stem().and_then(|stem| stem.to_str())
|
||||
{
|
||||
key_ids.push(key_id.to_string());
|
||||
}
|
||||
}
|
||||
key_ids.sort_unstable();
|
||||
Ok(key_ids)
|
||||
}
|
||||
|
||||
/// One page of the key set, ordered by key identifier.
|
||||
///
|
||||
/// Paging is real here rather than a first-page-only approximation:
|
||||
/// callers that must see every key — the deletion sweep above all, which
|
||||
/// only destroys expired material for keys it actually lists — depend on
|
||||
/// `truncated` and `next_marker` to reach past the first page.
|
||||
pub(crate) async fn list_keys(
|
||||
&self,
|
||||
request: &ListKeysRequest,
|
||||
@@ -1218,44 +1247,43 @@ impl LocalKmsClient {
|
||||
) -> Result<ListKeysResponse> {
|
||||
debug!("Listing keys");
|
||||
|
||||
let mut keys = Vec::new();
|
||||
let limit = request.limit.unwrap_or(100) as usize;
|
||||
let mut count = 0;
|
||||
let key_ids = self.sorted_key_ids().await?;
|
||||
let page = paginate_keys(&key_ids, request, String::as_str);
|
||||
|
||||
let mut entries = fs::read_dir(&self.config.key_dir).await?;
|
||||
// Only the page is read from disk, so the cost of a list stays bounded
|
||||
// by the requested limit rather than by the size of the key set.
|
||||
let mut keys = Vec::with_capacity(page.items.len());
|
||||
for key_id in page.items {
|
||||
// A key that vanished or cannot be decoded is dropped from the page
|
||||
// instead of failing it: concurrent removal is normal, and the
|
||||
// cursor is derived from the identifier list, so the listing still
|
||||
// advances past it.
|
||||
let key_info = match self.describe_key(key_id, None).await {
|
||||
Ok(key_info) => key_info,
|
||||
Err(error) => {
|
||||
debug!(key_id, %error, "skipping unreadable key while listing");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
if count >= limit {
|
||||
break;
|
||||
}
|
||||
|
||||
let path = entry.path();
|
||||
if path.extension().is_some_and(|ext| ext == "key")
|
||||
&& let Some(stem) = path.file_stem()
|
||||
&& let Some(key_id) = stem.to_str()
|
||||
&& let Ok(key_info) = self.describe_key(key_id, None).await
|
||||
if let Some(ref status_filter) = request.status_filter
|
||||
&& &key_info.status != status_filter
|
||||
{
|
||||
// Apply filters
|
||||
if let Some(ref status_filter) = request.status_filter
|
||||
&& &key_info.status != status_filter
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Some(ref usage_filter) = request.usage_filter
|
||||
&& &key_info.usage != usage_filter
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
keys.push(key_info);
|
||||
count += 1;
|
||||
continue;
|
||||
}
|
||||
if let Some(ref usage_filter) = request.usage_filter
|
||||
&& &key_info.usage != usage_filter
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
keys.push(key_info);
|
||||
}
|
||||
|
||||
Ok(ListKeysResponse {
|
||||
keys,
|
||||
next_marker: None, // Simple implementation without pagination
|
||||
truncated: false,
|
||||
next_marker: page.next_marker,
|
||||
truncated: page.truncated,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1294,6 +1322,32 @@ impl LocalKmsClient {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read-modify-write of a key's mutable metadata under the per-key write
|
||||
/// lock, carrying the existing key material over untouched.
|
||||
///
|
||||
/// `mutate` reports whether it changed anything; an unchanged record is
|
||||
/// never rewritten, so a repeated no-op update neither rewrites the key
|
||||
/// file nor risks a failed commit on an unrelated call.
|
||||
async fn update_key_metadata<F>(&self, key_id: &str, mutate: F) -> Result<()>
|
||||
where
|
||||
F: FnOnce(&mut MasterKeyInfo) -> Result<bool>,
|
||||
{
|
||||
let _write_guard = self.lock_key_for_write(key_id).await;
|
||||
let mut master_key = self.load_master_key(key_id).await?;
|
||||
if !mutate(&mut master_key)? {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Preserve the existing key material (see enable_key): a metadata edit
|
||||
// must never regenerate the master key, or every DEK wrapped by it
|
||||
// becomes undecryptable.
|
||||
let key_material = self.get_key_material(key_id).await?;
|
||||
self.save_master_key(&master_key, &key_material).await?;
|
||||
|
||||
debug!(key_id, "Local KMS key metadata updated");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Test-only lifecycle driver: the product path goes through [`KmsBackend`].
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn schedule_key_deletion(
|
||||
@@ -1386,7 +1440,8 @@ impl LocalKmsBackend {
|
||||
crate::config::BackendConfig::Local(local_config) => local_config.clone(),
|
||||
crate::config::BackendConfig::VaultKv2(_)
|
||||
| crate::config::BackendConfig::VaultTransit(_)
|
||||
| crate::config::BackendConfig::Static(_) => {
|
||||
| crate::config::BackendConfig::Static(_)
|
||||
| crate::config::BackendConfig::Aws(_) => {
|
||||
return Err(KmsError::configuration_error("Expected Local backend configuration"));
|
||||
}
|
||||
};
|
||||
@@ -1411,12 +1466,15 @@ impl KmsBackend for LocalKmsBackend {
|
||||
// Generate key material
|
||||
let key_material = generate_key_material(algorithm)?;
|
||||
|
||||
let master_key = MasterKeyInfo::new_with_description(
|
||||
let mut master_key = MasterKeyInfo::new_with_description(
|
||||
key_id.clone(),
|
||||
algorithm.to_string(),
|
||||
Some("local-kms".to_string()),
|
||||
request.description.clone(),
|
||||
);
|
||||
// Persist the caller's tags: the response below reports them, and
|
||||
// describe_key reads them back out of this record.
|
||||
master_key.metadata = request.tags.clone();
|
||||
|
||||
// Save to disk
|
||||
self.client.save_new_master_key(&master_key, &key_material).await?;
|
||||
@@ -1584,9 +1642,15 @@ impl KmsBackend for LocalKmsBackend {
|
||||
// Schedule for deletion (default 30 days)
|
||||
ensure_key_status_permits(key_id, &master_key.status, StateGatedOperation::ScheduleDeletion)?;
|
||||
|
||||
let days = request.pending_window_in_days.unwrap_or(30);
|
||||
if !(7..=30).contains(&days) {
|
||||
return Err(KmsError::invalid_parameter("pending_window_in_days must be between 7 and 30".to_string()));
|
||||
// Defensive: KmsManager::delete_key is the enforcement point for the
|
||||
// waiting window and rejects out-of-range requests before any
|
||||
// backend runs. This repeats the bound for callers holding a backend
|
||||
// handle directly (tests, maintenance tasks).
|
||||
let days = request.pending_window_in_days.unwrap_or(DEFAULT_PENDING_DELETION_WINDOW_DAYS);
|
||||
if !(MIN_PENDING_DELETION_WINDOW_DAYS..=MAX_PENDING_DELETION_WINDOW_DAYS).contains(&days) {
|
||||
return Err(KmsError::invalid_parameter(format!(
|
||||
"pending_window_in_days must be between {MIN_PENDING_DELETION_WINDOW_DAYS} and {MAX_PENDING_DELETION_WINDOW_DAYS}"
|
||||
)));
|
||||
}
|
||||
|
||||
let deletion_date = Zoned::now() + Duration::from_secs(days as u64 * 86400);
|
||||
@@ -1684,10 +1748,52 @@ impl KmsBackend for LocalKmsBackend {
|
||||
self.client.disable_key(key_id, None).await
|
||||
}
|
||||
|
||||
async fn update_key_description(&self, key_id: &str, description: Option<&str>) -> Result<()> {
|
||||
self.client
|
||||
.update_key_metadata(key_id, |master_key| {
|
||||
if master_key.description.as_deref() == description {
|
||||
return Ok(false);
|
||||
}
|
||||
master_key.description = description.map(str::to_string);
|
||||
Ok(true)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn tag_key(&self, key_id: &str, tags: &HashMap<String, String>) -> Result<()> {
|
||||
ensure_tag_keys_are_mutable(tags.keys().map(String::as_str))?;
|
||||
self.client
|
||||
.update_key_metadata(key_id, |master_key| {
|
||||
let mut changed = false;
|
||||
for (tag_key, value) in tags {
|
||||
changed |= master_key.metadata.insert(tag_key.clone(), value.clone()).as_ref() != Some(value);
|
||||
}
|
||||
Ok(changed)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn untag_key(&self, key_id: &str, tag_keys: &[String]) -> Result<()> {
|
||||
ensure_tag_keys_are_mutable(tag_keys.iter().map(String::as_str))?;
|
||||
self.client
|
||||
.update_key_metadata(key_id, |master_key| {
|
||||
let mut changed = false;
|
||||
for tag_key in tag_keys {
|
||||
changed |= master_key.metadata.remove(tag_key).is_some();
|
||||
}
|
||||
Ok(changed)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn health_check(&self) -> Result<bool> {
|
||||
self.client.health_check().await.map(|_| true)
|
||||
}
|
||||
|
||||
fn local_backup_client(&self) -> Option<&LocalKmsClient> {
|
||||
Some(&self.client)
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> BackendCapabilities {
|
||||
// Rotation stays unadvertised until historical key versions can be
|
||||
// retained (see LocalKmsClient::rotate_key); without version history
|
||||
@@ -1696,6 +1802,7 @@ impl KmsBackend for LocalKmsBackend {
|
||||
.with_enable_disable(true)
|
||||
.with_schedule_deletion(true)
|
||||
.with_physical_delete(true)
|
||||
.with_update_key_metadata(true)
|
||||
}
|
||||
|
||||
async fn remove_expired_key(&self, key_id: &str, now: &Zoned) -> Result<ExpiredKeyRemoval> {
|
||||
@@ -2606,6 +2713,7 @@ mod tests {
|
||||
key_id: "durable-key".to_string(),
|
||||
pending_window_in_days: None,
|
||||
force_immediate: Some(true),
|
||||
confirm_key_id: None,
|
||||
})
|
||||
.await
|
||||
.expect("delete key");
|
||||
@@ -2613,6 +2721,41 @@ mod tests {
|
||||
assert!(fsync_recorder::dir_sync_count(dir) > dirs_before, "delete must fsync the key directory");
|
||||
}
|
||||
|
||||
/// KmsManager::delete_key is the enforcement point for the waiting window;
|
||||
/// this pins the backend's defensive copy of the same bound, which is all
|
||||
/// that stands between a direct backend caller and a one-day window.
|
||||
#[tokio::test]
|
||||
async fn delete_key_refuses_a_window_outside_the_supported_range() {
|
||||
let (client, _temp_dir) = create_test_client().await;
|
||||
let key_id = "window-bounds-key";
|
||||
client.create_key(key_id, "AES_256", None).await.expect("create key");
|
||||
let backend = LocalKmsBackend { client };
|
||||
|
||||
for days in [MIN_PENDING_DELETION_WINDOW_DAYS - 1, MAX_PENDING_DELETION_WINDOW_DAYS + 1] {
|
||||
let result = backend
|
||||
.delete_key(DeleteKeyRequest {
|
||||
key_id: key_id.to_string(),
|
||||
pending_window_in_days: Some(days),
|
||||
..Default::default()
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
matches!(result, Err(KmsError::InvalidOperation { .. })),
|
||||
"a {days}-day window must be refused, got {result:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let state = backend
|
||||
.describe_key(DescribeKeyRequest {
|
||||
key_id: key_id.to_string(),
|
||||
})
|
||||
.await
|
||||
.expect("describe should succeed")
|
||||
.key_metadata
|
||||
.key_state;
|
||||
assert_eq!(state, KeyState::Enabled, "a refused window must not schedule the key");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn interrupted_update_commit_recovers_to_complete_old_or_new_state() {
|
||||
use durable_file::{CommitStep, failpoint};
|
||||
@@ -2969,4 +3112,131 @@ mod tests {
|
||||
.expect("repeat removal");
|
||||
assert_eq!(outcome, crate::backends::ExpiredKeyRemoval::Removed);
|
||||
}
|
||||
|
||||
// -- Listing and pagination ---------------------------------------------
|
||||
|
||||
fn page_request(limit: u32, marker: Option<&str>) -> ListKeysRequest {
|
||||
ListKeysRequest {
|
||||
limit: Some(limit),
|
||||
marker: marker.map(str::to_string),
|
||||
usage_filter: None,
|
||||
status_filter: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_keys(client: &LocalKmsClient, key_ids: &[String]) {
|
||||
for key_id in key_ids {
|
||||
client
|
||||
.create_key(key_id, "AES_256", None)
|
||||
.await
|
||||
.expect("key should be created");
|
||||
}
|
||||
}
|
||||
|
||||
/// Paging must reach every key exactly once. A backend that reports the
|
||||
/// first page as the whole key set strands everything behind it — the
|
||||
/// deletion sweep would never destroy expired material past page one.
|
||||
#[tokio::test]
|
||||
async fn list_keys_pages_through_the_whole_key_set() {
|
||||
let (client, _temp_dir) = create_test_client().await;
|
||||
let expected: Vec<String> = (0..7).map(|index| format!("page-key-{index:02}")).collect();
|
||||
create_keys(&client, &expected).await;
|
||||
|
||||
let mut seen = Vec::new();
|
||||
let mut marker: Option<String> = None;
|
||||
// Bounded so a listing that cannot advance fails the assertion below
|
||||
// instead of hanging the test run.
|
||||
for _ in 0..expected.len() + 1 {
|
||||
let response = client
|
||||
.list_keys(&page_request(3, marker.as_deref()), None)
|
||||
.await
|
||||
.expect("list should succeed");
|
||||
assert!(response.keys.len() <= 3, "a page must not exceed the requested limit");
|
||||
seen.extend(response.keys.iter().map(|key| key.key_id.clone()));
|
||||
if !response.truncated {
|
||||
assert!(response.next_marker.is_none(), "a final page must not offer a cursor");
|
||||
break;
|
||||
}
|
||||
marker = Some(response.next_marker.expect("a truncated page must offer a cursor"));
|
||||
}
|
||||
|
||||
assert_eq!(seen, expected, "paging must visit every key exactly once, in identifier order");
|
||||
}
|
||||
|
||||
/// Exact-limit boundary: a page that ends on the last key is complete.
|
||||
#[tokio::test]
|
||||
async fn list_keys_page_ending_on_the_last_key_is_not_truncated() {
|
||||
let (client, _temp_dir) = create_test_client().await;
|
||||
let key_ids: Vec<String> = (0..3).map(|index| format!("exact-key-{index}")).collect();
|
||||
create_keys(&client, &key_ids).await;
|
||||
|
||||
let response = client
|
||||
.list_keys(&page_request(3, None), None)
|
||||
.await
|
||||
.expect("list should succeed");
|
||||
assert_eq!(response.keys.len(), 3);
|
||||
assert!(!response.truncated);
|
||||
assert!(response.next_marker.is_none());
|
||||
|
||||
// One key short of the set, the same listing is truncated.
|
||||
let response = client
|
||||
.list_keys(&page_request(2, None), None)
|
||||
.await
|
||||
.expect("list should succeed");
|
||||
assert!(response.truncated);
|
||||
assert_eq!(response.next_marker.as_deref(), Some("exact-key-1"));
|
||||
}
|
||||
|
||||
/// The cursor is an identifier, not an index, so it keeps working after the
|
||||
/// key it names is destroyed — which is exactly what the deletion sweep
|
||||
/// does to the keys it retires between pages.
|
||||
#[tokio::test]
|
||||
async fn list_keys_resumes_after_a_deleted_marker_key() {
|
||||
let (client, _temp_dir) = create_test_client().await;
|
||||
let key_ids: Vec<String> = ["marker-a", "marker-b", "marker-c"].iter().map(|id| id.to_string()).collect();
|
||||
create_keys(&client, &key_ids).await;
|
||||
|
||||
fs::remove_file(client.master_key_path("marker-b").expect("key path"))
|
||||
.await
|
||||
.expect("key file should be removable");
|
||||
|
||||
let response = client
|
||||
.list_keys(&page_request(10, Some("marker-b")), None)
|
||||
.await
|
||||
.expect("list should succeed");
|
||||
let listed: Vec<&str> = response.keys.iter().map(|key| key.key_id.as_str()).collect();
|
||||
assert_eq!(listed, vec!["marker-c"], "a vanished marker must not restart the listing");
|
||||
assert!(!response.truncated);
|
||||
}
|
||||
|
||||
/// A zero limit means zero keys, and no cursor to loop on.
|
||||
#[tokio::test]
|
||||
async fn list_keys_with_zero_limit_returns_an_empty_page() {
|
||||
let (client, _temp_dir) = create_test_client().await;
|
||||
create_keys(&client, &["zero-limit-key".to_string()]).await;
|
||||
|
||||
let response = client
|
||||
.list_keys(&page_request(0, None), None)
|
||||
.await
|
||||
.expect("a zero-limit list must succeed");
|
||||
assert!(response.keys.is_empty());
|
||||
assert!(!response.truncated);
|
||||
assert!(response.next_marker.is_none());
|
||||
}
|
||||
|
||||
/// A limit past the end of the key set returns everything, once.
|
||||
#[tokio::test]
|
||||
async fn list_keys_limit_beyond_the_key_set_returns_one_complete_page() {
|
||||
let (client, _temp_dir) = create_test_client().await;
|
||||
let key_ids: Vec<String> = (0..3).map(|index| format!("huge-limit-key-{index}")).collect();
|
||||
create_keys(&client, &key_ids).await;
|
||||
|
||||
let response = client
|
||||
.list_keys(&page_request(u32::MAX, None), None)
|
||||
.await
|
||||
.expect("list should succeed");
|
||||
assert_eq!(response.keys.len(), 3);
|
||||
assert!(!response.truncated);
|
||||
assert!(response.next_marker.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,9 @@ use crate::types::*;
|
||||
use async_trait::async_trait;
|
||||
use jiff::Zoned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub mod aws;
|
||||
#[cfg(test)]
|
||||
mod contract_tests;
|
||||
pub mod local;
|
||||
@@ -98,6 +100,122 @@ pub(crate) fn ensure_key_status_permits(key_id: &str, status: &KeyStatus, operat
|
||||
ensure_key_state_permits(key_id, &state, operation)
|
||||
}
|
||||
|
||||
/// Tag key that carries the key's identity rather than user metadata.
|
||||
///
|
||||
/// The key-creation path lifts `name` out of the caller's tag map and uses it
|
||||
/// as the key id, so a key's `name` tag and its id are the same string.
|
||||
/// Rewriting or dropping it after creation would leave the key addressable
|
||||
/// under an id its own metadata no longer states. Metadata updates therefore
|
||||
/// reject it; only creation may set it.
|
||||
pub const RESERVED_KEY_NAME_TAG: &str = "name";
|
||||
|
||||
/// Reject a metadata update that would rewrite or remove
|
||||
/// [`RESERVED_KEY_NAME_TAG`].
|
||||
///
|
||||
/// Enforced by every backend that implements tag updates, so no call path —
|
||||
/// including a direct [`KmsBackend`] user that bypasses the manager — can
|
||||
/// detach a key from its identity.
|
||||
pub(crate) fn ensure_tag_keys_are_mutable<'a>(tag_keys: impl IntoIterator<Item = &'a str>) -> Result<()> {
|
||||
for tag_key in tag_keys {
|
||||
if tag_key == RESERVED_KEY_NAME_TAG {
|
||||
return Err(KmsError::invalid_parameter(format!(
|
||||
"Tag '{RESERVED_KEY_NAME_TAG}' identifies the key and cannot be updated or removed"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Page size used when a [`ListKeysRequest`] does not ask for one.
|
||||
pub(crate) const DEFAULT_LIST_KEYS_PAGE_SIZE: u32 = 100;
|
||||
|
||||
/// One page of a key set the backend has to slice itself.
|
||||
pub(crate) struct KeyPage<'a, T> {
|
||||
/// The identifiers this page covers, in listing order.
|
||||
pub(crate) items: &'a [T],
|
||||
/// Where the next page resumes; `None` when this page is the last one.
|
||||
pub(crate) next_marker: Option<String>,
|
||||
/// Whether keys remain beyond this page.
|
||||
pub(crate) truncated: bool,
|
||||
}
|
||||
|
||||
/// Cut the page `request` asks for out of `sorted`.
|
||||
///
|
||||
/// `sorted` must be ordered by the identifier `key_id_of` returns, and the
|
||||
/// marker is an *exclusive lower bound* on that identifier rather than an index
|
||||
/// into the sequence. That is what makes paging survive concurrent mutation:
|
||||
/// the next page resumes at the first identifier greater than the marker, so a
|
||||
/// key added or removed elsewhere in the ordering — including the marker key
|
||||
/// itself, which the deletion sweep routinely destroys — cannot make the
|
||||
/// listing skip keys or restart from the beginning.
|
||||
///
|
||||
/// A `limit` of zero is honoured as written: the caller asked for no keys and
|
||||
/// gets an empty, non-truncated page (see [`list_keys_page_size`]).
|
||||
///
|
||||
/// Filters are applied by the caller to `items` after this slice, so a filtered
|
||||
/// page can be shorter than `limit` — and even empty — while more keys remain.
|
||||
/// Callers must page until `truncated` is false rather than until a page comes
|
||||
/// back short.
|
||||
pub(crate) fn paginate_keys<'a, T>(sorted: &'a [T], request: &ListKeysRequest, key_id_of: impl Fn(&T) -> &str) -> KeyPage<'a, T> {
|
||||
let Some(limit) = list_keys_page_size(request.limit) else {
|
||||
return KeyPage {
|
||||
items: &[],
|
||||
next_marker: None,
|
||||
truncated: false,
|
||||
};
|
||||
};
|
||||
|
||||
let start = match request.marker.as_deref() {
|
||||
Some(marker) => sorted.partition_point(|item| key_id_of(item) <= marker),
|
||||
None => 0,
|
||||
};
|
||||
// `partition_point` never exceeds the length, so both bounds stay in range
|
||||
// however large `limit` is.
|
||||
let end = start.saturating_add(limit).min(sorted.len());
|
||||
let items = &sorted[start..end];
|
||||
let truncated = end < sorted.len();
|
||||
|
||||
KeyPage {
|
||||
items,
|
||||
// Resuming from the last identifier on the page, not from an index,
|
||||
// keeps the cursor meaningful after the key it names disappears.
|
||||
next_marker: if truncated {
|
||||
items.last().map(|item| key_id_of(item).to_string())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
truncated,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the page size of a [`ListKeysRequest`]; `None` means the caller
|
||||
/// asked for no keys at all.
|
||||
///
|
||||
/// `Some(0)` is a well-formed request for an empty page — the reading rustfs
|
||||
/// already gives `max-keys=0` on the S3 listing path — not a malformed one and
|
||||
/// not an omitted value. Rounding it up to a default would hand back a full
|
||||
/// page of keys to a caller that explicitly asked for none.
|
||||
pub(crate) fn list_keys_page_size(limit: Option<u32>) -> Option<usize> {
|
||||
match limit.unwrap_or(DEFAULT_LIST_KEYS_PAGE_SIZE) {
|
||||
0 => None,
|
||||
size => Some(size as usize),
|
||||
}
|
||||
}
|
||||
|
||||
/// The response to a request for zero keys.
|
||||
///
|
||||
/// `truncated` is false even when keys exist: a zero-length page carries no
|
||||
/// identifier to resume from, so claiming more results would hand back a cursor
|
||||
/// the caller can never advance and turn a `while truncated` loop into a
|
||||
/// non-terminating one.
|
||||
pub(crate) fn empty_key_page() -> ListKeysResponse {
|
||||
ListKeysResponse {
|
||||
keys: Vec::new(),
|
||||
next_marker: None,
|
||||
truncated: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Simplified KMS backend interface for manager
|
||||
#[async_trait]
|
||||
pub trait KmsBackend: Send + Sync {
|
||||
@@ -153,6 +271,38 @@ pub trait KmsBackend: Send + Sync {
|
||||
Err(KmsError::unsupported_capability("backend without rotation support", "rotate_key"))
|
||||
}
|
||||
|
||||
/// Replace a key's free-form description; `None` clears it.
|
||||
///
|
||||
/// Backends that advertise [`BackendCapabilities::update_key_metadata`]
|
||||
/// must override this method; the default rejects the operation.
|
||||
async fn update_key_description(&self, _key_id: &str, _description: Option<&str>) -> Result<()> {
|
||||
Err(KmsError::unsupported_capability(
|
||||
"backend without key metadata updates",
|
||||
"update_key_description",
|
||||
))
|
||||
}
|
||||
|
||||
/// Add or overwrite the given tags, leaving every other tag untouched.
|
||||
///
|
||||
/// Implementations must run [`ensure_tag_keys_are_mutable`] before
|
||||
/// persisting anything. Backends that advertise
|
||||
/// [`BackendCapabilities::update_key_metadata`] must override this method;
|
||||
/// the default rejects the operation.
|
||||
async fn tag_key(&self, _key_id: &str, _tags: &HashMap<String, String>) -> Result<()> {
|
||||
Err(KmsError::unsupported_capability("backend without key metadata updates", "tag_key"))
|
||||
}
|
||||
|
||||
/// Remove the given tags.
|
||||
///
|
||||
/// Tags that are not set are ignored, so repeating the call is a no-op
|
||||
/// rather than an error. Implementations must run
|
||||
/// [`ensure_tag_keys_are_mutable`] before persisting anything. Backends
|
||||
/// that advertise [`BackendCapabilities::update_key_metadata`] must
|
||||
/// override this method; the default rejects the operation.
|
||||
async fn untag_key(&self, _key_id: &str, _tag_keys: &[String]) -> Result<()> {
|
||||
Err(KmsError::unsupported_capability("backend without key metadata updates", "untag_key"))
|
||||
}
|
||||
|
||||
/// Health check
|
||||
async fn health_check(&self) -> Result<bool>;
|
||||
|
||||
@@ -181,6 +331,19 @@ pub trait KmsBackend: Send + Sync {
|
||||
async fn remove_expired_key(&self, _key_id: &str, _now: &Zoned) -> Result<ExpiredKeyRemoval> {
|
||||
Err(KmsError::unsupported_capability("backend without deletion support", "remove_expired_key"))
|
||||
}
|
||||
|
||||
/// The running client to export a full-material backup bundle from.
|
||||
///
|
||||
/// Only the Local backend owns key material RustFS is allowed to export in
|
||||
/// full (see [`crate::backup::BackupResponsibility`]); every other backend
|
||||
/// keeps its cryptographic root outside RustFS and returns `None` here.
|
||||
///
|
||||
/// The export must run against the *running* client so that its fence
|
||||
/// actually blocks concurrent create/delete work — a second client opened
|
||||
/// on the same key directory would fence nothing.
|
||||
fn local_backup_client(&self) -> Option<&local::LocalKmsClient> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Outcome of [`KmsBackend::remove_expired_key`].
|
||||
@@ -222,6 +385,8 @@ pub struct BackendCapabilities {
|
||||
pub versioning: bool,
|
||||
/// Irreversible physical deletion of key material
|
||||
pub physical_delete: bool,
|
||||
/// Updating a key's description and tags after creation
|
||||
pub update_key_metadata: bool,
|
||||
}
|
||||
|
||||
impl BackendCapabilities {
|
||||
@@ -238,6 +403,7 @@ impl BackendCapabilities {
|
||||
schedule_deletion: false,
|
||||
versioning: false,
|
||||
physical_delete: false,
|
||||
update_key_metadata: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -288,6 +454,12 @@ impl BackendCapabilities {
|
||||
self.physical_delete = physical_delete;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set whether description and tag updates are supported
|
||||
pub const fn with_update_key_metadata(mut self, update_key_metadata: bool) -> Self {
|
||||
self.update_key_metadata = update_key_metadata;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for BackendCapabilities {
|
||||
@@ -366,6 +538,7 @@ mod tests {
|
||||
assert!(!capabilities.schedule_deletion);
|
||||
assert!(!capabilities.versioning);
|
||||
assert!(!capabilities.physical_delete);
|
||||
assert!(!capabilities.update_key_metadata);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -374,6 +547,12 @@ mod tests {
|
||||
("enable_key", MinimalBackend.enable_key("any-key").await),
|
||||
("disable_key", MinimalBackend.disable_key("any-key").await),
|
||||
("rotate_key", MinimalBackend.rotate_key("any-key").await),
|
||||
(
|
||||
"update_key_description",
|
||||
MinimalBackend.update_key_description("any-key", Some("new")).await,
|
||||
),
|
||||
("tag_key", MinimalBackend.tag_key("any-key", &HashMap::new()).await),
|
||||
("untag_key", MinimalBackend.untag_key("any-key", &[]).await),
|
||||
] {
|
||||
let error = result.expect_err("backends must opt in to lifecycle operations by overriding them");
|
||||
assert!(
|
||||
@@ -395,6 +574,20 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_tag_is_rejected_by_metadata_updates() {
|
||||
let error = ensure_tag_keys_are_mutable([RESERVED_KEY_NAME_TAG])
|
||||
.expect_err("the identity tag must not be writable through a metadata update");
|
||||
assert!(
|
||||
matches!(&error, KmsError::InvalidOperation { message } if message.contains(RESERVED_KEY_NAME_TAG)),
|
||||
"expected a typed rejection naming the tag, got {error:?}"
|
||||
);
|
||||
|
||||
// Ordinary tags — including ones that merely contain the reserved name
|
||||
// — stay writable.
|
||||
ensure_tag_keys_are_mutable(["team", "nickname", "Name"]).expect("ordinary tags must remain writable");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_backend_capabilities_golden() {
|
||||
let temp_dir = tempfile::tempdir().expect("temp dir should be created");
|
||||
@@ -443,4 +636,84 @@ mod tests {
|
||||
|
||||
insta::assert_json_snapshot!("static_backend_capabilities", capabilities_snapshot(backend.capabilities()));
|
||||
}
|
||||
|
||||
// -- Pagination boundaries ----------------------------------------------
|
||||
|
||||
fn key_ids(count: usize) -> Vec<String> {
|
||||
(0..count).map(|index| format!("key-{index:02}")).collect()
|
||||
}
|
||||
|
||||
fn page_request(limit: Option<u32>, marker: Option<&str>) -> ListKeysRequest {
|
||||
ListKeysRequest {
|
||||
limit,
|
||||
marker: marker.map(str::to_string),
|
||||
usage_filter: None,
|
||||
status_filter: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn page_of(keys: &[String], limit: Option<u32>, marker: Option<&str>) -> (Vec<String>, Option<String>, bool) {
|
||||
let page = paginate_keys(keys, &page_request(limit, marker), String::as_str);
|
||||
(page.items.to_vec(), page.next_marker, page.truncated)
|
||||
}
|
||||
|
||||
/// Zero keys requested, zero keys returned — and no cursor, so a caller
|
||||
/// looping on `truncated` terminates instead of asking forever. Slicing a
|
||||
/// zero-length page out of a non-empty key set must not reach for the
|
||||
/// element before the page either.
|
||||
#[test]
|
||||
fn zero_limit_returns_an_empty_untruncated_page() {
|
||||
let keys = key_ids(3);
|
||||
assert_eq!(page_of(&keys, Some(0), None), (Vec::new(), None, false));
|
||||
assert_eq!(page_of(&keys, Some(0), Some("key-01")), (Vec::new(), None, false));
|
||||
// Also at the ends of the key set, where a page has no predecessor.
|
||||
assert_eq!(page_of(&[], Some(0), None), (Vec::new(), None, false));
|
||||
assert_eq!(page_of(&keys, Some(0), Some("key-02")), (Vec::new(), None, false));
|
||||
|
||||
assert_eq!(list_keys_page_size(Some(0)), None);
|
||||
assert_eq!(list_keys_page_size(None), Some(DEFAULT_LIST_KEYS_PAGE_SIZE as usize));
|
||||
assert_eq!(list_keys_page_size(Some(7)), Some(7));
|
||||
}
|
||||
|
||||
/// A limit past the end of the key set is not an overflow.
|
||||
#[test]
|
||||
fn oversized_limit_returns_the_whole_key_set_once() {
|
||||
let keys = key_ids(3);
|
||||
assert_eq!(page_of(&keys, Some(u32::MAX), None), (keys.clone(), None, false));
|
||||
assert_eq!(page_of(&keys, Some(u32::MAX), Some("key-01")), (vec![keys[2].clone()], None, false));
|
||||
}
|
||||
|
||||
/// The cursor is an identifier, so a marker naming a key that no longer
|
||||
/// exists resumes after where it would have been instead of restarting.
|
||||
#[test]
|
||||
fn marker_for_a_removed_key_resumes_after_it() {
|
||||
let keys = vec!["key-00".to_string(), "key-02".to_string()];
|
||||
assert_eq!(page_of(&keys, Some(10), Some("key-01")), (vec!["key-02".to_string()], None, false));
|
||||
// A marker past every key ends the listing rather than wrapping.
|
||||
assert_eq!(page_of(&keys, Some(10), Some("key-99")), (Vec::new(), None, false));
|
||||
// A marker before every key yields the whole set.
|
||||
assert_eq!(page_of(&keys, Some(10), Some("key")), (keys.clone(), None, false));
|
||||
}
|
||||
|
||||
/// Truncation flips exactly at the page boundary, and paging covers the
|
||||
/// key set once end to end.
|
||||
#[test]
|
||||
fn pages_tile_the_key_set_exactly_at_the_limit_boundary() {
|
||||
let keys = key_ids(4);
|
||||
assert_eq!(page_of(&keys, Some(4), None), (keys.clone(), None, false));
|
||||
assert_eq!(page_of(&keys, Some(3), None), (keys[..3].to_vec(), Some("key-02".to_string()), true));
|
||||
|
||||
let mut seen = Vec::new();
|
||||
let mut marker = None;
|
||||
loop {
|
||||
let (items, next_marker, truncated) = page_of(&keys, Some(2), marker.as_deref());
|
||||
seen.extend(items);
|
||||
if !truncated {
|
||||
assert!(next_marker.is_none(), "a final page must not offer a cursor");
|
||||
break;
|
||||
}
|
||||
marker = Some(next_marker.expect("a truncated page must offer a cursor"));
|
||||
}
|
||||
assert_eq!(seen, keys, "paging must tile the key set exactly once");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,16 +26,16 @@ use std::sync::{Arc, Mutex};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
/// One canned HTTP response.
|
||||
pub(crate) struct ScriptedResponse {
|
||||
status: u16,
|
||||
body: String,
|
||||
/// One scripted connection outcome.
|
||||
pub(crate) enum ScriptedResponse {
|
||||
Http { status: u16, body: String },
|
||||
Close,
|
||||
}
|
||||
|
||||
impl ScriptedResponse {
|
||||
/// A 200 response carrying `data` inside the standard Vault envelope.
|
||||
pub(crate) fn ok(data: serde_json::Value) -> Self {
|
||||
Self {
|
||||
Self::Http {
|
||||
status: 200,
|
||||
body: serde_json::json!({
|
||||
"request_id": "scripted",
|
||||
@@ -50,11 +50,16 @@ impl ScriptedResponse {
|
||||
|
||||
/// An error response in Vault's `{"errors": [...]}` format.
|
||||
pub(crate) fn error(status: u16, message: &str) -> Self {
|
||||
Self {
|
||||
Self::Http {
|
||||
status,
|
||||
body: serde_json::json!({ "errors": [message] }).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Close the connection after consuming a request without sending an HTTP response.
|
||||
pub(crate) fn close() -> Self {
|
||||
Self::Close
|
||||
}
|
||||
}
|
||||
|
||||
/// A scripted stand-in Vault listening on a loopback port.
|
||||
@@ -88,14 +93,14 @@ impl ScriptedVault {
|
||||
let response = responses
|
||||
.next()
|
||||
.unwrap_or_else(|| ScriptedResponse::error(599, "scripted vault: script exhausted"));
|
||||
let payload = format!(
|
||||
"HTTP/1.1 {} Scripted\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
|
||||
response.status,
|
||||
response.body.len(),
|
||||
response.body
|
||||
);
|
||||
let _ = stream.write_all(payload.as_bytes()).await;
|
||||
let _ = stream.shutdown().await;
|
||||
if let ScriptedResponse::Http { status, body } = response {
|
||||
let payload = format!(
|
||||
"HTTP/1.1 {status} Scripted\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
|
||||
body.len(),
|
||||
);
|
||||
let _ = stream.write_all(payload.as_bytes()).await;
|
||||
let _ = stream.shutdown().await;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: crates/kms/src/backends/aws.rs
|
||||
expression: capabilities_snapshot(backend.capabilities())
|
||||
---
|
||||
{
|
||||
"decrypt": true,
|
||||
"enable_disable": true,
|
||||
"encrypt": true,
|
||||
"generate_data_key": true,
|
||||
"physical_delete": false,
|
||||
"rotate": true,
|
||||
"schedule_deletion": true,
|
||||
"update_key_metadata": false,
|
||||
"versioning": true
|
||||
}
|
||||
+1
@@ -10,5 +10,6 @@ expression: capabilities_snapshot(backend.capabilities())
|
||||
"physical_delete": true,
|
||||
"rotate": false,
|
||||
"schedule_deletion": true,
|
||||
"update_key_metadata": true,
|
||||
"versioning": false
|
||||
}
|
||||
|
||||
+1
@@ -10,5 +10,6 @@ expression: capabilities_snapshot(backend.capabilities())
|
||||
"physical_delete": false,
|
||||
"rotate": false,
|
||||
"schedule_deletion": false,
|
||||
"update_key_metadata": false,
|
||||
"versioning": false
|
||||
}
|
||||
|
||||
+1
@@ -10,5 +10,6 @@ expression: capabilities_snapshot(backend.capabilities())
|
||||
"physical_delete": true,
|
||||
"rotate": true,
|
||||
"schedule_deletion": true,
|
||||
"update_key_metadata": true,
|
||||
"versioning": true
|
||||
}
|
||||
|
||||
+1
@@ -10,5 +10,6 @@ expression: capabilities_snapshot(backend.capabilities())
|
||||
"physical_delete": true,
|
||||
"rotate": true,
|
||||
"schedule_deletion": true,
|
||||
"update_key_metadata": true,
|
||||
"versioning": true
|
||||
}
|
||||
|
||||
@@ -19,9 +19,12 @@
|
||||
//!
|
||||
//! ## Ciphertext format
|
||||
//!
|
||||
//! encrypted_data(plaintext_len+16) || nonce (12 bytes)
|
||||
//! A JSON-serialized `DataKeyEnvelope` carrying the AES-256-GCM ciphertext, the
|
||||
//! 12-byte nonce and the authenticated encryption context. This is a
|
||||
//! RustFS-internal format; it is not interchangeable with MinIO's KMS
|
||||
//! ciphertext (see the note on `StaticConfig`).
|
||||
|
||||
use crate::backends::{BackendCapabilities, KmsBackend};
|
||||
use crate::backends::{BackendCapabilities, KmsBackend, empty_key_page, list_keys_page_size};
|
||||
use crate::config::{BackendConfig, KmsConfig};
|
||||
use crate::encryption::DataKeyEnvelope;
|
||||
use crate::error::{KmsError, Result};
|
||||
@@ -262,6 +265,12 @@ impl StaticKmsBackend {
|
||||
|
||||
/// List the single configured key, honouring the pagination marker.
|
||||
pub(crate) fn list_configured_key(&self, request: &ListKeysRequest) -> Result<ListKeysResponse> {
|
||||
// A caller asking for no keys gets none, even from a backend whose
|
||||
// whole key set is one key.
|
||||
if list_keys_page_size(request.limit).is_none() {
|
||||
return Ok(empty_key_page());
|
||||
}
|
||||
|
||||
let key_info = KeyInfo {
|
||||
key_id: self.key_id.clone(),
|
||||
description: Some("Static single-key KMS backend".to_string()),
|
||||
@@ -431,6 +440,32 @@ mod tests {
|
||||
(backend, key_id, key)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metadata_updates_report_the_capability_gap() {
|
||||
let (backend, key_id, _key) = create_test_backend().await;
|
||||
assert!(
|
||||
!backend.capabilities().update_key_metadata,
|
||||
"Static KMS owns no mutable key record, so it must not advertise metadata updates"
|
||||
);
|
||||
|
||||
for (operation, result) in [
|
||||
("update_key_description", backend.update_key_description(&key_id, Some("new")).await),
|
||||
(
|
||||
"tag_key",
|
||||
backend
|
||||
.tag_key(&key_id, &HashMap::from([("team".to_string(), "storage".to_string())]))
|
||||
.await,
|
||||
),
|
||||
("untag_key", backend.untag_key(&key_id, &["team".to_string()]).await),
|
||||
] {
|
||||
let error = result.expect_err("Static KMS is read-only: metadata updates must be rejected");
|
||||
assert!(
|
||||
matches!(error, KmsError::UnsupportedCapability { .. }),
|
||||
"expected UnsupportedCapability for {operation}, got {error:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_generate_and_decrypt_data_key() {
|
||||
let (backend, key_id, _key) = create_test_backend().await;
|
||||
@@ -631,6 +666,23 @@ mod tests {
|
||||
assert!(!response.truncated);
|
||||
}
|
||||
|
||||
/// A zero limit means zero keys, even for a backend whose whole key set is
|
||||
/// a single configured key.
|
||||
#[tokio::test]
|
||||
async fn zero_limit_list_returns_an_empty_page() {
|
||||
let (backend, _key_id, _key) = create_test_backend().await;
|
||||
|
||||
let response = backend
|
||||
.list_configured_key(&ListKeysRequest {
|
||||
limit: Some(0),
|
||||
..Default::default()
|
||||
})
|
||||
.expect("a zero-limit list must succeed");
|
||||
assert!(response.keys.is_empty());
|
||||
assert!(!response.truncated);
|
||||
assert!(response.next_marker.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lifecycle_mutations_are_unsupported_at_the_product_surface() {
|
||||
let (backend, key_id, _key) = create_test_backend().await;
|
||||
@@ -657,6 +709,7 @@ mod tests {
|
||||
key_id: key_id.clone(),
|
||||
pending_window_in_days: Some(7),
|
||||
force_immediate: None,
|
||||
confirm_key_id: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
+1094
-57
File diff suppressed because it is too large
Load Diff
@@ -57,6 +57,42 @@ const DEFAULT_REFRESH_RETRY_INTERVAL: Duration = Duration::from_secs(5);
|
||||
/// Default seconds between token file re-reads for [`TokenFileSource`].
|
||||
const DEFAULT_TOKEN_FILE_POLL_INTERVAL_SECS: u64 = 30;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Metrics
|
||||
//
|
||||
// Both gauges describe the one credential generation currently installed, so
|
||||
// they carry no labels: the Vault address, mount, auth path and token are all
|
||||
// off limits as label values, and there is exactly one generation to describe.
|
||||
// The renewal loop republishes them on a bounded cadence while it waits, so a
|
||||
// scrape landing between refresh cycles never reads a TTL frozen at the last
|
||||
// refresh, or a fail-closed state that flipped after it.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Gauge: seconds left before the active Vault token expires; `0` once it has.
|
||||
const METRIC_TOKEN_TTL_SECONDS: &str = "rustfs_kms_vault_token_ttl_seconds";
|
||||
/// Gauge: `1` while [`VaultCredentialProvider::current`] refuses to hand out
|
||||
/// the token because it is inside the fail-closed safety window, `0` otherwise.
|
||||
const METRIC_CREDENTIALS_FAIL_CLOSED: &str = "rustfs_kms_vault_credentials_fail_closed";
|
||||
|
||||
/// How often the renewal loop republishes the credential gauges while waiting.
|
||||
/// Bounds how stale a scrape can be, without any additional Vault traffic.
|
||||
const CREDENTIAL_GAUGE_INTERVAL: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Register metric descriptions once per process.
|
||||
fn describe_credential_metrics() {
|
||||
static DESCRIBE: std::sync::Once = std::sync::Once::new();
|
||||
DESCRIBE.call_once(|| {
|
||||
metrics::describe_gauge!(
|
||||
METRIC_TOKEN_TTL_SECONDS,
|
||||
"Seconds remaining before the Vault token backing the KMS backend expires"
|
||||
);
|
||||
metrics::describe_gauge!(
|
||||
METRIC_CREDENTIALS_FAIL_CLOSED,
|
||||
"1 while the Vault credential provider refuses to serve its token because the token is inside the fail-closed safety window"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// A crate-owned secret value, zeroized on drop and redacted in Debug output.
|
||||
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
|
||||
pub(crate) struct SecretString(String);
|
||||
@@ -627,6 +663,45 @@ impl VaultCredentialProvider {
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
/// Publish the credential gauges for the generation currently installed.
|
||||
///
|
||||
/// The fail-closed gauge re-evaluates the very gate
|
||||
/// [`VaultCredentialProvider::current`] applies, so what operators see and
|
||||
/// what the request path does cannot drift apart.
|
||||
fn record_credential_gauges(&self) {
|
||||
let handle = self.current.load();
|
||||
let now = Instant::now();
|
||||
let fail_closed = match handle.expires_at() {
|
||||
Some(expires_at) => {
|
||||
metrics::gauge!(METRIC_TOKEN_TTL_SECONDS).set(expires_at.saturating_duration_since(now).as_secs_f64());
|
||||
now + self.policy.safety_window >= expires_at
|
||||
}
|
||||
// A generation without an expiry has no remaining TTL to report
|
||||
// and can never lapse, so it can never fail closed either.
|
||||
None => false,
|
||||
};
|
||||
metrics::gauge!(METRIC_CREDENTIALS_FAIL_CLOSED).set(if fail_closed { 1.0 } else { 0.0 });
|
||||
}
|
||||
|
||||
/// Wait until `deadline`, republishing the credential gauges on the
|
||||
/// observation cadence. Reports `false` when cancellation cut the wait
|
||||
/// short.
|
||||
async fn wait_publishing_gauges(&self, deadline: Instant, cancel: &CancellationToken) -> bool {
|
||||
loop {
|
||||
self.record_credential_gauges();
|
||||
let now = Instant::now();
|
||||
if now >= deadline {
|
||||
return true;
|
||||
}
|
||||
let slice = (deadline - now).min(CREDENTIAL_GAUGE_INTERVAL);
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return false,
|
||||
_ = tokio::time::sleep(slice) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Refresh the credentials if generation `observed` is still current.
|
||||
///
|
||||
/// Single-flight: concurrent callers serialize on the refresh lock, and a
|
||||
@@ -711,17 +786,22 @@ impl fmt::Debug for VaultCredentialProvider {
|
||||
/// again immediately (the renewal point is already in the past), so the
|
||||
/// provider keeps trying to recover even after the fail-closed window has
|
||||
/// been reached.
|
||||
///
|
||||
/// Both waits run through [`VaultCredentialProvider::wait_publishing_gauges`],
|
||||
/// which is the only place the credential gauges are published: the loop is
|
||||
/// already the component that tracks token expiry, and doing it here keeps the
|
||||
/// request path free of any metric work.
|
||||
async fn renewal_loop(provider: Arc<VaultCredentialProvider>, cancel: CancellationToken) {
|
||||
describe_credential_metrics();
|
||||
loop {
|
||||
let handle = provider.snapshot();
|
||||
let Some(renew_at) = handle.renew_at() else {
|
||||
// The current generation never expires; nothing left to schedule.
|
||||
provider.record_credential_gauges();
|
||||
return;
|
||||
};
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return,
|
||||
_ = tokio::time::sleep_until(renew_at) => {}
|
||||
if !provider.wait_publishing_gauges(renew_at, &cancel).await {
|
||||
return;
|
||||
}
|
||||
|
||||
match provider.refresh(handle.generation, &cancel).await {
|
||||
@@ -733,10 +813,9 @@ async fn renewal_loop(provider: Arc<VaultCredentialProvider>, cancel: Cancellati
|
||||
error = %error,
|
||||
"Vault credential refresh failed; retrying until the credentials recover"
|
||||
);
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return,
|
||||
_ = tokio::time::sleep(provider.policy.retry_interval) => {}
|
||||
let retry_at = Instant::now() + provider.policy.retry_interval;
|
||||
if !provider.wait_publishing_gauges(retry_at, &cancel).await {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1354,4 +1433,125 @@ mod tests {
|
||||
assert!(!rendered.contains(TEST_TOKEN), "debug output must not leak the vault token: {rendered}");
|
||||
assert!(rendered.contains("vault-token"), "the file path is not a secret");
|
||||
}
|
||||
|
||||
// -- Metric emission ----------------------------------------------------
|
||||
//
|
||||
// Each test installs a thread-local debugging recorder and drives a
|
||||
// paused-clock current-thread runtime inside it, so the renewal loop's
|
||||
// gauge publications land on exact virtual timestamps.
|
||||
|
||||
use metrics_util::MetricKind;
|
||||
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
|
||||
|
||||
type MetricEntry = (
|
||||
metrics_util::CompositeKey,
|
||||
Option<metrics::Unit>,
|
||||
Option<metrics::SharedString>,
|
||||
DebugValue,
|
||||
);
|
||||
|
||||
/// Run `test` on a paused current-thread runtime under a debugging
|
||||
/// recorder and return one snapshot of everything it emitted.
|
||||
///
|
||||
/// A single snapshot per test on purpose: `Snapshotter::snapshot` drains
|
||||
/// the recorded state, so taking it per assertion would only show the
|
||||
/// first assertion any data.
|
||||
fn record_metrics<Out>(
|
||||
test: impl FnOnce() -> std::pin::Pin<Box<dyn std::future::Future<Output = Out>>>,
|
||||
) -> (Vec<MetricEntry>, Out) {
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
let out = metrics::with_local_recorder(&recorder, || {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.start_paused(true)
|
||||
.build()
|
||||
.expect("current-thread runtime must build");
|
||||
runtime.block_on(test())
|
||||
});
|
||||
(snapshotter.snapshot().into_vec(), out)
|
||||
}
|
||||
|
||||
/// Last value of a gauge, plus the labels it was published with.
|
||||
fn gauge(snapshot: &[MetricEntry], name: &str) -> Option<(f64, Vec<String>)> {
|
||||
snapshot.iter().find_map(|(composite, _unit, _description, value)| {
|
||||
let matches = composite.kind() == MetricKind::Gauge && composite.key().name() == name;
|
||||
match (matches, value) {
|
||||
(true, DebugValue::Gauge(value)) => Some((
|
||||
value.into_inner(),
|
||||
composite.key().labels().map(|label| label.key().to_string()).collect(),
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renewal_loop_republishes_token_ttl_while_it_waits() {
|
||||
let (snapshot, ()) = record_metrics(|| {
|
||||
Box::pin(async {
|
||||
let (provider, _state) = scripted_provider(
|
||||
Duration::from_secs(60),
|
||||
true,
|
||||
test_policy(Duration::from_secs(10), Duration::from_secs(5)),
|
||||
)
|
||||
.await;
|
||||
let task = provider.spawn_renewal_task().expect("lease-bound tokens need renewal");
|
||||
|
||||
// Well inside the first half of the lease: nothing has been
|
||||
// renewed yet, so only the observation cadence can have moved
|
||||
// the gauge off its initial 60s.
|
||||
tokio::time::sleep(Duration::from_secs(25)).await;
|
||||
task.shutdown().await;
|
||||
})
|
||||
});
|
||||
|
||||
let (ttl, labels) = gauge(&snapshot, METRIC_TOKEN_TTL_SECONDS).expect("token TTL gauge must be published");
|
||||
assert!(
|
||||
(ttl - 40.0).abs() < 1.0,
|
||||
"expected ~40s left of a 60s lease at the last observation, got {ttl}"
|
||||
);
|
||||
assert!(labels.is_empty(), "credential gauges must carry no labels, got {labels:?}");
|
||||
assert_eq!(
|
||||
gauge(&snapshot, METRIC_CREDENTIALS_FAIL_CLOSED).map(|(value, _)| value),
|
||||
Some(0.0),
|
||||
"a token outside its safety window must not report fail-closed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fail_closed_gauge_tracks_the_gate_the_request_path_applies() {
|
||||
let (snapshot, refused) = record_metrics(|| {
|
||||
Box::pin(async {
|
||||
let (provider, state) = scripted_provider(
|
||||
Duration::from_secs(60),
|
||||
true,
|
||||
test_policy(Duration::from_secs(10), Duration::from_secs(5)),
|
||||
)
|
||||
.await;
|
||||
state.fail_renew.store(true, Ordering::SeqCst);
|
||||
state.fail_login.store(true, Ordering::SeqCst);
|
||||
let task = provider.spawn_renewal_task().expect("renewal task");
|
||||
|
||||
// 60s lease minus the 10s safety window: by 51s the provider
|
||||
// is refusing the token, and the gauge must already say so.
|
||||
tokio::time::sleep(Duration::from_secs(51)).await;
|
||||
let refused = provider.current().is_err();
|
||||
task.shutdown().await;
|
||||
refused
|
||||
})
|
||||
});
|
||||
|
||||
assert!(refused, "a token inside the safety window must be refused");
|
||||
assert_eq!(
|
||||
gauge(&snapshot, METRIC_CREDENTIALS_FAIL_CLOSED).map(|(value, _)| value),
|
||||
Some(1.0),
|
||||
"the gauge must report the same fail-closed state the request path enforces"
|
||||
);
|
||||
let (ttl, _labels) = gauge(&snapshot, METRIC_TOKEN_TTL_SECONDS).expect("token TTL gauge must be published");
|
||||
assert!(
|
||||
(ttl - 10.0).abs() < 1.0,
|
||||
"expected the TTL gauge to track the lease down into its safety window, got {ttl}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user