mirror of
https://github.com/rustfs/rustfs.git
synced 2026-08-26 05:56:50 +00:00
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:
@@ -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
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user