Merge commit from fork

* fix(admin): bound IAM import archive expansion

MAX_IAM_IMPORT_SIZE caps the compressed upload at 10 MB, but every member of the
archive was then read with read_to_end into an unbounded Vec. Deflate ratios well
above 100:1 are easy to construct, so a small authorized upload could expand
without limit across the seven members ImportIam reads.

Add a shared expansion budget (MAX_IAM_IMPORT_EXPANDED_SIZE, 10x the compressed
cap) drawn down by every member, and route all seven reads through one helper
that reads a byte past the remaining budget to detect overrun. Sharing the budget
bounds the archive as a whole rather than letting each member spend the full
limit independently.

Covers R03-CAN-024 through R03-CAN-030 plus R04-CAN-077 (backlog #1471) — one
fix rather than seven, since all seven call sites were byte-identical.

* fix(kms): confine local key paths and refuse silent key replacement

Local KMS key identifiers arrive from request input — the `name` tag on CreateKey,
the `keyId` body field or query parameter on DeleteKey — and were joined onto
`key_dir` with no validation. An identifier such as `../../tmp/evil` escaped the
configured directory, making key creation a constrained arbitrary-file write and
`DeleteKey` with `force_immediate` a cross-directory delete.

Validate in `master_key_path` and make it fallible, so every filesystem path in
this backend inherits the guard: decode_stored_key, load_master_key,
save_master_key, create_key and delete_key all derive their paths there. The rule
is containment rather than a character allowlist, so identifiers already in use
keep resolving; only separators, NUL, absolute paths and non-single-component
forms are refused. Note `.` and `..` are contained rather than refused — the
`.key` suffix turns them into the ordinary filenames `..key` and `...key`.

Separately, `LocalKmsBackend::create_key` had no existence check, while the
sibling `KmsClient::create_key` has always had one. Since `save_master_key`
renames over its destination, creating a key under an existing name silently
replaced its material and destroyed the ability to decrypt everything wrapped
under it — and the backend path is the one the admin API uses. It now returns
KeyAlreadyExists, matching StaticKmsBackend.

Covers R03-CAN-072, R03-CAN-073 and R07-CAN-103 (backlog #1475). R03-CAN-073
needed no separate change: delete_key routes both its load and its remove_file
through master_key_path.

* fix(swift): bound SLO manifest reads to the 2 MiB manifest limit

The three Swift SLO handlers that load a stored manifest (handle_slo_get,
handle_slo_get_manifest, handle_slo_delete) read the `<object>.slo-manifest`
object to EOF with AsyncReadExt::read_to_end. That key is predictable and
writable through the ordinary object PUT path, so a tenant can replace the
manifest with an arbitrarily large object and then make the server allocate
its full size on every SLO GET, multipart-manifest=get, or
multipart-manifest=delete request - a memory amplification bounded only by
the stored object size (CWE-400 / CWE-770). The 2 MiB manifest limit that
handle_slo_put enforces was not applied on the read side.

Introduce MAX_SLO_MANIFEST_SIZE (the existing 2 MiB PUT limit, now a named
constant) and a shared read_manifest_bytes helper that reads through a
`take(limit + 1)` and rejects anything larger, so an oversized manifest is
refused instead of being buffered first. All three call sites go through the
helper. handle_slo_put now checks the size before parsing the JSON.

Regression tests: test_read_manifest_bytes_rejects_oversized_manifest and
test_read_manifest_bytes_stops_reading_oversized_manifest (which asserts the
reader is not consumed past the limit), plus a boundary test that a manifest
at exactly 2 MiB is still accepted.

* fix(protocols): authorize every object in FTPS/WebDAV recursive deletes

The FTPS and WebDAV gateways authorized only the container before a
recursive delete and then destroyed everything inside it without a
further check:

- FTPS RMD (and DELE on a bucket path ending in '/') cleared
  s3:DeleteBucket, then delete_bucket_recursively listed the bucket and
  deleted every object.
- WebDAV DELETE on a bucket did the same via its own
  delete_bucket_recursively.
- WebDAV DELETE on a directory cleared s3:DeleteObject for the directory
  marker key ("dir/") only, then listed that prefix and deleted every
  child under it.

A principal holding s3:DeleteBucket (or s3:DeleteObject on a single
marker key) could therefore erase objects it had no s3:DeleteObject
permission for, and the operation reported success.

Deletion stays recursive - that is the expected behaviour for these
protocols - but each object now clears s3:DeleteObject on its own key
before it is removed, and the enumeration clears s3:ListBucket. A denial
aborts the whole operation with access denied rather than being skipped,
so the caller can never be told the delete succeeded while objects were
left behind or removed without authorization.

The test double gained shared-state cloning, delete_object/delete_bucket
call logs, and list/delete queue helpers so the regression tests can
observe that nothing is deleted once a deny lands.

* fix(server,ecstore): bound TLS handshakes and remote volume RPC waits

Three call sites let an unauthenticated client or a misbehaving peer hold
server resources with no deadline.

TLS listener (R03-CAN-035): process_connection awaited
`acceptor.accept(socket)` with no bound. A client that opens a TCP
connection and never finishes the handshake parks a Tokio task and a socket
forever, and the connection cap (RUSTFS_API_MAX_CONNECTIONS) is unlimited by
default, so nothing else sheds it. The handshake now runs under
accept_tls_with_deadline(), reusing the existing HTTP/1 header-read budget —
the established slow-client bound for the pre-request phase — and the
expiry is recorded through the same log/metric path as a handshake error,
under a new TIMEOUT failure kind.

Remote disk RPCs (R03-CAN-049, R03-CAN-050): list_volumes and delete_volume
passed Duration::ZERO, which execute_with_timeout treats as "no deadline",
so a peer that accepts the request and never answers stalls the coordinator
(and, for delete_volume, the bucket-deletion workflow). Both now pass
get_max_timeout_duration(), matching every sibling method in the file.

Regression tests: a silent TLS peer must be shed by the handshake deadline;
list_volumes/delete_volume against a peer that completes the TCP connect and
then goes silent must fail with DiskError::Timeout instead of hanging.

* fix(security): stop leaking signed headers and bound OIDC/KMS credentials

Three independent hygiene fixes found by the security review.

R03-CAN-018 (crates/signer): try_get_canonical_headers and get_signed_headers
logged the complete header map at DEBUG before signing. Runtime callers pass
session credentials and SSE-C key material through these headers, so anyone
able to raise the log level (or read DEBUG logs) recovered
X-Amz-Security-Token and SSE-C keys verbatim. The statements were debugging
leftovers with no operational value and are deleted rather than redacted.

R03-CAN-014 (crates/iam): the OIDC HTTP adapter buffered provider responses
with an unbounded Response::bytes(), so a configured, compromised or
attacker-pointed IdP endpoint could stream an arbitrarily large or endless
body into memory (the ValidateOidcConfig admin handler lets a ServerInfo
caller choose the endpoint). Responses are now read incrementally and fail
closed past MAX_OIDC_RESPONSE_SIZE, and the already SSRF-hardened client
builder gains request and connect timeouts so a stalled provider cannot pin
the calling task indefinitely.

R07-CAN-105 (helm): the Vault KMS token was serialized into the chart
ConfigMap, exposing it to every subject allowed to get ConfigMaps in the
namespace. It now renders into a dedicated Secret that the Deployment and
StatefulSet consume via envFrom; the Secret is separate from the main
credentials Secret so it also works when secret.existingSecret is set.

Regression tests:
- rustfs-signer: signing_never_logs_signed_header_material
- rustfs-iam: oidc_response_body_past_the_limit_is_rejected,
  oidc_response_body_at_the_limit_is_accepted
- scripts/test_helm_templates.sh: KMS token must never render in plaintext

* fix(webdav): enforce body limit, request timeout and connection cap

The configured WebDAV maximum body size was enforced from Content-Length, so a
chunked request declared no length and bypassed it entirely. The configured
request timeout was never applied to the connection at all, and the accept loop
spawned a task per connection with no bound, so an unauthenticated client could
hold resources indefinitely and in unbounded number.

Enforce the limit on bytes actually read rather than the declared length, apply
the configured timeout to the request, and bound accepted connections with a new
RUSTFS_WEBDAV_MAX_CONNECTIONS (default 1024) surfaced in the config report.

Covers R03-CAN-051, R03-CAN-052, R03-CAN-067, R04-CAN-089, R05-CAN-094 and
R05-CAN-097 (backlog #1471, #1474).

* fix(security): stop STS credentials from crossing the parent trust boundary

Two related credential-boundary holes let a short-lived STS credential act
with the full, unrestricted authority of the long-term user it was minted
from.

AddUser (R03-CAN-021, CWE-269/863): should_check_deny_only relaxes the admin
policy check to deny-only when a Console/STS session targets the IAM user it
represents. Nothing then stopped that session from calling AddUser with its
own parent's access key, so the handler wrote an attacker-chosen secret key
and status over the parent's stored Credentials via create_user ->
save_user_identity. A session that expires in minutes became permanent
control of the account. AddUser now rejects any temp or service-account
requester whose resolved parent equals the target access key, resolving the
parent the same way should_check_deny_only does (parent_user field, else the
JWT `parent` claim, since some stores persist the parent only in the token).

FTPS/SFTP/WebDAV password auth (R04-CAN-086, CWE-287/862): these protocols
looked the access key up with check_key, which falls back to the STS account
cache, and then compared only the stored secret. An STS access key plus
secret therefore authenticated with no session token presented and no
session-policy claims applied - the holder got the parent's full permissions.
Password authentication now rejects temporary credentials before the secret
comparison. The discriminator is is_temp() && !is_service_account(), the same
one IamCache::update_user_with_claims uses to route an identity into the STS
cache, so service accounts - which resolve policy from stored IAM state
rather than a client-presented token - keep working over these protocols.

Regression tests cover both predicates and pin the guards to their call
sites so neither can be dropped without a test failure.
This commit is contained in:
Zhengchao An
2026-07-27 00:22:50 +08:00
committed by GitHub
parent 887868e7cd
commit b2a376c2d2
32 changed files with 1924 additions and 187 deletions
+77 -6
View File
@@ -37,8 +37,8 @@ use s3s::dto::{
AbortMultipartUploadInput, AbortMultipartUploadOutput, CompleteMultipartUploadInput, CompleteMultipartUploadOutput,
CopyObjectInput, CopyObjectOutput, CopyPartResult, CreateBucketOutput, CreateMultipartUploadInput,
CreateMultipartUploadOutput, DeleteBucketOutput, DeleteObjectOutput, ETag, GetObjectOutput, HeadBucketOutput,
HeadObjectOutput, ListBucketsOutput, ListObjectsV2Input, ListObjectsV2Output, PutObjectInput, PutObjectOutput, StreamingBlob,
Timestamp, UploadPartCopyInput, UploadPartCopyOutput, UploadPartInput, UploadPartOutput,
HeadObjectOutput, ListBucketsOutput, ListObjectsV2Input, ListObjectsV2Output, Object, ObjectKey, PutObjectInput,
PutObjectOutput, StreamingBlob, Timestamp, UploadPartCopyInput, UploadPartCopyOutput, UploadPartInput, UploadPartOutput,
};
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
@@ -121,6 +121,14 @@ pub struct HeadObjectCall {
pub key: String,
}
/// Recorded invocation of delete_object. Tests assert on these to observe
/// which objects a recursive delete path actually removed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeleteObjectCall {
pub bucket: String,
pub key: String,
}
struct Inner {
// Response queues. Each method pops from its own queue. Empty queue
// plus no default means a configured-miss error.
@@ -148,6 +156,8 @@ struct Inner {
upload_part_calls: Vec<UploadPartCall>,
complete_multipart_calls: Vec<CompleteCall>,
head_object_calls: Vec<HeadObjectCall>,
delete_object_calls: Vec<DeleteObjectCall>,
delete_bucket_calls: Vec<String>,
// Cancellation-test support. When stall_upload_part is true every
// upload_part invocation signals upload_part_entered and then awaits
@@ -197,6 +207,8 @@ impl Inner {
upload_part_calls: Vec::new(),
complete_multipart_calls: Vec::new(),
head_object_calls: Vec::new(),
delete_object_calls: Vec::new(),
delete_bucket_calls: Vec::new(),
stall_upload_part: false,
upload_part_entered: None,
stall_put_object: false,
@@ -213,8 +225,13 @@ impl Inner {
/// tested, and keep another clone for observation. Method calls are
/// fire-and-forget from the driver's perspective and synchronous on the
/// test side.
///
/// Cloning shares the same queues and observation logs, so a test can hand
/// one clone to a driver that takes its backend by value and keep another
/// for assertions.
#[derive(Clone)]
pub struct DummyBackend {
inner: Mutex<Inner>,
inner: Arc<Mutex<Inner>>,
}
// Drivers whose trait bounds require `Debug` (for example FtpsDriver) cannot be
@@ -237,7 +254,7 @@ impl DummyBackend {
/// configured-miss error until a queue is populated.
pub fn new() -> Self {
Self {
inner: Mutex::new(Inner::new()),
inner: Arc::new(Mutex::new(Inner::new())),
}
}
@@ -377,6 +394,43 @@ impl DummyBackend {
.push_back(Ok(ListObjectsV2Output::default()));
}
/// Queue a list_objects_v2 Ok response listing the given keys as a
/// single, non-truncated page. Recursive-delete tests use this to give
/// the delete loop something to iterate over.
pub fn queue_list_objects_v2_ok_with_keys(&self, keys: &[&str]) {
let contents = keys
.iter()
.map(|key| Object {
key: Some(ObjectKey::from((*key).to_string())),
..Default::default()
})
.collect();
let out = ListObjectsV2Output {
contents: Some(contents),
is_truncated: Some(false),
..Default::default()
};
self.inner.lock().expect("lock").list_objects_v2.push_back(Ok(out));
}
/// Queue a delete_object Ok response.
pub fn queue_delete_object_ok(&self) {
self.inner
.lock()
.expect("lock")
.delete_object
.push_back(Ok(DeleteObjectOutput::default()));
}
/// Queue a delete_bucket Ok response.
pub fn queue_delete_bucket_ok(&self) {
self.inner
.lock()
.expect("lock")
.delete_bucket
.push_back(Ok(DeleteBucketOutput::default()));
}
/// Queue a list_objects_v2 error. Used to verify that callers do
/// not fall through to a destructive operation when the empty-check
/// itself fails.
@@ -497,6 +551,16 @@ impl DummyBackend {
}
/// Snapshot the head_object call log.
/// Snapshot the recorded delete_object invocations.
pub fn delete_object_calls(&self) -> Vec<DeleteObjectCall> {
self.inner.lock().expect("lock").delete_object_calls.clone()
}
/// Snapshot the buckets passed to delete_bucket.
pub fn delete_bucket_calls(&self) -> Vec<String> {
self.inner.lock().expect("lock").delete_bucket_calls.clone()
}
pub fn head_object_calls(&self) -> Vec<HeadObjectCall> {
self.inner.lock().expect("lock").head_object_calls.clone()
}
@@ -565,7 +629,12 @@ impl StorageBackend for DummyBackend {
}
async fn delete_object(&self, bucket: &str, key: &str, _ak: &str, _sk: &str) -> Result<DeleteObjectOutput, Self::Error> {
match self.inner.lock().expect("lock").delete_object.pop_front() {
let mut inner = self.inner.lock().expect("lock");
inner.delete_object_calls.push(DeleteObjectCall {
bucket: bucket.to_string(),
key: key.to_string(),
});
match inner.delete_object.pop_front() {
Some(r) => r,
None => Err(DummyError::NoSuchKey(format!("{bucket}/{key}"))),
}
@@ -636,7 +705,9 @@ impl StorageBackend for DummyBackend {
}
async fn delete_bucket(&self, bucket: &str, _ak: &str, _sk: &str) -> Result<DeleteBucketOutput, Self::Error> {
match self.inner.lock().expect("lock").delete_bucket.pop_front() {
let mut inner = self.inner.lock().expect("lock");
inner.delete_bucket_calls.push(bucket.to_string());
match inner.delete_bucket.pop_front() {
Some(r) => r,
None => Err(DummyError::NoSuchBucket(bucket.to_string())),
}
+105
View File
@@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use rustfs_credentials::Credentials;
use rustfs_policy::auth::UserIdentity;
use std::net::IpAddr;
#[cfg(test)]
@@ -43,6 +44,21 @@ impl ProtocolPrincipal {
}
}
/// Returns `true` when `credentials` are short-lived STS/AssumeRole credentials.
///
/// SECURITY: password-based protocol logins (FTPS, SFTP, WebDAV Basic) have nowhere to carry the
/// session token that an STS credential is only valid with, so accepting the access/secret pair
/// alone would authenticate the holder as the parent user with none of the session-policy
/// restrictions the token encodes. Such logins must be rejected.
///
/// Service accounts also hold a signed token, but their policy is resolved from stored IAM state
/// rather than from a token the client must present, so they stay eligible for these protocols.
/// The `is_temp() && !is_service_account()` pairing is the same STS discriminator the IAM manager
/// uses when routing an identity into the STS account cache.
pub fn is_temporary_credential(credentials: &Credentials) -> bool {
credentials.is_temp() && !credentials.is_service_account()
}
/// Session context for protocol operations
#[derive(Debug, Clone)]
pub struct SessionContext {
@@ -85,6 +101,95 @@ pub fn test_session(protocol: Protocol) -> SessionContext {
#[cfg(test)]
mod regression_prevention {
use super::*;
use rustfs_credentials::{IAM_POLICY_CLAIM_NAME_SA, INHERITED_POLICY_TYPE};
use serde_json::Value;
use std::collections::HashMap;
use time::{Duration, OffsetDateTime};
fn service_account_claims() -> HashMap<String, Value> {
let mut claims = HashMap::new();
claims.insert(IAM_POLICY_CLAIM_NAME_SA.to_string(), Value::String(INHERITED_POLICY_TYPE.to_string()));
claims
}
#[test]
fn sts_credentials_are_temporary() {
let sts = Credentials {
access_key: "VV0V3VYJK2PV6EG45X2Y".to_string(),
secret_key: "CS_TEST_SECRET_DO_NOT_LOG".to_string(),
session_token: "jwt-session-token".to_string(),
parent_user: "alice".to_string(),
..Default::default()
};
assert!(is_temporary_credential(&sts));
}
#[test]
fn service_accounts_are_not_temporary() {
// Service accounts also carry a signed token; they must keep working over FTPS/SFTP/WebDAV.
let service_account = Credentials {
access_key: "39KNO04Z34D6T4AGL6E6".to_string(),
secret_key: "CS_TEST_SECRET_DO_NOT_LOG".to_string(),
session_token: "jwt-session-token".to_string(),
parent_user: "alice".to_string(),
claims: Some(service_account_claims()),
..Default::default()
};
assert!(service_account.is_service_account());
assert!(!is_temporary_credential(&service_account));
}
#[test]
fn long_term_credentials_are_not_temporary() {
let long_term = Credentials {
access_key: "alice".to_string(),
secret_key: "CS_TEST_SECRET_DO_NOT_LOG".to_string(),
..Default::default()
};
assert!(!is_temporary_credential(&long_term));
}
#[test]
fn expired_sts_credentials_are_rejected_by_the_validity_gate() {
// is_temp() goes false once the session expires, so the STS guard alone would let an
// expired session in. The `is_valid` check every password path runs first is what covers
// this case; assert both halves so neither can be dropped unnoticed.
let expired = Credentials {
access_key: "VV0V3VYJK2PV6EG45X2Y".to_string(),
secret_key: "CS_TEST_SECRET_DO_NOT_LOG".to_string(),
session_token: "jwt-session-token".to_string(),
parent_user: "alice".to_string(),
expiration: Some(OffsetDateTime::now_utc() - Duration::hours(1)),
..Default::default()
};
assert!(!is_temporary_credential(&expired));
assert!(!expired.is_valid());
}
#[test]
fn password_auth_paths_reject_temporary_credentials() {
let guard = concat!("is_temporary_credential(&identity.", "credentials)");
for (protocol, source) in [
("ftps", include_str!("../ftps/server.rs")),
("webdav", include_str!("../webdav/server.rs")),
("sftp", include_str!("../sftp/server.rs")),
] {
let guard_at = source
.find(guard)
.unwrap_or_else(|| panic!("{protocol} password authentication must reject temporary STS credentials"));
let accept_at = source
.find(r#"result = "authenticated""#)
.unwrap_or_else(|| panic!("{protocol} has no authenticated log line to anchor the guard against"));
assert!(
guard_at < accept_at,
"{protocol} must reject temporary STS credentials before authentication succeeds"
);
}
}
// Compile-time check that every Protocol variant is acknowledged here.
// This is intentionally an exhaustive match with no wildcard arm: if a
+53
View File
@@ -170,6 +170,13 @@ where
bucket: &str,
session_context: &crate::common::session::SessionContext,
) -> Result<()> {
// SECURITY: s3:DeleteBucket does not imply the right to destroy the
// bucket contents. Enumerating and deleting each object are separate
// authorization boundaries and must be cleared on their own.
authorize_operation(session_context, &S3Action::ListBucket, bucket, None)
.await
.map_err(|_| Error::new(ErrorKind::PermanentFileNotAvailable, "Access denied"))?;
// First, delete all objects in the bucket (with pagination)
let mut continuation_token = None;
loop {
@@ -196,6 +203,10 @@ where
if let Some(objects) = output.contents {
for obj in objects {
if let Some(obj_key) = obj.key {
authorize_operation(session_context, &S3Action::DeleteObject, bucket, Some(&obj_key))
.await
.map_err(|_| Error::new(ErrorKind::PermanentFileNotAvailable, "Access denied"))?;
let _ = self
.storage
.delete_object(
@@ -929,6 +940,48 @@ mod tests {
);
}
/// RMD deletes every object in the bucket, so `s3:DeleteBucket` alone must
/// not be enough: each object needs its own `s3:DeleteObject` boundary. The
/// backend is primed so that the whole recursive delete would succeed if the
/// per-object check were removed again.
#[tokio::test]
async fn ftps_rmd_denied_per_object_does_not_delete_bucket_contents() {
use super::FtpsDriver;
use crate::common::dummy_storage::DummyBackend;
use crate::common::gateway::{S3Action, with_test_auth_override};
use crate::common::session::{Protocol, test_session};
use unftp_core::storage::StorageBackend as _;
let backend = DummyBackend::new();
backend.queue_list_objects_v2_ok_with_keys(&["secret.txt"]);
backend.queue_delete_object_ok();
backend.queue_delete_bucket_ok();
let driver = FtpsDriver::new(backend.clone());
let user = super::super::server::FtpsUser {
username: "bucket-only-user".to_string(),
name: None,
session_context: test_session(Protocol::Ftps),
};
let result = with_test_auth_override(
|action, _bucket, _object| !matches!(action, S3Action::DeleteObject),
driver.rmd(&user, "/victim-bucket"),
)
.await;
assert!(result.is_err(), "RMD must fail closed when s3:DeleteObject is denied for a bucket member");
assert!(
backend.delete_object_calls().is_empty(),
"no object may be deleted once s3:DeleteObject is denied, got {:?}",
backend.delete_object_calls()
);
assert!(
backend.delete_bucket_calls().is_empty(),
"the bucket must survive when its contents could not be authorized for deletion"
);
}
proptest::proptest! {
#[test]
fn parse_s3_path_never_leaks_control_bytes_or_traversal_in_ok_output(
+14 -1
View File
@@ -15,7 +15,7 @@
use super::config::{FtpsConfig, FtpsInitError};
use super::driver::FtpsDriver;
use crate::common::client::s3::StorageBackend;
use crate::common::session::{Protocol, ProtocolPrincipal, SessionContext};
use crate::common::session::{Protocol, ProtocolPrincipal, SessionContext, is_temporary_credential};
use crate::constants::{network::DEFAULT_SOURCE_IP, paths::ROOT_PATH};
use libunftp::options::FtpsRequired;
use rustfs_config::{DEFAULT_TLS_RELOAD_ENABLE, DEFAULT_TLS_RELOAD_INTERVAL, ENV_TLS_RELOAD_ENABLE, ENV_TLS_RELOAD_INTERVAL};
@@ -465,6 +465,19 @@ impl Authenticator for FtpsAuthenticator {
AuthenticationError::BadUser
})?;
if is_temporary_credential(&identity.credentials) {
warn!(
event = EVENT_FTPS_AUTH_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_FTPS_AUTH,
result = "temporary_credential_rejected",
phase = "authenticate",
username = %masked_username,
"FTPS auth rejected temporary credential"
);
return Err(AuthenticationError::BadUser);
}
// Constant-time secret comparison to prevent timing side-channel
// attacks. Same primitive used by the SFTP handler and rustfs/src/auth.rs.
let secret_matches: bool = identity
+14 -1
View File
@@ -34,7 +34,7 @@ use super::lifecycle::{SessionDiag, SessionRegistry, new_session_registry};
#[cfg(target_os = "linux")]
use super::wedge_watchdog;
use crate::common::client::s3::StorageBackend;
use crate::common::session::{Protocol, ProtocolPrincipal, SessionContext};
use crate::common::session::{Protocol, ProtocolPrincipal, SessionContext, is_temporary_credential};
use russh::keys::{self, PrivateKey, PublicKeyBase64};
use russh::server::{Auth, ChannelOpenHandle, Msg, Session};
use russh::{Channel, ChannelId, ChannelOpenFailure, MethodKind, MethodSet, Pty, Sig};
@@ -1101,6 +1101,19 @@ impl<S: StorageBackend + Send + Sync + 'static> russh::server::Handler for SshSe
return Ok(Auth::reject());
}
if is_temporary_credential(&identity.credentials) {
warn!(
event = EVENT_SFTP_AUTH_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_SFTP_AUTH,
result = "temporary_credential_rejected",
user = %masked_user,
peer = %peer_addr,
"sftp auth state changed"
);
return Ok(Auth::reject());
}
// Constant-time secret comparison to prevent timing side-channel
// attacks. Same primitive used by rustfs/src/auth.rs.
use subtle::ConstantTimeEq;
+81 -32
View File
@@ -27,6 +27,9 @@ use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::Cursor;
/// Maximum accepted size of an SLO manifest document
const MAX_SLO_MANIFEST_SIZE: usize = 2 * 1024 * 1024;
/// SLO manifest segment descriptor
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SLOSegment {
@@ -274,14 +277,14 @@ pub async fn handle_slo_put(
.map_err(|e| SwiftError::BadRequest(format!("Failed to read manifest: {}", e)))?
.to_bytes();
// 2. Parse manifest
let manifest = SLOManifest::from_json(&manifest_bytes)?;
// 3. Validate manifest size (2MB limit)
if manifest_bytes.len() > 2 * 1024 * 1024 {
// 2. Validate manifest size (2MB limit)
if manifest_bytes.len() > MAX_SLO_MANIFEST_SIZE {
return Err(SwiftError::BadRequest("Manifest exceeds 2MB".to_string()));
}
// 3. Parse manifest
let manifest = SLOManifest::from_json(&manifest_bytes)?;
// 4. Validate segments exist and match ETags/sizes
manifest.validate(account, creds).await?;
@@ -326,6 +329,30 @@ pub async fn handle_slo_put(
.map_err(|e| SwiftError::InternalServerError(format!("Failed to build response: {}", e)))
}
/// Read a stored SLO manifest without buffering more than [`MAX_SLO_MANIFEST_SIZE`].
///
/// The manifest lives at a caller-predictable `<object>.slo-manifest` key, so its content
/// is attacker-controlled: the read must be bounded rather than sized by the stored object.
async fn read_manifest_bytes<R>(reader: R) -> Result<Vec<u8>, SwiftError>
where
R: tokio::io::AsyncRead + Unpin,
{
use tokio::io::AsyncReadExt;
let mut manifest_bytes = Vec::new();
reader
.take(MAX_SLO_MANIFEST_SIZE as u64 + 1)
.read_to_end(&mut manifest_bytes)
.await
.map_err(|e| SwiftError::InternalServerError(format!("Failed to read manifest: {}", e)))?;
if manifest_bytes.len() > MAX_SLO_MANIFEST_SIZE {
return Err(SwiftError::BadRequest("Manifest exceeds 2MB".to_string()));
}
Ok(manifest_bytes)
}
/// Handle GET /v1/{account}/{container}/{object} for SLO
pub async fn handle_slo_get(
account: &str,
@@ -341,16 +368,9 @@ pub async fn handle_slo_get(
// 1. Load manifest
let manifest_key = format!("{}.slo-manifest", object);
let mut manifest_reader = object::get_object(account, container, &manifest_key, creds, None).await?;
let manifest_reader = object::get_object(account, container, &manifest_key, creds, None).await?;
// Read manifest bytes
let mut manifest_bytes = Vec::new();
use tokio::io::AsyncReadExt;
manifest_reader
.stream
.read_to_end(&mut manifest_bytes)
.await
.map_err(|e| SwiftError::InternalServerError(format!("Failed to read manifest: {}", e)))?;
let manifest_bytes = read_manifest_bytes(manifest_reader.stream).await?;
let manifest = SLOManifest::from_json(&manifest_bytes)?;
@@ -472,16 +492,9 @@ pub async fn handle_slo_get_manifest(
// Load and return the manifest JSON directly
let manifest_key = format!("{}.slo-manifest", object);
let mut manifest_reader = object::get_object(account, container, &manifest_key, creds, None).await?;
let manifest_reader = object::get_object(account, container, &manifest_key, creds, None).await?;
// Read manifest bytes
let mut manifest_bytes = Vec::new();
use tokio::io::AsyncReadExt;
manifest_reader
.stream
.read_to_end(&mut manifest_bytes)
.await
.map_err(|e| SwiftError::InternalServerError(format!("Failed to read manifest: {}", e)))?;
let manifest_bytes = read_manifest_bytes(manifest_reader.stream).await?;
let trans_id = generate_trans_id();
Response::builder()
@@ -508,16 +521,9 @@ pub async fn handle_slo_delete(
// 1. Load manifest
let manifest_key = format!("{}.slo-manifest", object);
let mut manifest_reader = object::get_object(account, container, &manifest_key, creds, None).await?;
let manifest_reader = object::get_object(account, container, &manifest_key, creds, None).await?;
// Read manifest bytes
let mut manifest_bytes = Vec::new();
use tokio::io::AsyncReadExt;
manifest_reader
.stream
.read_to_end(&mut manifest_bytes)
.await
.map_err(|e| SwiftError::InternalServerError(format!("Failed to read manifest: {}", e)))?;
let manifest_bytes = read_manifest_bytes(manifest_reader.stream).await?;
let manifest = SLOManifest::from_json(&manifest_bytes)?;
@@ -971,4 +977,47 @@ mod tests {
// Empty path
assert!(parse_segment_path("").is_err());
}
#[tokio::test]
async fn test_read_manifest_bytes_accepts_manifest_at_size_limit() {
let source = std::io::Cursor::new(vec![b'x'; MAX_SLO_MANIFEST_SIZE]);
let bytes = read_manifest_bytes(source).await.expect("manifest at the limit is accepted");
assert_eq!(bytes.len(), MAX_SLO_MANIFEST_SIZE);
}
#[tokio::test]
async fn test_read_manifest_bytes_rejects_oversized_manifest() {
let source = std::io::Cursor::new(vec![b'x'; MAX_SLO_MANIFEST_SIZE + 1]);
let result = read_manifest_bytes(source).await.map(|bytes| bytes.len());
assert!(
matches!(result, Err(SwiftError::BadRequest(_))),
"manifest above the limit must be rejected, got {:?}",
result
);
}
/// A stored manifest is attacker-controlled, so the read must stop at the limit
/// instead of buffering the whole object.
#[tokio::test]
async fn test_read_manifest_bytes_stops_reading_oversized_manifest() {
use tokio::io::AsyncReadExt;
let total = 32 * 1024 * 1024u64;
let mut source = tokio::io::repeat(b'x').take(total);
let result = read_manifest_bytes(&mut source).await.map(|bytes| bytes.len());
assert!(
matches!(result, Err(SwiftError::BadRequest(_))),
"oversized manifest must be rejected, got {:?}",
result
);
let consumed = total - source.limit();
assert!(
consumed <= MAX_SLO_MANIFEST_SIZE as u64 + 1,
"read {} bytes, expected at most {}",
consumed,
MAX_SLO_MANIFEST_SIZE + 1
);
}
}
+1
View File
@@ -59,6 +59,7 @@ Configure WebDAV via environment variables:
| `RUSTFS_WEBDAV_CA_FILE` | CA file for client verification | - |
| `RUSTFS_WEBDAV_MAX_BODY_SIZE` | Max upload size (bytes) | 5GB |
| `RUSTFS_WEBDAV_REQUEST_TIMEOUT` | Request timeout (seconds) | 300 |
| `RUSTFS_WEBDAV_MAX_CONNECTIONS` | Max concurrently served connections | 1024 |
## Quick Start
+12
View File
@@ -44,6 +44,8 @@ pub struct WebDavConfig {
pub max_body_size: u64,
/// Request timeout in seconds (default: 300)
pub request_timeout_secs: u64,
/// Maximum number of connections served concurrently (default: 1024)
pub max_connections: usize,
}
impl WebDavConfig {
@@ -51,6 +53,8 @@ impl WebDavConfig {
pub const DEFAULT_MAX_BODY_SIZE: u64 = 5 * 1024 * 1024 * 1024;
/// Default request timeout (300 seconds)
pub const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 300;
/// Default concurrent connection cap
pub const DEFAULT_MAX_CONNECTIONS: usize = 1024;
/// Validates the configuration
pub async fn validate(&self) -> Result<(), WebDavInitError> {
@@ -84,6 +88,13 @@ impl WebDavConfig {
return Err(WebDavInitError::InvalidConfig("request_timeout_secs cannot be zero".to_string()));
}
// Validate connection cap. Zero is rejected rather than treated as
// "unlimited": an unbounded accept loop is the resource-exhaustion
// hole this cap exists to close.
if self.max_connections == 0 {
return Err(WebDavInitError::InvalidConfig("max_connections cannot be zero".to_string()));
}
Ok(())
}
}
@@ -98,6 +109,7 @@ impl Default for WebDavConfig {
ca_file: None,
max_body_size: Self::DEFAULT_MAX_BODY_SIZE,
request_timeout_secs: Self::DEFAULT_REQUEST_TIMEOUT_SECS,
max_connections: Self::DEFAULT_MAX_CONNECTIONS,
}
}
}
+115 -5
View File
@@ -1000,6 +1000,13 @@ where
/// Recursively delete all objects in a bucket, then delete the bucket itself
async fn delete_bucket_recursively(&self, bucket: &str) -> FsResult<()> {
// SECURITY: s3:DeleteBucket does not imply the right to destroy the
// bucket contents. Enumerating and deleting each object are separate
// authorization boundaries and must be cleared on their own.
authorize_operation(&self.session_context, &S3Action::ListBucket, bucket, None)
.await
.map_err(|_| FsError::Forbidden)?;
// First, delete all objects in the bucket (with pagination)
let mut continuation_token = None;
loop {
@@ -1024,6 +1031,10 @@ where
if let Some(objects) = output.contents {
for obj in objects {
if let Some(obj_key) = obj.key {
authorize_operation(&self.session_context, &S3Action::DeleteObject, bucket, Some(&obj_key))
.await
.map_err(|_| FsError::Forbidden)?;
let _ = self
.storage
.delete_object(
@@ -1370,6 +1381,14 @@ where
.await
.map_err(|_| FsError::Forbidden)?;
// SECURITY: clearing s3:DeleteObject on the directory marker key
// says nothing about the children stored under it. Enumerating the
// prefix and deleting each child are separate authorization
// boundaries and must be cleared on their own.
authorize_operation(&self.session_context, &S3Action::ListBucket, &bucket, Some(&prefix_with_slash))
.await
.map_err(|_| FsError::Forbidden)?;
// List and delete all objects with this prefix
let mut continuation_token = None;
loop {
@@ -1395,6 +1414,10 @@ where
if let Some(objects) = output.contents {
for obj in objects {
if let Some(obj_key) = obj.key {
authorize_operation(&self.session_context, &S3Action::DeleteObject, &bucket, Some(&obj_key))
.await
.map_err(|_| FsError::Forbidden)?;
let _ = self
.storage
.delete_object(
@@ -1692,11 +1715,12 @@ where
mod tests {
use super::WebDavDriver;
use crate::common::client::s3::StorageBackend as S3StorageBackend;
use crate::common::gateway::{S3Action, with_test_auth_override};
use crate::common::session::{Protocol, ProtocolPrincipal, SessionContext};
use async_trait::async_trait;
use bytes::Bytes;
use dav_server::davpath::DavPath;
use dav_server::fs::FsError;
use dav_server::fs::{DavFileSystem, FsError};
use futures_util::StreamExt;
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
use rustfs_credentials::Credentials;
@@ -1887,6 +1911,7 @@ mod tests {
objects: HashMap<(String, String), Vec<u8>>,
put_keys: Vec<String>,
delete_keys: Vec<String>,
deleted_buckets: Vec<String>,
fail_delete_keys: HashSet<String>,
}
@@ -2006,11 +2031,34 @@ mod tests {
async fn list_objects_v2(
&self,
_input: ListObjectsV2Input,
input: ListObjectsV2Input,
_access_key: &str,
_secret_key: &str,
) -> Result<ListObjectsV2Output, Self::Error> {
unreachable!("list_objects_v2 is not used in rename regression tests")
let prefix = input.prefix.map(|p| p.to_string()).unwrap_or_default();
let mut keys: Vec<String> = self
.state
.lock()
.expect("recording storage lock poisoned")
.objects
.keys()
.filter(|(bucket, key)| *bucket == input.bucket && key.starts_with(&prefix))
.map(|(_, key)| key.clone())
.collect();
keys.sort();
Ok(ListObjectsV2Output {
contents: Some(
keys.into_iter()
.map(|key| Object {
key: Some(ObjectKey::from(key)),
..Default::default()
})
.collect(),
),
is_truncated: Some(false),
..Default::default()
})
}
async fn list_buckets(&self, _access_key: &str, _secret_key: &str) -> Result<ListBucketsOutput, Self::Error> {
@@ -2028,11 +2076,16 @@ mod tests {
async fn delete_bucket(
&self,
_bucket: &str,
bucket: &str,
_access_key: &str,
_secret_key: &str,
) -> Result<DeleteBucketOutput, Self::Error> {
unreachable!("delete_bucket is not used in rename regression tests")
self.state
.lock()
.expect("recording storage lock poisoned")
.deleted_buckets
.push(bucket.to_string());
Ok(DeleteBucketOutput::default())
}
async fn copy_object(
@@ -2248,6 +2301,63 @@ mod tests {
}
}
/// A bucket DELETE wipes every object in the bucket, so `s3:DeleteBucket`
/// alone must not be enough: each object needs its own `s3:DeleteObject`
/// boundary. The backend would happily complete the whole recursive delete
/// if the per-object check were removed again.
#[tokio::test]
async fn bucket_delete_denied_per_object_leaves_contents_and_bucket_intact() {
let (driver, storage) = recording_driver(&[("bucket", "secret.txt", b"secret")], &[]);
let path = DavPath::new("/bucket/").expect("path should parse");
let err = with_test_auth_override(
|action, _bucket, _object| !matches!(action, S3Action::DeleteObject),
driver.remove_dir(&path),
)
.await
.expect_err("bucket DELETE must fail closed when s3:DeleteObject is denied for a bucket member");
assert_eq!(err, FsError::Forbidden);
let state = storage.state.lock().expect("recording storage lock poisoned");
assert!(state.delete_keys.is_empty(), "no object may be deleted once the deny lands");
assert!(
state.deleted_buckets.is_empty(),
"the bucket must survive when its contents could not be authorized for deletion"
);
assert!(state.objects.contains_key(&("bucket".to_string(), "secret.txt".to_string())));
}
/// A directory DELETE authorizes the `dir/` marker key, but the children
/// stored under that prefix are separate resources and each needs its own
/// `s3:DeleteObject` boundary.
#[tokio::test]
async fn directory_delete_denied_for_child_leaves_child_intact() {
let (driver, storage) = recording_driver(&[("bucket", "dir/child.txt", b"child")], &[]);
let path = DavPath::new("/bucket/dir/").expect("path should parse");
let err = with_test_auth_override(
|action, _bucket, object| !matches!((action, object), (S3Action::DeleteObject, Some("dir/child.txt"))),
driver.remove_dir(&path),
)
.await
.expect_err("directory DELETE must fail closed when a child object denies s3:DeleteObject");
assert_eq!(err, FsError::Forbidden);
let state = storage.state.lock().expect("recording storage lock poisoned");
assert!(
state.delete_keys.is_empty(),
"the denied child must not be deleted, got {:?}",
state.delete_keys
);
assert!(
state
.objects
.contains_key(&("bucket".to_string(), "dir/child.txt".to_string()))
);
}
#[tokio::test]
async fn directory_rename_returns_error_when_delete_fails_after_successful_copy() {
let (driver, storage) = recording_driver(
+586 -63
View File
@@ -15,26 +15,30 @@
use super::config::{WebDavConfig, WebDavInitError};
use super::driver::WebDavDriver;
use crate::common::client::s3::StorageBackend;
use crate::common::session::{Protocol, ProtocolPrincipal, SessionContext};
use crate::common::session::{Protocol, ProtocolPrincipal, SessionContext, is_temporary_credential};
use bytes::Bytes;
use dav_server::DavHandler;
use dav_server::fakels::FakeLs;
use http_body_util::{BodyExt, Full};
use http_body_util::{BodyExt, Full, LengthLimitError, Limited};
use hyper::body::Body as HttpBody;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use hyper_util::rt::{TokioIo, TokioTimer};
use rustfs_config::{DEFAULT_TLS_RELOAD_ENABLE, DEFAULT_TLS_RELOAD_INTERVAL, ENV_TLS_RELOAD_ENABLE, ENV_TLS_RELOAD_INTERVAL};
use rustfs_tls_runtime::{ReloadableServerCertResolver, TlsReloadOptions, spawn_server_cert_reload_loop};
use rustfs_utils::MaskedAccessKey;
use rustls::ServerConfig;
use std::convert::Infallible;
use std::io;
use std::net::IpAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use subtle::ConstantTimeEq;
use tokio::net::TcpListener;
use tokio::sync::{broadcast, watch};
use tokio::sync::{Semaphore, broadcast, watch};
use tokio::time::timeout;
use tokio_rustls::TlsAcceptor;
use tracing::{Instrument, debug, error, info, info_span, warn};
@@ -47,6 +51,13 @@ const EVENT_WEBDAV_CONNECTION_STATE: &str = "webdav_connection_state";
const EVENT_WEBDAV_REQUEST_VALIDATION_FAILED: &str = "webdav_request_validation_failed";
const EVENT_WEBDAV_REQUEST_BODY_FAILED: &str = "webdav_request_body_failed";
const EVENT_WEBDAV_AUTH_STATE: &str = "webdav_auth_state";
const EVENT_WEBDAV_CONNECTION_CAP_STATE: &str = "webdav_connection_cap_state";
/// Response body handed back to Hyper.
///
/// Boxed instead of collected: buffering the dav-server body would
/// materialise a whole object in memory for every GET.
type WebDavBody = Pin<Box<dyn HttpBody<Data = Bytes, Error = io::Error> + Send>>;
/// WebDAV server implementation
pub struct WebDavServer<S>
@@ -78,7 +89,7 @@ where
}
/// Start the WebDAV server
pub async fn start(&self, mut shutdown_rx: broadcast::Receiver<()>) -> Result<(), WebDavInitError> {
pub async fn start(&self, shutdown_rx: broadcast::Receiver<()>) -> Result<(), WebDavInitError> {
info!(
event = EVENT_WEBDAV_SERVER_STATE,
component = LOG_COMPONENT_PROTOCOLS,
@@ -87,10 +98,16 @@ where
bind_addr = %self.config.bind_addr,
tls_enabled = self.config.tls_enabled,
max_body_size = self.config.max_body_size,
max_connections = self.config.max_connections,
"WebDAV server starting"
);
let listener = TcpListener::bind(self.config.bind_addr).await?;
self.serve(listener, shutdown_rx).await
}
/// Serve connections from an already bound listener
async fn serve(&self, listener: TcpListener, mut shutdown_rx: broadcast::Receiver<()>) -> Result<(), WebDavInitError> {
info!(
event = EVENT_WEBDAV_SERVER_STATE,
component = LOG_COMPONENT_PROTOCOLS,
@@ -135,8 +152,47 @@ where
};
let storage = self.storage.clone();
let request_timeout = Duration::from_secs(self.config.request_timeout_secs);
let connection_limiter = Arc::new(Semaphore::new(self.config.max_connections.min(Semaphore::MAX_PERMITS)));
loop {
// Admission control: hold a permit before accepting, so at
// saturation the kernel backlog absorbs the burst instead of the
// process spawning an unbounded number of connection tasks. The
// permit travels into the task and is released when it ends.
let permit = match connection_limiter.clone().try_acquire_owned() {
Ok(permit) => permit,
Err(_) => {
debug!(
event = EVENT_WEBDAV_CONNECTION_CAP_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_WEBDAV_SERVER,
state = "saturated",
max_connections = self.config.max_connections,
"WebDAV connection cap saturated"
);
tokio::select! {
permit = connection_limiter.clone().acquire_owned() => match permit {
Ok(permit) => permit,
// The semaphore is never closed; fail safe by
// stopping the accept loop if it ever is.
Err(_) => break,
},
_ = shutdown_rx.recv() => {
info!(
event = EVENT_WEBDAV_SERVER_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_WEBDAV_SERVER,
state = "shutdown_requested",
"WebDAV shutdown requested"
);
let _ = reload_shutdown_tx.send(true);
break;
}
}
}
};
tokio::select! {
accept_result = listener.accept() => {
match accept_result {
@@ -153,11 +209,14 @@ where
);
tokio::spawn(
async move {
let _permit = permit;
if let Some(acceptor) = tls_acceptor {
match acceptor.accept(stream).await {
Ok(tls_stream) => {
// A handshake that never completes would otherwise
// hold its connection permit forever.
match timeout(request_timeout, acceptor.accept(stream)).await {
Ok(Ok(tls_stream)) => {
let io = TokioIo::new(tls_stream);
if let Err(e) = Self::handle_connection_impl(io, storage, source_ip, max_body_size).await {
if let Err(e) = Self::handle_connection_impl(io, storage, source_ip, max_body_size, request_timeout).await {
debug!(
event = EVENT_WEBDAV_CONNECTION_STATE,
component = LOG_COMPONENT_PROTOCOLS,
@@ -170,7 +229,7 @@ where
);
}
}
Err(e) => {
Ok(Err(e)) => {
debug!(
event = EVENT_WEBDAV_CONNECTION_STATE,
component = LOG_COMPONENT_PROTOCOLS,
@@ -181,10 +240,21 @@ where
"webdav connection ended with error"
);
}
Err(_) => {
debug!(
event = EVENT_WEBDAV_CONNECTION_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_WEBDAV_SERVER,
result = "tls_handshake_timeout",
peer = %source_ip,
timeout_secs = request_timeout.as_secs(),
"webdav connection ended with error"
);
}
}
} else {
let io = TokioIo::new(stream);
if let Err(e) = Self::handle_connection_impl(io, storage, source_ip, max_body_size).await {
if let Err(e) = Self::handle_connection_impl(io, storage, source_ip, max_body_size, request_timeout).await {
debug!(
event = EVENT_WEBDAV_CONNECTION_STATE,
component = LOG_COMPONENT_PROTOCOLS,
@@ -244,16 +314,24 @@ where
storage: S,
source_ip: IpAddr,
max_body_size: u64,
request_timeout: Duration,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
where
I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
{
let service = service_fn(move |req: Request<hyper::body::Incoming>| {
let storage = storage.clone();
async move { Self::handle_request(req, storage, source_ip, max_body_size).await }
async move { Self::handle_request(req, storage, source_ip, max_body_size, request_timeout).await }
});
http1::Builder::new().serve_connection(io, service).await?;
// A peer that opens a connection and dribbles (or never finishes)
// request headers is disconnected once the configured request
// timeout elapses. The timer is required for the deadline to apply.
http1::Builder::new()
.timer(TokioTimer::new())
.header_read_timeout(request_timeout)
.serve_connection(io, service)
.await?;
Ok(())
}
@@ -264,8 +342,12 @@ where
storage: S,
source_ip: IpAddr,
max_body_size: u64,
) -> Result<Response<Full<Bytes>>, Infallible> {
// Check Content-Length against max_body_size before reading body
request_timeout: Duration,
) -> Result<Response<WebDavBody>, Infallible> {
// Advisory fast path only: a declared Content-Length lets an
// oversized request be rejected before any body is read. The
// authoritative limit is enforced in `dispatch_dav` against the
// bytes actually received, which a chunked request cannot dodge.
if let Some(content_length) = req.headers().get("content-length")
&& let Ok(length_str) = content_length.to_str()
&& let Ok(length) = length_str.parse::<u64>()
@@ -324,49 +406,7 @@ where
.locksystem(FakeLs::new())
.build_handler();
// Convert request body
let (parts, body) = req.into_parts();
let body_bytes = match body.collect().await {
Ok(collected) => collected.to_bytes(),
Err(e) => {
error!(
event = EVENT_WEBDAV_REQUEST_BODY_FAILED,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_WEBDAV_SERVER,
result = "request_body_read_failed",
source_ip = %source_ip,
error = %e,
"webdav request body failed"
);
return Ok(error_response(StatusCode::BAD_REQUEST, "Failed to read request body"));
}
};
// Create request for dav-server using Bytes
let dav_req = Request::from_parts(parts, dav_server::body::Body::from(body_bytes));
// Handle the request
let dav_resp = dav_handler.handle(dav_req).await;
// Convert response
let (parts, body) = dav_resp.into_parts();
let body_bytes = match body.collect().await {
Ok(collected) => collected.to_bytes(),
Err(e) => {
error!(
event = EVENT_WEBDAV_REQUEST_BODY_FAILED,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_WEBDAV_SERVER,
result = "response_body_read_failed",
source_ip = %source_ip,
error = %e,
"webdav request body failed"
);
return Ok(error_response(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error"));
}
};
Ok(Response::from_parts(parts, Full::new(body_bytes)))
Ok(dispatch_dav(req, dav_handler, source_ip, max_body_size, request_timeout).await)
}
/// Authenticate user against IAM system
@@ -442,6 +482,19 @@ where
WebDavInitError::Server("User not found".to_string())
})?;
if is_temporary_credential(&identity.credentials) {
warn!(
event = EVENT_WEBDAV_AUTH_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_WEBDAV_AUTH,
result = "temporary_credential_rejected",
source_ip = %source_ip,
access_key = %masked_access_key,
"WebDAV auth rejected temporary credential"
);
return Err(WebDavInitError::Server("Invalid credentials".to_string()));
}
// Constant-time secret comparison to prevent timing side-channel
// attacks. Same primitive used by the SFTP handler and rustfs/src/auth.rs.
let secret_matches: bool = identity
@@ -491,21 +544,114 @@ where
}
}
/// Read the request body and run it through the dav handler.
///
/// Both limits configured for the listener are enforced here: the body is
/// truncated at `max_body_size` bytes actually received (a chunked upload
/// declares no length, so a header check cannot bound it), and neither the
/// body read nor the dav handler may run past `request_timeout`.
async fn dispatch_dav<B>(
req: Request<B>,
dav_handler: DavHandler,
source_ip: IpAddr,
max_body_size: u64,
request_timeout: Duration,
) -> Response<WebDavBody>
where
B: HttpBody<Data = Bytes> + Send + 'static,
B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
let (parts, body) = req.into_parts();
let limit = usize::try_from(max_body_size).unwrap_or(usize::MAX);
let body_bytes = match timeout(request_timeout, Limited::new(body, limit).collect()).await {
Ok(Ok(collected)) => collected.to_bytes(),
Ok(Err(e)) if e.downcast_ref::<LengthLimitError>().is_some() => {
warn!(
event = EVENT_WEBDAV_REQUEST_VALIDATION_FAILED,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_WEBDAV_SERVER,
result = "payload_too_large",
max_body_size,
source_ip = %source_ip,
"webdav request validation failed"
);
return error_response(
StatusCode::PAYLOAD_TOO_LARGE,
&format!("Request body too large. Maximum size is {} bytes", max_body_size),
);
}
Ok(Err(e)) => {
error!(
event = EVENT_WEBDAV_REQUEST_BODY_FAILED,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_WEBDAV_SERVER,
result = "request_body_read_failed",
source_ip = %source_ip,
error = %e,
"webdav request body failed"
);
return error_response(StatusCode::BAD_REQUEST, "Failed to read request body");
}
Err(_) => {
warn!(
event = EVENT_WEBDAV_REQUEST_VALIDATION_FAILED,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_WEBDAV_SERVER,
result = "request_body_read_timeout",
timeout_secs = request_timeout.as_secs(),
source_ip = %source_ip,
"webdav request validation failed"
);
return error_response(StatusCode::REQUEST_TIMEOUT, "Request timed out");
}
};
// Create request for dav-server using Bytes
let dav_req = Request::from_parts(parts, dav_server::body::Body::from(body_bytes));
let dav_resp = match timeout(request_timeout, dav_handler.handle(dav_req)).await {
Ok(resp) => resp,
Err(_) => {
warn!(
event = EVENT_WEBDAV_REQUEST_VALIDATION_FAILED,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_WEBDAV_SERVER,
result = "request_handling_timeout",
timeout_secs = request_timeout.as_secs(),
source_ip = %source_ip,
"webdav request validation failed"
);
return error_response(StatusCode::REQUEST_TIMEOUT, "Request timed out");
}
};
// Streamed straight to Hyper: collecting here would hold the whole
// object in memory for the duration of a GET.
let (parts, body) = dav_resp.into_parts();
Response::from_parts(parts, Box::pin(body) as WebDavBody)
}
/// Create unauthorized response with WWW-Authenticate header
fn unauthorized_response() -> Response<Full<Bytes>> {
fn unauthorized_response() -> Response<WebDavBody> {
Response::builder()
.status(StatusCode::UNAUTHORIZED)
.header("WWW-Authenticate", "Basic realm=\"RustFS WebDAV\"")
.body(Full::new(Bytes::from("Unauthorized")))
.unwrap_or_else(|_| Response::new(Full::new(Bytes::from("Unauthorized"))))
.body(fixed_body("Unauthorized"))
.unwrap_or_else(|_| Response::new(fixed_body("Unauthorized")))
}
/// Create error response
fn error_response(status: StatusCode, message: &str) -> Response<Full<Bytes>> {
fn error_response(status: StatusCode, message: &str) -> Response<WebDavBody> {
Response::builder()
.status(status)
.body(Full::new(Bytes::from(message.to_string())))
.unwrap_or_else(|_| Response::new(Full::new(Bytes::from("Internal Server Error"))))
.body(fixed_body(message.to_string()))
.unwrap_or_else(|_| Response::new(fixed_body("Internal Server Error")))
}
/// Wrap a fixed byte payload in the streaming response body type
fn fixed_body(message: impl Into<Bytes>) -> WebDavBody {
Box::pin(Full::new(message.into()).map_err(|never| match never {}))
}
/// Decode base64 string
@@ -513,3 +659,380 @@ fn base64_decode(encoded: &str) -> Result<Vec<u8>, ()> {
use base64::Engine;
base64::engine::general_purpose::STANDARD.decode(encoded).map_err(|_| ())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::client::s3::StorageBackend;
use async_trait::async_trait;
use dav_server::memfs::MemFs;
use futures_util::stream;
use http_body_util::StreamBody;
use hyper::body::Frame;
use s3s::dto::*;
use std::fmt::{Debug, Formatter};
use std::net::{Ipv4Addr, SocketAddr};
use std::task::{Context, Poll};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
const TEST_IP: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
/// Storage double for the connection-level tests. Those requests are
/// rejected before authentication succeeds, so storage is never reached.
#[derive(Clone)]
struct StubStorage;
impl Debug for StubStorage {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str("StubStorage")
}
}
#[async_trait]
impl StorageBackend for StubStorage {
type Error = std::io::Error;
async fn get_object(
&self,
_bucket: &str,
_key: &str,
_access_key: &str,
_secret_key: &str,
_start_pos: Option<u64>,
) -> Result<GetObjectOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn get_object_range(
&self,
_bucket: &str,
_key: &str,
_access_key: &str,
_secret_key: &str,
_start_pos: u64,
_length: u64,
) -> Result<GetObjectOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn put_object(
&self,
_input: PutObjectInput,
_access_key: &str,
_secret_key: &str,
) -> Result<PutObjectOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn delete_object(
&self,
_bucket: &str,
_key: &str,
_access_key: &str,
_secret_key: &str,
) -> Result<DeleteObjectOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn head_object(
&self,
_bucket: &str,
_key: &str,
_access_key: &str,
_secret_key: &str,
) -> Result<HeadObjectOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn head_bucket(
&self,
_bucket: &str,
_access_key: &str,
_secret_key: &str,
) -> Result<HeadBucketOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn list_objects_v2(
&self,
_input: ListObjectsV2Input,
_access_key: &str,
_secret_key: &str,
) -> Result<ListObjectsV2Output, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn list_buckets(&self, _access_key: &str, _secret_key: &str) -> Result<ListBucketsOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn create_bucket(
&self,
_bucket: &str,
_access_key: &str,
_secret_key: &str,
) -> Result<CreateBucketOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn delete_bucket(
&self,
_bucket: &str,
_access_key: &str,
_secret_key: &str,
) -> Result<DeleteBucketOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn copy_object(
&self,
_input: CopyObjectInput,
_access_key: &str,
_secret_key: &str,
) -> Result<CopyObjectOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn create_multipart_upload(
&self,
_input: CreateMultipartUploadInput,
_access_key: &str,
_secret_key: &str,
) -> Result<CreateMultipartUploadOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn upload_part(
&self,
_input: UploadPartInput,
_access_key: &str,
_secret_key: &str,
) -> Result<UploadPartOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn complete_multipart_upload(
&self,
_input: CompleteMultipartUploadInput,
_access_key: &str,
_secret_key: &str,
) -> Result<CompleteMultipartUploadOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn abort_multipart_upload(
&self,
_input: AbortMultipartUploadInput,
_access_key: &str,
_secret_key: &str,
) -> Result<AbortMultipartUploadOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
async fn upload_part_copy(
&self,
_input: UploadPartCopyInput,
_access_key: &str,
_secret_key: &str,
) -> Result<UploadPartCopyOutput, Self::Error> {
unreachable!("connection tests should not hit storage")
}
}
/// Request body that never produces a frame, standing in for a peer that
/// opens a chunked upload and then stalls.
struct StalledBody;
impl HttpBody for StalledBody {
type Data = Bytes;
type Error = io::Error;
fn poll_frame(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Result<Frame<Bytes>, io::Error>>> {
Poll::Pending
}
}
fn memfs_handler() -> DavHandler {
DavHandler::builder()
.filesystem(MemFs::new())
.locksystem(FakeLs::new())
.build_handler()
}
/// Chunked upload: no Content-Length header, `chunks` frames of `chunk_len` bytes.
fn chunked_request(
chunks: usize,
chunk_len: usize,
) -> Request<StreamBody<impl stream::Stream<Item = io::Result<Frame<Bytes>>>>> {
let frames: Vec<io::Result<Frame<Bytes>>> = (0..chunks)
.map(|_| Ok(Frame::data(Bytes::from(vec![b'a'; chunk_len]))))
.collect();
Request::builder()
.method("PUT")
.uri("/upload.bin")
.body(StreamBody::new(stream::iter(frames)))
.expect("build chunked request")
}
fn get_request(uri: &str) -> Request<Full<Bytes>> {
Request::builder()
.method("GET")
.uri(uri)
.body(Full::new(Bytes::new()))
.expect("build get request")
}
/// R03-CAN-051 / R03-CAN-067 / R05-CAN-094: a chunked upload declares no
/// Content-Length, so the limit has to hold on the bytes actually read.
#[tokio::test]
async fn chunked_upload_over_max_body_size_is_rejected() {
let handler = memfs_handler();
let resp = dispatch_dav(chunked_request(8, 8), handler.clone(), TEST_IP, 16, Duration::from_secs(30)).await;
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
// The oversized body must not have reached the filesystem.
let stored = dispatch_dav(get_request("/upload.bin"), handler, TEST_IP, 16, Duration::from_secs(30)).await;
assert_eq!(stored.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn chunked_upload_within_max_body_size_is_accepted() {
let handler = memfs_handler();
let resp = dispatch_dav(chunked_request(2, 4), handler.clone(), TEST_IP, 16, Duration::from_secs(30)).await;
assert_eq!(resp.status(), StatusCode::CREATED);
let stored = dispatch_dav(get_request("/upload.bin"), handler, TEST_IP, 16, Duration::from_secs(30)).await;
assert_eq!(stored.status(), StatusCode::OK);
let bytes = stored.into_body().collect().await.expect("collect body").to_bytes();
assert_eq!(bytes.len(), 8);
}
/// R04-CAN-089 / R05-CAN-094: a request whose body never arrives must be
/// cut off at the configured request timeout.
#[tokio::test(start_paused = true)]
async fn stalled_request_body_hits_request_timeout() {
let req = Request::builder()
.method("PUT")
.uri("/stalled.bin")
.body(StalledBody)
.expect("build stalled request");
let resp = timeout(
Duration::from_secs(600),
dispatch_dav(req, memfs_handler(), TEST_IP, 1024, Duration::from_secs(30)),
)
.await
.expect("stalled body was never cut off by the configured request timeout");
assert_eq!(resp.status(), StatusCode::REQUEST_TIMEOUT);
}
/// R03-CAN-052: the object body must reach Hyper as a stream. A collected
/// body reports an exact size hint; a streamed one does not.
#[tokio::test]
async fn get_response_body_is_streamed_not_buffered() {
let handler = memfs_handler();
let put = dispatch_dav(chunked_request(4, 4), handler.clone(), TEST_IP, 1024, Duration::from_secs(30)).await;
assert_eq!(put.status(), StatusCode::CREATED);
let resp = dispatch_dav(get_request("/upload.bin"), handler, TEST_IP, 1024, Duration::from_secs(30)).await;
assert_eq!(resp.status(), StatusCode::OK);
assert!(
resp.body().size_hint().upper().is_none(),
"response body was collected into memory instead of streamed"
);
let bytes = resp.into_body().collect().await.expect("collect body").to_bytes();
assert_eq!(bytes.len(), 16);
}
/// R04-CAN-089: a peer that opens a connection and never finishes its
/// request headers must be disconnected at the configured timeout.
#[tokio::test(start_paused = true)]
async fn slow_request_headers_hit_request_timeout() {
let (mut client, server) = tokio::io::duplex(1024);
let conn = tokio::spawn(WebDavServer::<StubStorage>::handle_connection_impl(
TokioIo::new(server),
StubStorage,
TEST_IP,
1024,
Duration::from_secs(30),
));
client
.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n")
.await
.expect("write partial headers");
let outcome = timeout(Duration::from_secs(600), conn).await;
assert!(outcome.is_ok(), "connection outlived the configured request timeout");
}
/// R05-CAN-097: the accept loop must not serve more connections at once
/// than the configured cap.
#[tokio::test]
async fn accept_loop_is_bounded_by_max_connections() {
let config = WebDavConfig {
bind_addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
tls_enabled: false,
cert_dir: None,
ca_file: None,
max_body_size: 1024,
request_timeout_secs: 30,
max_connections: 1,
};
let server = WebDavServer::new(config, StubStorage).await.expect("build server");
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.expect("bind listener");
let addr = listener.local_addr().expect("listener addr");
let (shutdown_tx, shutdown_rx) = broadcast::channel(1);
let serving = tokio::spawn(async move { server.serve(listener, shutdown_rx).await });
// The first client occupies the single permit; keep-alive holds it
// after the response.
let mut first = TcpStream::connect(addr).await.expect("connect first");
first
.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")
.await
.expect("write first");
let mut buf = [0u8; 64];
let read = first.read(&mut buf).await.expect("read first");
assert!(read > 0, "first connection was not served");
// The second client lands in the backlog and must not be served.
let mut second = TcpStream::connect(addr).await.expect("connect second");
second
.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")
.await
.expect("write second");
let blocked = timeout(Duration::from_millis(500), second.read(&mut buf)).await;
assert!(blocked.is_err(), "second connection was served while the cap was saturated");
// Releasing the first permit admits the queued connection.
drop(first);
let served = timeout(Duration::from_secs(10), second.read(&mut buf))
.await
.expect("second connection was never served")
.expect("read second");
assert!(served > 0, "second connection returned no data");
let _ = shutdown_tx.send(());
let _ = timeout(Duration::from_secs(10), serving).await;
}
#[tokio::test]
async fn config_rejects_zero_max_connections() {
let config = WebDavConfig {
tls_enabled: false,
max_connections: 0,
..WebDavConfig::default()
};
let err = config.validate().await.expect_err("zero max_connections must be rejected");
assert!(matches!(err, WebDavInitError::InvalidConfig(_)), "unexpected error: {err}");
}
}