0.34.6_repo_cleanup

This commit is contained in:
Mateusz Gruszczyński committed 2026-10-22 09:31:15 +02:00
1 parent ce1a90397c
commit 133d2f0f91
273 files changed
+5969 -6926

No files matched your search

-2
View File
@@ -7,9 +7,7 @@ fn default_error_fallback_statuses() -> Vec<u16> {
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct ErrorFallback {
/// Stable ID of an internal Custom Location within the same vhost.
pub target: String,
/// HTTP statuses intercepted before normal response finalization/cache publication.
#[serde(default = "default_error_fallback_statuses")]
pub statuses: Vec<u16>,
}
-70
View File
@@ -23,13 +23,9 @@ pub const DEFAULT_PROXY_SEND_TIMEOUT_SECONDS: u64 = 60;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ProxyTimeouts {
/// TCP/TLS connect timeout for each backend connection. Explicit null inherits the runtime default.
pub connect_timeout_seconds: Option<u64>,
/// Deadline until upstream response headers arrive. Explicit null inherits the process startup value.
pub response_header_timeout_seconds: Option<u64>,
/// Maximum idle gap while reading the upstream response body. Explicit null inherits the process startup value.
pub read_timeout_seconds: Option<u64>,
/// Maximum idle gap while streaming the client request body upstream. Explicit null inherits the process startup value.
pub send_timeout_seconds: Option<u64>,
}
impl Default for ProxyTimeouts {
@@ -91,18 +87,13 @@ impl MethodPolicy {
.flatten()
}
}
/// Per-vhost request Content-Type filtering. This inspects only headers and
/// deliberately never reads the body before deciding whether to reject it.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(default, deny_unknown_fields)]
pub struct ContentTypePolicy {
pub enabled: bool,
/// Exact media types (`multipart/form-data`) or type families (`image/*`).
pub blocked: Vec<String>,
}
/// MIME media type tokens use the HTTP tchar alphabet, excluding `*` here;
/// `type/*` is the only accepted wildcard form in configured patterns.
fn mime_token(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 127
@@ -141,10 +132,6 @@ impl ContentTypePolicy {
Ok(())
}
/// Reject matching media types before body parsing, upstream routing, and cache lookup.
/// Multiple or malformed Content-Type values are ambiguous, so reject them
/// when filtering is enabled rather than let the backend interpret them differently.
/// An absent Content-Type header is not matched (the policy is not a body WAF).
pub fn blocks(&self, headers: &http::HeaderMap) -> bool {
if !self.enabled {
return false;
@@ -159,8 +146,6 @@ impl ContentTypePolicy {
let Ok(raw) = raw.to_str() else {
return true;
};
// A comma outside a quoted parameter indicates a combined/ambiguous
// header. RFC MIME parameters may legitimately contain quoted commas.
let mut quoted = false;
let mut escaped = false;
for byte in raw.bytes() {
@@ -237,7 +222,6 @@ impl ProxyTimeouts {
pub enum PathMatch {
#[default]
Prefix,
/// Nginx-style ^~ prefix: an exact/longest prefix match skips regex routes.
PrefixPriority,
Exact,
Regex,
@@ -317,41 +301,28 @@ impl Source {
pub struct Vhost {
#[serde(default = "yes")]
pub websockets: bool,
/// Opt-in compatibility for legacy WebSocket origins. This affects only
/// WebSocket upstream handshakes and leaves ordinary HTTP unchanged.
#[serde(default)]
pub websocket_legacy_support: bool,
/// RFC 8441 WebSocket Extended CONNECT over HTTP/2.
#[serde(default)]
pub websocket_rfc8441: bool,
/// Experimental RFC 9220 WebSocket Extended CONNECT over HTTP/3.
/// Classic HTTP/1.1 Upgrade remains the default WebSocket transport.
#[serde(default)]
pub websocket_rfc9220: bool,
/// Per-vhost HTTP/2 opt-out. TLS listeners may still advertise h2 for other vhosts.
#[serde(default = "yes")]
pub http2_enabled: bool,
/// Per-vhost QUIC opt-out. Shared UDP listeners may remain active for other vhosts.
#[serde(default = "yes")]
pub http3_enabled: bool,
/// Trust Cloudflare client IP/country headers only when the immediate peer is a Cloudflare edge address.
#[serde(default)]
pub cloudflare_client_ip: bool,
/// Emit proxy-owned Server-Timing diagnostics for this vhost.
#[serde(default)]
pub timing_headers: bool,
/// Expose the selected backend ID in X-RustProxy-Backend. Opt-in because it reveals topology.
#[serde(default)]
pub backend_header: bool,
/// Expose upstream response-header latency in X-RustProxy-Backend-Time.
#[serde(default)]
pub backend_timing_header: bool,
#[serde(default)]
pub rate_limit: crate::rate_limit::Settings,
/// Optional allow/block policy for HTTP methods. Vhost and location policies stack.
#[serde(default)]
pub method_policy: MethodPolicy,
/// Optional request Content-Type denylist (normal vhosts only in the panel).
#[serde(default)]
pub content_type_policy: ContentTypePolicy,
#[serde(default)]
@@ -359,18 +330,12 @@ pub struct Vhost {
pub id: String,
#[serde(default = "yes")]
pub enabled: bool,
/// Redirect cleartext requests for this vhost to the selected HTTPS frontend.
#[serde(default)]
pub force_ssl: bool,
/// Redirect the www/non-www companion to a selected exact hostname.
#[serde(default)]
pub www_redirect: bool,
/// Canonical hostname for the quick www redirect. None preserves the legacy
/// first-hostname behavior. Other vhost hostnames remain independent aliases.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub www_redirect_target: Option<String>,
/// Forward the effective client IP to the application using Forwarded/X-Forwarded-For/X-Real-IP.
/// Disable only for applications that must see the RustProxy transport peer instead.
#[serde(default = "yes")]
pub forward_client_ip: bool,
pub frontend: Frontend,
@@ -382,11 +347,8 @@ pub struct Vhost {
pub tinyauth: crate::tinyauth::Settings,
#[serde(default)]
pub certificate_id: Option<String>,
/// Explicitly accept serving an SNI name with a certificate that does not
/// contain it in DNS SAN. Clients will still report a TLS name mismatch.
#[serde(default)]
pub allow_certificate_mismatch: bool,
/// Optional protocol/cipher override. None inherits the global TLS policy.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tls_policy: Option<crate::tls::ProtocolPolicy>,
#[serde(default)]
@@ -397,10 +359,8 @@ pub struct Vhost {
pub transform: crate::transform::Overrides,
#[serde(default)]
pub pages: crate::pages::VhostPages,
/// Main source for the vhost fallback. Missing in older configs means Reverse Proxy.
#[serde(default)]
pub source: Source,
/// Nginx-style internal error_page/proxy_intercept_errors behavior for the main source.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error_fallback: Option<ErrorFallback>,
#[serde(default)]
@@ -409,11 +369,8 @@ pub struct Vhost {
pub load_balancing: crate::balance::Settings,
#[serde(default)]
pub routes: Vec<PathRoute>,
/// Optional reusable ACL profile. The profile and the inline ACL are both enforced.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub acl_profile_id: Option<String>,
/// Additional reusable profiles. Explicit denies outrank all allows across
/// selected profiles. Inline ACL remains an independent restriction.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub acl_profile_ids: Vec<String>,
#[serde(default)]
@@ -423,10 +380,8 @@ pub struct Vhost {
#[serde(default)]
pub security_headers: SecurityHeaders,
#[serde(default)] pub user_agent_blocking: crate::user_agent::Policy,
/// Nginx-style upstream timeout controls. Empty values inherit process defaults.
#[serde(default)]
pub proxy_timeouts: ProxyTimeouts,
/// Runtime-only marker for a published Docker vhost whose service currently has no route target.
#[serde(skip)]
pub(crate) transient_unavailable: bool,
}
@@ -440,19 +395,13 @@ pub struct Frontend {
pub struct Listener {
pub address: SocketAddr,
pub tls: bool,
/// Enabling HTTP/2 never disables the HTTP/1.1 ALPN fallback.
pub http2: bool,
/// Per-listener HTTP/2 lifecycle limits. Missing values inherit the legacy
/// global defaults for backward-compatible configuration loading.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub http2_settings: Option<crate::settings::Http2Connections>,
/// Cleartext HTTP/2 support using the HTTP/2 prior-knowledge preface.
#[serde(default)]
pub h2c: bool,
pub http3: Option<crate::http3::Settings>,
}
// Missing H3 means the secure default; explicit null remains a persisted opt-out.
// Do not skip null during serialization, or a reload would silently re-enable it.
impl<'de> Deserialize<'de> for Listener {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
@@ -509,7 +458,6 @@ pub struct PoolMember {
pub weight: u16,
#[serde(default = "yes")]
pub enabled: bool,
/// False reserves this origin for path-pinned locations only.
#[serde(default = "yes")]
pub pool_eligible: bool,
#[serde(default)]
@@ -536,12 +484,8 @@ pub struct PoolMember {
pub tls_server_name: Option<String>,
#[serde(default)]
pub tls_verify: bool,
/// Maximum number of complete proxy exchanges assigned to this backend.
/// Zero keeps the historical unlimited behavior.
#[serde(default)]
pub max_concurrent_requests: u32,
/// Maximum time a request may wait for backend capacity when the limit is
/// reached. Zero rejects immediately with 503.
#[serde(default)]
pub queue_timeout_ms: u64,
}
@@ -564,19 +508,13 @@ impl PoolMember {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PathRoute {
/// Source selected for this location. A local return ignores this field.
#[serde(default)]
pub source: Source,
/// None balances over the whole pool. Some pins this path to one healthy
/// member; never fail over a path to an unrelated application.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backend_id: Option<String>,
pub id: String,
/// Internal named location. It is never selected by the public URI matcher and
/// can only be reached through an error fallback from this vhost.
#[serde(default)]
pub internal: bool,
/// Prefix/exact path or a Rust-regex pattern, depending on `match_type`.
#[serde(default = "root")]
pub path_prefix: String,
#[serde(default)]
@@ -585,30 +523,22 @@ pub struct PathRoute {
pub enabled: bool,
#[serde(default)]
pub cache: Option<bool>,
/// Optional reusable ACL profile applied in addition to vhost policy.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub acl_profile_id: Option<String>,
#[serde(default)]
pub acl: Option<Acl>,
/// Location-scoped country allow/block policy, stacked with vhost/profile policy.
#[serde(default)]
pub country_access: crate::rate_limit::CountryAccess,
/// Location-scoped HTTP method allow/block policy, stacked with vhost policy.
#[serde(default)]
pub method_policy: MethodPolicy,
#[serde(default)]
pub headers: HeaderRules,
/// Optional origin-path transformation. Query parameters are preserved.
#[serde(default)]
pub rewrite: PathRewrite,
/// Nginx-style local `return`: when present no backend connection is opened.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub response: Option<LocationResponse>,
/// Local HTTP redirect; mutually exclusive with `response`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub redirect: Option<LocationRedirect>,
/// Intercept selected upstream/Web Server error statuses and internally dispatch
/// the original request to another internal Custom Location.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error_fallback: Option<ErrorFallback>,
}
-4
View File
@@ -1,4 +1,3 @@
// Custom-location redirect model.
fn redirect_status() -> u16 {
302
}
@@ -6,9 +5,6 @@ fn preserve_redirect_query() -> bool {
true
}
/// Local redirect action for a custom location. `rewrite_pattern` is optional;
/// when present it is applied to the normalized request path and supports the
/// Rust regex replacement syntax (`$1`, `${name}`, ...).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LocationRedirect {
+33
View File
@@ -264,3 +264,36 @@ mod default_listener_tests {
}
}
}
mod websocket_protocol_flags_tests {
use super::Vhost;
#[test]
fn rfc8441_vhost_flag_deserializes_explicitly() {
let value = serde_json::json!({
"id": "ws-h2",
"frontend": {"hosts": ["example.test"], "listener_ids": ["http"]},
"backends": [{"id": "origin", "url": "http://127.0.0.1:9000", "allow_private": true}],
"websockets": true,
"websocket_rfc8441": true,
"http2_enabled": true
});
let host: Vhost = serde_json::from_value(value).unwrap();
assert!(host.websockets && host.websocket_rfc8441 && host.http2_enabled);
}
#[test]
fn rfc9220_vhost_flag_deserializes_explicitly() {
let value = serde_json::json!({
"id": "ws-h3",
"frontend": {"hosts": ["example.test"], "listener_ids": ["https"]},
"backends": [{"id": "origin", "url": "http://127.0.0.1:9000", "allow_private": true}],
"websockets": true,
"websocket_rfc9220": true
});
let host: Vhost = serde_json::from_value(value).unwrap();
assert!(host.websockets && host.websocket_rfc9220);
assert!(r#"{"websocket_rfc9220":true}"#.contains("\"websocket_rfc9220\":true"));
}
}
-18
View File
@@ -22,10 +22,6 @@ impl Default for PathRoute {
}
}
impl PathRoute {
/// Older documents persisted the main vhost fallback as a synthetic `root`
/// custom location. 0.16 keeps that fallback separate from user locations;
/// only the untouched synthetic shape is normalized away. A deliberate `/`
/// location with any custom behavior remains a real override.
pub fn is_legacy_main_fallback(&self) -> bool {
self.id == "root"
&& self.path_prefix == "/"
@@ -143,9 +139,6 @@ impl Vhost {
"backend queue_timeout_ms must be 0..60000"
);
}
// The main vhost backend is an unconditional internal fallback in 0.16.
// Normalize the untouched pre-0.16 synthetic root route out of the custom
// location list so adding/removing Custom locations cannot delete fallback.
self.routes.retain(|route| !route.is_legacy_main_fallback());
if let Some(fallback) = &mut self.error_fallback {
fallback.validate()?;
@@ -197,8 +190,6 @@ impl Vhost {
);
}
}
// Reject cycles at configuration time; a runtime depth guard remains as a
// second line of defense for hot-reload/state inconsistencies.
let mut starts = vec![None];
starts.extend(self.routes.iter().filter(|route| route.enabled).map(|route| Some(route.id.as_str())));
for start in starts {
@@ -230,9 +221,6 @@ impl Vhost {
self.proxy_timeouts.validate()?;
self.rate_limit.validate()?;
if let Some(policy) = &self.tls_policy {
// Listener-aware HTTP/3 compatibility is checked during full config
// compilation. A vhost may keep the H3 feature flag enabled while it
// is currently attached only to TCP listeners.
policy.validate()?;
}
if let Some(server) = &self.server_header {
@@ -316,8 +304,6 @@ pub fn validate_listener(listener: Listener) -> Result<()> {
);
Ok(())
}
/// Return the other side of a www/non-www redirect pair. The target and its
/// counterpart must both be routable, even if only one was configured.
fn www_partner(host: &str) -> Result<String> {
if let Some(bare) = host.strip_prefix("www.") {
ensure!(!bare.is_empty() && bare.parse::<std::net::IpAddr>().is_err(),
@@ -340,8 +326,6 @@ impl Vhost {
Ok(canonical)
}
/// Hostnames owned by the vhost at runtime. Both the selected canonical
/// host and its www/non-www partner are claimed, even if one is implicit.
pub fn routing_hosts(&self) -> Result<Vec<String>> {
let mut hosts = self.frontend.hosts.clone();
if !self.www_redirect {
@@ -389,8 +373,6 @@ impl Frontend {
Ok(result)
}
}
/// Consolidate identical / same-family wildcard sockets, but never widen routing
/// permissions. Vhost selection still checks its own unmerged bindings.
pub fn listener_plan(config: &Config, policy: &ValidationPolicy) -> Result<Vec<Listener>> {
let mut candidates: Vec<Listener> = config
.listeners