mirror of
https://github.com/telemt/telemt.git
synced 2026-11-22 07:16:38 +03:00
WEB: bounded opt-in wildcard host routing added
This commit is contained in:
@@ -185,12 +185,24 @@ pub(super) fn build_upstream(
|
||||
impl ProxyConfig {
|
||||
/// Compares selected endpoints separately from source-only configuration equality.
|
||||
pub(crate) fn web_decoy_endpoints_equal(&self, other: &Self) -> bool {
|
||||
fn selected(config: &ProxyConfig) -> impl Iterator<Item = (&String, SocketAddr)> {
|
||||
fn selected(config: &ProxyConfig) -> impl Iterator<Item = ((u8, &str), SocketAddr)> {
|
||||
config
|
||||
.web
|
||||
.runtime
|
||||
.iter()
|
||||
.flat_map(|runtime| runtime.vhosts.iter())
|
||||
.flat_map(|runtime| {
|
||||
runtime
|
||||
.vhosts
|
||||
.iter()
|
||||
.map(|(host, vhost)| ((0, host.as_str()), vhost))
|
||||
.chain(
|
||||
runtime
|
||||
.wildcards
|
||||
.iter()
|
||||
.map(|(suffix, vhost)| ((1, suffix.as_str()), vhost)),
|
||||
)
|
||||
.chain(runtime.catch_all.iter().map(|vhost| ((2, "*"), vhost)))
|
||||
})
|
||||
.filter_map(|(host, vhost)| match vhost.decoy.as_ref() {
|
||||
WebRuntimeDecoy::HttpUpstream { addr, .. } => Some((host, *addr)),
|
||||
WebRuntimeDecoy::StaticDirectory(_) => None,
|
||||
|
||||
@@ -357,3 +357,32 @@ async fn grouped_hosts_share_one_resolved_origin_and_endpoint_inventory() {
|
||||
reordered.rebuild_runtime_web().unwrap();
|
||||
assert!(!loaded.config.web_decoy_endpoints_equal(&reordered));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wildcard_dns_only_endpoint_changes_are_visible_without_source_changes() {
|
||||
for selector in ["*.example.com", "*"] {
|
||||
let text = SOURCE
|
||||
.replace("[web]", "[web]\nallow_wildcard_hosts = true")
|
||||
.replace(
|
||||
"host = \"proxy.example.com\"",
|
||||
&format!("host = \"{selector}\""),
|
||||
)
|
||||
+ "\n[web.limits]\nmemory_envelope_bytes = 1610612736\n";
|
||||
let mut snapshots = Vec::new();
|
||||
for addr in ["127.0.0.2:18081", "127.0.0.3:18081"] {
|
||||
let mut parsed = source(&text);
|
||||
prepare(&mut parsed.config, |_, _| {
|
||||
std::future::ready(Ok(vec![addr.parse().unwrap()]))
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
snapshots.push(pipeline::finish(parsed).unwrap().config);
|
||||
}
|
||||
assert_eq!(
|
||||
serde_json::to_value(&snapshots[0]).unwrap(),
|
||||
serde_json::to_value(&snapshots[1]).unwrap()
|
||||
);
|
||||
assert!(!snapshots[0].web_decoy_endpoints_equal(&snapshots[1]));
|
||||
assert!(snapshots[0].web_decoy_endpoints_equal(&snapshots[0]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,127 +35,11 @@ const WEB_CAPABILITY_CONTEXT_V2: &[u8] = b"tdesktop-web-proxy-bridge-v2\n";
|
||||
const WEB_DEBUG_FINGERPRINT_CONTEXT: &[u8] = b"telemt-web-debug-key-fingerprint-v1\0";
|
||||
const MAX_WEB_STATIC_DEPTH: usize = 64;
|
||||
|
||||
/// Builds the immutable WEB routing and decoy snapshot for one generation.
|
||||
pub(super) fn rebuild(config: &mut ProxyConfig) -> Result<()> {
|
||||
let auth = config.runtime_user_auth().ok_or_else(|| {
|
||||
ProxyError::Config("WEB runtime requires the user authentication snapshot".to_string())
|
||||
})?;
|
||||
let mut runtime_vhosts = BTreeMap::new();
|
||||
let mut runtime_profiles = Vec::new();
|
||||
let mut runtime_capabilities = Vec::new();
|
||||
let mut static_files = 0usize;
|
||||
let mut static_bytes = 0usize;
|
||||
|
||||
let carrier_candidates: Arc<[WebCarrier]> = config.web.carrier_candidates().into();
|
||||
for (vhost_idx, vhost) in config.web.vhosts.iter().enumerate() {
|
||||
let decoy = Arc::new(build_decoy(
|
||||
config,
|
||||
vhost_idx,
|
||||
vhost,
|
||||
&config.web.limits,
|
||||
&mut static_files,
|
||||
&mut static_bytes,
|
||||
)?);
|
||||
let mut host_profiles: Vec<_> = vhost
|
||||
.host
|
||||
.iter()
|
||||
.chain(vhost.hosts.iter().flatten())
|
||||
.map(|host| {
|
||||
(
|
||||
host,
|
||||
Vec::with_capacity(vhost.profiles.len()),
|
||||
Vec::with_capacity(vhost.profiles.len()),
|
||||
HashSet::with_capacity(vhost.profiles.len()),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
for profile in &vhost.profiles {
|
||||
let user_id = auth.user_id_by_name(&profile.user).ok_or_else(|| {
|
||||
ProxyError::Config(format!(
|
||||
"WEB profile references unknown access user `{}`",
|
||||
profile.user
|
||||
))
|
||||
})?;
|
||||
let auth_entry = auth.entry_by_id(user_id).ok_or_else(|| {
|
||||
ProxyError::Config("WEB profile user snapshot is inconsistent".to_string())
|
||||
})?;
|
||||
let (client_secret, client_secret_len) =
|
||||
client_secret(auth_entry.secret, profile.secret_mode);
|
||||
let key_fingerprint = debug_key_fingerprint(&client_secret[..client_secret_len]);
|
||||
let shared = Arc::new(WebRuntimeProfileShared {
|
||||
public_addr: vhost.public_addr,
|
||||
user: profile.user.clone(),
|
||||
credential_id: auth_entry.credential_id,
|
||||
secret_mode: profile.secret_mode,
|
||||
carrier: config.web.carrier,
|
||||
carrier_negotiation_enabled: config.web.carrier_negotiation_enabled(),
|
||||
carrier_learning: config.web.carrier_negotiation_enabled()
|
||||
&& config.web.carrier_learning,
|
||||
carriers: Arc::clone(&carrier_candidates),
|
||||
carrier_negotiation_deadlines_secs: config
|
||||
.web
|
||||
.timeouts
|
||||
.carrier_negotiation_deadlines_secs,
|
||||
key_fingerprint,
|
||||
max_sessions: profile
|
||||
.max_sessions
|
||||
.unwrap_or(config.web.limits.max_sessions_global),
|
||||
max_streams: profile
|
||||
.max_streams
|
||||
.unwrap_or(config.web.limits.max_streams_global),
|
||||
max_streams_per_session: profile
|
||||
.max_streams_per_session
|
||||
.unwrap_or(config.web.limits.max_streams_per_session),
|
||||
});
|
||||
// Only host-bound bindings and capability indexes expand with the alias count.
|
||||
for (host, profiles, capability_table, capabilities) in &mut host_profiles {
|
||||
let capability = derive_web_capability(
|
||||
&client_secret[..client_secret_len],
|
||||
host.as_bytes(),
|
||||
vhost.base_path.as_bytes(),
|
||||
)?;
|
||||
if !capabilities.insert(capability) {
|
||||
return Err(ProxyError::Config(format!(
|
||||
"WEB vhost `{host}` contains profiles with the same client capability"
|
||||
)));
|
||||
}
|
||||
profiles.push(Arc::new(WebRuntimeProfile {
|
||||
host: (*host).clone(),
|
||||
capability,
|
||||
shared: Arc::clone(&shared),
|
||||
}));
|
||||
capability_table.push(capability);
|
||||
}
|
||||
}
|
||||
for (host, profiles, capability_table, _) in host_profiles {
|
||||
runtime_capabilities.extend(capability_table.iter().copied());
|
||||
runtime_profiles.extend(profiles.iter().cloned());
|
||||
runtime_vhosts.insert(
|
||||
host.clone(),
|
||||
Arc::new(WebRuntimeVhost {
|
||||
host: host.clone(),
|
||||
base: if vhost.base_path.is_empty() {
|
||||
"/".to_string()
|
||||
} else {
|
||||
format!("/{}/", vhost.base_path)
|
||||
},
|
||||
decoy_fasttrack_mode: config.web.decoy_fasttrack_mode,
|
||||
decoy: Arc::clone(&decoy),
|
||||
decoy_header_secs: config.web.timeouts.decoy_header_secs,
|
||||
profiles,
|
||||
capabilities: capability_table.into_boxed_slice(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
config.web.runtime = Some(Arc::new(WebRuntimeConfig {
|
||||
vhosts: runtime_vhosts,
|
||||
profiles: runtime_profiles,
|
||||
capabilities: runtime_capabilities.into_boxed_slice(),
|
||||
}));
|
||||
Ok(())
|
||||
}
|
||||
// Exact bindings and wildcard templates share one immutable snapshot builder.
|
||||
mod build;
|
||||
pub(super) use build::rebuild;
|
||||
// Cold wildcard derivation uses the existing immutable authentication snapshot.
|
||||
mod wildcard;
|
||||
|
||||
fn debug_key_fingerprint(secret: &[u8]) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
static NEXT_SNAPSHOT: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// Builds the immutable WEB routing and decoy snapshot for one generation.
|
||||
pub(in crate::config::load) fn rebuild(config: &mut ProxyConfig) -> Result<()> {
|
||||
let auth = config.runtime_user_auth().ok_or_else(|| {
|
||||
ProxyError::Config("WEB runtime requires the user authentication snapshot".to_string())
|
||||
})?;
|
||||
let snapshot_id = NEXT_SNAPSHOT
|
||||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
|
||||
value.checked_add(1)
|
||||
})
|
||||
.map_err(|_| ProxyError::Config("WEB snapshot identity exhausted".to_string()))?;
|
||||
let mut wildcards = BTreeMap::new();
|
||||
let mut catch_all = None;
|
||||
let mut runtime_vhosts = BTreeMap::new();
|
||||
let mut runtime_profiles = Vec::new();
|
||||
let mut runtime_capabilities = Vec::new();
|
||||
let mut static_files = 0usize;
|
||||
let mut static_bytes = 0usize;
|
||||
|
||||
let carrier_candidates: Arc<[WebCarrier]> = config.web.carrier_candidates().into();
|
||||
for (vhost_idx, vhost) in config.web.vhosts.iter().enumerate() {
|
||||
let decoy = Arc::new(build_decoy(
|
||||
config,
|
||||
vhost_idx,
|
||||
vhost,
|
||||
&config.web.limits,
|
||||
&mut static_files,
|
||||
&mut static_bytes,
|
||||
)?);
|
||||
let mut host_profiles: Vec<_> = vhost
|
||||
.host
|
||||
.iter()
|
||||
.chain(vhost.hosts.iter().flatten())
|
||||
.filter(|host| !host.starts_with('*'))
|
||||
.map(|host| {
|
||||
(
|
||||
host,
|
||||
Vec::with_capacity(vhost.profiles.len()),
|
||||
Vec::with_capacity(vhost.profiles.len()),
|
||||
HashSet::with_capacity(vhost.profiles.len()),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let has_wildcards = vhost
|
||||
.host
|
||||
.iter()
|
||||
.chain(vhost.hosts.iter().flatten())
|
||||
.any(|host| host.starts_with('*'));
|
||||
let mut shared_profiles = Vec::new();
|
||||
let mut contexts = HashSet::new();
|
||||
for profile in &vhost.profiles {
|
||||
let user_id = auth.user_id_by_name(&profile.user).ok_or_else(|| {
|
||||
ProxyError::Config(format!(
|
||||
"WEB profile references unknown access user `{}`",
|
||||
profile.user
|
||||
))
|
||||
})?;
|
||||
let auth_entry = auth.entry_by_id(user_id).ok_or_else(|| {
|
||||
ProxyError::Config("WEB profile user snapshot is inconsistent".to_string())
|
||||
})?;
|
||||
let (client_secret, client_secret_len) =
|
||||
client_secret(auth_entry.secret, profile.secret_mode);
|
||||
let key_fingerprint = debug_key_fingerprint(&client_secret[..client_secret_len]);
|
||||
let shared = Arc::new(WebRuntimeProfileShared {
|
||||
derivation_context: wildcard::derivation_context(
|
||||
&client_secret[..client_secret_len],
|
||||
vhost.base_path.as_bytes(),
|
||||
),
|
||||
public_addr: vhost.public_addr,
|
||||
user: profile.user.clone(),
|
||||
credential_id: auth_entry.credential_id,
|
||||
secret_mode: profile.secret_mode,
|
||||
carrier: config.web.carrier,
|
||||
carrier_negotiation_enabled: config.web.carrier_negotiation_enabled(),
|
||||
carrier_learning: config.web.carrier_negotiation_enabled()
|
||||
&& config.web.carrier_learning,
|
||||
carriers: Arc::clone(&carrier_candidates),
|
||||
carrier_negotiation_deadlines_secs: config
|
||||
.web
|
||||
.timeouts
|
||||
.carrier_negotiation_deadlines_secs,
|
||||
key_fingerprint,
|
||||
max_sessions: profile
|
||||
.max_sessions
|
||||
.unwrap_or(config.web.limits.max_sessions_global),
|
||||
max_streams: profile
|
||||
.max_streams
|
||||
.unwrap_or(config.web.limits.max_streams_global),
|
||||
max_streams_per_session: profile
|
||||
.max_streams_per_session
|
||||
.unwrap_or(config.web.limits.max_streams_per_session),
|
||||
});
|
||||
if has_wildcards {
|
||||
if !contexts.insert(shared.derivation_context) {
|
||||
return Err(ProxyError::Config(
|
||||
"WEB wildcard group contains duplicate client capabilities".to_string(),
|
||||
));
|
||||
}
|
||||
shared_profiles.push(Arc::clone(&shared));
|
||||
}
|
||||
// Only host-bound bindings and capability indexes expand with the alias count.
|
||||
for (host, profiles, capability_table, capabilities) in &mut host_profiles {
|
||||
let capability = derive_web_capability(
|
||||
&client_secret[..client_secret_len],
|
||||
host.as_bytes(),
|
||||
vhost.base_path.as_bytes(),
|
||||
)?;
|
||||
if !capabilities.insert(capability) {
|
||||
return Err(ProxyError::Config(format!(
|
||||
"WEB vhost `{host}` contains profiles with the same client capability"
|
||||
)));
|
||||
}
|
||||
profiles.push(Arc::new(WebRuntimeProfile {
|
||||
host: (*host).clone(),
|
||||
capability,
|
||||
shared: Arc::clone(&shared),
|
||||
}));
|
||||
capability_table.push(capability);
|
||||
}
|
||||
}
|
||||
if has_wildcards {
|
||||
let template = Arc::new(WebRuntimeVhost {
|
||||
wildcard: Some(WebRuntimeWildcard {
|
||||
group_id: vhost_idx,
|
||||
profiles: shared_profiles,
|
||||
}),
|
||||
host: String::new(),
|
||||
base: if vhost.base_path.is_empty() {
|
||||
"/".to_string()
|
||||
} else {
|
||||
format!("/{}/", vhost.base_path)
|
||||
},
|
||||
decoy_fasttrack_mode: config.web.decoy_fasttrack_mode,
|
||||
decoy: Arc::clone(&decoy),
|
||||
decoy_header_secs: config.web.timeouts.decoy_header_secs,
|
||||
profiles: Vec::new(),
|
||||
capabilities: Box::new([]),
|
||||
});
|
||||
for selector in vhost.host.iter().chain(vhost.hosts.iter().flatten()) {
|
||||
if selector == "*" {
|
||||
catch_all = Some(Arc::clone(&template));
|
||||
} else if let Some(suffix) = selector.strip_prefix("*.") {
|
||||
wildcards.insert(suffix.to_string(), Arc::clone(&template));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (host, profiles, capability_table, _) in host_profiles {
|
||||
runtime_capabilities.extend(capability_table.iter().copied());
|
||||
runtime_profiles.extend(profiles.iter().cloned());
|
||||
runtime_vhosts.insert(
|
||||
host.clone(),
|
||||
Arc::new(WebRuntimeVhost {
|
||||
wildcard: None,
|
||||
host: host.clone(),
|
||||
base: if vhost.base_path.is_empty() {
|
||||
"/".to_string()
|
||||
} else {
|
||||
format!("/{}/", vhost.base_path)
|
||||
},
|
||||
decoy_fasttrack_mode: config.web.decoy_fasttrack_mode,
|
||||
decoy: Arc::clone(&decoy),
|
||||
decoy_header_secs: config.web.timeouts.decoy_header_secs,
|
||||
profiles,
|
||||
capabilities: capability_table.into_boxed_slice(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
config.web.runtime = Some(Arc::new(WebRuntimeConfig {
|
||||
snapshot_id,
|
||||
wildcards,
|
||||
catch_all,
|
||||
vhosts: runtime_vhosts,
|
||||
profiles: runtime_profiles,
|
||||
capabilities: runtime_capabilities.into_boxed_slice(),
|
||||
}));
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
use super::*;
|
||||
|
||||
// A length-delimited full digest fences secret, mode and endpoint changes without
|
||||
// performing HMAC while a process session registry is locked.
|
||||
pub(super) fn derivation_context(secret: &[u8], base: &[u8]) -> [u8; 32] {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(b"telemt-web-derivation-context-v1\0");
|
||||
digest.update([if base.is_empty() { 1 } else { 2 }]);
|
||||
digest.update((secret.len() as u64).to_be_bytes());
|
||||
digest.update(secret);
|
||||
digest.update((base.len() as u64).to_be_bytes());
|
||||
digest.update(base);
|
||||
digest.finalize().into()
|
||||
}
|
||||
|
||||
impl ProxyConfig {
|
||||
/// Derives one complete bounded table after the process HMAC budget is reserved.
|
||||
pub(crate) fn wildcard_capabilities(
|
||||
&self,
|
||||
vhost: &WebRuntimeVhost,
|
||||
host: &str,
|
||||
) -> Result<Box<[[u8; 32]]>> {
|
||||
let group = vhost
|
||||
.wildcard
|
||||
.as_ref()
|
||||
.ok_or_else(|| ProxyError::Config("WEB wildcard template is missing".to_string()))?;
|
||||
let auth = self.runtime_user_auth().ok_or_else(|| {
|
||||
ProxyError::Config("WEB authentication snapshot is missing".to_string())
|
||||
})?;
|
||||
let mut capabilities = Vec::with_capacity(group.profiles.len());
|
||||
for profile in &group.profiles {
|
||||
let entry = auth
|
||||
.user_id_by_name(&profile.user)
|
||||
.and_then(|id| auth.entry_by_id(id))
|
||||
.ok_or_else(|| {
|
||||
ProxyError::Config(
|
||||
"WEB wildcard authentication snapshot is inconsistent".to_string(),
|
||||
)
|
||||
})?;
|
||||
let (secret, len) = client_secret(entry.secret, profile.secret_mode);
|
||||
capabilities.push(derive_web_capability(
|
||||
&secret[..len],
|
||||
host.as_bytes(),
|
||||
vhost.base.trim_matches('/').as_bytes(),
|
||||
)?);
|
||||
}
|
||||
Ok(capabilities.into_boxed_slice())
|
||||
}
|
||||
}
|
||||
@@ -261,6 +261,7 @@ const LISTENER_CONFIG_KEYS: &[&str] = &[
|
||||
];
|
||||
|
||||
const WEB_CONFIG_KEYS: &[&str] = &[
|
||||
"allow_wildcard_hosts",
|
||||
"enabled",
|
||||
"carrier",
|
||||
"carrier_method",
|
||||
@@ -277,6 +278,7 @@ const WEB_CONFIG_KEYS: &[&str] = &[
|
||||
];
|
||||
|
||||
const WEB_LIMITS_CONFIG_KEYS: &[&str] = &[
|
||||
"wildcard",
|
||||
"max_header_bytes",
|
||||
"max_body_bytes",
|
||||
"max_frame_payload_bytes",
|
||||
@@ -535,3 +537,12 @@ pub(super) fn handle_unknown_config_keys(parsed_toml: &toml::Value) -> Result<()
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const WEB_WILDCARD_LIMITS_CONFIG_KEYS: &[&str] = &[
|
||||
"max_rules",
|
||||
"max_profiles_per_request",
|
||||
"cache_hosts",
|
||||
"cache_bytes",
|
||||
"cold_hmac_per_minute",
|
||||
"cold_hmac_burst",
|
||||
];
|
||||
|
||||
@@ -37,6 +37,7 @@ fn known_config_keys_for_suggestion() -> Vec<&'static str> {
|
||||
LISTENER_CONFIG_KEYS,
|
||||
WEB_CONFIG_KEYS,
|
||||
WEB_LIMITS_CONFIG_KEYS,
|
||||
WEB_WILDCARD_LIMITS_CONFIG_KEYS,
|
||||
WEB_DEBUG_CONFIG_KEYS,
|
||||
WEB_TIMEOUTS_CONFIG_KEYS,
|
||||
WEB_VHOST_CONFIG_KEYS,
|
||||
@@ -242,6 +243,13 @@ pub(super) fn collect_unknown_config_keys(parsed_toml: &toml::Value) -> Vec<Unkn
|
||||
&["web", "limits"],
|
||||
WEB_LIMITS_CONFIG_KEYS,
|
||||
);
|
||||
check_known_table(
|
||||
parsed_toml,
|
||||
&mut unknown,
|
||||
&known_for_suggestion,
|
||||
&["web", "limits", "wildcard"],
|
||||
WEB_WILDCARD_LIMITS_CONFIG_KEYS,
|
||||
);
|
||||
check_known_table(
|
||||
parsed_toml,
|
||||
&mut unknown,
|
||||
|
||||
@@ -75,7 +75,7 @@ pub(super) fn validate_source(config: &mut ProxyConfig) -> Result<()> {
|
||||
));
|
||||
}
|
||||
|
||||
validate_limits(&config.web.limits)?;
|
||||
validate_limits(&config.web.limits, config.web.allow_wildcard_hosts)?;
|
||||
debug::validate(&config.web.debug, &config.web.limits)?;
|
||||
let carriers = negotiation::validate(&config.web)?;
|
||||
if carriers.contains(&WebCarrier::Https) && config.web.limits.max_http_handlers < 2 {
|
||||
@@ -182,7 +182,7 @@ fn validate_web_listener(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_limits(limits: &WebLimitsConfig) -> Result<()> {
|
||||
fn validate_limits(limits: &WebLimitsConfig, wildcard: bool) -> Result<()> {
|
||||
if !(8192..=MAX_WEB_HEADER_BYTES).contains(&limits.max_header_bytes) {
|
||||
return config_error("web.limits.max_header_bytes must be within [8192, 65536]");
|
||||
}
|
||||
@@ -412,7 +412,7 @@ fn validate_limits(limits: &WebLimitsConfig) -> Result<()> {
|
||||
"web.limits pending ceilings must preserve one uplink batch and downlink progress",
|
||||
);
|
||||
}
|
||||
memory::validate(limits)?;
|
||||
memory::validate(limits, wildcard)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ const WEB_OVERLOAD_CONNECTION_BYTES: usize = 4 * 1024;
|
||||
const WEB_CAPABILITY_INDEX_ENTRY_BYTES: usize = 64;
|
||||
|
||||
/// Validates process-wide body, header, queue, static, and debug reservations.
|
||||
pub(super) fn validate(limits: &WebLimitsConfig) -> Result<()> {
|
||||
pub(super) fn validate(limits: &WebLimitsConfig, wildcard: bool) -> Result<()> {
|
||||
if limits.max_carrier_learning_entries == 0 {
|
||||
return config_error("web.limits.max_carrier_learning_entries must be > 0");
|
||||
}
|
||||
@@ -83,9 +83,15 @@ pub(super) fn validate(limits: &WebLimitsConfig) -> Result<()> {
|
||||
.ok_or_else(|| {
|
||||
ProxyError::Config("web.limits lane state reservation overflowed usize".to_string())
|
||||
})?;
|
||||
let wildcard_reservation = if wildcard {
|
||||
wildcard_reservation(limits)?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let reserved = limits
|
||||
.pending_bytes_global
|
||||
.checked_add(limits.max_body_bytes_global)
|
||||
.checked_add(wildcard_reservation)
|
||||
.and_then(|value| value.checked_add(limits.max_body_bytes_global))
|
||||
.and_then(|value| value.checked_add(limits.max_static_bytes))
|
||||
.and_then(|value| value.checked_add(debug_ring_index))
|
||||
.and_then(|value| value.checked_add(status_pages))
|
||||
@@ -106,6 +112,52 @@ pub(super) fn validate(limits: &WebLimitsConfig) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Cache entries include their digest index and allocator overhead. Detached entry
|
||||
// leases remain charged until the last borrower releases them. Handler scratch and
|
||||
// authenticated host bindings have independent existing concurrency ceilings.
|
||||
fn wildcard_reservation(limits: &WebLimitsConfig) -> Result<usize> {
|
||||
let wildcard = &limits.wildcard;
|
||||
if wildcard.max_rules == 0
|
||||
|| wildcard.max_profiles_per_request == 0
|
||||
|| wildcard.cache_bytes == 0
|
||||
|| wildcard.cold_hmac_per_minute == 0
|
||||
|| (wildcard.cold_hmac_burst as usize) < wildcard.max_profiles_per_request
|
||||
{
|
||||
return config_error(
|
||||
"web.limits.wildcard requires positive bounds and a burst covering a complete profile table",
|
||||
);
|
||||
}
|
||||
let rules = wildcard
|
||||
.max_rules
|
||||
.checked_mul(1024)
|
||||
.and_then(|value| {
|
||||
limits
|
||||
.max_profiles
|
||||
.checked_mul(1024)
|
||||
.and_then(|profiles| value.checked_add(profiles))
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
ProxyError::Config("WEB wildcard template reservations overflowed usize".to_string())
|
||||
})?;
|
||||
wildcard
|
||||
.max_profiles_per_request
|
||||
.checked_mul(32)
|
||||
.and_then(|value| value.checked_add(1024))
|
||||
.and_then(|value| value.checked_mul(limits.max_http_handlers))
|
||||
.and_then(|value| value.checked_add(wildcard.cache_bytes))
|
||||
.and_then(|value| value.checked_add(rules))
|
||||
.and_then(|value| {
|
||||
limits
|
||||
.max_bootstraps_global
|
||||
.checked_add(limits.max_sessions_global)
|
||||
.and_then(|bindings| bindings.checked_mul(1024))
|
||||
.and_then(|bindings| value.checked_add(bindings))
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
ProxyError::Config("WEB wildcard memory reservations overflowed usize".to_string())
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -113,13 +165,13 @@ mod tests {
|
||||
#[test]
|
||||
fn default_envelope_includes_bounded_lane_and_learning_metadata() {
|
||||
let limits = WebLimitsConfig::default();
|
||||
assert!(validate(&limits).is_ok());
|
||||
assert!(validate(&limits, false).is_ok());
|
||||
|
||||
let previous_envelope = WebLimitsConfig {
|
||||
memory_envelope_bytes: 768 * 1024 * 1024,
|
||||
..limits
|
||||
};
|
||||
assert!(validate(&previous_envelope).is_err());
|
||||
assert!(validate(&previous_envelope, false).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -128,7 +180,7 @@ mod tests {
|
||||
max_profiles: usize::MAX,
|
||||
..WebLimitsConfig::default()
|
||||
};
|
||||
let error = validate(&limits).unwrap_err().to_string();
|
||||
let error = validate(&limits, false).unwrap_err().to_string();
|
||||
assert!(error.contains("web capability index reservation overflowed usize"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,45 @@
|
||||
use super::*;
|
||||
|
||||
/// Bounds expanded routing tables before normalizing exact hostname selectors.
|
||||
/// Bounds exact bindings and wildcard rules before normalizing hostname selectors.
|
||||
pub(super) fn validate_vhosts(config: &mut ProxyConfig) -> Result<()> {
|
||||
let limits = &config.web.limits;
|
||||
let mut host_count = 0usize;
|
||||
let mut rule_count = 0usize;
|
||||
let mut profile_count = 0usize;
|
||||
for (vhost_idx, vhost) in config.web.vhosts.iter().enumerate() {
|
||||
let count = match (&vhost.host, &vhost.hosts) {
|
||||
(Some(_), None) => 1,
|
||||
(None, Some(hosts)) if !hosts.is_empty() => hosts.len(),
|
||||
match (&vhost.host, &vhost.hosts) {
|
||||
(Some(_), None) => {}
|
||||
(None, Some(hosts)) if !hosts.is_empty() => {}
|
||||
_ => {
|
||||
return config_error(&format!(
|
||||
"web.vhosts[{vhost_idx}] requires exactly one of host or non-empty hosts"
|
||||
));
|
||||
}
|
||||
};
|
||||
}
|
||||
let selectors = vhost.host.iter().chain(vhost.hosts.iter().flatten());
|
||||
let patterns = selectors
|
||||
.clone()
|
||||
.filter(|host| host.trim().starts_with('*'))
|
||||
.count();
|
||||
let exact = selectors.count() - patterns;
|
||||
rule_count = rule_count.checked_add(patterns).ok_or_else(|| {
|
||||
ProxyError::Config("WEB wildcard rule count overflowed usize".to_string())
|
||||
})?;
|
||||
if patterns > 0
|
||||
&& (!config.web.allow_wildcard_hosts
|
||||
|| rule_count > limits.wildcard.max_rules
|
||||
|| vhost.profiles.len() > limits.wildcard.max_profiles_per_request)
|
||||
{
|
||||
return config_error(&format!(
|
||||
"web.vhosts[{vhost_idx}] wildcard selectors require allow_wildcard_hosts and must fit web.limits.wildcard bounds"
|
||||
));
|
||||
}
|
||||
host_count = host_count
|
||||
.checked_add(count)
|
||||
.checked_add(exact)
|
||||
.ok_or_else(|| ProxyError::Config("WEB hostname count overflowed usize".to_string()))?;
|
||||
profile_count = count
|
||||
.checked_mul(vhost.profiles.len())
|
||||
profile_count = exact
|
||||
.checked_add(usize::from(patterns > 0))
|
||||
.and_then(|count| count.checked_mul(vhost.profiles.len()))
|
||||
.and_then(|expanded| profile_count.checked_add(expanded))
|
||||
.ok_or_else(|| ProxyError::Config("WEB profile count overflowed usize".to_string()))?;
|
||||
if host_count > limits.max_vhosts {
|
||||
@@ -43,7 +63,16 @@ pub(super) fn validate_vhosts(config: &mut ProxyConfig) -> Result<()> {
|
||||
} else {
|
||||
format!("web.vhosts[{vhost_idx}].hosts[{host_idx}]")
|
||||
};
|
||||
*host = normalize_web_host(host, &field)?;
|
||||
*host = if config.web.allow_wildcard_hosts && host.trim() == "*" {
|
||||
"*".to_string()
|
||||
} else if config.web.allow_wildcard_hosts
|
||||
&& let Some(suffix) = host.trim().strip_prefix("*.")
|
||||
{
|
||||
let normalized = normalize_web_host(&format!("x.{suffix}"), &field)?;
|
||||
format!("*.{}", &normalized[2..])
|
||||
} else {
|
||||
normalize_web_host(host, &field)?
|
||||
};
|
||||
if !hosts.insert(host.clone()) {
|
||||
return config_error(&format!("duplicate WEB vhost host `{host}` at {field}"));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user