Compare commits

..

10 Commits

Author SHA1 Message Date
Hauser Zhi 328f4fbc47 Merge branch 'main' into fix/security-policy-s3select-rpc 2026-11-26 15:30:11 +08:00
overtrue c68bb025dc fix(keystone): namespace parent_user by Keystone user ID
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
2026-11-26 09:56:17 +08:00
overtrue c9d178567f fix(rpc): gate gRPC boot-epoch proofs on verified signatures
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
2026-11-26 09:56:17 +08:00
overtrue 76308ae4e1 fix(s3select): bound uncompressed record sizes and decoding
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
2026-11-26 09:56:17 +08:00
overtrue 11c6203988 fix(s3select): bound SQL operator and nesting depth at parse
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
2026-11-26 09:56:17 +08:00
overtrue 200ecc0060 fix(s3select): restrict SQL functions to an explicit allowlist
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
2026-11-26 09:56:17 +08:00
overtrue d701d57d23 fix(policy): treat anonymous-matching principals as public
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
2026-11-26 09:56:17 +08:00
overtrue 63a871cc6b fix(policy): prefer parent over raw sub for aws:userid variable
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
2026-11-26 09:56:17 +08:00
overtrue 1d04cc52f9 fix(policy,utils): eliminate exponential wildcard matching
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
2026-11-26 09:56:17 +08:00
overtrue 26cbc44105 fix(policy): scope NotAction Allow to named action families
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
2026-11-26 09:56:17 +08:00
38 changed files with 4022 additions and 528 deletions
Generated
+38 -29
View File
@@ -255,7 +255,7 @@ version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -266,7 +266,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -2015,7 +2015,7 @@ dependencies = [
"maybe-owned",
"rustix",
"rustix-linux-procfs",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
"winx",
]
@@ -4186,7 +4186,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -4507,7 +4507,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -4701,7 +4701,7 @@ checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
dependencies = [
"io-lifetimes 2.0.4",
"rustix",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -5892,7 +5892,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
dependencies = [
"io-lifetimes 3.0.1",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -7196,7 +7196,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.60.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -9149,7 +9149,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -9483,7 +9483,7 @@ dependencies = [
"cfg-if",
"libc",
"rustix",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -10434,7 +10434,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway"
version = "0.67.0"
source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"arc-swap",
"bytes",
@@ -10481,7 +10481,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-core"
version = "0.64.0"
source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"bytes",
"futures-core",
@@ -10502,7 +10502,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-corpus"
version = "0.1.0"
source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"serde",
"serde_json",
@@ -10512,7 +10512,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-corpus-recorder"
version = "0.1.0"
source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"bytes",
"http 1.5.0",
@@ -10527,7 +10527,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-dialect-rustfs-admin"
version = "0.13.0"
source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"bytes",
"form_urlencoded",
@@ -10541,7 +10541,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-http"
version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"hmac 0.13.0",
"http 1.5.0",
@@ -10559,7 +10559,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-macros"
version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"proc-macro2",
"quote",
@@ -10569,7 +10569,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-sig"
version = "0.16.0"
source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"hmac 0.13.0",
"http 1.5.0",
@@ -10584,7 +10584,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-stream"
version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"bitflags 2.13.2",
"bytes",
@@ -10595,7 +10595,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-types"
version = "0.42.0+aws.2026-10-02"
source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"bytes",
"crc-fast",
@@ -10617,7 +10617,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-xml"
version = "0.4.0"
source = "git+https://github.com/rustfs/gateway.git?rev=b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b#b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b"
source = "git+https://github.com/rustfs/gateway.git?rev=095d4763a3f58a5e1d22fe7a231bf1c105473de8#095d4763a3f58a5e1d22fe7a231bf1c105473de8"
dependencies = [
"quick-xml 0.41.0",
]
@@ -11873,7 +11873,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -11955,7 +11955,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -12779,7 +12779,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -12930,7 +12930,7 @@ dependencies = [
"cfg-if",
"libc",
"psm",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -13241,7 +13241,7 @@ dependencies = [
"getrandom 0.3.4",
"once_cell",
"rustix",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -14354,7 +14354,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -14509,6 +14509,15 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -14681,7 +14690,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
dependencies = [
"bitflags 2.13.2",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -14953,7 +14962,7 @@ dependencies = [
"sha1 0.11.0",
"time",
"typed-path",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
"zeroize",
"zopfli",
"zstd 0.14.4",
+7 -7
View File
@@ -153,17 +153,17 @@ rustfs-utils = { path = "crates/utils", version = "1.0.5" }
rustfs-zip = { path = "./crates/zip", version = "1.0.5" }
# Pin the gateway and its protocol crates to the same revision.
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", version = "0.2.0", default-features = false }
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", version = "0.2.0", default-features = false }
# The gateway framework itself, consumed for its extension traits by the ring-2
# adapter. `default-features = false` keeps the `server` feature, and with it the
# server crate, out of the build.
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", version = "0.67.0", default-features = false }
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", version = "0.67.0", default-features = false }
# Test-only: builds the `EffectiveHost` a host-resolution test queries with.
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", version = "0.64.0", default-features = false }
rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", version = "0.1.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b", version = "0.13.0", default-features = false }
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", version = "0.64.0", default-features = false }
rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", version = "0.1.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "095d4763a3f58a5e1d22fe7a231bf1c105473de8", version = "0.13.0", default-features = false }
# Async Runtime and Networking
async-channel = "2.5.0"
@@ -829,8 +829,6 @@ async fn test_bucket_tags_opa_contract() -> TestResult {
.send()
.await?;
opa.expect_bucket_tags("s3:PutObject", source, Some("finance")).await?;
// A non-empty x-amz-tagging header is authorized after PutObject.
opa.expect_bucket_tags("s3:PutObjectTagging", source, Some("finance")).await?;
let version = written.version_id().ok_or("versioned PUT must return a version ID")?;
let read = client
.get_object()
@@ -906,8 +904,6 @@ async fn test_bucket_tags_opa_contract() -> TestResult {
opa.expect_versioned_tag_permission(source, "report", version).await?;
}
opa.expect_bucket_tags("s3:PutObject", destination, Some("finance")).await?;
opa.expect_bucket_tags("s3:PutObjectTagging", destination, Some("finance"))
.await?;
}
let tags = admin.get_object_tagging().bucket(destination).key("copied").send().await?;
assert_eq!(tags.tag_set().len(), 1);
+3 -6
View File
@@ -741,7 +741,7 @@ impl BucketMetadata {
}
pub fn save_file_path(&self) -> String {
bucket_metadata_path(&self.name)
format!("{}/{}/{}", BUCKET_META_PREFIX, self.name.as_str(), BUCKET_METADATA_FILE)
}
pub fn versioning(&self) -> bool {
@@ -1745,17 +1745,14 @@ pub(crate) async fn load_bucket_metadata_parse_with_presence(
Ok((bm, persisted))
}
fn bucket_metadata_path(bucket: &str) -> String {
format!("{BUCKET_META_PREFIX}/{bucket}/{BUCKET_METADATA_FILE}")
}
async fn read_bucket_metadata(api: Arc<ECStore>, bucket: &str) -> Result<BucketMetadata> {
if bucket.is_empty() {
error!("bucket name empty");
return Err(Error::other("invalid argument"));
}
let file_path = bucket_metadata_path(bucket);
let bm = BucketMetadata::new(bucket);
let file_path = bm.save_file_path();
let data = read_config(api, &file_path).await?;
@@ -2175,6 +2175,10 @@ fn verify_tonic_rpc_signature_with_policy(
&& has_v2_auth_headers(headers)
&& tonic_boot_epoch_challenge(headers).is_ok_and(|challenge| challenge.is_some());
if replay_scope_strict && !bootstrap {
// The server answers this rejection with its boot-epoch proof so a signed peer can retry
// with a replay scope. Verify the method-bound v2 HMAC first so unsigned, legacy-only, or
// forged callers are rejected for the signature itself without consuming replay-cache slots.
verified_tonic_rpc_nonce(audience, path, headers, true)?;
return Err(std::io::Error::other("RPC replay-scoped authentication required"));
}
@@ -3291,6 +3295,64 @@ mod tests {
);
}
#[test]
fn replay_scope_strictness_reports_missing_scope_only_to_signed_callers() {
ensure_test_rpc_secret();
let path = "/node_service.NodeService/ReadVersion";
let mut headers = gen_tonic_signature_headers("node-a:9000", "node_service.NodeService", "ReadVersion", None)
.expect("v2 compatibility headers should build");
let signed = verify_tonic_rpc_signature_with_policy("node-a:9000", path, &headers, false, true, false)
.expect_err("strict replay scope must reject a signed v2-only request");
assert_eq!(signed.to_string(), "RPC replay-scoped authentication required");
assert_eq!(tonic_rpc_auth_failure_reason(&signed), "replay_scope_required");
// A body-digested v2-only mutation must also verify its v2 HMAC before reporting
// `replay_scope_required`, without inserting its nonce into the replay cache for a
// request that is rejected prior to execution.
let digest = hex_simd::encode_to_string(Sha256::digest(b"strict-body"), hex_simd::AsciiCase::Lower);
let mutation_path = "/node_service.NodeService/WriteAll";
let mutation_headers = gen_tonic_signature_headers("node-a:9000", "node_service.NodeService", "WriteAll", Some(&digest))
.expect("body-digested v2 headers should build");
let mutation_nonce = Uuid::parse_str(
mutation_headers[RPC_NONCE_HEADER]
.to_str()
.expect("v2 nonce header must be ASCII"),
)
.expect("body-digested v2 nonce must be a UUID");
let mutation_rejected =
verify_tonic_rpc_signature_with_policy("node-a:9000", mutation_path, &mutation_headers, false, true, false)
.expect_err("strict replay scope must reject a signed body-digested v2-only request");
assert_eq!(mutation_rejected.to_string(), "RPC replay-scoped authentication required");
assert!(
!LOCAL_RPC_NONCE_CACHE
.lock()
.expect("nonce cache lock")
.contains_nonce(&mutation_nonce),
"rejected replay_scope_required requests must not consume replay-cache slots"
);
let cross_method =
verify_tonic_rpc_signature_with_policy("node-a:9000", "/node_service.NodeService/Ping", &headers, false, true, false)
.expect_err("a v2 signature bound to another method must not report replay_scope_required");
assert_eq!(cross_method.to_string(), "Invalid RPC v2 signature");
let wrong_audience = verify_tonic_rpc_signature_with_policy("node-b:9000", path, &headers, false, true, false)
.expect_err("a v2 signature bound to another audience must not report replay_scope_required");
assert_eq!(wrong_audience.to_string(), "Invalid RPC v2 signature");
headers.insert(RPC_SIGNATURE_V2_HEADER, HeaderValue::from_static("invalid"));
let forged = verify_tonic_rpc_signature_with_policy("node-a:9000", path, &headers, false, true, false)
.expect_err("a forged v2 signature must be rejected as invalid_v2_signature");
assert_eq!(forged.to_string(), "Invalid RPC v2 signature");
let legacy = gen_signature_headers(TONIC_RPC_PREFIX, &Method::GET).expect("legacy auth headers should build");
for unsigned_or_legacy in [legacy, HeaderMap::new()] {
let error = verify_tonic_rpc_signature_with_policy("node-a:9000", path, &unsigned_or_legacy, false, true, false)
.expect_err("a request without v2 metadata must be rejected as v2_required");
assert_eq!(error.to_string(), "RPC v2 authentication required");
}
}
#[test]
fn boot_epoch_response_proof_binds_audience_challenge_and_epoch() {
ensure_test_rpc_secret();
+1 -2
View File
@@ -5899,8 +5899,7 @@ impl SetDisks {
);
prepared
} else {
let tokens = vec![None; shuffle_disks.len()];
(shuffle_disks, tokens)
(shuffle_disks.clone(), vec![None; shuffle_disks.len()])
};
let commit_context_prepare_started = rustfs_io_metrics::put_stage_timer();
let transaction_epoch =
+12 -115
View File
@@ -1079,9 +1079,8 @@ fn clamp_ask_disks_to_available(ask_disks: i32, available_disks: usize) -> i32 {
ask_disks.min(bounded_usize_to_i32(available_disks))
}
fn parse_version_marker(bucket: &str, key_marker: Option<&str>, marker: String) -> Result<VersionMarker> {
VersionMarker::parse(&marker)
.map_err(|_| StorageError::InvalidVersionID(bucket.to_owned(), key_marker.unwrap_or_default().to_owned(), marker))
fn parse_version_marker(marker: String) -> Result<VersionMarker> {
Ok(VersionMarker::parse(marker)?)
}
fn version_marker_for_entries(
@@ -1499,9 +1498,11 @@ impl ECStore {
}
let has_version_marker = version_marker.is_some();
let version_marker = version_marker
.map(|raw| parse_version_marker(bucket, marker.as_deref(), raw))
.transpose()?;
let version_marker = if let Some(marker) = version_marker {
Some(parse_version_marker(marker)?)
} else {
None
};
let effective_max_keys = list_versions_scan_limit(max_keys, has_version_marker);
let opts = ListPathOptions {
@@ -2986,9 +2987,7 @@ impl SetDisks {
}
let has_version_marker = version_marker.is_some();
let version_marker = version_marker
.map(|raw| parse_version_marker(bucket, marker.as_deref(), raw))
.transpose()?;
let version_marker = version_marker.map(parse_version_marker).transpose()?;
let effective_max_keys = list_versions_scan_limit(max_keys, has_version_marker);
let opts = ListPathOptions {
bucket: bucket.to_owned(),
@@ -5357,87 +5356,6 @@ mod test {
assert!(resumed.next_continuation_token.is_none());
}
#[tokio::test]
async fn list_object_versions_rejects_invalid_version_id_marker_and_accepts_control_delimiter() {
use crate::storage_api_contracts::bucket::BucketOperations as _;
use crate::storage_api_contracts::object::ObjectIO as _;
let bucket = "invalid-version-marker";
let (_dirs, store) = crate::bucket::metadata_sys::test_support::isolated_store_over_temp_disks().await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
store
.make_bucket(bucket, &crate::storage_api_contracts::bucket::MakeBucketOptions::default())
.await
.expect("create bucket");
store
.put_object(
bucket,
"obj-a",
&mut crate::object_api::PutObjReader::from_vec(vec![1]),
&crate::object_api::ObjectOptions::default(),
)
.await
.expect("seed object");
let err = store
.clone()
.inner_list_object_versions(bucket, "", Some("k".to_string()), Some("v".to_string()), Some("\x0f".to_string()), 8)
.await
.expect_err("non-UUID version-id-marker must be rejected");
assert!(
matches!(
&err,
StorageError::InvalidVersionID(err_bucket, err_key, err_version)
if err_bucket == bucket && err_key == "k" && err_version == "v"
),
"expected InvalidVersionID, got: {err:?}"
);
let delete_err = store.pools[0].disk_set[0]
.clone()
.inner_list_object_versions_for_recursive_delete(bucket, "", Some("k".to_string()), Some("v".to_string()), 8)
.await
.expect_err("recursive-delete listing must reject non-UUID version-id-marker");
assert!(
matches!(
&delete_err,
StorageError::InvalidVersionID(err_bucket, err_key, err_version)
if err_bucket == bucket && err_key == "k" && err_version == "v"
),
"expected InvalidVersionID, got: {delete_err:?}"
);
let control_delim_page = store
.clone()
.inner_list_object_versions(bucket, "", None, None, Some("\x0f".to_string()), 8)
.await
.expect("control-character delimiter without version-id-marker must succeed");
assert_eq!(
control_delim_page
.objects
.iter()
.map(|object| object.name.as_str())
.collect::<Vec<_>>(),
vec!["obj-a"]
);
assert!(control_delim_page.prefixes.is_empty());
let valid_null_marker_page = store
.clone()
.inner_list_object_versions(bucket, "", Some("k".to_string()), Some("null".to_string()), Some("\x0f".to_string()), 8)
.await
.expect("valid null version-id-marker with control-character delimiter must succeed");
assert_eq!(
valid_null_marker_page
.objects
.iter()
.map(|object| object.name.as_str())
.collect::<Vec<_>>(),
vec!["obj-a"]
);
assert!(valid_null_marker_page.prefixes.is_empty());
}
// ECA-03 / #944: a page whose raw keys fully collapse into fewer than max_keys
// common prefixes must still report truncation and carry a continuation marker,
// otherwise every key beyond the scan window is silently dropped.
@@ -8527,33 +8445,12 @@ mod test {
#[test]
fn test_null_version_marker_handling() {
let parsed = parse_version_marker("bucket", Some("key"), "null".to_string()).expect("null marker should parse");
let parsed = parse_version_marker("null".to_string()).expect("null marker should parse");
assert_eq!(parsed, VersionMarker::Null);
let valid_uuid = "550e8400-e29b-41d4-a716-446655440000";
let parsed = parse_version_marker("bucket", Some("key"), valid_uuid.to_string()).expect("uuid marker should parse");
let parsed = parse_version_marker(valid_uuid.to_string()).expect("uuid marker should parse");
assert_eq!(parsed, VersionMarker::Version(Uuid::parse_str(valid_uuid).unwrap()));
let invalid = parse_version_marker("bkt", Some("k"), "v".to_string()).expect_err("invalid marker should fail");
assert!(
matches!(
&invalid,
StorageError::InvalidVersionID(bucket, key, version)
if bucket == "bkt" && key == "k" && version == "v"
),
"expected InvalidVersionID, got: {invalid:?}"
);
let invalid_without_key =
parse_version_marker("bkt", None, "v".to_string()).expect_err("invalid marker without key should fail");
assert!(
matches!(
&invalid_without_key,
StorageError::InvalidVersionID(bucket, key, version)
if bucket == "bkt" && key.is_empty() && version == "v"
),
"expected InvalidVersionID with empty key, got: {invalid_without_key:?}"
);
}
/// Test that next_version_idmarker returns "null" for non-versioned objects
@@ -8579,7 +8476,7 @@ mod test {
// Server parses "null" as an explicit null-version marker
let server_response = "null";
let client_request = server_response;
let parsed = parse_version_marker("bucket", Some("key"), client_request.to_string()).expect("null marker should parse");
let parsed = parse_version_marker(client_request.to_string()).expect("null marker should parse");
assert_eq!(parsed, VersionMarker::Null);
// Scenario 2: Versioned object
@@ -8589,7 +8486,7 @@ mod test {
let uuid_str = "550e8400-e29b-41d4-a716-446655440000";
let server_response = uuid_str;
let client_request = server_response;
let parsed = parse_version_marker("bucket", Some("key"), client_request.to_string()).expect("uuid marker should parse");
let parsed = parse_version_marker(client_request.to_string()).expect("uuid marker should parse");
assert_eq!(parsed, VersionMarker::Version(Uuid::parse_str(uuid_str).unwrap()));
}
+63 -6
View File
@@ -212,13 +212,19 @@ impl KeystoneAuthProvider {
claims.insert("keystone_roles".to_string(), json!(token.roles));
claims.insert("auth_source".to_string(), json!("keystone"));
// Keep `parent_user` in the `keystone:` namespace (matching `access_key`) so an external
// Keystone username can never collide with a local IAM user or the root access key in
// service-account ownership or admin checks. The username remains available in `name`
// and `claims["keystone_username"]`.
let access_key = format!("keystone:{}", token.user_id);
Credentials {
access_key: format!("keystone:{}", token.user_id),
access_key: access_key.clone(),
secret_key: String::new(), // Not used for token auth
session_token: token.token.clone(),
expiration: Some(token.expires_at),
status: "active".to_string(),
parent_user: token.username.clone(),
parent_user: access_key,
groups,
claims: Some(claims),
name: Some(token.username.clone()),
@@ -303,13 +309,64 @@ mod tests {
let cred = provider.keystone_token_to_credentials(&token);
assert_eq!(cred.access_key, "keystone:user123");
assert_eq!(cred.parent_user, "testuser");
assert_eq!(cred.parent_user, "keystone:user123");
assert_eq!(cred.name.as_deref(), Some("testuser"));
assert_eq!(cred.groups, Some(vec!["Member".to_string(), "admin".to_string()]));
assert!(cred.claims.is_some());
let claims = cred.claims.unwrap();
assert_eq!(claims.get("keystone_user_id").unwrap().as_str().unwrap(), "user123");
assert_eq!(claims.get("keystone_project_id").unwrap().as_str().unwrap(), "proj456");
let claims = cred.claims.expect("keystone claims must be populated");
assert_eq!(claims.get("keystone_user_id").and_then(|v| v.as_str()), Some("user123"));
assert_eq!(claims.get("keystone_username").and_then(|v| v.as_str()), Some("testuser"));
assert_eq!(claims.get("keystone_project_id").and_then(|v| v.as_str()), Some("proj456"));
}
#[test]
fn test_keystone_parent_user_uses_namespaced_identity_not_username() {
let client = KeystoneClient::new(
"http://localhost:5000".to_string(),
crate::KeystoneVersion::V3,
None,
None,
None,
"Default".to_string(),
true,
Duration::from_secs(30),
);
let provider = KeystoneAuthProvider::new(client, 100, Duration::from_secs(60), true);
for (user_id, colliding_username) in [("uid-alice", "alice"), ("uid-root-lookalike", "rustfsadmin")] {
let token = KeystoneToken {
token: "test-token".to_string(),
user_id: user_id.to_string(),
username: colliding_username.to_string(),
project_id: None,
project_name: None,
domain_id: Some("default".to_string()),
domain_name: Some("Default".to_string()),
roles: vec!["member".to_string()],
expires_at: time::OffsetDateTime::now_utc() + time::Duration::hours(1),
issued_at: time::OffsetDateTime::now_utc(),
};
let cred = provider.keystone_token_to_credentials(&token);
let expected_identity = format!("keystone:{user_id}");
assert_eq!(cred.access_key, expected_identity);
assert_eq!(cred.parent_user, expected_identity);
assert_ne!(
cred.parent_user, colliding_username,
"parent_user must never carry the bare Keystone username"
);
assert_eq!(cred.name.as_deref(), Some(colliding_username));
assert_eq!(
cred.claims
.as_ref()
.and_then(|claims| claims.get("keystone_username"))
.and_then(|value| value.as_str()),
Some(colliding_username)
);
}
}
#[test]
+24 -1
View File
@@ -85,12 +85,25 @@ impl ActionSet {
/// `NotAction` always uses plain wildcard matching, so `NotAction: "s3:*"`
/// still excludes force-delete. An Allow grants force-delete only when its
/// `Action` list names it: an Allow built from `NotAction` alone never does.
///
/// An Allow built from `NotAction` stays within the action families named in
/// `not_actions`: excluding S3 actions never implies `admin:*`, `sts:*`, or
/// `kms:*` grants even when the statement carries a wildcard resource, while
/// an explicit admin `NotAction` keeps covering sibling admin actions. A Deny
/// keeps its full reach across every action family.
pub fn statement_covers(&self, not_actions: &ActionSet, action: &Action, deny: bool) -> bool {
if not_actions.is_match_for_effect(action, true) {
return false;
}
if self.is_empty() {
return deny || !action_requires_explicit_grant(action);
if not_actions.is_empty() {
return false;
}
if deny {
return true;
}
return !action_requires_explicit_grant(action)
&& not_actions.iter().any(|excluded| same_action_family(excluded, action));
}
self.is_match_for_effect(action, deny)
}
@@ -217,6 +230,16 @@ fn action_requires_explicit_grant(action: &Action) -> bool {
)
}
fn same_action_family(left: &Action, right: &Action) -> bool {
matches!(
(left, right),
(Action::S3Action(_), Action::S3Action(_))
| (Action::AdminAction(_), Action::AdminAction(_))
| (Action::StsAction(_), Action::StsAction(_))
| (Action::KmsAction(_), Action::KmsAction(_))
)
}
impl From<&Action> for &str {
fn from(value: &Action) -> &'static str {
match value {
+189
View File
@@ -1466,6 +1466,100 @@ mod test {
Ok(())
}
#[tokio::test]
async fn test_aws_userid_policy_variable_is_issuer_scoped_for_federated_sessions() -> Result<()> {
let resource_policy = Policy::parse_config(
br#"{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::homes/${aws:userid}/*"]
}
]
}"#,
)?;
let condition_policy = Policy::parse_config(
br#"{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": ["arn:aws:s3:::homes"],
"Condition": {
"StringLike": {
"s3:prefix": ["${aws:userid}/*"]
}
}
}
]
}"#,
)?;
let empty_conditions = HashMap::new();
// Two federated issuers can emit the same (or wildcard) `sub`; `parent` separates them.
for sub in ["1001", "*"] {
let mut claims = HashMap::new();
claims.insert("sub".to_string(), Value::String(sub.to_string()));
claims.insert("parent".to_string(), Value::String("partner-parent".to_string()));
let get_args = |object| Args {
account: "sts-access-key",
groups: &None,
action: Action::S3Action(crate::policy::action::S3Action::GetObjectAction),
bucket: "homes",
conditions: &empty_conditions,
is_owner: false,
object,
claims: &claims,
deny_only: false,
};
assert!(resource_policy.is_allowed(&get_args("partner-parent/file")).await);
assert!(!resource_policy.is_allowed(&get_args("corporate-parent/file")).await);
assert!(!resource_policy.is_allowed(&get_args("1001/file")).await);
for (prefix, expected) in [
("partner-parent/file", true),
("corporate-parent/file", false),
("1001/file", false),
] {
let conditions = HashMap::from([("prefix".to_string(), vec![prefix.to_string()])]);
let list_args = Args {
account: "sts-access-key",
groups: &None,
action: Action::S3Action(crate::policy::action::S3Action::ListBucketAction),
bucket: "homes",
conditions: &conditions,
is_owner: false,
object: "",
claims: &claims,
deny_only: false,
};
assert_eq!(condition_policy.is_allowed(&list_args).await, expected, "sub={sub} prefix={prefix}");
}
}
// When `parent` is absent, `${aws:userid}` still falls back to `sub`.
let sub_only_claims = HashMap::from([("sub".to_string(), Value::String("legacy-sub".to_string()))]);
let fallback_args = Args {
account: "sts-access-key",
groups: &None,
action: Action::S3Action(crate::policy::action::S3Action::GetObjectAction),
bucket: "homes",
conditions: &empty_conditions,
is_owner: false,
object: "legacy-sub/file",
claims: &sub_only_claims,
deny_only: false,
};
assert!(resource_policy.is_allowed(&fallback_args).await);
Ok(())
}
#[tokio::test]
async fn test_aws_policy_variables_concatenation() -> Result<()> {
let data = r#"
@@ -4337,6 +4431,101 @@ mod test {
assert!(!allows(&deny_all_but("s3:GetObject"), "s3:ForceDeleteObject").await);
}
#[tokio::test]
async fn not_action_allow_does_not_grant_cross_family_actions() {
async fn eval(policy: &Policy, action: &str, bucket: &str, object: &str) -> bool {
let conditions = HashMap::new();
let claims = HashMap::new();
let groups = None;
let args = Args {
account: "user",
groups: &groups,
action: Action::try_from(action).expect("action parses"),
bucket,
conditions: &conditions,
is_owner: false,
object,
claims: &claims,
deny_only: false,
};
policy.is_allowed(&args).await
}
// Admin/STS/KMS requests often pass an empty bucket/object (which resolves to
// "/") or a warehouse bucket; an S3 NotAction Allow must never cross into them.
for (resource_clause, bucket, object) in [
(r#""Resource":["arn:aws:s3:::*"]"#, "", ""),
(r#""Resource":["arn:aws:s3:::*/*"]"#, "", ""),
(r#""Resource":["*"]"#, "", ""),
(r#""NotResource":["arn:aws:s3:::secret/*"]"#, "", ""),
(r#""Resource":["arn:aws:s3:::warehouse","arn:aws:s3:::warehouse/*"]"#, "warehouse", ""),
] {
for not_action in ["s3:DeleteObject", "s3:*"] {
let iam = Policy::parse_config(
format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","NotAction":["{not_action}"],{resource_clause}}}]}}"#
)
.as_bytes(),
)
.expect("NotAction policy parses");
for action in [
"admin:CreateUser",
"admin:AttachUserOrGroupPolicy",
"admin:ListUsers",
"admin:GetTableBucket",
"sts:AssumeRole",
"kms:ListKeys",
"kms:Decrypt",
] {
assert!(
!eval(&iam, action, bucket, object).await,
"IAM NotAction {not_action} with {resource_clause} must not grant {action}"
);
}
}
}
// The same statement still grants non-excluded S3 actions (except force-delete).
let s3_not_delete = Policy::parse_config(
br#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","NotAction":["s3:DeleteObject"],"Resource":["arn:aws:s3:::*"]}]}"#,
)
.expect("S3 NotAction policy parses");
assert!(allows(&s3_not_delete, "s3:GetObject").await);
assert!(!allows(&s3_not_delete, "s3:DeleteObject").await);
assert!(!allows(&s3_not_delete, "s3:ForceDeleteObject").await);
// An explicit admin NotAction stays confined to admin actions.
let admin_not_delete = Policy::parse_config(
br#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","NotAction":["admin:DeleteUser"],"Resource":["*"]}]}"#,
)
.expect("admin NotAction policy parses");
assert!(eval(&admin_not_delete, "admin:CreateUser", "", "").await);
assert!(!eval(&admin_not_delete, "admin:DeleteUser", "", "").await);
assert!(!allows(&admin_not_delete, "s3:GetObject").await);
assert!(!eval(&admin_not_delete, "kms:ListKeys", "", "").await);
assert!(!eval(&admin_not_delete, "sts:AssumeRole", "", "").await);
// Deny + NotAction keeps covering every non-excluded action family.
let deny = Policy::parse_config(
br#"{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["admin:*"]},
{"Effect":"Allow","Action":["kms:*"]},
{"Effect":"Allow","Action":["sts:*"]},
{"Effect":"Deny","NotAction":["s3:GetObject"],"Resource":["arn:aws:s3:::*"]}
]}"#,
)
.expect("deny NotAction policy parses");
assert!(!eval(&deny, "admin:CreateUser", "", "").await);
assert!(!eval(&deny, "kms:ListKeys", "", "").await);
assert!(!eval(&deny, "sts:AssumeRole", "", "").await);
// An empty ActionSet paired with an empty NotAction fails closed.
let empty = crate::policy::ActionSet::default();
assert!(!empty.statement_covers(&empty, &Action::S3Action(S3Action::GetObjectAction), false));
assert!(!empty.statement_covers(&empty, &Action::S3Action(S3Action::GetObjectAction), true));
}
async fn bucket_allows(policy: &BucketPolicy, action: &str) -> bool {
let conditions = HashMap::new();
policy
+29
View File
@@ -133,6 +133,13 @@ impl Principal {
}
false
}
/// Returns `true` when the principal admits callers it does not name, matching
/// either the wildcard account `"*"` or the empty account `""` used to evaluate
/// unauthenticated requests.
pub fn is_public(&self) -> bool {
self.is_match("*") || self.is_match("")
}
}
impl Validator for Principal {
@@ -236,4 +243,26 @@ mod test {
assert!(!principal.is_match("logging.s3.amazonaws.com"));
assert!(!principal.is_match("other-principal"));
}
#[test_case(r#""*""#, true ; "wildcard_string")]
#[test_case(r#"{"AWS": ["*"]}"#, true ; "aws_wildcard")]
#[test_case(r#"{"AWS": "**"}"#, true ; "aws_double_wildcard")]
#[test_case(r#"{"AWS": "?"}"#, true ; "aws_single_char_wildcard")]
#[test_case(r#"{"AWS": [""]}"#, true ; "aws_empty_array")]
#[test_case(r#"{"AWS": ""}"#, true ; "aws_empty_string")]
#[test_case(r#"{"AWS": ["alice", ""]}"#, true ; "aws_named_and_empty")]
#[test_case(r#"{"AWS": ["?nobody"]}"#, true ; "aws_leading_question_mark")]
#[test_case(r#"{"AWS": ["*?nobody"]}"#, true ; "aws_star_question_mark")]
#[test_case(r#"{"AWS": ["alice"]}"#, false ; "aws_named")]
#[test_case(r#"{"AWS": ["alice*"]}"#, false ; "aws_named_prefix")]
#[test_case(r#"{"AWS": ["arn:aws:iam::123456789012:root"]}"#, false ; "aws_arn")]
#[test_case(r#"{"Service": ""}"#, false ; "service_empty")]
#[test_case(r#"{"Service": "logging.s3.amazonaws.com"}"#, false ; "service_named")]
fn test_principal_is_public(json: &str, expected: bool) {
let principal: Principal = serde_json::from_str(json).expect("Should parse");
assert_eq!(principal.is_public(), expected, "input: {json}");
// Unauthenticated requests are evaluated under the empty account; any principal
// matching it must be classified as public.
assert!(!principal.is_match("") || principal.is_public(), "input: {json}");
}
}
+177 -14
View File
@@ -72,38 +72,201 @@ fn inner_match(pattern: impl AsRef<str>, name: impl AsRef<str>, simple: bool) ->
}
fn deep_match(mut pattern: &[u8], mut name: &[u8], simple: bool) -> bool {
while !pattern.is_empty() {
match pattern[0] {
// Fast path: match literal and `?` prefix without heap allocation.
while let Some(&p) = pattern.first() {
match p {
b'*' => break,
b'?' => {
if name.is_empty() {
return simple;
}
name = &name[1..];
pattern = &pattern[1..];
}
b'*' => {
return pattern.len() == 1
|| deep_match(&pattern[1..], name, simple)
|| (!name.is_empty() && deep_match(pattern, &name[1..], simple));
}
_ => {
if name.is_empty() || name[0] != pattern[0] {
if name.first() != Some(&p) {
return false;
}
name = &name[1..];
pattern = &pattern[1..];
}
}
}
if pattern.is_empty() {
return name.is_empty();
}
// Collapse consecutive leading `*` tokens; a trailing run matches everything.
while pattern.first() == Some(&b'*') {
pattern = &pattern[1..];
}
if pattern.is_empty() {
return true;
}
// Allocation-free fast paths when no further `*` remains in the pattern.
if !pattern.contains(&b'*') {
if !pattern.contains(&b'?') {
return name.ends_with(pattern);
}
if !simple {
return name.len() >= pattern.len()
&& pattern
.iter()
.zip(&name[name.len() - pattern.len()..])
.all(|(&p, &c)| p == b'?' || p == c);
}
}
star_match(pattern, name, simple)
}
/// Iteratively matches the remainder of a pattern immediately following a `*`.
///
/// Maintains reachable positions in `name` (`O(name.len())` space independent of
/// `pattern.len()`) and collapses consecutive `*` tokens in `O(1)` each, avoiding
/// both exponential backtracking and recursion stack growth.
fn star_match(pattern: &[u8], name: &[u8], simple: bool) -> bool {
let n = name.len();
// dp[j]: the pattern prefix processed so far (starting from the leading `*`)
// matches `name[..j]`.
let mut dp = vec![true; n + 1];
let mut prev_was_star = true;
for &p in pattern {
match p {
b'*' => {
if prev_was_star {
continue;
}
prev_was_star = true;
let Some(first) = dp.iter().position(|&matched| matched) else {
return false;
};
dp[first..].fill(true);
}
b'?' => {
prev_was_star = false;
// In simple mode, reaching `?` when `name` is exhausted accepts
// whatever follows in `pattern`.
if simple && dp[n] {
return true;
}
let mut any = false;
for j in (1..=n).rev() {
let matched = dp[j - 1];
dp[j] = matched;
any |= matched;
}
dp[0] = false;
if !any {
return false;
}
}
literal => {
prev_was_star = false;
let mut any = false;
for j in (1..=n).rev() {
let matched = dp[j - 1] && name[j - 1] == literal;
dp[j] = matched;
any |= matched;
}
dp[0] = false;
if !any {
return false;
}
}
}
name = &name[1..];
pattern = &pattern[1..];
}
name.is_empty() && pattern.is_empty()
dp[n]
}
#[cfg(test)]
mod tests {
use super::{is_match, is_match_as_pattern_prefix, is_simple_match};
#[test]
fn many_wildcards_match_without_backtracking() {
let name = format!("vault/{}", "a".repeat(1000));
let pattern = format!("vault/{}", "*a".repeat(100));
assert!(is_match(&pattern, &name));
assert!(is_simple_match(&pattern, &name));
assert!(!is_match(format!("{pattern}*b"), &name));
assert!(!is_simple_match(format!("{pattern}*b"), &name));
let repeated = format!("{}*b", "a*".repeat(80));
let aaa = "a".repeat(800);
assert!(!is_match(&repeated, &aaa));
assert!(!is_simple_match(&repeated, &aaa));
}
#[test]
fn deep_star_runs_do_not_overflow_stack() {
let stars = "*".repeat(200_000);
assert!(is_match(&stars, "tenant-bkt/report.txt"));
assert!(is_simple_match(&stars, "tenant-bkt/report.txt"));
let stars_suffix = format!("{stars}x");
let long_name = "a".repeat(1024);
assert!(!is_match(&stars_suffix, &long_name));
assert!(!is_simple_match(&stars_suffix, &long_name));
assert!(is_match(&stars_suffix, format!("{long_name}x")));
let middle_stars = format!("a{}b{}c", "*".repeat(50_000), "*".repeat(50_000));
assert!(is_match(&middle_stars, format!("a{}b{}c", "x".repeat(200), "y".repeat(200))));
assert!(!is_match(&middle_stars, format!("a{}c", "x".repeat(200))));
}
#[test]
fn utf8_multibyte_patterns_and_names_match() {
assert!(is_match("桶/目录/*文档*", "桶/目录/2026年文档.txt"));
assert!(!is_match("桶/目录/*文档*", "桶/目录/2026年表格.txt"));
assert!(is_match("café*naïve", "café-et-naïve"));
assert!(!is_match("café*naïve", "café-et-naive"));
assert!(is_simple_match("*🎉*🚀", "prefix🎉mid🚀"));
assert!(!is_simple_match("*🎉*🚀", "prefix🎉mid"));
}
/// Reference backtracking definition used only for small exhaustive equivalence checks.
fn backtracking_match(pattern: &[u8], name: &[u8], simple: bool) -> bool {
match pattern.split_first() {
None => name.is_empty(),
Some((b'*', rest)) => {
backtracking_match(rest, name, simple) || (!name.is_empty() && backtracking_match(pattern, &name[1..], simple))
}
Some((b'?', _)) if name.is_empty() => simple,
Some((&p, rest)) => !name.is_empty() && (p == b'?' || p == name[0]) && backtracking_match(rest, &name[1..], simple),
}
}
fn strings(alphabet: &str, max_len: usize) -> Vec<String> {
let mut all = vec![String::new()];
let mut longest = all.clone();
for _ in 0..max_len {
longest = longest
.iter()
.flat_map(|s| alphabet.chars().map(move |c| format!("{s}{c}")))
.collect();
all.extend_from_slice(&longest);
}
all
}
#[test]
fn agrees_with_backtracking_match() {
let names = strings("ab", 5);
for pattern in strings("ab*?", 5) {
for name in &names {
let expected = |simple| backtracking_match(pattern.as_bytes(), name.as_bytes(), simple);
assert_eq!(is_match(&pattern, name), expected(false), "is_match({pattern:?}, {name:?})");
assert_eq!(is_simple_match(&pattern, name), expected(true), "is_simple_match({pattern:?}, {name:?})");
}
}
}
#[test_case::test_case("*", "s3:GetObject" => true ; "1")]
#[test_case::test_case("", "s3:GetObject" => false ; "2")]
#[test_case::test_case("", "" => true; "3")]
+36 -6
View File
@@ -158,10 +158,16 @@ impl VariableResolver {
self.context.username.clone()
}
/// `parent` is the issuer-scoped identity RustFS authorizes and exposes through the
/// `aws:userid` condition key. A raw federated `sub` is unique only within its issuer,
/// so it must never shadow `parent`.
fn resolve_userid_values(&self) -> Option<Vec<String>> {
self.get_claim_as_strings("parent")
.or_else(|| self.get_claim_as_strings("sub"))
}
fn resolve_userid(&self) -> Option<String> {
self.get_claim_as_strings("sub")
.or_else(|| self.get_claim_as_strings("parent"))
.and_then(|mut vec| vec.pop())
self.resolve_userid_values().and_then(|mut vec| vec.pop())
}
fn resolve_principal_type(&self) -> String {
@@ -238,9 +244,7 @@ impl PolicyVariableResolver for VariableResolver {
match variable_name {
"aws:username" => self.resolve_username().map(|s| vec![s]),
"aws:userid" => self
.get_claim_as_strings("sub")
.or_else(|| self.get_claim_as_strings("parent")),
"aws:userid" => self.resolve_userid_values(),
_ => self.resolve(variable_name).await.map(|s| vec![s]),
}
@@ -481,6 +485,32 @@ mod tests {
assert_eq!(result, vec!["AIDACKCEVSQ6C2EXAMPLE-bucket".to_string()]);
}
#[tokio::test]
async fn test_resolve_aws_variables_userid_prefers_parent_over_sub() {
let mut claims = HashMap::new();
claims.insert("sub".to_string(), Value::String("1001".to_string()));
claims.insert("parent".to_string(), Value::String("issuer-scoped-parent".to_string()));
let mut context = VariableContext::new();
context.claims = Some(claims);
let resolver = VariableResolver::new(context.clone());
assert_eq!(resolver.resolve("aws:userid").await, Some("issuer-scoped-parent".to_string()));
assert_eq!(
resolver.resolve_multiple("aws:userid").await,
Some(vec!["issuer-scoped-parent".to_string()])
);
let result = resolve_aws_variables("homes/${aws:userid}/*", &resolver).await;
assert_eq!(result, vec!["homes/issuer-scoped-parent/*".to_string()]);
let cached = CachedAwsVariableResolver::new(context);
assert_eq!(cached.resolve("aws:userid").await, Some("issuer-scoped-parent".to_string()));
assert_eq!(
resolve_aws_variables("homes/${aws:userid}/*", &cached).await,
vec!["homes/issuer-scoped-parent/*".to_string()]
);
}
#[tokio::test]
async fn test_resolve_aws_variables_with_multiple_variables() {
let mut claims = HashMap::new();
+149 -68
View File
@@ -20,8 +20,9 @@ use async_compression::tokio::bufread::BzDecoder;
use bytes::{Buf as _, Bytes};
use datafusion::object_store::{Error as ObjectStoreError, Result as ObjectStoreResult};
use flate2::bufread::GzDecoder;
use futures::{StreamExt, stream};
use futures::{Stream, StreamExt, TryStreamExt as _, stream};
use futures_core::stream::BoxStream;
use memchr::{memchr, memchr2};
use std::{
error::Error as StdError,
io::{self, BufRead as _, Read as _},
@@ -356,7 +357,8 @@ impl io::Read for BlockingChannelReader {
}
}
pub(crate) fn compressed_input_stream(
#[cfg(test)]
fn compressed_input_stream(
reader: SelectInputReader,
compressed_size: u64,
format: CompressionFormat,
@@ -366,22 +368,58 @@ pub(crate) fn compressed_input_stream(
query_guard: Option<QueryExecutionGuard>,
) -> ObjectStoreResult<BoxStream<'static, ObjectStoreResult<Bytes>>> {
let record_size = RecordSizeTracker::new(record_delimiter).map_err(select_object_store_error)?;
compressed_input_stream_with_tracker(
reader,
compressed_size,
format,
input_metrics,
record_size,
max_processed_bytes,
query_guard,
)
}
pub(crate) fn compressed_input_stream_with_tracker(
reader: SelectInputReader,
compressed_size: u64,
format: CompressionFormat,
input_metrics: Arc<SelectInputMetrics>,
record_size: RecordSizeTracker,
max_processed_bytes: u64,
query_guard: Option<QueryExecutionGuard>,
) -> ObjectStoreResult<BoxStream<'static, ObjectStoreResult<Bytes>>> {
let reader = compressed_input_reader(reader, compressed_size, format, input_metrics, max_processed_bytes, query_guard);
let stream = ReaderStream::with_capacity(reader, SELECT_DECODE_CHUNK_BYTES);
Ok(stream::try_unfold((stream, record_size), |(mut stream, mut record_size)| async move {
let stream = ReaderStream::with_capacity(reader, SELECT_DECODE_CHUNK_BYTES).map_err(input_io_error);
Ok(record_size_limited_stream(stream, record_size, select_object_store_error))
}
/// Fails the stream with `OverMaxRecordSize` once a record exceeds
/// `MAX_SELECT_RECORD_BYTES`. The `ScanRange` splitter and the Arrow decoders
/// buffer whole records, so every CSV and JSON Lines input path applies it,
/// compressed or uncompressed.
pub(crate) fn record_size_limited_stream<S, E>(
stream: S,
record_size: RecordSizeTracker,
map_error: fn(SelectError) -> E,
) -> BoxStream<'static, Result<Bytes, E>>
where
S: Stream<Item = Result<Bytes, E>> + Send + 'static,
E: Send + 'static,
{
stream::try_unfold((stream.boxed(), record_size), move |(mut stream, mut record_size)| async move {
match stream.next().await {
Some(Ok(bytes)) => {
record_size.observe(&bytes).map_err(select_object_store_error)?;
record_size.observe(&bytes).map_err(map_error)?;
Ok(Some((bytes, (stream, record_size))))
}
Some(Err(error)) => Err(input_io_error(error)),
Some(Err(error)) => Err(error),
None => {
record_size.finish().map_err(select_object_store_error)?;
record_size.finish().map_err(map_error)?;
Ok(None)
}
}
})
.boxed())
.boxed()
}
pub(crate) fn input_io_error(source: io::Error) -> ObjectStoreError {
@@ -395,7 +433,7 @@ pub(crate) fn input_io_error(source: io::Error) -> ObjectStoreError {
}
}
fn select_object_store_error(source: SelectError) -> ObjectStoreError {
pub(crate) fn select_object_store_error(source: SelectError) -> ObjectStoreError {
ObjectStoreError::Generic {
store: "EcObjectStore",
source: Box::new(source),
@@ -657,84 +695,127 @@ pub(crate) fn find_error_source<'a, T: StdError + 'static>(error: &'a (dyn StdEr
None
}
struct RecordSizeTracker {
delimiter: Vec<u8>,
prefix: Vec<usize>,
enum RecordDelimiterMatcher {
/// Default CSV line endings (`\r`, `\n`, or `\r\n`) when no custom `RecordDelimiter` is configured.
DefaultCsvLineEnding,
SingleByte(u8),
MultiByte {
delimiter: Vec<u8>,
prefix: Vec<usize>,
matched: usize,
},
}
pub(crate) struct RecordSizeTracker {
matcher: RecordDelimiterMatcher,
record_bytes: usize,
matched: usize,
}
impl RecordSizeTracker {
fn new(delimiter: Vec<u8>) -> Result<Self, SelectError> {
pub(crate) fn default_csv() -> Self {
Self {
matcher: RecordDelimiterMatcher::DefaultCsvLineEnding,
record_bytes: 0,
}
}
pub(crate) fn new(delimiter: Vec<u8>) -> Result<Self, SelectError> {
if delimiter.is_empty() {
return Err(SelectError::InvalidDataSource);
}
let mut prefix = vec![0; delimiter.len()];
let mut matched = 0;
for index in 1..delimiter.len() {
while matched > 0 && delimiter[index] != delimiter[matched] {
matched = prefix[matched - 1];
let matcher = if delimiter.len() == 1 {
RecordDelimiterMatcher::SingleByte(delimiter[0])
} else {
let mut prefix = vec![0; delimiter.len()];
let mut matched = 0;
for index in 1..delimiter.len() {
while matched > 0 && delimiter[index] != delimiter[matched] {
matched = prefix[matched - 1];
}
if delimiter[index] == delimiter[matched] {
matched += 1;
}
prefix[index] = matched;
}
if delimiter[index] == delimiter[matched] {
matched += 1;
RecordDelimiterMatcher::MultiByte {
delimiter,
prefix,
matched: 0,
}
prefix[index] = matched;
}
};
Ok(Self {
delimiter,
prefix,
matcher,
record_bytes: 0,
matched: 0,
})
}
fn observe(&mut self, bytes: &[u8]) -> Result<(), SelectError> {
if self.delimiter.len() == 1 {
return self.observe_single_byte_delimiter(bytes);
}
for &byte in bytes {
self.record_bytes = self.record_bytes.checked_add(1).ok_or(SelectError::OverMaxRecordSize)?;
while self.matched > 0 && byte != self.delimiter[self.matched] {
self.matched = self.prefix[self.matched - 1];
}
if byte == self.delimiter[self.matched] {
self.matched += 1;
}
if self.matched == self.delimiter.len() {
let payload_bytes = self.record_bytes - self.delimiter.len();
if payload_bytes > MAX_SELECT_RECORD_BYTES {
fn observe(&mut self, mut bytes: &[u8]) -> Result<(), SelectError> {
match &mut self.matcher {
RecordDelimiterMatcher::DefaultCsvLineEnding => {
while let Some(index) = memchr2(b'\r', b'\n', bytes) {
let payload_bytes = self.record_bytes.checked_add(index).ok_or(SelectError::OverMaxRecordSize)?;
if payload_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
bytes = &bytes[index + 1..];
}
self.record_bytes = self
.record_bytes
.checked_add(bytes.len())
.ok_or(SelectError::OverMaxRecordSize)?;
if self.record_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
self.matched = 0;
} else if self.record_bytes - self.matched > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
Ok(())
}
RecordDelimiterMatcher::SingleByte(delimiter) => {
let delimiter = *delimiter;
while let Some(index) = memchr(delimiter, bytes) {
let payload_bytes = self.record_bytes.checked_add(index).ok_or(SelectError::OverMaxRecordSize)?;
if payload_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
bytes = &bytes[index + 1..];
}
self.record_bytes = self
.record_bytes
.checked_add(bytes.len())
.ok_or(SelectError::OverMaxRecordSize)?;
if self.record_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
Ok(())
}
RecordDelimiterMatcher::MultiByte {
delimiter,
prefix,
matched,
} => {
for &byte in bytes {
self.record_bytes = self.record_bytes.checked_add(1).ok_or(SelectError::OverMaxRecordSize)?;
while *matched > 0 && byte != delimiter[*matched] {
*matched = prefix[*matched - 1];
}
if byte == delimiter[*matched] {
*matched += 1;
}
if *matched == delimiter.len() {
let payload_bytes = self.record_bytes - delimiter.len();
if payload_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
*matched = 0;
} else if self.record_bytes - *matched > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
}
Ok(())
}
}
Ok(())
}
fn observe_single_byte_delimiter(&mut self, mut bytes: &[u8]) -> Result<(), SelectError> {
let delimiter = self.delimiter[0];
while let Some(index) = bytes.iter().position(|byte| *byte == delimiter) {
let payload_bytes = self.record_bytes.checked_add(index).ok_or(SelectError::OverMaxRecordSize)?;
if payload_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
bytes = &bytes[index + 1..];
}
self.record_bytes = self
.record_bytes
.checked_add(bytes.len())
.ok_or(SelectError::OverMaxRecordSize)?;
if self.record_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
Ok(())
}
fn finish(&self) -> Result<(), SelectError> {
+227 -25
View File
@@ -22,12 +22,13 @@ use crate::{
SelectInputMetrics, SelectObjectOptions, SelectObjectSnapshot, SelectObjectSnapshotReadError, SelectStorageError,
SelectStore, SnapshotConsistencyError,
input_stream::{
CompressionFormat, SELECT_DECODE_CHUNK_BYTES, compressed_input_reader, compressed_input_stream, input_io_error,
processed_bytes_limit,
CompressionFormat, MAX_SELECT_RECORD_BYTES, RecordSizeTracker, SELECT_DECODE_CHUNK_BYTES, compressed_input_reader,
compressed_input_stream_with_tracker, input_io_error, processed_bytes_limit, record_size_limited_stream,
select_object_store_error,
},
query::{
ast::{JsonPathSegment, JsonSource},
parser::RustFsDialect,
parser::{BoundedRustFsDialect, validate_set_operator_budget},
session::QueryExecutionTracker,
},
resolve_select_object_store_handle, select_is_err_bucket_not_found, select_is_err_object_not_found,
@@ -47,6 +48,7 @@ use datafusion::{
sqlparser::{
ast::{Expr, Ident, JsonPathElem, ObjectNamePart, SetExpr, Statement, TableFactor},
parser::Parser as SqlParser,
tokenizer::Tokenizer,
},
},
};
@@ -345,6 +347,37 @@ impl EcObjectStore {
.unwrap_or_else(|| b"\n".to_vec())
}
fn record_size_tracker(&self) -> Result<RecordSizeTracker> {
if let Some(csv) = self.input.request.input_serialization.csv.as_ref() {
if csv.record_delimiter.is_none() {
return Ok(RecordSizeTracker::default_csv());
}
return RecordSizeTracker::new(self.record_delimiter()).map_err(select_object_store_error);
}
RecordSizeTracker::new(b"\n".to_vec()).map_err(select_object_store_error)
}
/// Applies the 1 MiB record size limit to uncompressed CSV and JSON Lines input,
/// matching compressed input enforcement.
fn limit_record_size<S>(&self, stream: S) -> Result<BoxStream<'static, Result<Bytes>>>
where
S: Stream<Item = Result<Bytes>> + Send + 'static,
{
if self
.input
.request
.input_serialization
.csv
.as_ref()
.is_some_and(|csv| csv.allow_quoted_record_delimiter.unwrap_or(false))
{
// The CSV normalizer owns logical-record limits.
return Ok(stream.boxed());
}
let record_size = self.record_size_tracker()?;
Ok(record_size_limited_stream(stream, record_size, select_object_store_error))
}
fn record_delimiter_for_conversion(&self) -> Option<Vec<u8>> {
let delimiter = self.record_delimiter();
(self.need_convert || (delimiter.len() == 2 && delimiter != NORMALIZED_RECORD_DELIMITER)).then_some(delimiter)
@@ -467,16 +500,22 @@ impl EcObjectStore {
return Ok(Bytes::new());
}
let mut end = select_default_read_buffer_size_u64().min(object_size);
let max_probe = u64::try_from(MAX_SELECT_RECORD_BYTES.saturating_add(delimiter.len())).unwrap_or(u64::MAX);
let mut end = select_default_read_buffer_size_u64().min(object_size).min(max_probe);
loop {
let bytes = self.read_raw_range(0..end).await?;
if let Some(pos) = find_delimiter(&bytes, delimiter) {
let header_end = find_delimiter(&bytes, delimiter);
// Stop widening the read once the header cannot fit the 1 MiB record limit.
if header_end.unwrap_or(bytes.len()) > MAX_SELECT_RECORD_BYTES {
return Err(select_object_store_error(SelectError::OverMaxRecordSize));
}
if let Some(pos) = header_end {
return Ok(bytes.slice(0..pos + delimiter.len()));
}
if end == object_size {
return Ok(bytes);
}
end = end.saturating_mul(2).min(object_size);
end = end.saturating_mul(2).min(object_size).min(max_probe);
}
}
@@ -515,10 +554,19 @@ pub(crate) fn is_json_document_input(input: &SelectObjectContentInput) -> bool {
/// Preserves the pre-typed-path single-key behavior of public legacy constructors.
pub(crate) fn legacy_json_source_from_input(input: &SelectObjectContentInput) -> JsonSource {
if !is_json_document_input(input) {
const MAX_LEGACY_EXPRESSION_BYTES: usize = 256 * 1024;
if !is_json_document_input(input) || input.request.expression.len() > MAX_LEGACY_EXPRESSION_BYTES {
return JsonSource::default();
}
let Ok(mut statements) = SqlParser::parse_sql(&RustFsDialect, &input.request.expression) else {
let dialect = BoundedRustFsDialect::default();
let Ok(tokens) = Tokenizer::new(&dialect, &input.request.expression).tokenize() else {
return JsonSource::default();
};
if validate_set_operator_budget(&tokens).is_err() {
return JsonSource::default();
}
let Ok(mut statements) = SqlParser::new(&dialect).with_tokens(tokens).parse_statements() else {
return JsonSource::default();
};
if statements.len() != 1 {
@@ -963,17 +1011,13 @@ impl ObjectStore for EcObjectStore {
let stream = ReaderStream::with_capacity(reader, SELECT_DECODE_CHUNK_BYTES).map_err(input_io_error);
GetResultPayload::Stream(self.convert_csv_stream(stream))
} else {
let input_record_delimiter = if self.input.request.input_serialization.csv.is_some() {
self.record_delimiter()
} else {
b"\n".to_vec()
};
let stream = compressed_input_stream(
let record_size = self.record_size_tracker()?;
let stream = compressed_input_stream_with_tracker(
reader.stream,
original_size,
compression,
Arc::clone(&self.input_metrics),
input_record_delimiter,
record_size,
max_processed_bytes,
query_guard,
)?;
@@ -1013,10 +1057,17 @@ impl ObjectStore for EcObjectStore {
} else {
None
};
// The ScanRange splitter buffers each record up to its delimiter, so the
// record size limit has to come first.
let record_size = RecordSizeTracker::new(delimiter.clone()).map_err(select_object_store_error)?;
let stream = scan_range_stream(
meter_uncompressed_input_stream(
ReaderStream::with_capacity(reader.stream, SELECT_DEFAULT_READ_BUFFER_SIZE),
Arc::clone(&self.input_metrics),
record_size_limited_stream(
meter_uncompressed_input_stream(
ReaderStream::with_capacity(reader.stream, SELECT_DEFAULT_READ_BUFFER_SIZE),
Arc::clone(&self.input_metrics),
),
record_size,
|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error),
),
delimiter,
scan_range,
@@ -1040,6 +1091,7 @@ impl ObjectStore for EcObjectStore {
let stream = bytes_stream(ReaderStream::with_capacity(reader.stream, SELECT_DEFAULT_READ_BUFFER_SIZE), stream_size);
if meter_input {
let stream = meter_uncompressed_input_stream(stream, Arc::clone(&self.input_metrics));
let stream = self.limit_record_size(stream)?;
let stream = self.convert_csv_stream(stream);
GetResultPayload::Stream(stream)
} else {
@@ -1263,13 +1315,7 @@ where
Some(Ok(bytes)) => state.push_chunk(&bytes),
Some(Err(err)) => {
state.done = true;
return Some((
Err(o_Error::Generic {
store: "EcObjectStore",
source: Box::new(err),
}),
state,
));
return Some((Err(input_io_error(err)), state));
}
None => {
if state.offset < state.expected_end {
@@ -1639,6 +1685,23 @@ mod test {
assert_eq!(legacy_json_source_from_input(&quoted_key).scalar_column(), Some("LongKey"));
}
#[test]
fn legacy_source_adapter_bounds_operator_and_set_chains_on_small_stack() {
let plus_chain = format!("SELECT {} FROM S3Object.employees", vec!["1"; 64 * 1024].join("+"));
let trailing_err = format!("SELECT {}+) FROM S3Object.employees", vec!["1"; 64 * 1024].join("+"));
let union_chain = vec!["SELECT 1"; 16 * 1024].join(" UNION ");
for expression in [plus_chain, trailing_err, union_chain] {
let input = json_document_input("bucket", "input.json", &expression);
let source = std::thread::Builder::new()
.stack_size(1024 * 1024)
.spawn(move || legacy_json_source_from_input(&input))
.expect("spawn bounded-stack worker")
.join()
.expect("bounded parser must not overflow worker stack");
assert_eq!(source, JsonSource::default());
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial_test::serial]
async fn legacy_public_constructors_preserve_single_key_json_source() {
@@ -3235,6 +3298,145 @@ mod test {
}
}
#[tokio::test]
async fn uncompressed_input_enforces_the_record_size_limit() {
const BUCKET: &str = "select-uncompressed-record-limit";
let env = crate::storage_api::select_test_ecstore_env().await;
env.make_bucket(BUCKET, false).await;
// (JSON Lines, ScanRange, ScanRange starting after CSV header)
let cases = [
(false, false, false),
(false, true, false),
(false, true, true),
(true, false, false),
(true, true, false),
];
for (json, scan_range, after_header) in cases {
for size in [MAX_SELECT_RECORD_BYTES, MAX_SELECT_RECORD_BYTES + 1] {
let mut data = if json {
let mut record = br#"{"v":""#.to_vec();
record.resize(size - 2, b'a');
record.extend_from_slice(b"\"}");
record
} else {
vec![b'a'; size]
};
data.push(b'\n');
if after_header {
data.extend_from_slice(b"1\n");
}
let object = format!("{json}-{scan_range}-{after_header}-{size}");
let mut reader = SelectPutObjReader::from_vec(data.clone());
env.ecstore
.put_object(BUCKET, &object, &mut reader, &Default::default())
.await
.expect("write record limit fixture");
let mut input = if json {
(*json_input(BUCKET, &object, JsonType::LINES)).clone()
} else {
(*csv_input(BUCKET, &object)).clone()
};
if after_header {
let csv = input.request.input_serialization.csv.as_mut().expect("CSV input");
csv.file_header_info = Some(FileHeaderInfo::USE);
}
if scan_range {
let start = if after_header { size + 1 } else { 0 };
input.request.scan_range = Some(ScanRange {
start: Some(i64::try_from(start).expect("fixture offset")),
end: Some(i64::try_from(start + 1).expect("fixture offset")),
});
}
let store = EcObjectStore::build_with_snapshot(
Arc::new(input),
Arc::new(GreedyMemoryPool::new(4 * MAX_SELECT_RECORD_BYTES)),
None,
Arc::new(SelectInputMetrics::default()),
prepare_test_snapshot(BUCKET, &object).await,
JsonSource::default(),
)
.expect("record limit store");
let output = match store.get_opts(&Path::from(object.as_str()), GetOptions::default()).await {
Ok(result) => {
let GetResultPayload::Stream(stream) = result.payload else { panic!("uncompressed stream") };
stream.try_collect::<Vec<_>>().await
}
Err(error) => Err(error),
};
if size > MAX_SELECT_RECORD_BYTES {
let error = output.expect_err("uncompressed records over 1 MiB must fail like compressed ones");
assert_eq!(
QueryError::from(DataFusionError::from(error)).select_error(),
SelectError::OverMaxRecordSize,
"object={object}"
);
} else {
assert_eq!(output.expect("records within the limit must pass").concat(), data, "object={object}");
}
}
}
}
#[tokio::test]
async fn default_csv_record_limit_handles_cr_only_line_endings() {
const BUCKET: &str = "select-cr-only-csv-limit";
let env = crate::storage_api::select_test_ecstore_env().await;
env.make_bucket(BUCKET, false).await;
let valid_cr_csv = format!("a,b\r{}", format!("{},val\r", "x".repeat(95)).repeat(15_000)).into_bytes();
assert!(
valid_cr_csv.len() > MAX_SELECT_RECORD_BYTES,
"fixture must span more than 1 MiB across CR-only records"
);
let mut oversized_cr_csv = vec![b'a'; MAX_SELECT_RECORD_BYTES + 1];
oversized_cr_csv.push(b'\r');
for compression in [None, Some(CompressionFormat::Gzip)] {
for (name, raw, should_fail) in [("valid-cr", &valid_cr_csv, false), ("oversized-cr", &oversized_cr_csv, true)] {
let bytes = match compression {
Some(format) => encode_compressed_fixture(format, raw).await,
None => raw.clone(),
};
let object = format!("{name}-{compression:?}");
let mut reader = SelectPutObjReader::from_vec(bytes);
env.ecstore
.put_object(BUCKET, &object, &mut reader, &Default::default())
.await
.expect("write CR CSV fixture");
let mut input = (*csv_input(BUCKET, &object)).clone();
input.request.input_serialization.compression_type = compression.map(|format| match format {
CompressionFormat::Gzip => CompressionType::GZIP,
CompressionFormat::Bzip2 => CompressionType::BZIP2,
});
let store = EcObjectStore::build_with_snapshot(
Arc::new(input),
Arc::new(GreedyMemoryPool::new(4 * MAX_SELECT_RECORD_BYTES)),
None,
Arc::new(SelectInputMetrics::default()),
prepare_test_snapshot(BUCKET, &object).await,
JsonSource::default(),
)
.expect("CR CSV store");
let result = store
.get_opts(&Path::from(object.as_str()), GetOptions::default())
.await
.expect("open CR CSV stream");
let GetResultPayload::Stream(stream) = result.payload else { panic!("CSV stream") };
let output = stream.try_collect::<Vec<_>>().await;
if should_fail {
let error = output.expect_err("oversized CR-only record must fail");
assert_eq!(
QueryError::from(DataFusionError::from(error)).select_error(),
SelectError::OverMaxRecordSize,
"object={object}"
);
} else {
assert_eq!(output.expect("valid CR-only CSV over 1 MiB must pass").concat(), *raw, "object={object}");
}
}
}
}
#[tokio::test]
async fn quoted_record_delimiters_preserve_compressed_crlf_size_boundaries() {
use crate::input_stream::MAX_SELECT_RECORD_BYTES;
+85 -2
View File
@@ -12,13 +12,41 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::VecDeque;
use std::{
collections::VecDeque,
sync::atomic::{AtomicUsize, Ordering},
};
use datafusion::sql::sqlparser::dialect::Dialect;
use datafusion::sql::sqlparser::{
ast::Expr,
dialect::Dialect,
keywords::Keyword,
parser::{Parser as SqlParser, ParserError},
tokenizer::Token,
};
use super::ast::ExtStatement;
use crate::QueryResult;
/// Maximum number of infix and postfix operators in one S3 Select expression.
///
/// sqlparser's recursion limit only guards nested sub-expressions. Operator chains
/// (`1+1+...+1`, `a OR b OR ...`, `x IS NULL IS NULL ...`) are parsed in a loop where
/// each operator nests the expression built so far one level deeper. The resulting
/// AST is later cloned, dropped, and planned recursively on a worker-thread stack,
/// so operator count must be bounded during parsing.
pub const MAX_SELECT_OPERATORS: usize = 256;
/// Maximum number of SQL set-operation keywords (`UNION`, `EXCEPT`, `INTERSECT`,
/// `MINUS`) allowed before parsing. sqlparser builds `SetExpr::SetOperation` chains
/// in a loop without touching `Dialect::parse_infix`, so unbounded chains would
/// overflow the stack on drop even though S3 Select rejects set operations.
pub const MAX_SELECT_SET_OPERATORS: usize = 16;
/// Maximum nested field-access segments (`a.b.c...` or `a[0][1]...`) in one expression,
/// bounding `CoreFunctionPlanner::plan_compound_identifier` recursion depth.
pub const MAX_SELECT_FIELD_ACCESS_DEPTH: usize = 64;
#[derive(Debug, Default)]
pub struct RustFsDialect;
@@ -40,6 +68,61 @@ impl Dialect for RustFsDialect {
}
}
/// [`RustFsDialect`] that rejects expressions with more than [`MAX_SELECT_OPERATORS`]
/// infix or postfix operators. The budget is per instance, so construct a fresh
/// dialect for every parse.
#[derive(Debug, Default)]
pub struct BoundedRustFsDialect {
operators: AtomicUsize,
}
impl Dialect for BoundedRustFsDialect {
fn is_identifier_start(&self, ch: char) -> bool {
RustFsDialect.is_identifier_start(ch)
}
fn is_identifier_part(&self, ch: char) -> bool {
RustFsDialect.is_identifier_part(ch)
}
fn supports_group_by_expr(&self) -> bool {
RustFsDialect.supports_group_by_expr()
}
fn supports_partiql(&self) -> bool {
RustFsDialect.supports_partiql()
}
/// Called by sqlparser before every infix or postfix operator.
fn parse_infix(&self, _parser: &mut SqlParser, _expr: &Expr, _precedence: u8) -> Option<Result<Expr, ParserError>> {
if self.operators.load(Ordering::Relaxed) >= MAX_SELECT_OPERATORS {
// `RecursionLimitExceeded` is the only error sqlparser's speculative
// `maybe_parse` does not swallow, and matches nested-parenthesis errors.
return Some(Err(ParserError::RecursionLimitExceeded));
}
self.operators.fetch_add(1, Ordering::Relaxed);
// `None` hands the operator back to sqlparser's standard infix parsing.
None
}
}
/// Rejects token streams with more than [`MAX_SELECT_SET_OPERATORS`] set-operation
/// keywords before sqlparser constructs a deeply nested `SetExpr::SetOperation` tree.
pub fn validate_set_operator_budget(tokens: &[Token]) -> Result<(), ParserError> {
let mut set_operators = 0usize;
for token in tokens {
if let Token::Word(word) = token
&& matches!(word.keyword, Keyword::UNION | Keyword::EXCEPT | Keyword::INTERSECT | Keyword::MINUS)
{
set_operators += 1;
if set_operators > MAX_SELECT_SET_OPERATORS {
return Err(ParserError::RecursionLimitExceeded);
}
}
}
Ok(())
}
pub trait Parser {
fn parse(&self, sql: &str) -> QueryResult<VecDeque<ExtStatement>>;
}
+36 -14
View File
@@ -441,12 +441,20 @@ impl SessionCtxFactory {
};
let rt = RuntimeEnvBuilder::new().with_memory_limit(memory_limit_bytes, 1.0).build()?;
let config = SessionConfig::new().with_target_partitions(self.target_partitions);
// Arrow CSV reserves two usize offsets for every cell outside the
// DataFusion memory pool. Bound that reservation to at most 4 MiB and
// one sixteenth of the configured query budget, including narrow input.
let config = if context.input.request.input_serialization.csv.is_some() {
// Bound decoder batch rows for CSV and JSON Lines to match the configured
// query budget, and disable batch coalescing across S3 Select formats so
// downstream operators cannot re-buffer unbounded batches outside the pool.
let config = if context.input.request.input_serialization.csv.is_some()
|| (context.input.request.input_serialization.json.is_some() && !is_json_document_input(&context.input))
{
let batch_rows = (memory_limit_bytes / 16 / (MAX_SELECT_COLUMNS * 2 * size_of::<usize>())).clamp(1, 256);
config.with_batch_size(batch_rows)
let mut config = config.with_batch_size(batch_rows);
config.options_mut().execution.coalesce_batches = false;
config
} else if is_json_document_input(&context.input) {
let mut config = config;
config.options_mut().execution.coalesce_batches = false;
config
} else {
config
};
@@ -1035,12 +1043,26 @@ mod tests {
#[tokio::test]
async fn decoder_batch_budgets_keep_parquet_downstream_execution_single_row() {
let factory = SessionCtxFactory::new(true);
for (budget, expected) in [(64 * 1024 * 1024, 256), (8 * 1024 * 1024, 32), (1024, 1)] {
let session = factory
.create_session_ctx_inner(&test_context(), None, JsonSource::default(), None, None, budget)
.await
.expect("CSV session");
assert_eq!(session.inner().config().batch_size(), expected);
for json_lines in [false, true] {
let mut context = test_context();
if json_lines {
let input = Arc::make_mut(&mut context.input);
input.request.input_serialization.csv = None;
input.request.input_serialization.json = Some(JsonInput {
r#type: Some(JsonType::LINES),
});
}
for (budget, expected) in [(64 * 1024 * 1024, 256), (8 * 1024 * 1024, 32), (1024, 1)] {
let session = factory
.create_session_ctx_inner(&context, None, JsonSource::default(), None, None, budget)
.await
.expect("delimited session");
assert_eq!(session.inner().config().batch_size(), expected, "json_lines={json_lines}");
assert!(
!session.inner().config().options().execution.coalesce_batches,
"coalesce_batches must be disabled for json_lines={json_lines}"
);
}
}
for parquet in [false, true] {
let mut context = test_context();
@@ -1050,16 +1072,16 @@ mod tests {
input.request.input_serialization.parquet = Some(ParquetInput::default());
} else {
input.request.input_serialization.json = Some(JsonInput {
r#type: Some(JsonType::LINES),
r#type: Some(JsonType::DOCUMENT),
});
}
let session = factory.create_session_ctx(&context).await.expect("non-CSV session");
let session = factory.create_session_ctx(&context).await.expect("non-delimited session");
assert_eq!(
session.inner().config().batch_size(),
if parquet { 1 } else { SessionConfig::new().batch_size() }
);
assert!(!session.inner().config().options().execution.coalesce_batches);
if parquet {
assert!(!session.inner().config().options().execution.coalesce_batches);
assert_eq!(session.inner().config().target_partitions(), 1);
}
}
File diff suppressed because it is too large Load Diff
@@ -637,7 +637,7 @@ impl Stream for JsonDocumentBatchStream {
}
}
fn json_decoder_layout(schema: &SchemaRef, requested_batch_size: usize) -> DFResult<(usize, usize)> {
pub(super) fn json_decoder_layout(schema: &SchemaRef, requested_batch_size: usize) -> DFResult<(usize, usize)> {
let fields = schema.flattened_fields().len();
let field_slots = fields.checked_mul(2).ok_or_else(decoder_resource_error)?;
let offset_bytes_per_row = field_slots
+101 -27
View File
@@ -28,8 +28,8 @@ use datafusion::{
record_batch::RecordBatch,
},
datasource::{
file_format::{DEFAULT_SCHEMA_INFER_MAX_RECORD, csv::CsvFormat, json::JsonFormat},
listing::{ListingOptions, ListingTable, ListingTableConfig, ListingTableUrl},
file_format::{DEFAULT_SCHEMA_INFER_MAX_RECORD, csv::CsvFormat},
listing::ListingTableUrl,
},
error::{DataFusionError, Result as DFResult},
execution::{RecordBatchStream, SendableRecordBatchStream},
@@ -62,7 +62,12 @@ use tokio::{
};
use crate::{
dispatcher::{json_document_table::JsonDocumentTable, json_lines_schema, parquet_table::ParquetSelectTable},
dispatcher::{
delimited_table::{DelimitedFormat, DelimitedSelectTable},
json_document_table::JsonDocumentTable,
json_lines_schema,
parquet_table::ParquetSelectTable,
},
execution::factory::QueryExecutionFactoryRef,
instance::{DEFAULT_MAX_CONCURRENT_QUERIES, DEFAULT_QUERY_TIMEOUT_SECS},
metadata::{MetadataProvider, TableHandleProviderRef, base_table::BaseTableProvider},
@@ -75,7 +80,6 @@ use super::schema_inference::{PrefixBoundary, infer_csv_schema, read_schema_pref
static IGNORE: LazyLock<FileHeaderInfo> = LazyLock::new(|| FileHeaderInfo::IGNORE);
static NONE: LazyLock<FileHeaderInfo> = LazyLock::new(|| FileHeaderInfo::NONE);
static USE: LazyLock<FileHeaderInfo> = LazyLock::new(|| FileHeaderInfo::USE);
const EXACT_OBJECT_FILE_EXTENSION: &str = "";
#[derive(Clone)]
pub struct SimpleQueryDispatcher {
@@ -447,7 +451,7 @@ impl SimpleQueryDispatcher {
let path = format!("s3://{}/{}", self.input.bucket, self.input.key);
let table_path = ListingTableUrl::parse(path)?;
let mut csv_format = None;
let (listing_options, need_rename_volume_name, need_ignore_volume_name) =
let (format, need_rename_volume_name, need_ignore_volume_name) =
if let Some(csv) = self.input.request.input_serialization.csv.as_ref() {
let mut need_rename_volume_name = false;
let mut need_ignore_volume_name = false;
@@ -509,19 +513,11 @@ impl SimpleQueryDispatcher {
.with_comment(None)
.with_newlines_in_values(true);
}
csv_format = Some(CsvFormat::default().with_options(file_format.options().clone()));
(
ListingOptions::new(Arc::new(file_format)).with_file_extension(EXACT_OBJECT_FILE_EXTENSION),
need_rename_volume_name,
need_ignore_volume_name,
)
let options = file_format.options().clone();
csv_format = Some(CsvFormat::default().with_options(options.clone()));
(DelimitedFormat::Csv(Box::new(options)), need_rename_volume_name, need_ignore_volume_name)
} else if self.input.request.input_serialization.json.is_some() {
let file_format = JsonFormat::default();
(
ListingOptions::new(Arc::new(file_format)).with_file_extension(EXACT_OBJECT_FILE_EXTENSION),
false,
false,
)
(DelimitedFormat::JsonLines, false, false)
} else {
return Err(SelectError::InvalidDataSource.into());
};
@@ -559,7 +555,7 @@ impl SimpleQueryDispatcher {
Ok(schema)
})
.await?;
let config = if need_rename_volume_name {
let schema = if need_rename_volume_name {
let mut new_fields = Vec::new();
for (i, field) in resolve_schema.fields().iter().enumerate() {
let f_name = field.name();
@@ -574,17 +570,12 @@ impl SimpleQueryDispatcher {
new_fields.push(mut_field);
}
}
let new_schema = Arc::new(Schema::new(new_fields).with_metadata(resolve_schema.metadata().clone()));
ListingTableConfig::new(table_path)
.with_listing_options(listing_options)
.with_schema(new_schema)
Arc::new(Schema::new(new_fields).with_metadata(resolve_schema.metadata().clone()))
} else {
ListingTableConfig::new(table_path)
.with_listing_options(listing_options)
.with_schema(resolve_schema)
resolve_schema
};
// rename default
let provider = Arc::new(ListingTable::try_new(config)?);
let provider =
DelimitedSelectTable::try_new(session.inner(), table_path.object_store(), &self.input.key, schema, format).await?;
let current_session_table_provider = self.build_table_handle_provider()?;
let metadata_provider =
MetadataProvider::new(provider, current_session_table_provider, self.func_manager.clone(), session.clone());
@@ -2049,6 +2040,89 @@ mod tests {
assert_eq!(field_names(batches[0].schema().fields()), ["z", "a"]);
}
#[tokio::test]
async fn delimited_input_stays_within_tight_memory_budget_and_enforces_record_limit() {
const TIGHT_MEMORY_LIMIT_BYTES: usize = 8 * 1024 * 1024;
const RECORDS: usize = 64;
let line = "x".repeat(256 * 1024);
// 64 rows * 128 KiB = 8 MiB CSV payload processed with a WHERE filter under an 8 MiB pool.
let csv_records = format!("id,name\n{}", format!("1,{}\n", &line[..line.len() / 2]).repeat(RECORDS));
// 64 rows * 128 KiB = 8 MiB JSON Lines payload processed with a WHERE filter under an 8 MiB pool.
let json_records = format!("{{\"id\":\"1\",\"name\":\"{}\"}}\n", &line[..line.len() / 2]).repeat(RECORDS);
// Oversized single uncompressed records (> 1 MiB) must fail with OverMaxRecordSize.
let oversized_csv = format!("id,name\n1,{}\n", "x".repeat(1024 * 1024 + 1));
let oversized_json = format!("{{\"id\":\"1\",\"name\":\"{}\"}}\n", "x".repeat(1024 * 1024));
// Logical quoted CSV record spanning 64 * 256 KiB = 16 MiB must fail under the 8 MiB pool.
let oversized_quoted_csv = format!("id,name\n1,\"{}\"\n", [line.as_str(); RECORDS].join("\n"));
let cases = [
(csv_records, false, TIGHT_MEMORY_LIMIT_BYTES, Ok(RECORDS)),
(json_records, true, TIGHT_MEMORY_LIMIT_BYTES, Ok(RECORDS)),
(
oversized_csv,
false,
DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES,
Err(SelectError::OverMaxRecordSize),
),
(
oversized_json,
true,
DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES,
Err(SelectError::OverMaxRecordSize),
),
(oversized_quoted_csv, false, TIGHT_MEMORY_LIMIT_BYTES, Err(SelectError::ResourceExhausted)),
// Valid large JSON Lines object (120 * 70 KiB = ~8.4 MiB) must succeed under the default 64 MiB limit.
(
format!("{{\"id\":\"1\",\"name\":\"{}\"}}\n", "x".repeat(70_000)).repeat(120),
true,
DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES,
Ok(120),
),
];
let env = snapshot_test_env().await;
for (index, (data, json, memory_limit, expected)) in cases.into_iter().enumerate() {
let mut input = test_input();
input.bucket = format!("select-delimited-budget-{index}");
input.key = "records".to_owned();
if json {
input.request.input_serialization.csv = None;
input.request.input_serialization.json = Some(JsonInput {
r#type: Some(JsonType::LINES),
});
}
env.make_bucket(&input.bucket, false).await;
env.put_object_bytes(&input.bucket, &input.key, data.into_bytes()).await;
let snapshot = env.prepare_select_object_snapshot(&input.bucket, &input.key).await;
let input = Arc::new(input);
let optimizer = Arc::new(CascadeOptimizerBuilder::default().build());
let dispatcher = SimpleQueryDispatcherBuilder::default()
.with_input(Arc::clone(&input))
.with_default_table_provider(Arc::new(BaseTableProvider::default()))
.with_session_factory(Arc::new(SessionCtxFactory::new(false)))
.with_parser(Arc::new(DefaultParser::default()))
.with_query_execution_factory(Arc::new(SqlQueryExecutionFactory::new(optimizer, Arc::new(LocalScheduler {}))))
.with_func_manager(Arc::new(SimpleFunctionMetadataManager::default()))
.with_memory_limit_bytes(memory_limit)
.build()
.expect("query dispatcher should build");
// Keep every row through a FilterExec to confirm filtered batches stream without coalescing.
let sql = "SELECT s.id FROM S3Object s WHERE s.name <> ''".to_owned();
let query = Query::new_with_snapshot(QueryContext { input }, sql, snapshot);
let rows = match dispatcher.execute_query(&query).await {
Ok(output) => output
.into_record_batch_stream()
.expect("record stream")
.try_collect::<Vec<_>>()
.await
.map(|batches| batches.iter().map(RecordBatch::num_rows).sum::<usize>())
.map_err(|error| QueryError::from(error).select_error()),
Err(error) => Err(error.select_error()),
};
assert_eq!(rows, expected, "fixture={index}");
}
}
#[tokio::test(flavor = "current_thread")]
async fn blocking_select_planning_keeps_runtime_responsive_and_admission_after_cancel() {
for phase in ["SQL parse", "schema inference", "SQL plan"] {
@@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
mod delimited_table;
mod json_document_schema;
mod json_document_table;
mod json_lines_schema;
@@ -21,7 +21,7 @@ use datafusion::{
},
datasource::file_format::{DEFAULT_SCHEMA_INFER_MAX_RECORD, csv::CsvFormat},
error::{DataFusionError, Result},
execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation},
execution::memory_pool::{MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation},
object_store::Error as ObjectStoreError,
};
use futures::{StreamExt, stream::BoxStream};
@@ -65,7 +65,7 @@ impl PrefixBoundary {
}
}
fn consume(&mut self, input: &[u8], prefix: &[u8]) -> Result<(usize, bool)> {
fn consume(&mut self, input: &[u8], prefix: &[u8], json_sample_limit: usize) -> Result<(usize, bool)> {
match self {
Self::JsonLines { records, line_start } => {
for (index, byte) in input.iter().enumerate() {
@@ -83,7 +83,7 @@ impl PrefixBoundary {
if nonblank {
*records += 1;
}
if *records == DEFAULT_SCHEMA_INFER_MAX_RECORD {
if *records == DEFAULT_SCHEMA_INFER_MAX_RECORD || (*records > 0 && end >= json_sample_limit) {
return Ok((index + 1, true));
}
}
@@ -129,17 +129,31 @@ pub(super) async fn read_schema_prefix(
mut boundary: PrefixBoundary,
) -> Result<SchemaPrefix> {
let reservation = MemoryConsumer::new("S3 Select schema prefix").register(memory_pool);
// Keep multi-record JSON Lines inference samples within the query memory budget
// (accounting for downstream schema-inference working memory) while still allowing
// a single record to probe up to MAX_SCHEMA_PREFIX_BYTES.
let json_sample_limit = match memory_pool.memory_limit() {
MemoryLimit::Finite(limit) => MAX_SCHEMA_PREFIX_BYTES.min((limit / 32).max(1)),
MemoryLimit::Infinite | MemoryLimit::Unknown => MAX_SCHEMA_PREFIX_BYTES,
};
let mut bytes = Vec::new();
let mut parsed = 0;
while let Some(chunk) = stream.next().await.transpose()? {
let mut offset = 0;
while offset < chunk.len() {
let remaining = MAX_SCHEMA_PREFIX_BYTES - bytes.len();
let step_limit = match &boundary {
PrefixBoundary::JsonLines { records, .. } if *records > 0 => json_sample_limit,
PrefixBoundary::JsonLines { .. } if bytes.len() < json_sample_limit => json_sample_limit,
_ => MAX_SCHEMA_PREFIX_BYTES,
};
let remaining = step_limit.saturating_sub(bytes.len());
if remaining == 0 {
if let PrefixBoundary::JsonLines { records, line_start } = &boundary
&& *records > 0
{
bytes.truncate(*line_start);
bytes.shrink_to_fit();
reservation.try_resize(bytes.capacity())?;
return Ok(SchemaPrefix { bytes, reservation });
}
return Err(prefix_limit_error());
@@ -162,19 +176,21 @@ pub(super) async fn read_schema_prefix(
offset = end;
continue;
}
let (consumed, done) = boundary.consume(&bytes[parsed..], &bytes)?;
let (consumed, done) = boundary.consume(&bytes[parsed..], &bytes, json_sample_limit)?;
parsed += consumed;
bytes.truncate(parsed);
offset = end;
if done {
bytes.shrink_to_fit();
reservation.try_resize(bytes.capacity())?;
return Ok(SchemaPrefix { bytes, reservation });
}
}
}
if parsed < bytes.len() {
boundary.consume(&bytes[parsed..], &bytes)?;
boundary.consume(&bytes[parsed..], &bytes, json_sample_limit)?;
}
boundary.consume(&[], &bytes)?;
boundary.consume(&[], &bytes, json_sample_limit)?;
Ok(SchemaPrefix { bytes, reservation })
}
@@ -13,3 +13,4 @@
// limitations under the License.
pub mod simple_func_manager;
pub mod size_bound;
@@ -19,10 +19,110 @@ use datafusion::execution::SessionStateDefaults;
use datafusion::logical_expr::{AggregateUDF, ScalarUDF, WindowUDF};
use rustfs_s3select_api::query::function::FunctionMetadataManager;
use rustfs_s3select_api::{QueryError, QueryResult};
use tracing::debug;
use crate::function::size_bound::bound_result_size;
pub type SimpleFunctionMetadataManagerRef = Arc<SimpleFunctionMetadataManager>;
/// Explicit allowlist of canonical DataFusion scalar function names exposed to S3 Select SQL.
///
/// S3 Select must not expose the entire DataFusion catalog (such as `arrow_cast`,
/// `repeat`, `lpad`, `rpad`, `replace`, `levenshtein`, `version`, `uuid`, regex,
/// encoding, crypto, or nested-array builders). Aliases declared by an allowlisted
/// UDF (such as `length` / `char_length` for `character_length`, `substring` for
/// `substr`, `trim` for `btrim`, and `pow` for `power`) are registered alongside it.
const ALLOWED_SCALAR_FUNCTIONS: &[&str] = &[
// Conditional
"coalesce",
"greatest",
"least",
"nullif",
"nvl",
"nvl2",
// String
"ascii",
"bit_length",
"btrim",
"character_length",
"chr",
"concat",
"concat_ws",
"contains",
"ends_with",
"initcap",
"left",
"lower",
"ltrim",
"octet_length",
"reverse",
"right",
"rtrim",
"split_part",
"starts_with",
"strpos",
"substr",
"substr_index",
"upper",
// Math
"abs",
"acos",
"acosh",
"asin",
"asinh",
"atan",
"atan2",
"atanh",
"cbrt",
"ceil",
"cos",
"cosh",
"cot",
"degrees",
"exp",
"floor",
"isnan",
"iszero",
"ln",
"log",
"log10",
"log2",
"nanvl",
"pi",
"power",
"radians",
"round",
"signum",
"sin",
"sinh",
"sqrt",
"tan",
"tanh",
"trunc",
// Date / Time
"current_date",
"current_time",
"date_bin",
"date_part",
"date_trunc",
"from_unixtime",
"make_date",
"make_time",
"now",
"to_char",
"to_date",
"to_local_time",
"to_time",
"to_timestamp",
"to_timestamp_micros",
"to_timestamp_millis",
"to_timestamp_nanos",
"to_timestamp_seconds",
"to_unixtime",
];
/// Explicit allowlist of canonical DataFusion aggregate function names exposed to S3 Select SQL.
const ALLOWED_AGGREGATE_FUNCTIONS: &[&str] = &["avg", "count", "max", "min", "sum"];
#[derive(Debug)]
pub struct SimpleFunctionMetadataManager {
/// Scalar functions that are registered with the context
@@ -40,28 +140,19 @@ impl Default for SimpleFunctionMetadataManager {
aggregate_functions: Default::default(),
window_functions: Default::default(),
};
SessionStateDefaults::default_scalar_functions().into_iter().for_each(|udf| {
let existing_udf = func_meta_manager.register_udf(udf.clone());
if let Ok(()) = existing_udf {
debug!("Overwrote an existing UDF: {}", udf.name());
for udf in SessionStateDefaults::default_scalar_functions() {
if ALLOWED_SCALAR_FUNCTIONS.contains(&udf.name()) {
let _ = func_meta_manager.register_udf(udf);
}
});
}
SessionStateDefaults::default_aggregate_functions()
.into_iter()
.for_each(|udaf| {
let existing_udaf = func_meta_manager.register_udaf(udaf.clone());
if let Ok(()) = existing_udaf {
debug!("Overwrote an existing UDAF: {}", udaf.name());
}
});
SessionStateDefaults::default_window_functions().into_iter().for_each(|udwf| {
let existing_udwf = func_meta_manager.register_udwf(udwf.clone());
if let Ok(()) = existing_udwf {
debug!("Overwrote an existing UDWF: {}", udwf.name());
for udaf in SessionStateDefaults::default_aggregate_functions() {
if ALLOWED_AGGREGATE_FUNCTIONS.contains(&udaf.name()) {
let _ = func_meta_manager.register_udaf(udaf);
}
});
}
// S3 Select does not support window functions, so no default window UDFs are registered.
func_meta_manager
}
@@ -69,7 +160,11 @@ impl Default for SimpleFunctionMetadataManager {
impl FunctionMetadataManager for SimpleFunctionMetadataManager {
fn register_udf(&mut self, f: Arc<ScalarUDF>) -> QueryResult<()> {
self.scalar_functions.insert(f.inner().name().to_uppercase(), f);
let f = bound_result_size(f);
self.scalar_functions.insert(f.inner().name().to_uppercase(), Arc::clone(&f));
for alias in f.aliases() {
self.scalar_functions.insert(alias.to_uppercase(), Arc::clone(&f));
}
Ok(())
}
@@ -117,3 +212,86 @@ impl FunctionMetadataManager for SimpleFunctionMetadataManager {
self.window_functions.keys().cloned().collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn allowlist_entries_all_resolve_in_default_manager() {
let manager = SimpleFunctionMetadataManager::default();
for name in ALLOWED_SCALAR_FUNCTIONS {
assert!(manager.udf(name).is_ok(), "allowlisted scalar function '{name}' must be registered");
}
for alias in [
"length",
"char_length",
"substring",
"trim",
"pow",
"ifnull",
"position",
"instr",
] {
assert!(manager.udf(alias).is_ok(), "allowlisted alias '{alias}' must be registered");
}
for name in ALLOWED_AGGREGATE_FUNCTIONS {
assert!(manager.udaf(name).is_ok(), "allowlisted aggregate function '{name}' must be registered");
}
assert!(manager.udwfs().is_empty(), "S3 Select must not register default window functions");
}
#[test]
fn disallowed_datafusion_functions_are_not_registered() {
let manager = SimpleFunctionMetadataManager::default();
for disallowed in [
"arrow_cast",
"arrow_try_cast",
"arrow_typeof",
"arrow_field",
"arrow_metadata",
"cast_to_type",
"try_cast_to_type",
"repeat",
"lpad",
"rpad",
"replace",
"levenshtein",
"version",
"uuid",
"input_file_name",
"file_row_index",
"encode",
"decode",
"regexp_like",
"regexp_match",
"regexp_replace",
"regexp_count",
"regexp_instr",
"random",
"rand",
"factorial",
] {
assert!(
manager.udf(disallowed).is_err(),
"non-S3-Select scalar function '{disallowed}' must not be registered"
);
}
for disallowed in [
"array_agg",
"string_agg",
"median",
"percentile_cont",
"first_value",
"last_value",
] {
assert!(
manager.udaf(disallowed).is_err(),
"non-S3-Select aggregate function '{disallowed}' must not be registered"
);
}
for disallowed in ["row_number", "rank", "dense_rank", "lag", "lead"] {
assert!(manager.udwf(disallowed).is_err(), "window function '{disallowed}' must not be registered");
}
}
}
@@ -0,0 +1,478 @@
// 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.
//! Result-size guard for scalar functions whose output can expand beyond a single
//! input column (`concat`, `concat_ws`, `to_char`, and count-sized functions such
//! as `repeat`, `lpad`, and `rpad` if registered).
//!
//! Scalar results are built outside the DataFusion memory pool, so any unbounded
//! allocation can exhaust memory or abort the process via `handle_alloc_error`.
//! This wrapper checks a saturating upper bound on the bytes a call would produce
//! before invoking the inner UDF.
use std::sync::Arc;
use datafusion::arrow::array::{Array, AsArray};
use datafusion::arrow::datatypes::{DataType, FieldRef, Int32Type, Int64Type, UInt32Type, UInt64Type};
use datafusion::common::config::ConfigOptions;
use datafusion::common::tree_node::{Transformed, TransformedResult as _, TreeNode as _};
use datafusion::common::{Result as DFResult, ScalarValue, exec_err};
use datafusion::logical_expr::interval_arithmetic::Interval;
use datafusion::logical_expr::preimage::PreimageResult;
use datafusion::logical_expr::simplify::{ExprSimplifyResult, SimplifyContext};
use datafusion::logical_expr::sort_properties::{ExprProperties, SortProperties};
use datafusion::logical_expr::udf_eq::UdfEq;
use datafusion::logical_expr::{
ColumnarValue, Documentation, Expr, ExpressionPlacement, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl,
Signature, StructFieldMapping,
};
use rustfs_s3select_api::query::session::DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES;
/// Largest result, in bytes, a guarded scalar function may build for a single batch.
pub(crate) const MAX_SCALAR_RESULT_BYTES: usize = DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES / 4;
/// Conservative expansion factor for chrono `strftime` specifiers (for example `%c`, `%B`).
const TO_CHAR_FORMAT_EXPANSION_FACTOR: usize = 20;
const TO_CHAR_PER_ROW_OVERHEAD_BYTES: usize = 64;
const UNKNOWN_SCALAR_ESTIMATE_BYTES: usize = 64;
/// How a guarded function sizes its result from its arguments.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum ResultSize {
/// `repeat(string, count)`: each row builds `len(string) * count` bytes.
Repeat,
/// `lpad(string, length[, fill])` / `rpad`: each row builds `length` characters,
/// which DataFusion allocates at up to four bytes per character.
Pad,
/// `concat(arg1, ..., argN)`: each row concatenates all non-null arguments.
Concat,
/// `concat_ws(sep, arg1, ..., argN)`: each row concatenates `arg1..` with `sep`.
ConcatWs,
/// `to_char(datetime, format)`: expands strftime specifiers in `format`.
ToChar,
}
impl ResultSize {
fn for_function(name: &str) -> Option<Self> {
match name {
"repeat" => Some(Self::Repeat),
"lpad" | "rpad" => Some(Self::Pad),
"concat" => Some(Self::Concat),
"concat_ws" => Some(Self::ConcatWs),
"to_char" => Some(Self::ToChar),
_ => None,
}
}
/// Upper bound of the bytes the function builds for this batch. Arguments the
/// function would reject anyway contribute nothing so the inner function reports
/// the original type/argument error.
fn bytes(self, args: &[ColumnarValue], number_rows: usize) -> usize {
// All-scalar arguments are evaluated once, not once per row.
let rows = if args.iter().all(|arg| matches!(arg, ColumnarValue::Scalar(_))) {
1
} else {
number_rows
};
match (self, args) {
(Self::Repeat, [string, count]) => string_lengths(string, rows)
.zip(counts(count, rows))
.fold(0usize, |total, (len, count)| total.saturating_add(len.saturating_mul(count))),
(Self::Pad, [_, length, ..]) => {
counts(length, rows).fold(0usize, |total, length| total.saturating_add(length.saturating_mul(4)))
}
(Self::Concat, args) => args
.iter()
.fold(0usize, |total, arg| total.saturating_add(columnar_total_bytes(arg, rows))),
(Self::ConcatWs, [separator, rest @ ..]) => {
let values_bytes = rest
.iter()
.fold(0usize, |total, arg| total.saturating_add(columnar_total_bytes(arg, rows)));
let sep_bytes = columnar_total_bytes(separator, rows).saturating_mul(rest.len().saturating_sub(1));
values_bytes.saturating_add(sep_bytes)
}
(Self::ToChar, [_, format]) => columnar_total_bytes(format, rows)
.saturating_mul(TO_CHAR_FORMAT_EXPANSION_FACTOR)
.saturating_add(rows.saturating_mul(TO_CHAR_PER_ROW_OVERHEAD_BYTES)),
_ => 0,
}
}
fn check_literal_simplify_args(self, name: &str, args: &[Expr]) -> DFResult<()> {
let total = match self {
Self::Concat => args
.iter()
.fold(0usize, |acc, expr| acc.saturating_add(literal_expr_bytes(expr))),
Self::ConcatWs => match args {
[separator, rest @ ..] => {
let values_bytes = rest
.iter()
.fold(0usize, |acc, expr| acc.saturating_add(literal_expr_bytes(expr)));
let sep_bytes = literal_expr_bytes(separator).saturating_mul(rest.len().saturating_sub(1));
values_bytes.saturating_add(sep_bytes)
}
[] => 0,
},
Self::Repeat | Self::Pad | Self::ToChar => 0,
};
if total > MAX_SCALAR_RESULT_BYTES {
return exec_err!("string size overflow on {name}, max size is {MAX_SCALAR_RESULT_BYTES}, but got {total}");
}
Ok(())
}
}
fn literal_expr_bytes(expr: &Expr) -> usize {
let Expr::Literal(scalar, _) = expr else {
return 0;
};
scalar_byte_len(scalar)
}
fn scalar_byte_len(scalar: &ScalarValue) -> usize {
match scalar {
ScalarValue::Utf8(Some(s)) | ScalarValue::LargeUtf8(Some(s)) | ScalarValue::Utf8View(Some(s)) => s.len(),
ScalarValue::Binary(Some(b))
| ScalarValue::LargeBinary(Some(b))
| ScalarValue::BinaryView(Some(b))
| ScalarValue::FixedSizeBinary(_, Some(b)) => b.len(),
ScalarValue::Null
| ScalarValue::Utf8(None)
| ScalarValue::LargeUtf8(None)
| ScalarValue::Utf8View(None)
| ScalarValue::Binary(None)
| ScalarValue::LargeBinary(None)
| ScalarValue::BinaryView(None)
| ScalarValue::FixedSizeBinary(_, None) => 0,
_ => UNKNOWN_SCALAR_ESTIMATE_BYTES,
}
}
fn columnar_total_bytes(value: &ColumnarValue, rows: usize) -> usize {
match value {
ColumnarValue::Scalar(scalar) => scalar_byte_len(scalar).saturating_mul(rows),
ColumnarValue::Array(array) => match array.data_type() {
DataType::Utf8 => array
.as_string::<i32>()
.iter()
.fold(0usize, |acc, s| acc.saturating_add(s.map_or(0, str::len))),
DataType::LargeUtf8 => array
.as_string::<i64>()
.iter()
.fold(0usize, |acc, s| acc.saturating_add(s.map_or(0, str::len))),
DataType::Utf8View => array
.as_string_view()
.iter()
.fold(0usize, |acc, s| acc.saturating_add(s.map_or(0, str::len))),
DataType::Binary => array
.as_binary::<i32>()
.iter()
.fold(0usize, |acc, b| acc.saturating_add(b.map_or(0, <[u8]>::len))),
DataType::LargeBinary => array
.as_binary::<i64>()
.iter()
.fold(0usize, |acc, b| acc.saturating_add(b.map_or(0, <[u8]>::len))),
DataType::BinaryView => array
.as_binary_view()
.iter()
.fold(0usize, |acc, b| acc.saturating_add(b.map_or(0, <[u8]>::len))),
DataType::FixedSizeBinary(width) => usize::try_from(*width)
.unwrap_or(0)
.saturating_mul(array.len().saturating_sub(array.null_count())),
DataType::Null => 0,
_ => UNKNOWN_SCALAR_ESTIMATE_BYTES.saturating_mul(array.len().saturating_sub(array.null_count())),
},
}
}
fn string_lengths<'a>(value: &'a ColumnarValue, rows: usize) -> Box<dyn Iterator<Item = usize> + 'a> {
match value {
ColumnarValue::Scalar(scalar) => {
let len = match scalar {
ScalarValue::Utf8(Some(s)) | ScalarValue::LargeUtf8(Some(s)) | ScalarValue::Utf8View(Some(s)) => s.len(),
_ => 0,
};
Box::new(std::iter::repeat_n(len, rows))
}
ColumnarValue::Array(array) => match array.data_type() {
DataType::Utf8 => Box::new(array.as_string::<i32>().iter().map(|s| s.map_or(0, str::len))),
DataType::LargeUtf8 => Box::new(array.as_string::<i64>().iter().map(|s| s.map_or(0, str::len))),
DataType::Utf8View => Box::new(array.as_string_view().iter().map(|s| s.map_or(0, str::len))),
_ => Box::new(std::iter::repeat_n(0, rows)),
},
}
}
fn counts<'a>(value: &'a ColumnarValue, rows: usize) -> Box<dyn Iterator<Item = usize> + 'a> {
let i64_to_count = |count: Option<i64>| count.and_then(|count| usize::try_from(count).ok()).unwrap_or(0);
let i32_to_count = |count: Option<i32>| count.and_then(|count| usize::try_from(count).ok()).unwrap_or(0);
let u64_to_count = |count: Option<u64>| count.map_or(0, |count| usize::try_from(count).unwrap_or(usize::MAX));
let u32_to_count = |count: Option<u32>| count.map_or(0, |count| usize::try_from(count).unwrap_or(usize::MAX));
match value {
ColumnarValue::Scalar(ScalarValue::Int64(count)) => Box::new(std::iter::repeat_n(i64_to_count(*count), rows)),
ColumnarValue::Scalar(ScalarValue::Int32(count)) => Box::new(std::iter::repeat_n(i32_to_count(*count), rows)),
ColumnarValue::Scalar(ScalarValue::UInt64(count)) => Box::new(std::iter::repeat_n(u64_to_count(*count), rows)),
ColumnarValue::Scalar(ScalarValue::UInt32(count)) => Box::new(std::iter::repeat_n(u32_to_count(*count), rows)),
ColumnarValue::Array(array) => match array.data_type() {
DataType::Int64 => Box::new(array.as_primitive::<Int64Type>().iter().map(i64_to_count)),
DataType::Int32 => Box::new(array.as_primitive::<Int32Type>().iter().map(i32_to_count)),
DataType::UInt64 => Box::new(array.as_primitive::<UInt64Type>().iter().map(u64_to_count)),
DataType::UInt32 => Box::new(array.as_primitive::<UInt32Type>().iter().map(u32_to_count)),
_ => Box::new(std::iter::repeat_n(0, rows)),
},
_ => Box::new(std::iter::repeat_n(0, rows)),
}
}
/// Wraps `udf` so that an oversized result fails the call instead of being allocated.
/// Functions whose result is bounded by their input are returned unchanged.
pub(crate) fn bound_result_size(udf: Arc<ScalarUDF>) -> Arc<ScalarUDF> {
if (udf.inner().as_ref() as &dyn std::any::Any).is::<ResultSizeBoundedUdf>() {
return udf;
}
match ResultSize::for_function(udf.name()) {
Some(result_size) => Arc::new(ScalarUDF::new_from_impl(ResultSizeBoundedUdf {
inner: Arc::clone(udf.inner()).into(),
result_size,
})),
None => udf,
}
}
/// A [`ScalarUDF`] whose `invoke_with_args` checks the size of the result the inner
/// function would build; all other behavior delegates to the inner function.
#[derive(Debug, PartialEq, Eq, Hash)]
struct ResultSizeBoundedUdf {
inner: UdfEq<Arc<dyn ScalarUDFImpl>>,
result_size: ResultSize,
}
impl ScalarUDFImpl for ResultSizeBoundedUdf {
fn name(&self) -> &str {
self.inner.name()
}
fn schema_name(&self, args: &[Expr]) -> DFResult<String> {
self.inner.schema_name(args)
}
fn signature(&self) -> &Signature {
self.inner.signature()
}
fn return_type(&self, arg_types: &[DataType]) -> DFResult<DataType> {
self.inner.return_type(arg_types)
}
fn return_field_from_args(&self, args: ReturnFieldArgs) -> DFResult<FieldRef> {
self.inner.return_field_from_args(args)
}
fn is_strict(&self) -> bool {
self.inner.is_strict()
}
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DFResult<ColumnarValue> {
let bytes = self.result_size.bytes(&args.args, args.number_rows);
if bytes > MAX_SCALAR_RESULT_BYTES {
return exec_err!(
"string size overflow on {}, max size is {}, but got {}",
self.name(),
MAX_SCALAR_RESULT_BYTES,
bytes
);
}
self.inner.invoke_with_args(args)
}
fn with_updated_config(&self, config: &ConfigOptions) -> Option<ScalarUDF> {
self.inner.with_updated_config(config).map(|udf| {
ScalarUDF::new_from_impl(Self {
inner: Arc::clone(udf.inner()).into(),
result_size: self.result_size,
})
})
}
fn aliases(&self) -> &[String] {
self.inner.aliases()
}
fn simplify(&self, args: Vec<Expr>, info: &SimplifyContext) -> DFResult<ExprSimplifyResult> {
self.result_size.check_literal_simplify_args(self.name(), &args)?;
let simplified = self.inner.simplify(args, info)?;
match simplified {
ExprSimplifyResult::Original(args) => Ok(ExprSimplifyResult::Original(args)),
ExprSimplifyResult::Simplified(expr) => {
// Re-wrap any scalar UDF synthesized by simplification (for example
// `concat_ws('', ...)` rewriting into `concat(...)`) so the size bound
// cannot be bypassed.
let expr = expr
.transform_up(|node| match node {
Expr::ScalarFunction(mut func) => {
let bounded = bound_result_size(Arc::clone(&func.func));
if Arc::ptr_eq(&bounded, &func.func) {
Ok(Transformed::no(Expr::ScalarFunction(func)))
} else {
func.func = bounded;
Ok(Transformed::yes(Expr::ScalarFunction(func)))
}
}
other => Ok(Transformed::no(other)),
})
.data()?;
Ok(ExprSimplifyResult::Simplified(expr))
}
}
}
fn preimage(&self, args: &[Expr], lit_expr: &Expr, info: &SimplifyContext) -> DFResult<PreimageResult> {
self.inner.preimage(args, lit_expr, info)
}
fn conditional_arguments<'a>(&self, args: &'a [Expr]) -> Option<(Vec<&'a Expr>, Vec<&'a Expr>)> {
self.inner.conditional_arguments(args)
}
fn short_circuits(&self) -> bool {
self.inner.short_circuits()
}
fn evaluate_bounds(&self, input: &[&Interval]) -> DFResult<Interval> {
self.inner.evaluate_bounds(input)
}
fn propagate_constraints(&self, interval: &Interval, inputs: &[&Interval]) -> DFResult<Option<Vec<Interval>>> {
self.inner.propagate_constraints(interval, inputs)
}
fn struct_field_mapping(&self, literal_args: &[Option<ScalarValue>]) -> Option<StructFieldMapping> {
self.inner.struct_field_mapping(literal_args)
}
fn output_ordering(&self, inputs: &[ExprProperties]) -> DFResult<SortProperties> {
self.inner.output_ordering(inputs)
}
fn preserves_lex_ordering(&self, inputs: &[ExprProperties]) -> DFResult<bool> {
self.inner.preserves_lex_ordering(inputs)
}
fn strictly_order_preserving(&self, inputs: &[ExprProperties]) -> DFResult<bool> {
self.inner.strictly_order_preserving(inputs)
}
fn coerce_types(&self, arg_types: &[DataType]) -> DFResult<Vec<DataType>> {
self.inner.coerce_types(arg_types)
}
fn documentation(&self) -> Option<&Documentation> {
self.inner.documentation()
}
fn placement(&self, args: &[ExpressionPlacement]) -> ExpressionPlacement {
self.inner.placement(args)
}
}
#[cfg(test)]
mod tests {
use super::*;
use datafusion::arrow::array::{Int64Array, StringArray};
use datafusion::execution::SessionStateDefaults;
fn scalar_args(string: ScalarValue, count: i64) -> Vec<ColumnarValue> {
vec![
ColumnarValue::Scalar(string),
ColumnarValue::Scalar(ScalarValue::Int64(Some(count))),
]
}
#[test]
fn repeat_bound_is_len_times_count_regardless_of_offset_width() {
for string in [
ScalarValue::Utf8(Some("ab".into())),
ScalarValue::LargeUtf8(Some("ab".into())),
ScalarValue::Utf8View(Some("ab".into())),
] {
assert_eq!(ResultSize::Repeat.bytes(&scalar_args(string.clone(), 3), 8192), 6);
assert_eq!(ResultSize::Repeat.bytes(&scalar_args(string, 1 << 62), 1), 1 << 63);
}
assert_eq!(
ResultSize::Repeat.bytes(&scalar_args(ScalarValue::Utf8(Some("abc".into())), i64::MAX), 1),
usize::MAX,
"oversized counts saturate instead of wrapping"
);
assert_eq!(ResultSize::Repeat.bytes(&scalar_args(ScalarValue::Utf8(None), 1 << 62), 1), 0);
assert_eq!(ResultSize::Repeat.bytes(&scalar_args(ScalarValue::Utf8(Some("a".into())), -1), 1), 0);
}
#[test]
fn repeat_bound_sums_over_rows() {
let strings: ColumnarValue = ColumnarValue::Array(Arc::new(StringArray::from(vec![Some("abc"), None, Some("d")])));
let counts = ColumnarValue::Array(Arc::new(Int64Array::from(vec![Some(2), Some(1 << 40), Some(5)])));
assert_eq!(ResultSize::Repeat.bytes(&[strings.clone(), counts], 3), 11);
let scalar_count = ColumnarValue::Scalar(ScalarValue::Int64(Some(10)));
assert_eq!(ResultSize::Repeat.bytes(&[strings, scalar_count], 3), 40);
}
#[test]
fn pad_bound_is_four_bytes_per_requested_character_per_row() {
let string = ColumnarValue::Scalar(ScalarValue::Utf8(Some("a".into())));
let length = ColumnarValue::Scalar(ScalarValue::Int64(Some(10)));
let fill = ColumnarValue::Scalar(ScalarValue::Utf8(Some("*".into())));
assert_eq!(ResultSize::Pad.bytes(&[string.clone(), length.clone()], 8192), 40);
assert_eq!(ResultSize::Pad.bytes(&[string, length, fill], 8192), 40);
let strings = ColumnarValue::Array(Arc::new(StringArray::from(vec![Some("a"), Some("b")])));
let length = ColumnarValue::Scalar(ScalarValue::Int64(Some(i64::from(i32::MAX))));
assert!(ResultSize::Pad.bytes(&[strings, length], 2) > MAX_SCALAR_RESULT_BYTES);
}
#[test]
fn concat_and_to_char_bounds_accumulate_across_rows() {
let chunk = "x".repeat(1024 * 1024);
let col_val = ColumnarValue::Array(Arc::new(StringArray::from(vec![Some(chunk.as_str()); 4])));
let args = vec![col_val; 5];
assert_eq!(ResultSize::Concat.bytes(&args, 4), 20 * 1024 * 1024);
assert!(ResultSize::Concat.bytes(&args, 4) > MAX_SCALAR_RESULT_BYTES);
let sep = ColumnarValue::Scalar(ScalarValue::Utf8(Some(chunk)));
let short = ColumnarValue::Array(Arc::new(StringArray::from(vec![Some("a"); 4])));
let ws_args = vec![sep, short.clone(), short.clone(), short.clone(), short.clone(), short];
assert!(ResultSize::ConcatWs.bytes(&ws_args, 4) >= 16 * 1024 * 1024);
let fmt = ColumnarValue::Scalar(ScalarValue::Utf8(Some("%B".repeat(50_000))));
let dt = ColumnarValue::Array(Arc::new(Int64Array::from(vec![Some(0); 10])));
assert!(ResultSize::ToChar.bytes(&[dt, fmt], 10) > MAX_SCALAR_RESULT_BYTES);
}
#[test]
fn expected_expanding_functions_are_wrapped_and_idempotent() {
let mut wrapped = Vec::new();
for udf in SessionStateDefaults::default_scalar_functions() {
let name = udf.name().to_string();
let bounded = bound_result_size(Arc::clone(&udf));
if !Arc::ptr_eq(&udf, &bounded) {
assert_eq!(bounded.name(), name);
assert_eq!(bounded.aliases(), udf.aliases());
assert_eq!(bounded.signature(), udf.signature());
let double_bounded = bound_result_size(Arc::clone(&bounded));
assert!(Arc::ptr_eq(&bounded, &double_bounded), "wrapping must be idempotent");
wrapped.push(name);
}
}
wrapped.sort();
assert_eq!(wrapped, ["concat", "concat_ws", "lpad", "repeat", "rpad", "to_char"]);
}
}
+1 -4
View File
@@ -90,10 +90,7 @@ impl ContextProvider for MetadataProvider {
}
fn get_function_meta(&self, name: &str) -> Option<Arc<ScalarUDF>> {
self.func_manager
.udf(name)
.ok()
.or_else(|| self.session.inner().scalar_functions().get(name).cloned())
self.func_manager.udf(name).ok()
}
fn get_aggregate_meta(&self, name: &str) -> Option<Arc<AggregateUDF>> {
+1 -1
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
pub use rustfs_s3select_api::query::parser::RustFsDialect;
pub use rustfs_s3select_api::query::parser::{BoundedRustFsDialect, RustFsDialect};
#[cfg(test)]
use datafusion::sql::sqlparser::dialect::Dialect;
+66 -4
View File
@@ -22,10 +22,13 @@ use datafusion::sql::sqlparser::{
};
use rustfs_s3select_api::{
QueryError,
query::{ast::ExtStatement, parser::Parser as RustFsParser},
query::{
ast::ExtStatement,
parser::{Parser as RustFsParser, validate_set_operator_budget},
},
};
use super::dialect::RustFsDialect;
use super::dialect::BoundedRustFsDialect;
pub(crate) const MAX_SQL_EXPRESSION_BYTES: usize = 256 * 1024;
@@ -61,6 +64,7 @@ impl<'a> ExtParser<'a> {
return parser_err!("S3 Select expression exceeds 256 KiB");
}
let mut tokens = tokenizer.tokenize()?;
validate_set_operator_budget(&tokens)?;
validate_projection_width(&tokens)?;
rewrite_source_object_wildcards(&mut tokens);
Ok(ExtParser {
@@ -70,7 +74,7 @@ impl<'a> ExtParser<'a> {
/// Parse a SQL statement and produce a set of statements
pub fn parse_sql(sql: &str) -> Result<VecDeque<ExtStatement>> {
let dialect = &RustFsDialect {};
let dialect = &BoundedRustFsDialect::default();
ExtParser::parse_sql_with_dialect(sql, dialect)
}
@@ -186,7 +190,11 @@ fn ends_from_source(keyword: Keyword) -> bool {
#[cfg(test)]
mod tests {
use super::*;
use rustfs_s3select_api::query::ast::ExtStatement;
use crate::sql::dialect::RustFsDialect;
use rustfs_s3select_api::query::{
ast::ExtStatement,
parser::{MAX_SELECT_OPERATORS, MAX_SELECT_SET_OPERATORS},
};
#[test]
fn test_default_parser_creation() {
@@ -336,6 +344,60 @@ mod tests {
assert_eq!(statements.len(), 1, "Should have exactly one statement");
}
#[test]
fn test_ext_parser_parse_sql_bounds_operator_and_set_chains() {
let plus_chain = |terms: usize| format!("SELECT {} FROM S3Object", vec!["1"; terms].join("+"));
assert!(
ExtParser::parse_sql(&plus_chain(MAX_SELECT_OPERATORS + 1)).is_ok(),
"chain with exactly MAX_SELECT_OPERATORS operators must succeed"
);
assert_eq!(
ExtParser::parse_sql(&plus_chain(MAX_SELECT_OPERATORS + 2)),
Err(ParserError::RecursionLimitExceeded)
);
let or_chain = |terms: usize| format!("SELECT * FROM S3Object s WHERE {}", vec!["s.id='1'"; terms].join(" OR "));
assert_eq!(
ExtParser::parse_sql(&or_chain(MAX_SELECT_OPERATORS + 1)),
Err(ParserError::RecursionLimitExceeded)
);
let is_null_chain = |ops: usize| format!("SELECT 1{} FROM S3Object", " IS NULL".repeat(ops));
assert!(ExtParser::parse_sql(&is_null_chain(MAX_SELECT_OPERATORS)).is_ok());
assert_eq!(
ExtParser::parse_sql(&is_null_chain(MAX_SELECT_OPERATORS + 1)),
Err(ParserError::RecursionLimitExceeded)
);
let union_chain = |unions: usize| vec!["SELECT 1"; unions + 1].join(" UNION ");
assert!(ExtParser::parse_sql(&union_chain(MAX_SELECT_SET_OPERATORS)).is_ok());
assert_eq!(
ExtParser::parse_sql(&union_chain(MAX_SELECT_SET_OPERATORS + 1)),
Err(ParserError::RecursionLimitExceeded)
);
// Long chains close to the 256 KiB expression limit, including trailing syntax
// errors that trigger `Drop` on a partially built AST, must fail cleanly without
// overflowing a release-profile 1 MiB worker stack.
for sql in [
plus_chain(120 * 1024),
format!("SELECT {}+) FROM S3Object", vec!["1"; 120 * 1024].join("+")),
or_chain(4096),
is_null_chain(4096),
union_chain(10_000),
] {
assert!(sql.len() <= MAX_SQL_EXPRESSION_BYTES, "test SQL must exercise parser, not byte cap");
let result = std::thread::Builder::new()
.stack_size(1024 * 1024)
.spawn(move || ExtParser::parse_sql(&sql).map(|_| ()))
.expect("spawn 1 MiB stack worker")
.join()
.expect("parser thread must not overflow stack");
assert_eq!(result, Err(ParserError::RecursionLimitExceeded));
}
}
#[test]
fn test_ext_parser_parse_sql_with_dialect() {
let sql = "SELECT * FROM S3Object";
@@ -15,12 +15,16 @@
use std::sync::Arc;
use async_trait::async_trait;
use datafusion::common::config::ConfigOptions;
use datafusion::common::tree_node::{Transformed, TransformedResult as _, TreeNode as _};
use datafusion::error::Result as DFResult;
use datafusion::execution::SessionStateBuilder;
use datafusion::logical_expr::LogicalPlan;
use datafusion::physical_optimizer::PhysicalOptimizerRule;
use datafusion::physical_optimizer::aggregate_statistics::AggregateStatistics;
use datafusion::physical_optimizer::join_selection::JoinSelection;
use datafusion::physical_plan::ExecutionPlan;
use datafusion::physical_plan::filter::FilterExec;
use datafusion::physical_planner::{
DefaultPhysicalPlanner as DFDefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner as DFPhysicalPlanner,
};
@@ -55,6 +59,7 @@ impl Default for DefaultPhysicalPlanner {
// repartitioning and local sorting steps to meet distribution and ordering requirements.
// Therefore, it should run before EnforceDistribution and EnforceSorting.
Arc::new(JoinSelection::new()),
Arc::new(StreamFilterOutput),
];
Self {
@@ -91,6 +96,35 @@ impl PhysicalPlanner for DefaultPhysicalPlanner {
}
}
/// Prevents `FilterExec` from coalescing filtered rows across input batches.
///
/// DataFusion's `FilterExec` buffers surviving rows until it reaches `batch_size`
/// outside the query memory pool. S3 Select scans emit already byte-bounded batches,
/// so setting `batch_size = 1` streams every non-empty filtered batch immediately.
#[derive(Debug)]
struct StreamFilterOutput;
impl PhysicalOptimizerRule for StreamFilterOutput {
fn optimize(&self, plan: Arc<dyn ExecutionPlan>, _config: &ConfigOptions) -> DFResult<Arc<dyn ExecutionPlan>> {
plan.transform_up(|node| {
let Some(filter) = node.downcast_ref::<FilterExec>() else {
return Ok(Transformed::no(node));
};
let filter: Arc<dyn ExecutionPlan> = Arc::new(filter.with_batch_size(1)?);
Ok(Transformed::yes(filter))
})
.data()
}
fn name(&self) -> &str {
"StreamFilterOutput"
}
fn schema_check(&self) -> bool {
true
}
}
impl PhysicalOptimizer for DefaultPhysicalPlanner {
fn optimize(&self, plan: Arc<dyn ExecutionPlan>, _session: &SessionCtx) -> QueryResult<Arc<dyn ExecutionPlan>> {
Ok(plan)
@@ -100,3 +134,41 @@ impl PhysicalOptimizer for DefaultPhysicalPlanner {
self.ext_physical_optimizer_rules.push(optimizer_rule);
}
}
#[cfg(test)]
mod tests {
use super::*;
use datafusion::arrow::array::{Int64Array, RecordBatch};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::datasource::memory::MemorySourceConfig;
use datafusion::execution::TaskContext;
use datafusion::logical_expr::Operator;
use datafusion::physical_expr::expressions::{binary, col, lit};
use datafusion::physical_plan::collect;
#[tokio::test]
async fn filter_output_is_not_coalesced_across_input_batches() {
let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)]));
let batches = [vec![1, 2, 3], vec![4, 5], vec![6], vec![7, 8, 9]]
.into_iter()
.map(|ids| RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(Int64Array::from(ids))]).expect("batch"))
.collect::<Vec<_>>();
let input = MemorySourceConfig::try_new_exec(&[batches], Arc::clone(&schema), None).expect("input");
let predicate = binary(col("id", &schema).expect("column"), Operator::NotEq, lit(6_i64), &schema).expect("predicate");
let filter: Arc<dyn ExecutionPlan> = Arc::new(FilterExec::try_new(predicate, input).expect("filter"));
let rows = |batches: Vec<RecordBatch>| batches.iter().map(RecordBatch::num_rows).collect::<Vec<_>>();
let coalesced = collect(Arc::clone(&filter), Arc::new(TaskContext::default()))
.await
.expect("stock filter");
assert_eq!(rows(coalesced), [8]);
let filter = StreamFilterOutput
.optimize(filter, &ConfigOptions::default())
.expect("optimized filter");
let streamed = collect(filter, Arc::new(TaskContext::default()))
.await
.expect("streaming filter");
assert_eq!(rows(streamed), [3, 2, 3]);
}
}
+45
View File
@@ -171,6 +171,11 @@ pub(crate) fn prepare_s3_select_statement(statement: &mut Statement) -> QueryRes
return Err(unsupported_structure("subqueries are not supported"));
}
let mut field_depth = FieldAccessDepthValidator;
if Visit::visit(&*query, &mut field_depth).is_break() {
return Err(unsupported_structure("nested field access depth exceeds limit"));
}
let source = {
let SetExpr::Select(select) = query.body.as_mut() else {
return Err(unsupported_structure("set operations and nested queries are not supported"));
@@ -598,6 +603,27 @@ impl Visitor for SubqueryDetector {
}
}
struct FieldAccessDepthValidator;
impl Visitor for FieldAccessDepthValidator {
type Break = ();
fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<Self::Break> {
let max_depth = rustfs_s3select_api::query::parser::MAX_SELECT_FIELD_ACCESS_DEPTH;
let exceeds = match expr {
Expr::CompoundIdentifier(parts) => parts.len() > max_depth,
Expr::CompoundFieldAccess { access_chain, .. } => access_chain.len() > max_depth,
Expr::JsonAccess { path, .. } => path.path.len() > max_depth,
_ => false,
};
if exceeds {
ControlFlow::Break(())
} else {
ControlFlow::Continue(())
}
}
}
#[cfg(test)]
mod tests {
use super::{path_projection_keys, prepare_s3_select_statement};
@@ -978,4 +1004,23 @@ mod tests {
);
}
}
#[test]
fn rejects_excessive_compound_field_access_depth() {
let max_depth = rustfs_s3select_api::query::parser::MAX_SELECT_FIELD_ACCESS_DEPTH;
let allowed_path = format!("s.items{}", "[0]".repeat(max_depth));
let allowed_statement = parse_statement(&format!("SELECT {allowed_path} FROM S3Object AS s"));
assert!(validate_s3_select_statement(&allowed_statement).is_ok());
let deep_path = format!("s.items{}", "[0]".repeat(max_depth + 1));
let deep_statement = parse_statement(&format!("SELECT {deep_path} FROM S3Object AS s"));
assert!(matches!(
validate_s3_select_statement(&deep_statement),
Err(ref err) if matches!(err.s3_select_policy_error(), Some(SelectError::UnsupportedSqlStructure { .. }))
));
// Dot chains are also bounded at parse time by sqlparser's recursion limit.
let deep_dots = vec!["a"; max_depth + 1].join(".");
assert!(ExtParser::parse_sql(&format!("SELECT {deep_dots} FROM S3Object")).is_err());
}
}
@@ -15,6 +15,7 @@
#[cfg(test)]
mod error_handling_tests {
use crate::get_global_db;
use datafusion::object_store::ObjectStoreExt as _;
use rustfs_s3select_api::request::{
CsvInput, ExpressionType, FileHeaderInfo, InputSerialization, SelectObjectContentInput, SelectObjectContentRequest,
};
@@ -174,6 +175,147 @@ mod error_handling_tests {
}
}
#[tokio::test]
async fn test_non_allowlisted_datafusion_functions_are_rejected() {
for sql in [
"SELECT length(repeat(arrow_cast('a', 'LargeUtf8'), 4611686018427387904)) FROM S3Object",
"SELECT length(repeat(arrow_cast(name, 'LargeUtf8'), 1000000000000000)) FROM S3Object",
"SELECT length(repeat('a', 1000000000)) FROM S3Object",
"SELECT length(lpad('a', 500000000)) FROM S3Object",
"SELECT length(rpad('a', 500000000)) FROM S3Object",
"SELECT levenshtein('abc', 'def') FROM S3Object",
"SELECT arrow_cast(name, 'LargeUtf8') FROM S3Object",
"SELECT version() FROM S3Object",
"SELECT uuid() FROM S3Object",
"SELECT replace(name, 'a', 'bb') FROM S3Object",
"SELECT regexp_replace(name, 'a', 'b') FROM S3Object",
"SELECT encode(name, 'hex') FROM S3Object",
"SELECT array_agg(name) FROM S3Object",
"SELECT string_agg(name, ',') FROM S3Object",
"SELECT row_number() OVER () FROM S3Object",
] {
let input = create_test_input_with_sql(sql);
let db = get_global_db(input.clone(), true)
.await
.expect("test database should initialize");
let query = Query::new(Context { input: Arc::new(input) }, sql.to_string());
let error = match db.execute(&query).await {
Err(error) => error,
Ok(_) => panic!("disallowed function must be rejected during planning: {sql}"),
};
assert_eq!(
error.select_error(),
SelectError::InvalidQuery,
"disallowed function must fail with InvalidQuery for {sql}: {error:?}"
);
}
}
#[tokio::test]
async fn test_standard_s3_select_functions_continue_working() {
for sql in [
"SELECT LOWER(name), UPPER(name), LENGTH(name) AS len1, CHAR_LENGTH(name) AS len2, CHARACTER_LENGTH(name) AS len3 FROM S3Object LIMIT 2",
"SELECT LEFT(name, 2), RIGHT(name, 2), TRIM(name) AS trimmed, BTRIM(name), LTRIM(name), RTRIM(name), STRPOS(name, 'a'), STARTS_WITH(name, 'A'), ENDS_WITH(name, 'e'), CONTAINS(name, 'l') FROM S3Object LIMIT 2",
"SELECT COALESCE(name, 'n/a'), NULLIF(name, 'Alice'), CONCAT(name, '-', department), CONCAT_WS(':', name, department) FROM S3Object LIMIT 2",
"SELECT ABS(-5), ROUND(3.14159, 2), SQRT(16), CEIL(1.2), FLOOR(1.8), POWER(2, 3) AS p1, POW(2, 4) AS p2 FROM S3Object LIMIT 1",
"SELECT DATE_PART('year', TO_TIMESTAMP('2025-01-02T03:04:05Z')), CURRENT_DATE(), NOW() FROM S3Object LIMIT 1",
"SELECT COUNT(*), SUM(CAST(age AS INT)), AVG(CAST(age AS INT)), MIN(CAST(age AS INT)), MAX(CAST(age AS INT)) FROM S3Object",
] {
let input = create_test_input_with_sql(sql);
let db = get_global_db(input.clone(), true)
.await
.expect("test database should initialize");
let query = Query::new(Context { input: Arc::new(input) }, sql.to_string());
let handle = db
.execute(&query)
.await
.unwrap_or_else(|error| panic!("standard S3 Select query must plan ({sql}): {error:?}"));
let batches = handle
.result()
.chunk_result()
.await
.unwrap_or_else(|error| panic!("standard S3 Select query must execute ({sql}): {error:?}"));
assert!(
batches.iter().map(|batch| batch.num_rows()).sum::<usize>() > 0,
"standard S3 Select query must return rows: {sql}"
);
}
}
#[tokio::test]
async fn test_retained_expanding_functions_respect_result_size_bound() {
// Test with a large format literal in `to_char` over the 10-row fixture (column-dependent
// timestamp prevents scalar-only folding): 10 rows * (100_000 * 20 + 64) > 16 MiB.
let huge_format = "%B".repeat(50_000);
let sql = format!("SELECT TO_CHAR(TO_TIMESTAMP(CAST(age AS BIGINT)), '{huge_format}') FROM S3Object");
let input = create_test_input_with_sql(&sql);
let db = get_global_db(input.clone(), true)
.await
.expect("test database should initialize");
let query = Query::new(Context { input: Arc::new(input) }, sql);
let error = match db.execute(&query).await {
Err(error) => error,
Ok(handle) => match handle.result().chunk_result().await {
Err(error) => error,
Ok(_) => panic!("oversized to_char result must fail"),
},
};
assert_eq!(error.select_error(), SelectError::InternalError, "unexpected error: {error:?}");
// Verify `concat_ws('', ...)` simplification re-wraps `concat` and enforces the bound:
// a single 200 KiB CSV column repeated 100 times (~20 MiB > 16 MiB) fails cleanly
// even though `concat_ws('', ...)` simplifies to `concat(...)` and SQL is < 1 KiB.
let repeated_cols = std::iter::repeat_n("payload", 100).collect::<Vec<_>>().join(", ");
let concat_sql = format!("SELECT LENGTH(CONCAT_WS('', {repeated_cols})) FROM S3Object");
let mut concat_input = create_test_input_with_sql(&concat_sql);
concat_input.key = "concat_bound.csv".to_string();
let db = get_global_db(concat_input.clone(), true)
.await
.expect("test database should initialize");
let query = Query::new(
Context {
input: Arc::new(concat_input.clone()),
},
concat_sql,
);
let state_machine = db.build_query_state_machine(query).await.expect("build query state machine");
let store_url = datafusion::execution::object_store::ObjectStoreUrl::parse(format!("s3://{}", concat_input.bucket))
.expect("valid test store url");
let store = state_machine
.session
.inner()
.runtime_env()
.object_store(&store_url)
.expect("test object store");
let csv_payload = format!("payload\n{}\n", "x".repeat(200 * 1024));
store
.put(
&datafusion::object_store::path::Path::from(concat_input.key.as_str()),
csv_payload.into_bytes().into(),
)
.await
.expect("put oversized concat fixture");
let plan = db
.build_logical_plan(Arc::clone(&state_machine))
.await
.expect("plan concat_ws query")
.expect("logical plan");
let output = db
.execute_logical_plan(plan, state_machine)
.await
.expect("start concat_ws execution");
let error = output
.result()
.chunk_result()
.await
.expect_err("oversized concat_ws result must fail instead of allocating");
assert_eq!(error.select_error(), SelectError::InternalError, "unexpected error: {error:?}");
}
#[tokio::test]
async fn test_invalid_column_references() {
let invalid_column_sqls = vec![
+205 -17
View File
@@ -172,33 +172,116 @@ pub fn has_string_suffix_in_slice(str: &str, list: &[impl AsRef<str>]) -> bool {
false
}
fn deep_match_rune(str_: &[u8], pattern: &[u8], simple: bool) -> bool {
let (mut str_, mut pattern) = (str_, pattern);
while !pattern.is_empty() {
match pattern[0] as char {
'*' => {
return if pattern.len() == 1 {
true
} else {
deep_match_rune(str_, &pattern[1..], simple)
|| (!str_.is_empty() && deep_match_rune(&str_[1..], pattern, simple))
};
}
'?' => {
fn deep_match_rune(mut str_: &[u8], mut pattern: &[u8], simple: bool) -> bool {
// Fast path: match literal and `?` prefix without heap allocation.
while let Some(&p) = pattern.first() {
match p {
b'*' => break,
b'?' => {
if str_.is_empty() {
return simple;
}
str_ = &str_[1..];
pattern = &pattern[1..];
}
_ => {
if str_.is_empty() || str_[0] != pattern[0] {
if str_.first() != Some(&p) {
return false;
}
str_ = &str_[1..];
pattern = &pattern[1..];
}
}
}
if pattern.is_empty() {
return str_.is_empty();
}
// Collapse consecutive leading `*` tokens; a trailing run matches everything.
while pattern.first() == Some(&b'*') {
pattern = &pattern[1..];
}
if pattern.is_empty() {
return true;
}
// Allocation-free fast paths when no further `*` remains in the pattern.
if !pattern.contains(&b'*') {
if !pattern.contains(&b'?') {
return str_.ends_with(pattern);
}
if !simple {
return str_.len() >= pattern.len()
&& pattern
.iter()
.zip(&str_[str_.len() - pattern.len()..])
.all(|(&p, &c)| p == b'?' || p == c);
}
}
star_match_rune(str_, pattern, simple)
}
/// Iteratively matches the remainder of a pattern immediately following a `*`.
///
/// Maintains reachable positions in `str_` (`O(str_.len())` space independent of
/// `pattern.len()`) and collapses consecutive `*` tokens in `O(1)` each, avoiding
/// both exponential backtracking and recursion stack growth.
fn star_match_rune(str_: &[u8], pattern: &[u8], simple: bool) -> bool {
let n = str_.len();
// dp[j]: the pattern prefix processed so far (starting from the leading `*`)
// matches `str_[..j]`.
let mut dp = vec![true; n + 1];
let mut prev_was_star = true;
for &p in pattern {
match p {
b'*' => {
if prev_was_star {
continue;
}
prev_was_star = true;
let Some(first) = dp.iter().position(|&matched| matched) else {
return false;
};
dp[first..].fill(true);
}
b'?' => {
prev_was_star = false;
// In simple mode, reaching `?` when `str_` is exhausted accepts
// whatever follows in `pattern`.
if simple && dp[n] {
return true;
}
let mut any = false;
for j in (1..=n).rev() {
let matched = dp[j - 1];
dp[j] = matched;
any |= matched;
}
dp[0] = false;
if !any {
return false;
}
}
literal => {
prev_was_star = false;
let mut any = false;
for j in (1..=n).rev() {
let matched = dp[j - 1] && str_[j - 1] == literal;
dp[j] = matched;
any |= matched;
}
dp[0] = false;
if !any {
return false;
}
}
}
str_ = &str_[1..];
pattern = &pattern[1..];
}
str_.is_empty() && pattern.is_empty()
dp[n]
}
/// Matches a pattern as a prefix against the given text.
@@ -559,6 +642,111 @@ pub fn strings_has_prefix_fold(s: &str, prefix: &str) -> bool {
mod tests {
use super::*;
#[test]
fn test_match_many_wildcards_without_backtracking() {
let name = "a".repeat(1000);
let pattern = "*a".repeat(100);
assert!(match_pattern(&pattern, &name));
assert!(match_simple(&pattern, &name));
assert!(!match_pattern(&format!("{pattern}*b"), &name));
assert!(!match_simple(&format!("{pattern}*b"), &name));
let repeated = format!("{}*b", "a*".repeat(80));
assert!(!match_pattern(&repeated, &name));
assert!(!match_simple(&repeated, &name));
}
#[test]
fn test_match_deep_star_runs_do_not_overflow_stack() {
let stars = "*".repeat(200_000);
assert!(match_pattern(&stars, "tenant-bkt/report.txt"));
assert!(match_simple(&stars, "tenant-bkt/report.txt"));
let stars_suffix = format!("{stars}x");
let long_name = "a".repeat(1024);
assert!(!match_pattern(&stars_suffix, &long_name));
assert!(!match_simple(&stars_suffix, &long_name));
assert!(match_pattern(&stars_suffix, &format!("{long_name}x")));
let middle_stars = format!("a{}b{}c", "*".repeat(50_000), "*".repeat(50_000));
assert!(match_pattern(&middle_stars, &format!("a{}b{}c", "x".repeat(200), "y".repeat(200))));
assert!(!match_pattern(&middle_stars, &format!("a{}c", "x".repeat(200))));
}
#[test]
fn test_match_utf8_multibyte() {
assert!(match_pattern("桶/目录/*文档*", "桶/目录/2026年文档.txt"));
assert!(!match_pattern("桶/目录/*文档*", "桶/目录/2026年表格.txt"));
assert!(match_simple("café*naïve", "café-et-naïve"));
assert!(!match_simple("café*naïve", "café-et-naive"));
assert!(match_simple("*🎉*🚀", "prefix🎉mid🚀"));
assert!(!match_simple("*🎉*🚀", "prefix🎉mid"));
}
#[test]
fn test_match_wildcards() {
let test_cases = [
("my-bucket/In*/Ka*/Ban", "my-bucket/India/Karnataka/Ban/Ban/Ban", true, true),
("my-bucket/In*/Ka*/Ban", "my-bucket/India/Karnataka/Bangalore", false, false),
("my-bucket/mnop*?and?", "my-bucket/mnopqanda", true, true),
("*", "", true, true),
("**", "", true, true),
("*a", "", false, false),
// Simple matching accepts a `?` reached at the end of the name, whatever follows it.
("a?", "a", false, true),
("?nobody", "", false, true),
("*?a*b", "xa", false, true),
("my-bucket/mnop*?and", "my-bucket/mnopand", false, true),
("*a?c", "aa", false, true),
("*a?*c", "aa", false, true),
];
for (pattern, name, expected, expected_simple) in test_cases {
assert_eq!(match_pattern(pattern, name), expected, "match_pattern({pattern:?}, {name:?})");
assert_eq!(match_simple(pattern, name), expected_simple, "match_simple({pattern:?}, {name:?})");
}
}
fn backtracking_match_rune(str_: &[u8], pattern: &[u8], simple: bool) -> bool {
match pattern.split_first() {
None => str_.is_empty(),
Some((b'*', rest)) => {
backtracking_match_rune(str_, rest, simple)
|| (!str_.is_empty() && backtracking_match_rune(&str_[1..], pattern, simple))
}
Some((b'?', _)) if str_.is_empty() => simple,
Some((&p, rest)) => {
!str_.is_empty() && (p == b'?' || p == str_[0]) && backtracking_match_rune(&str_[1..], rest, simple)
}
}
}
fn small_strings(alphabet: &str, max_len: usize) -> Vec<String> {
let mut all = vec![String::new()];
let mut longest = all.clone();
for _ in 0..max_len {
longest = longest
.iter()
.flat_map(|s| alphabet.chars().map(move |c| format!("{s}{c}")))
.collect();
all.extend_from_slice(&longest);
}
all
}
#[test]
fn test_match_agrees_with_backtracking_definition() {
let names = small_strings("ab", 5);
for pattern in small_strings("ab*?", 5) {
for name in &names {
let expected = |simple| backtracking_match_rune(name.as_bytes(), pattern.as_bytes(), simple);
assert_eq!(match_pattern(&pattern, name), expected(false), "match_pattern({pattern:?}, {name:?})");
assert_eq!(match_simple(&pattern, name), expected(true), "match_simple({pattern:?}, {name:?})");
}
}
}
#[test]
fn test_has_ellipses() {
// Tests for all args without ellipses.
+1 -1
View File
@@ -16,4 +16,4 @@ The gateway release serves S3 with rustfs/gateway. Remove `RUSTFS_S3_STACK` from
| `PutBucketPolicy` (`#2684`, `8f81762a6`) | For a malformed JSON policy body, both versions return HTTP 400. The gateway returns the XML error code `MalformedPolicy` (matching AWS S3). RustFS `1.0.5` returns `InvalidArgument`. Clients that classify bucket-policy validation errors by code need to handle both during a rollout. |
| `CreateBucket` (`#2684`, `8676d2f3b`) | For a successful default-region `CreateBucket` (`200 OK`), the gateway returns HTTP `Location: /<bucket>` (matching AWS S3 and `c-bkt-0001`). RustFS `1.0.5` omits the `Location` header. Clients that inspect `Location` on bucket creation need to handle its presence on gateway nodes and absence on `1.0.5` nodes during a rollout. |
`c-sig-0598` is recorded in the [pinned gateway conformance rulings](https://github.com/rustfs/gateway/blob/b4ea5ca3638dfbb0e3f34a6db99db534433dfe1b/conformance/rulings/rustfs-profile.toml); host-assembled conformance rulings are tracked in [`.config/conformance-rulings.toml`](../../.config/conformance-rulings.toml), and the signed `PutBucketPolicy` and `CreateBucket` `accepted-change` rulings are recorded in `rustfs/backlog#2684`.
`c-sig-0598` is recorded in the [pinned gateway conformance rulings](https://github.com/rustfs/gateway/blob/095d4763a3f58a5e1d22fe7a231bf1c105473de8/conformance/rulings/rustfs-profile.toml); host-assembled conformance rulings are tracked in [`.config/conformance-rulings.toml`](../../.config/conformance-rulings.toml), and the signed `PutBucketPolicy` and `CreateBucket` `accepted-change` rulings are recorded in `rustfs/backlog#2684`.
@@ -338,109 +338,4 @@ mod tests {
.expect_err("no store");
assert_eq!(err.code(), &S3ErrorCode::InternalError);
}
#[test]
#[serial_test::serial]
fn list_object_versions_rejects_invalid_version_id_marker_with_bad_request_and_handles_control_delimiter() {
use crate::app::gating_test_env::{run_large_stack_test, shared_gating_ambient, shared_gating_ecstore};
use crate::app::metadata_listing::{MetadataListQuery, VersionsQuery};
use rustfs_gateway::{Limits, MetaView, OperationCodec, ResponseBody, TargetKind, WireRequest};
run_large_stack_test("list-versions-invalid-marker", || async {
let usecase = DefaultBucketUsecase::with_context(Some(shared_gating_ambient().await));
let store = shared_gating_ecstore().await;
let bucket = BucketName::new(format!("list-versions-marker-{}", uuid::Uuid::new_v4().simple())).unwrap();
store
.make_bucket(bucket.as_str(), &MakeBucketOptions::default())
.await
.unwrap();
let err = usecase
.execute_list_object_versions(
owned_envelope(http::Method::GET),
gateway_dto::ListObjectVersionsInput {
bucket: bucket.clone(),
key_marker: Some("k".to_owned()),
version_id_marker: Some(OpaqueString::from("v")),
delimiter: Some("\x0f".to_owned()),
max_keys: Some(8),
..Default::default()
},
)
.await
.expect_err("invalid version-id-marker must be rejected");
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument);
assert_eq!(err.status_code(), Some(StatusCode::BAD_REQUEST));
let metadata_err = usecase
.list_object_versions_metadata(
&owned_envelope(http::Method::GET),
VersionsQuery {
listing: MetadataListQuery {
bucket: bucket.as_str().to_owned(),
delimiter: Some("\x0f".to_owned()),
max_keys: Some(8),
..Default::default()
},
key_marker: Some("k".to_owned()),
version_id_marker: Some("v".to_owned()),
},
)
.await
.expect_err("metadata listing must reject invalid version-id-marker");
assert_eq!(metadata_err.code(), &S3ErrorCode::InvalidArgument);
assert_eq!(metadata_err.status_code(), Some(StatusCode::BAD_REQUEST));
let output = usecase
.execute_list_object_versions(
owned_envelope(http::Method::GET),
gateway_dto::ListObjectVersionsInput {
bucket: bucket.clone(),
key_marker: Some("k".to_owned()),
version_id_marker: Some(OpaqueString::from("null")),
delimiter: Some("\x0f".to_owned()),
max_keys: Some(8),
..Default::default()
},
)
.await
.expect("valid version-id-marker with control delimiter must succeed");
assert_eq!(output.delimiter.as_deref(), Some("\x0f"));
let request = http::Request::get(format!("http://localhost/{}?versions&delimiter=%0F", bucket.as_str()))
.header(http::header::HOST, "localhost")
.body(bytes::Bytes::new())
.unwrap();
let wire = WireRequest::accept(request, &Limits::default()).unwrap();
let view = MetaView::of(&wire, TargetKind::Bucket).unwrap().with_rustfs_response_layout();
let encoded =
gateway_dto::ListObjectVersions::encode(output, &view, 200).expect("control delimiter response must encode");
assert_eq!(encoded.status, StatusCode::OK);
let ResponseBody::Complete(bytes) = encoded.body else {
panic!("ListObjectVersions must return an XML document");
};
let xml = String::from_utf8(bytes).expect("ListObjectVersions XML must be UTF-8");
assert!(xml.contains("<Delimiter>%0F</Delimiter>"), "unexpected XML: {xml}");
let metadata_output = usecase
.list_object_versions_metadata(
&owned_envelope(http::Method::GET),
VersionsQuery {
listing: MetadataListQuery {
bucket: bucket.as_str().to_owned(),
delimiter: Some("\x0f".to_owned()),
max_keys: Some(8),
..Default::default()
},
key_marker: Some("k".to_owned()),
version_id_marker: None,
},
)
.await
.expect("metadata listing with control delimiter must succeed");
metadata_output
.to_xml()
.expect("metadata listing XML with control delimiter must serialize");
});
}
}
+144 -2
View File
@@ -141,7 +141,7 @@ impl DefaultBucketUsecase {
let policy_public = match metadata_sys::get_bucket_policy(bucket).await {
Ok((cfg, _)) => cfg.statements.iter().any(|statement| {
matches!(statement.effect, Effect::Allow)
&& statement.principal.is_match("*")
&& statement.principal.is_public()
&& statement.conditions.is_empty()
&& statement.actions.is_match(&Action::S3Action(S3Action::ListBucketAction))
}),
@@ -197,7 +197,7 @@ impl DefaultBucketUsecase {
let is_public_policy = cfg
.statements
.iter()
.any(|statement| matches!(statement.effect, Effect::Allow) && statement.principal.is_match("*"));
.any(|statement| matches!(statement.effect, Effect::Allow) && statement.principal.is_public());
if is_public_policy {
match metadata_sys::get_public_access_block_config(bucket).await {
@@ -300,4 +300,146 @@ mod tests {
.unwrap_err();
assert_eq!(err.code(), &rustfs_s3_types::S3ErrorCode::InternalError);
}
#[test]
#[serial_test::serial]
fn block_public_policy_rejects_anonymous_matching_principals() {
use crate::app::gating_test_env::{run_large_stack_test, shared_gating_ambient};
use crate::app::runtime_sources::ServerContextSlot;
use crate::app::storage_api::owned_parity::authorize_bucket_config_mutation;
use rustfs_credentials::Credentials;
use rustfs_policy::policy::action::{Action, S3Action};
run_large_stack_test("bucket-policy-block-public-principals", || async {
let context = shared_gating_ambient().await;
let store = context.object_store();
let bucket_name = format!("block-public-policy-{}", uuid::Uuid::new_v4().simple());
store
.make_bucket(&bucket_name, &MakeBucketOptions::default())
.await
.expect("create bucket");
metadata_sys::update(
&bucket_name,
BUCKET_PUBLIC_ACCESS_BLOCK_CONFIG,
b"<PublicAccessBlockConfiguration><BlockPublicPolicy>true</BlockPublicPolicy></PublicAccessBlockConfiguration>"
.to_vec(),
)
.await
.expect("seed public access block");
let server = ServerContextSlot::new();
assert!(server.install(Arc::clone(&context)));
let usecase = DefaultBucketUsecase::with_context(Some(Arc::clone(&context)));
let authorized_put_envelope = || async {
let mut extensions = http::Extensions::new();
extensions.insert(Arc::clone(&server));
extensions.insert(ReqInfo {
cred: Some(Credentials {
access_key: "policy-test-owner".to_owned(),
..Default::default()
}),
is_owner: true,
..Default::default()
});
let mut envelope = RequestEnvelope::from_parts(
crate::app::RequestHead {
method: Method::PUT,
uri: format!("/{bucket_name}?policy").parse().expect("request URI"),
headers: http::HeaderMap::new(),
credentials: None,
region: None,
service: None,
},
extensions,
);
authorize_bucket_config_mutation(
&server,
&mut envelope,
&bucket_name,
Action::S3Action(S3Action::PutBucketPolicyAction),
)
.await
.expect("owner authorization installs incarnation snapshot");
envelope
};
for (label, principal_json) in [
("wildcard", r#"{"AWS":["*"]}"#),
("empty_array", r#"{"AWS":[""]}"#),
("empty_string", r#"{"AWS":""}"#),
("question_mark", r#"{"AWS":"?"}"#),
("leading_question_mark", r#"{"AWS":["?nobody"]}"#),
("mixed_named_and_empty", r#"{"AWS":["alice",""]}"#),
] {
let policy = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Principal":{principal_json},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::{bucket_name}/*"]}}]}}"#
);
let Err(err) = usecase
.execute_put_bucket_policy(authorized_put_envelope().await, &bucket_name, &policy)
.await
else {
panic!("BlockPublicPolicy must reject {label} principal");
};
assert_eq!(
err.code(),
&rustfs_s3_types::S3ErrorCode::AccessDenied,
"expected AccessDenied for {label}"
);
}
// A named principal Allow remains accepted under BlockPublicPolicy.
let named_policy = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Principal":{{"AWS":["alice"]}},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::{bucket_name}/*"]}}]}}"#
);
usecase
.execute_put_bucket_policy(authorized_put_envelope().await, &bucket_name, &named_policy)
.await
.expect("named principal policy should be accepted");
// A Deny statement with an empty principal is not a public grant.
let deny_policy = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Deny","Principal":{{"AWS":[""]}},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::{bucket_name}/*"]}}]}}"#
);
usecase
.execute_put_bucket_policy(authorized_put_envelope().await, &bucket_name, &deny_policy)
.await
.expect("Deny statement should not be rejected as a public grant");
// GetBucketPolicyStatus also classifies empty and `?` Allow principals as public.
let status_bucket = format!("policy-status-public-{}", uuid::Uuid::new_v4().simple());
store
.make_bucket(&status_bucket, &MakeBucketOptions::default())
.await
.expect("create status bucket");
for (label, principal_json, expected_public) in [
("empty_principal", r#"{"AWS":[""]}"#, true),
("leading_question_mark", r#"{"AWS":["?nobody"]}"#, true),
("named_principal", r#"{"AWS":["alice"]}"#, false),
] {
let policy = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Principal":{principal_json},"Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::{status_bucket}"]}}]}}"#
);
metadata_sys::update(&status_bucket, BUCKET_POLICY_CONFIG, policy.into_bytes())
.await
.expect("seed bucket policy");
let output = usecase
.execute_get_bucket_policy_status(
owned_envelope(Method::GET),
gateway_dto::GetBucketPolicyStatusInput {
bucket: bucket(&status_bucket),
..Default::default()
},
)
.await
.expect("get bucket policy status");
assert_eq!(
output.policy_status.and_then(|status| status.is_public),
Some(expected_public),
"unexpected policy status for {label}"
);
}
});
}
}
+79 -1
View File
@@ -18,6 +18,11 @@ use super::*;
use crate::app::storage_api::bucket_usecase::bucket::{ObjectLockConfigExt as _, VersioningConfigExt as _};
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result};
/// Maximum number of excluded prefixes accepted in a bucket versioning configuration.
const MAX_EXCLUDED_PREFIXES: usize = 100;
/// Maximum byte length of a single excluded prefix (matches the S3 object key limit).
const MAX_EXCLUDED_PREFIX_BYTES: usize = 1024;
fn versioning_configuration_has_object_lock_incompatible_settings(config: &PersistedVersioningConfiguration) -> bool {
config.suspended()
|| config.exclude_folders.unwrap_or(false)
@@ -27,7 +32,7 @@ fn versioning_configuration_has_object_lock_incompatible_settings(config: &Persi
.is_some_and(|excluded_prefixes| !excluded_prefixes.is_empty())
}
async fn validate_bucket_versioning_update(bucket: &str, config: &PersistedVersioningConfiguration) -> S3Result<()> {
fn validate_versioning_configuration_shape(config: &PersistedVersioningConfiguration) -> S3Result<()> {
if config
.status
.as_ref()
@@ -38,6 +43,29 @@ async fn validate_bucket_versioning_update(bucket: &str, config: &PersistedVersi
"bucket versioning configuration has an invalid status",
));
}
if let Some(excluded_prefixes) = config.excluded_prefixes.as_ref() {
if excluded_prefixes.len() > MAX_EXCLUDED_PREFIXES {
return Err(S3Error::with_message(
S3ErrorCode::InvalidArgument,
format!("bucket versioning configuration cannot exceed {MAX_EXCLUDED_PREFIXES} excluded prefixes"),
));
}
if excluded_prefixes
.iter()
.flatten()
.any(|prefix| prefix.len() > MAX_EXCLUDED_PREFIX_BYTES)
{
return Err(S3Error::with_message(
S3ErrorCode::InvalidArgument,
format!("bucket versioning excluded prefix cannot exceed {MAX_EXCLUDED_PREFIX_BYTES} bytes"),
));
}
}
Ok(())
}
async fn validate_bucket_versioning_update(bucket: &str, config: &PersistedVersioningConfiguration) -> S3Result<()> {
validate_versioning_configuration_shape(config)?;
match metadata_sys::get_object_lock_config(bucket).await {
Ok((object_lock_config, _)) => {
if object_lock_config.enabled() && versioning_configuration_has_object_lock_incompatible_settings(config) {
@@ -154,6 +182,56 @@ mod tests {
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument);
}
#[tokio::test]
async fn validate_bucket_versioning_update_rejects_excessive_excluded_prefix_count() {
let prefixes = (0..=MAX_EXCLUDED_PREFIXES)
.map(|i| Some(format!("tmp-{i}/")))
.collect::<Vec<_>>();
let config = PersistedVersioningConfiguration {
status: Some("Enabled".to_owned()),
excluded_prefixes: Some(prefixes),
..Default::default()
};
let err = validate_bucket_versioning_update("unregistered-test-bucket", &config)
.await
.expect_err("excessive excluded prefix count must be rejected before persistence");
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument);
}
#[tokio::test]
async fn validate_bucket_versioning_update_rejects_oversized_excluded_prefix() {
let config = PersistedVersioningConfiguration {
status: Some("Enabled".to_owned()),
excluded_prefixes: Some(vec![Some("*".repeat(MAX_EXCLUDED_PREFIX_BYTES + 1))]),
..Default::default()
};
let err = validate_bucket_versioning_update("unregistered-test-bucket", &config)
.await
.expect_err("oversized excluded prefix must be rejected before persistence");
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument);
}
#[test]
fn validate_versioning_configuration_shape_accepts_bounded_excluded_prefixes() {
let at_limit_count = PersistedVersioningConfiguration {
status: Some("Enabled".to_owned()),
excluded_prefixes: Some((0..MAX_EXCLUDED_PREFIXES).map(|i| Some(format!("tmp-{i}/"))).collect()),
..Default::default()
};
validate_versioning_configuration_shape(&at_limit_count).expect("max allowed excluded prefix count should pass");
let at_limit_len = PersistedVersioningConfiguration {
status: Some("Enabled".to_owned()),
excluded_prefixes: Some(vec![Some("a".repeat(MAX_EXCLUDED_PREFIX_BYTES))]),
..Default::default()
};
validate_versioning_configuration_shape(&at_limit_len).expect("max allowed excluded prefix length should pass");
}
#[test]
fn versioning_configuration_has_object_lock_incompatible_settings_rejects_suspended() {
let config = PersistedVersioningConfiguration {
+283 -36
View File
@@ -302,6 +302,23 @@ struct RpcRequestTarget {
method: Method,
}
/// Set by `check_auth` once the caller's internode request HMAC has been verified.
///
/// Boot-epoch and capability response proofs are HMACs keyed with the internode RPC secret over
/// caller-known values, so `RpcRequestPathService` only emits them when this marker is raised.
#[derive(Clone, Debug, Default)]
struct RpcSignatureVerified(Arc<AtomicBool>);
impl RpcSignatureVerified {
fn mark_verified(&self) {
self.0.store(true, Ordering::Release);
}
fn is_verified(&self) -> bool {
self.0.load(Ordering::Acquire)
}
}
#[derive(Clone)]
struct RpcRequestPathService<S> {
inner: S,
@@ -434,22 +451,10 @@ where
method: req.method().clone(),
};
req.extensions_mut().insert(target);
let signature_verified = RpcSignatureVerified::default();
req.extensions_mut().insert(signature_verified.clone());
let msgpack_manifest_capability_requested = storage::tonic_msgpack_manifest_capability_requested(req.headers());
let response_headers = tonic_boot_epoch_challenge(req.headers())
.ok()
.flatten()
.and_then(|challenge| {
storage::try_current_local_node_name()
.and_then(|node| normalize_tonic_rpc_audience(&node).ok())
.and_then(|audience| {
storage::tonic_boot_epoch_response_headers_with_msgpack_capability(
&audience,
challenge,
msgpack_manifest_capability_requested,
)
.ok()
})
});
let challenge = tonic_boot_epoch_challenge(req.headers()).ok().flatten();
let future = self.inner.call(req);
Box::pin(async move {
let mut response = storage::with_remote_background_io(resource_context, async move {
@@ -463,6 +468,20 @@ where
result
})
.await?;
// Answer the challenge only after `check_auth` verified the caller's request HMAC.
// Unauthenticated, forged, or unrouted requests must never receive secret-keyed proofs.
let response_headers = challenge.filter(|_| signature_verified.is_verified()).and_then(|challenge| {
storage::try_current_local_node_name()
.and_then(|node| normalize_tonic_rpc_audience(&node).ok())
.and_then(|audience| {
storage::tonic_boot_epoch_response_headers_with_msgpack_capability(
&audience,
challenge,
msgpack_manifest_capability_requested,
)
.ok()
})
});
if let Some(headers) = response_headers {
response.headers_mut().extend(headers);
}
@@ -3636,6 +3655,34 @@ fn hyper_body_write_close_kind(debug: &str) -> Option<&'static str> {
}
}
fn mark_rpc_signature_verified(req: &Request<()>) {
if let Some(verified) = req.extensions().get::<RpcSignatureVerified>() {
verified.mark_verified();
}
}
/// Whether an error from `verify_tonic_rpc_signature_with_bootstrap` was raised only after the
/// caller's request HMAC verified.
///
/// Only post-HMAC rejections may receive secret-keyed boot-epoch and capability proofs so cluster
/// restart recovery, strict replay-scope bootstrap, and replay-cache overload retries keep working
/// without emitting secret-keyed proofs to unauthenticated callers.
fn rpc_auth_failure_verified_signature(error: &std::io::Error, failure_reason: &str) -> bool {
storage::rpc_auth_is_resource_exhausted(error)
|| matches!(
failure_reason,
"stale_boot_epoch"
| "replay_scope_required"
| "replay_detected"
| "replay_cache_capacity"
| "replay_cache_memory"
| "replay_cache_allocation"
| "replay_cache_unavailable"
| "replay_expiry_overflow"
| "timestamp_expired_after_clock_regression"
)
}
fn rpc_auth_failure_status(error: &std::io::Error) -> Status {
if storage::rpc_auth_is_resource_exhausted(error) {
crate::error::rpc_replay_admission_exhausted_status()
@@ -3697,6 +3744,9 @@ fn check_auth(req: Request<()>) -> std::result::Result<Request<()>, Status> {
.map(|addr| addr.0.to_string())
.unwrap_or_else(|| "unknown".to_string());
let failure_reason = storage::tonic_rpc_auth_failure_reason(&e);
if rpc_auth_failure_verified_signature(&e, failure_reason) {
mark_rpc_signature_verified(&req);
}
let operation = match rpc_method {
"ReadAll" => INTERNODE_OPERATION_GRPC_READ_ALL,
"ReadMultiple" => INTERNODE_OPERATION_GRPC_READ_MULTIPLE,
@@ -3753,6 +3803,7 @@ fn check_auth(req: Request<()>) -> std::result::Result<Request<()>, Status> {
rejection
}
})?;
mark_rpc_signature_verified(&req);
if storage::rpc_background_admission(req.metadata().as_ref())
.map_err(|_| Status::unauthenticated("Invalid background admission request"))?
@@ -8591,30 +8642,40 @@ mod tests {
let audience = "127.0.0.1:9000";
rustfs_common::set_global_local_node_name(audience).await;
let challenge = uuid::Uuid::new_v4();
let node = InterceptedService::new(NodeServiceServer::new(make_server()), check_auth);
let service = RpcRequestPathService::new(Routes::new(node).prepare());
let response_for = |request_capability: bool| async move {
let mut request = HttpRequest::builder()
.method(Method::POST)
.uri("/node_service.NodeService/Ping")
.body(())
.expect("capability request");
request.headers_mut().insert(
"x-rustfs-rpc-boot-epoch-challenge",
challenge.to_string().parse().expect("challenge header"),
);
if request_capability {
let response_for = |signed: bool, request_capability: bool| {
let mut service = service.clone();
async move {
let mut request = HttpRequest::builder()
.method(Method::POST)
.uri(format!("http://{audience}/node_service.NodeService/Ping"))
.header("content-type", "application/grpc")
.body(Empty::<Bytes>::new())
.expect("capability request");
if signed {
let auth = storage::gen_tonic_signature_headers(audience, "node_service.NodeService", "Ping", None)
.expect("signed capability request");
request.headers_mut().extend(auth);
}
request.headers_mut().insert(
"x-rustfs-rpc-msgpack-manifest-request",
HeaderValue::from_static("msgpack-compat-manifest-v1"),
"x-rustfs-rpc-boot-epoch-challenge",
challenge.to_string().parse().expect("challenge header"),
);
if request_capability {
request.headers_mut().insert(
"x-rustfs-rpc-msgpack-manifest-request",
HeaderValue::from_static("msgpack-compat-manifest-v1"),
);
}
service.call(request).await.expect("capability response")
}
RpcRequestPathService::new(RpcPathObserver)
.call(request)
.await
.expect("capability response")
};
let legacy = response_for(false).await;
let legacy = response_for(true, false).await;
storage::verify_tonic_boot_epoch_response(audience, challenge, legacy.headers())
.expect("signed legacy request must still receive boot-epoch proof");
assert!(!legacy.headers().contains_key("x-rustfs-rpc-msgpack-manifest-capability"));
assert!(
!legacy
@@ -8622,7 +8683,9 @@ mod tests {
.contains_key("x-rustfs-rpc-msgpack-manifest-capability-proof")
);
let capable = response_for(true).await;
let capable = response_for(true, true).await;
storage::verify_tonic_boot_epoch_response(audience, challenge, capable.headers())
.expect("signed capable request must receive boot-epoch proof");
assert_eq!(
capable
.headers()
@@ -8636,6 +8699,18 @@ mod tests {
.contains_key("x-rustfs-rpc-msgpack-manifest-capability-proof")
);
let unsigned = response_for(false, true).await;
for name in [
"x-rustfs-rpc-boot-epoch",
"x-rustfs-rpc-boot-epoch-proof",
"x-rustfs-rpc-replay-cache-capability",
"x-rustfs-rpc-replay-cache-capability-proof",
"x-rustfs-rpc-msgpack-manifest-capability",
"x-rustfs-rpc-msgpack-manifest-capability-proof",
] {
assert!(!unsigned.headers().contains_key(name), "unsigned request must not receive {name}");
}
rustfs_common::set_global_local_node_name(&previous_node_name).await;
}
@@ -9614,6 +9689,178 @@ mod tests {
);
}
#[test]
fn rpc_auth_failure_verified_signature_classifies_post_hmac_errors_only() {
for error in [
std::io::Error::new(std::io::ErrorKind::WouldBlock, storage::RpcReplayCacheAdmissionError::Capacity),
std::io::Error::new(std::io::ErrorKind::WouldBlock, storage::RpcReplayCacheAdmissionError::MemoryBudget),
std::io::Error::new(std::io::ErrorKind::OutOfMemory, "replay cache allocation failed"),
std::io::Error::other("RPC boot epoch is stale"),
std::io::Error::other("RPC replay-scoped authentication required"),
std::io::Error::other("RPC request replay detected"),
std::io::Error::other("RPC replay cache unavailable"),
std::io::Error::other("RPC request timestamp expired after clock regression"),
] {
let reason = storage::tonic_rpc_auth_failure_reason(&error);
assert!(
rpc_auth_failure_verified_signature(&error, reason),
"post-HMAC error ({reason}) must allow boot-epoch/capability proofs"
);
}
for error in [
std::io::Error::other("Missing signature header"),
std::io::Error::other("Invalid signature"),
std::io::Error::other("RPC v2 authentication required"),
std::io::Error::other("Invalid RPC v2 signature"),
std::io::Error::other("Invalid RPC replay scope signature"),
std::io::Error::other("Request timestamp expired"),
std::io::Error::other("Missing RPC boot epoch"),
std::io::Error::other("RPC background admission requires v2 authentication"),
std::io::Error::other("opaque failure"),
] {
let reason = storage::tonic_rpc_auth_failure_reason(&error);
assert!(
!rpc_auth_failure_verified_signature(&error, reason),
"pre-HMAC error ({reason}) must never receive boot-epoch/capability proofs"
);
}
}
#[tokio::test]
#[serial_test::serial]
async fn rpc_boot_epoch_proof_requires_verified_request_signature() {
let _ = rustfs_credentials::set_global_rpc_secret("rpc-http-test-secret".to_string());
let previous_node_name = rustfs_common::get_global_local_node_name().await;
let audience = "127.0.0.1:9000";
let ping = "/node_service.NodeService/Ping";
let read_all = "/node_service.NodeService/ReadAll";
rustfs_common::set_global_local_node_name(audience).await;
let node = InterceptedService::new(NodeServiceServer::new(make_server()), check_auth);
let mut service = RpcRequestPathService::new(Routes::new(node).prepare());
let epoch_probe_challenge = uuid::Uuid::new_v4();
let current_epoch = storage::verify_tonic_boot_epoch_response(
audience,
epoch_probe_challenge,
&storage::tonic_boot_epoch_response_headers(audience, epoch_probe_challenge).expect("current epoch proof"),
)
.expect("current boot epoch");
let stale_epoch = uuid::Uuid::from_u128(current_epoch.as_u128() ^ 1);
let signed_v2 = storage::gen_tonic_signature_headers(audience, "node_service.NodeService", "Ping", None)
.expect("method-bound signature");
let mut signed_v3_current = signed_v2.clone();
signed_v3_current.extend(
storage::gen_tonic_replay_scope_headers(
audience,
ping,
signed_v2["x-rustfs-timestamp"].to_str().expect("timestamp"),
signed_v2["x-rustfs-content-sha256"].to_str().expect("body digest"),
current_epoch,
)
.expect("current-epoch replay-scoped signature"),
);
let signed_v3_replay = signed_v3_current.clone();
let mut signed_v3_stale = signed_v2.clone();
signed_v3_stale.extend(
storage::gen_tonic_replay_scope_headers(
audience,
ping,
signed_v2["x-rustfs-timestamp"].to_str().expect("timestamp"),
signed_v2["x-rustfs-content-sha256"].to_str().expect("body digest"),
stale_epoch,
)
.expect("stale-epoch replay-scoped signature"),
);
let mut forged_v2 = signed_v2.clone();
forged_v2.insert("x-rustfs-rpc-signature-v2", HeaderValue::from_static("invalid"));
let mut forged_v3 = signed_v3_stale.clone();
forged_v3.insert("x-rustfs-rpc-signature-v3", HeaderValue::from_static("invalid"));
let cross_method = signed_v2.clone();
let unrouted_signed = signed_v2.clone();
for (label, path, headers, expect_proof) in [
("signed v2 ping", ping, signed_v2, true),
("signed v3 current epoch ping", ping, signed_v3_current, true),
("replayed signed v3 ping", ping, signed_v3_replay, true),
("signed v3 stale epoch ping", ping, signed_v3_stale, true),
("forged v2 ping", ping, forged_v2, false),
("forged v3 ping", ping, forged_v3, false),
("cross-method v2 read_all", read_all, cross_method, false),
("unsigned ping", ping, HeaderMap::new(), false),
("unrouted unsigned", "/unrouted.Service/Method", HeaderMap::new(), false),
("unrouted signed", "/unrouted.Service/Method", unrouted_signed, false),
] {
let challenge = uuid::Uuid::new_v4();
let mut request = HttpRequest::builder()
.method(Method::POST)
.uri(format!("http://{audience}{path}"))
.header("content-type", "application/grpc")
.header("x-rustfs-rpc-boot-epoch-challenge", challenge.to_string())
.header("x-rustfs-rpc-msgpack-manifest-request", "msgpack-compat-manifest-v1")
.body(Empty::<Bytes>::new())
.expect("request");
request.headers_mut().extend(headers);
let response = service.call(request).await.expect("response");
if expect_proof {
let verified_epoch = storage::verify_tonic_boot_epoch_response(audience, challenge, response.headers())
.unwrap_or_else(|err| panic!("{label} must receive verifiable boot-epoch proof: {err}"));
assert_eq!(verified_epoch, current_epoch, "{label} must return current boot epoch");
assert!(
response.headers().contains_key("x-rustfs-rpc-replay-cache-capability-proof"),
"{label} must receive replay-cache capability proof"
);
assert!(
response
.headers()
.contains_key("x-rustfs-rpc-msgpack-manifest-capability-proof"),
"{label} must receive requested msgpack capability proof"
);
continue;
}
for name in [
"x-rustfs-rpc-boot-epoch",
"x-rustfs-rpc-boot-epoch-proof",
"x-rustfs-rpc-replay-cache-capability",
"x-rustfs-rpc-replay-cache-capability-proof",
"x-rustfs-rpc-msgpack-manifest-capability",
"x-rustfs-rpc-msgpack-manifest-capability-proof",
] {
assert!(
!response.headers().contains_key(name),
"{label} ({path}) must not return {name} to an unverified caller"
);
}
}
// Verify that a post-HMAC ResourceExhausted rejection from background admission still
// raises `RpcSignatureVerified` so the peer does not falsely revoke capabilities.
let bg_owner = rustfs_concurrency::adaptive::NodeAdmission::new(std::num::NonZeroU16::MIN);
let bg_headers = storage::with_remote_background_io(Some(storage::RemoteBackgroundIo::new(bg_owner)), async {
storage::gen_tonic_signature_headers(audience, "node_service.NodeService", "ReadAll", None)
})
.await
.expect("signed background RPC headers");
let verified_marker = RpcSignatureVerified::default();
let mut bg_request = Request::new(());
bg_request.metadata_mut().as_mut().extend(bg_headers);
bg_request.extensions_mut().insert(RpcRequestTarget {
uri: format!("http://{audience}{read_all}").parse().expect("RPC URI"),
method: Method::POST,
});
bg_request.extensions_mut().insert(verified_marker.clone());
let bg_error = check_auth(bg_request).expect_err("background request without admission token must reject");
assert_eq!(bg_error.code(), tonic::Code::ResourceExhausted);
assert!(
verified_marker.is_verified(),
"post-HMAC ResourceExhausted rejection must still mark RpcSignatureVerified"
);
rustfs_common::set_global_local_node_name(&previous_node_name).await;
}
#[tokio::test]
#[serial_test::serial]
async fn rpc_auth_rejection_records_failure_reason_metric() {
@@ -10137,7 +10384,7 @@ mod tests {
assert_eq!(info.real_ip, peer.ip());
assert_eq!(info.forwarded_proto.as_deref(), Some("https"));
let identity = rustfs_keystone::KEYSTONE_CREDENTIALS.try_with(Clone::clone).ok().flatten().map(|credentials| credentials.parent_user).unwrap_or_else(|| "anonymous".to_owned());
if request.headers().contains_key("x-auth-token") { assert_eq!(identity, "test-user"); }
if request.headers().contains_key("x-auth-token") { assert_eq!(identity, "keystone:user-id"); }
Ok::<_, Box<dyn std::error::Error + Send + Sync>>(Response::new(HybridBody::<EdgeBody, http_body_util::Empty<Bytes>>::Rest { rest_body: EdgeBody::from(Bytes::from(identity)) }))
});
let inner = Http3CoreService::new(inner);
@@ -10153,7 +10400,7 @@ mod tests {
assert_eq!(request(&mut client, HttpRequest::builder().uri("https://localhost/bucket/key").header("x-auth-token", "invalid-token").body(())?, Bytes::new()).await?.0, http::StatusCode::UNAUTHORIZED);
let (status, headers, body) = request(&mut client, HttpRequest::builder().uri("https://localhost/bucket/key").header("x-auth-token", "valid-token").header("x-forwarded-for", "203.0.113.1").body(())?, Bytes::new()).await?;
assert_eq!(status, http::StatusCode::OK);
assert_eq!(body, "test-user");
assert_eq!(body, "keystone:user-id");
assert!(headers.contains_key("x-amz-request-id"), "request context must survive HTTP/3 dispatch");
assert_eq!(request(&mut client, make_request()?, Bytes::new()).await?.2, "anonymous", "Keystone task-local credentials must not leak between streams");
assert_eq!(request(&mut client, make_request()?, Bytes::new()).await?.0, http::StatusCode::TOO_MANY_REQUESTS);
+5 -2
View File
@@ -389,8 +389,11 @@ mod tests {
"every plaintext POST Object SSE-C form upload must increment the counter"
);
let logs = String::from_utf8(buffer.0.lock().expect("log buffer").clone()).expect("UTF-8 logs");
let warning_count = logs.lines().filter(|line| line.contains("ssec_request_without_tls")).count();
assert_eq!(warning_count, 1, "the plaintext SSE-C warning must fire once per process");
let warning_lines: Vec<_> = logs
.lines()
.filter(|line| line.contains("ssec_request_without_tls"))
.collect();
assert_eq!(warning_lines.len(), 1, "the plaintext SSE-C warning must fire once per process");
}
#[test]