Skip to content

fix(policy,s3select,rpc): harden policy, S3 Select, and RPC auth - #9640

Merged
overtrue merged 11 commits into
mainfrom
fix/security-policy-s3select-rpc
Nov 26, 2026
Merged

overtrue merged 11 commits into
mainfrom
fix/security-policy-s3select-rpc

Conversation

@overtrue

Copy link
Copy Markdown
Collaborator

Related Issues

Tracks rustfs/backlog#3312 (rustfs/backlog#3317, rustfs/backlog#3318, rustfs/backlog#3319, rustfs/backlog#3321, rustfs/backlog#3326, rustfs/backlog#3339, rustfs/backlog#3348, rustfs/backlog#3357, rustfs/backlog#3362).

Summary of Changes

  • Policy evaluation and wildcard matching (crates/policy, crates/utils, rustfs):
    • Scope Allow statements constructed from NotAction to the action families explicitly named in their exclusion list, fail closed when both Action and NotAction are empty, and preserve cross-family Deny + NotAction reach as well as sibling admin coverage for explicit admin NotAction statements (rustfs/backlog#3321).
    • Replace recursive backtracking wildcard matching in crates/policy/src/policy/utils/wildcard.rs and crates/utils/src/string.rs with iterative O(name.len())-space dynamic programming that collapses consecutive * wildcards while keeping allocation-free fast paths for literal and single-* patterns, and cap bucket versioning ExcludedPrefixes at 100 entries and 1024 bytes per prefix in validate_bucket_versioning_update (rustfs/backlog#3318).
    • Share resolve_userid_values across VariableResolver::resolve and resolve_multiple so ${aws:userid} prefers the issuer-scoped parent claim over raw sub (matching aws:userid condition-key derivation while keeping sub as fallback when parent is absent) (rustfs/backlog#3339).
    • Add Principal::is_public() matching * or the empty anonymous account through the authorization wildcard matcher, and wire execute_put_bucket_policy and execute_get_bucket_policy_status to use it so anonymous-matching principal patterns are consistently classified as public under BlockPublicPolicy and policy status checks (rustfs/backlog#3357).
  • S3 Select query and stream hardening (crates/s3select-api, crates/s3select-query):
    • Replace unfiltered DataFusion default scalar, aggregate, and window UDF registration in SimpleFunctionMetadataManager with an explicit S3 Select function allowlist, remove the session scalar-function fallback from MetadataProvider::get_function_meta, and wrap retained expanding/count-sized scalar functions (concat, concat_ws, to_char, repeat, lpad, rpad) with pre-allocation result-size bounds including post-simplification re-wrapping (rustfs/backlog#3317).
    • Add BoundedRustFsDialect enforcing a per-parse infix/postfix operator budget (MAX_SELECT_OPERATORS) in both ExtParser::parse_sql and legacy_json_source_from_input, bound set-operation keyword counts before parsing, and bound nested field-access chains during statement preparation (rustfs/backlog#3319).
    • Enforce RecordSizeTracker (MAX_SELECT_RECORD_BYTES, 1 MiB) across uncompressed plain, ScanRange, and ScanRange header reads in EcObjectStore with CR/LF/CRLF handling for default CSV, replace unbounded stock DataFusion listing scans with a byte-bounded, memory-pool-accounted DelimitedSelectTable, bound CSV/JSON Lines batch sizes and multi-record JSON Lines schema sampling within the session memory pool, and add StreamFilterOutput to avoid filter re-coalescing (rustfs/backlog#3348).
  • Internode RPC authentication and Keystone identity isolation (crates/ecstore, crates/keystone, rustfs):
    • Stop attaching secret-keyed boot-epoch, replay-cache, and msgpack capability proofs before gRPC authentication in RpcRequestPathService::call; gate proof attachment on an RpcSignatureVerified marker set by check_auth only after internode HMAC verification succeeds (preserving recovery proofs for post-HMAC rejections), and verify v2 method-bound HMAC signatures before returning replay_scope_required in verify_tonic_rpc_signature_with_policy (rustfs/backlog#3326).
    • Set Credentials.parent_user in KeystoneAuthProvider::keystone_token_to_credentials to the namespaced Keystone user identity (keystone:<user_id>, matching access_key) instead of the bare Keystone username, while keeping the display username in Credentials.name and claims["keystone_username"] (rustfs/backlog#3362).

Verification

Tested on commit c68bb025dc974fd5b7602c5603766ac5e64e2c71 (9 commits on base 2fab66075f8d6aa2202bf856b29252c588fb2699, clean working tree):

  • Formatting, whitespace, and repository guards:
    • cargo fmt --all --check — passed.
    • git diff --check 2fab66075..HEAD — passed.
    • ./scripts/check_embedded_secrets.sh — passed.
    • ./scripts/check_logging_guardrails.sh — passed.
    • ./scripts/check_layer_dependencies.sh — passed.
    • ./scripts/check_s3s_footprint.sh --base 2fab66075 — passed (files=3, s3_error! lines=16, ecstore files=0).
    • ./scripts/check_architecture_migration_rules.sh — passed.
  • Unit, regression, and doctest suites:
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo nextest run -j 4 -p rustfs-policy --no-tests fail — 802 passed, 1 skipped.
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo nextest run -j 4 -p rustfs-utils --features string --no-tests fail -E 'test(string)' — 11 passed, 26 skipped.
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo nextest run -j 4 -p rustfs-s3select-api --no-tests fail — 235 passed, 0 skipped.
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo nextest run -j 4 -p rustfs-s3select-query --no-tests fail — 255 passed, 2 skipped.
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo nextest run -j 4 -p rustfs-keystone --no-tests fail — 34 passed, 0 skipped.
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo test -j 4 -p rustfs-keystone --doc — 2 passed (1 compile, 1 compile_fail), 0 failed.
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo nextest run -j 4 -p rustfs-ecstore --no-tests fail -E 'test(http_auth)' — 91 passed, 7673 skipped.
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo nextest run -j 4 -p rustfs --lib --no-tests fail -E 'test(bucket_usecase::policy) | test(bucket_usecase::versioning) | test(keystone) | test(/server::http::tests::(rpc_boot_epoch|rpc_auth|rpc_request_path_service)/)' — 50 passed, 6608 skipped.
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo nextest run -j 4 -p rustfs --lib --features http3 --no-tests fail -E 'test(http3_external_stack_enforces_readiness_keystone_context_and_rate_limit)' — 1 passed, 6666 skipped.
  • Package-scoped Clippy (-D warnings):
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo clippy -j 4 -p rustfs-policy -p rustfs-s3select-api -p rustfs-s3select-query -p rustfs-keystone --tests -- -D warnings — passed.
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo clippy -j 4 -p rustfs-utils --features string --tests -- -D warnings — passed.
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo clippy -j 4 -p rustfs-ecstore --lib -- -D warnings — passed.
    • CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo clippy -j 4 -p rustfs --lib -- -D warnings — passed.
  • Checks not run locally: full-workspace make pre-pr, release binary builds, and multi-node/Docker integration suites were not run locally and remain covered by CI; scoped verification covers all modified crates, tests, and feature-gated HTTP/3 Keystone integration.

auto-testing regression coverage: Skipped — security fixes are kept out of public rustfs/auto-testing until merged and released to avoid premature vulnerability disclosure.

Impact

  • NotAction Allow family scoping (rustfs/backlog#3321): Policies using Allow with NotAction only expand within the action families explicitly referenced in NotAction (for example, excluding an S3 action no longer implicitly allows admin, STS, or KMS actions); Deny with NotAction continues to span all action families.
  • ${aws:userid} resolution (rustfs/backlog#3339): Policy variable interpolation for ${aws:userid} now prefers the issuer-scoped parent claim over raw sub when both are present, matching aws:userid condition-key semantics; policies relying on raw sub while parent is populated will evaluate against parent instead.
  • Public policy classification and versioning prefix limits (rustfs/backlog#3357, rustfs/backlog#3318): Bucket policies whose principal matches the anonymous empty identity are now treated as public by BlockPublicPolicy and GetBucketPolicyStatus; bucket versioning ExcludedPrefixes is bounded to at most 100 entries and 1024 bytes per prefix.
  • S3 Select restrictions and resource caps (rustfs/backlog#3317, rustfs/backlog#3319, rustfs/backlog#3348): Queries calling non-allowlisted DataFusion functions, exceeding the per-parse operator/nesting/set-operation budgets, producing oversized expanding-function outputs, or reading uncompressed records exceeding 1 MiB (MAX_SELECT_RECORD_BYTES) now return errors rather than consuming unbounded CPU or memory.
  • Internode RPC response proofs (rustfs/backlog#3326): Unauthenticated or invalid-signature gRPC requests no longer receive boot-epoch, replay-cache, or msgpack capability proof headers; authenticated peers continue to receive recovery proofs on post-HMAC rejections.
  • Keystone parent_user namespacing (rustfs/backlog#3362): Keystone-authenticated sessions now populate Credentials.parent_user with keystone:<user_id> instead of the bare Keystone username, preventing collisions with local IAM users or root credentials; consumers needing the Keystone username can read Credentials.name or claims["keystone_username"].
  • Rollback: All changes are behavioral/in-memory with no persisted schema or on-disk format migration; reverting the PR restores prior behavior cleanly.

Additional Notes

  • Adversarial validation verdicts:
    • Security: Pass — trust boundaries tightened across IAM/bucket policy evaluation (NotAction, ${aws:userid}, public principal classification), wildcard matching and versioning prefix limits, S3 Select SQL function/parser/stream bounds, internode RPC proof gating, and Keystone identity namespacing, with negative regression tests for each boundary.
    • Correctness: Pass — literal/wildcard matcher equivalence, Deny + NotAction and sibling admin NotAction semantics, CR/LF/CRLF and ScanRange CSV/JSON Lines streaming behavior, post-HMAC internode recovery proofs, and Keystone claims preservation are verified by targeted unit and integration tests.
    • Concurrency/Durability: Pass — no new shared mutable global state, lock ordering changes, or persisted metadata format changes; S3 Select memory accounting uses the per-session DataFusion memory pool and RPC verification gating uses per-request extensions.
    • Compatibility: Pass — intentional tightening is documented under Impact; standard S3 Select SQL functions, valid wildcard patterns, authenticated internode RPC recovery flows, and sub fallback when parent is absent remain supported.
  • Supersedes / extends perf(policy): bound wildcard matching on adversarial inputs #9486: The wildcard-matching fix in this PR (rustfs/backlog#3318) supersedes and extends perf(policy): bound wildcard matching on adversarial inputs #9486 by also eliminating exponential backtracking in crates/utils/src/string.rs and bounding versioning ExcludedPrefixes in rustfs/src/app/bucket_usecase/versioning.rs.

Confine Allow statements built from NotAction to the action families named in their exclusion list so S3 NotAction policies on wildcard or bucket resources cannot implicitly grant admin, STS, or KMS actions. Fail closed when both Action and NotAction are empty, preserve explicit Deny + NotAction reach across all action families, and preserve explicit admin NotAction coverage for sibling admin actions.

Refs: rustfs/backlog#3321
Replace recursive backtracking in wildcard matching (rustfs-policy and rustfs-utils) with iterative O(name.len())-space dynamic programming that collapses consecutive '*' wildcards and preserves allocation-free fast paths for literal and single-'*' patterns. Also cap versioning ExcludedPrefixes count (100) and byte length (1024) in validate_bucket_versioning_update as defense in depth.

Refs: rustfs/backlog#3318
Share a single resolve_userid_values helper between VariableResolver::resolve and resolve_multiple that prefers the issuer-scoped parent claim over raw sub, aligning the ${aws:userid} policy variable with the aws:userid condition key derived in auth facts while retaining sub as a fallback when parent is absent.

Refs: rustfs/backlog#3339
Add Principal::is_public() matching either '*' or the empty anonymous account '' through the same wildcard matcher used during request authorization, and switch execute_put_bucket_policy and execute_get_bucket_policy_status to use it so empty and leading-'?' principals cannot bypass BlockPublicPolicy or evade public status classification.

Refs: rustfs/backlog#3357
Replace unfiltered DataFusion default scalar, aggregate, and window UDF registration in SimpleFunctionMetadataManager with an explicit S3 Select allowlist, register allowlisted scalar aliases directly, and remove the session scalar-function fallback from MetadataProvider::get_function_meta.

Wrap retained expanding scalar functions (concat, concat_ws, to_char) and any manually registered count-sized functions (repeat, lpad, rpad) with a pre-allocation result-size guard that also re-wraps scalar UDFs produced during expression simplification.

Refs: rustfs/backlog#3317
Add BoundedRustFsDialect enforcing a per-parse infix/postfix operator budget (MAX_SELECT_OPERATORS) via Dialect::parse_infix returning ParserError::RecursionLimitExceeded, and wire it into both ExtParser::parse_sql and legacy_json_source_from_input.

Also bound set-operation keyword counts before parsing (preventing deeply nested SetExpr chains from overflowing on drop) and bound nested field-access chains during statement preparation.

Refs: rustfs/backlog#3319
Apply RecordSizeTracker (MAX_SELECT_RECORD_BYTES) across uncompressed plain, ScanRange, and ScanRange header reads in EcObjectStore, recognizing CR, LF, and CRLF line endings for default CSV inputs without a custom RecordDelimiter.

Bound session batch sizes and disable batch coalescing for CSV and JSON Lines, replace DataFusion's unbounded stock listing table scan with a byte-bounded, memory-pool-accounted DelimitedSelectTable, keep multi-record JSON Lines schema sampling within the session memory pool budget, and add a StreamFilterOutput physical optimizer rule so FilterExec streams filtered batches without re-coalescing.

Refs: rustfs/backlog#3348
Stop computing and attaching secret-keyed boot-epoch, replay-cache, and msgpack capability response proofs before gRPC authentication runs in RpcRequestPathService::call.

Gate proof generation on an RpcSignatureVerified request marker raised by check_auth only after the internode HMAC signature has verified, including post-HMAC rejections (stale boot epoch, replay-scope retries, replay detection, and replay-cache/background admission resource exhaustion) required for cluster recovery.

Verify the method-bound v2 HMAC signature before returning replay_scope_required in verify_tonic_rpc_signature_with_policy so unsigned, legacy-only, or forged callers never trigger a post-HMAC rejection reason or consume replay-cache capacity.

Refs: rustfs/backlog#3326
Set Credentials.parent_user in KeystoneAuthProvider::keystone_token_to_credentials to the namespaced Keystone identity (keystone:<user_id>, matching access_key) instead of the bare Keystone username.

This prevents an external Keystone username from colliding with a local IAM user or the root access key in service-account ownership checks and the is-admin handler while keeping the username available in Credentials.name and claims["keystone_username"].

Update the keystone unit tests and HTTP/3 external stack test expectations, and add regression coverage verifying colliding usernames are never placed in parent_user.

Refs: rustfs/backlog#3362
@github-actions

Copy link
Copy Markdown
Contributor

CLA requirements are satisfied for this pull request.

@overtrue
overtrue added this pull request to the merge queue Nov 26, 2026
@overtrue
overtrue removed this pull request from the merge queue due to a manual request Nov 26, 2026
@overtrue
overtrue merged commit ac6253c into main Nov 26, 2026
25 checks passed
@overtrue
overtrue deleted the fix/security-policy-s3select-rpc branch November 26, 2026 21:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants