use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::RwLock;
use std::time::{Duration, Instant};
pub const ALTSVC_CACHE_MAX_ENTRIES: usize = 64;
pub const ALTSVC_MAX_HEADER_BYTES: usize = 8192;
pub const ALTSVC_MAX_ALTERNATIVES: usize = 16;
pub const ALTSVC_DEFAULT_MA_SECS: u64 = 86_400;
pub const SUPPRESSION_BASE: Duration = Duration::from_secs(5);
pub const SUPPRESSION_MAX: Duration = Duration::from_secs(300);
pub const SUPPRESSION_MAX_ENTRIES: usize = 64;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AltSvcOrigin {
scheme: String,
host: String,
port: u16,
}
impl AltSvcOrigin {
#[must_use]
pub fn new(scheme: &str, host: &str, port: u16) -> Option<Self> {
if host.is_empty() || port == 0 {
return None;
}
let host = host.trim().trim_end_matches('.').to_ascii_lowercase();
if host.is_empty() || host.len() > 253 {
return None;
}
if host.contains(['@', '/', '?', '#', ' ', '\t', '\r', '\n']) {
return None;
}
Some(Self {
scheme: scheme.to_ascii_lowercase(),
host,
port,
})
}
#[cfg(feature = "high-level-url")]
#[must_use]
pub fn from_url(url: &url::Url) -> Option<Self> {
let host = url.host_str()?;
let port = url.port_or_known_default().unwrap_or(443);
Self::new(url.scheme(), host, port)
}
#[must_use]
pub fn cache_key(&self) -> String {
format!("{}://{}:{}", self.scheme, self.host, self.port)
}
#[must_use]
pub fn host(&self) -> &str {
&self.host
}
#[must_use]
pub fn port(&self) -> u16 {
self.port
}
#[must_use]
pub fn scheme(&self) -> &str {
&self.scheme
}
}
#[derive(Debug, Clone)]
pub struct AltSvcEntry {
pub alt_host: String,
pub alt_port: u16,
pub expires_at: Instant,
pub generation: u64,
}
impl AltSvcEntry {
#[must_use]
pub fn is_expired(&self, now: Instant) -> bool {
now >= self.expires_at
}
}
#[derive(Debug, Clone, Copy)]
#[allow(
clippy::struct_excessive_bools,
reason = "trust is four orthogonal booleans (https, authenticated, proxy, hop); an enum would obscure call sites"
)]
pub struct AltSvcLearnContext {
pub is_https: bool,
pub tls_authenticated: bool,
pub via_proxy: bool,
pub origin_matches_hop: bool,
}
impl AltSvcLearnContext {
#[must_use]
pub fn trustworthy(self) -> bool {
self.is_https && self.tls_authenticated && !self.via_proxy && self.origin_matches_hop
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AltSvcLearnOutcome {
Absent,
Learned,
Cleared,
Rejected,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ParsedAlternative {
protocol: String,
authority: String,
ma: Option<u64>,
}
fn parse_alternatives(value: &str) -> Vec<ParsedAlternative> {
let mut out = Vec::new();
for part in split_header_list(value) {
if out.len() >= ALTSVC_MAX_ALTERNATIVES {
break;
}
let part = part.trim();
if part.is_empty() {
continue;
}
if part.eq_ignore_ascii_case("clear") {
continue;
}
let Some(eq) = part.find('=') else {
continue;
};
let (proto, rest) = part.split_at(eq);
let proto = proto.trim();
if proto.is_empty() || !is_token(proto) {
continue;
}
let rest = rest[1..].trim_start();
let Some((authority, params)) = parse_quoted_string(rest) else {
continue;
};
let mut ma: Option<u64> = None;
let mut ma_present = false;
let mut ma_invalid = false;
for param in params.split(';').skip(1) {
let param = param.trim();
if param.is_empty() {
continue;
}
let (name, pvalue) = match param.find('=') {
Some(i) => (param[..i].trim(), Some(param[i + 1..].trim())),
None => (param, None),
};
if name.eq_ignore_ascii_case("ma") {
ma_present = true;
if let Some(v) = pvalue {
let v = v.trim().trim_matches('"');
if let Ok(n) = v.parse::<u64>() {
ma = Some(n);
} else {
ma_invalid = true;
break;
}
} else {
ma_invalid = true;
break;
}
}
}
if ma_invalid {
continue;
}
if ma_present && ma.is_none() {
continue;
}
out.push(ParsedAlternative {
protocol: proto.to_owned(),
authority,
ma,
});
}
out
}
fn is_clear_value(value: &str) -> bool {
let v = value.trim().trim_matches('"').trim();
v.eq_ignore_ascii_case("clear")
}
fn split_header_list(value: &str) -> Vec<&str> {
let mut parts = Vec::new();
let mut start = 0usize;
let mut in_quotes = false;
let mut escaped = false;
for (i, b) in value.bytes().enumerate() {
if escaped {
escaped = false;
continue;
}
match b {
b'\\' if in_quotes => escaped = true,
b'"' => in_quotes = !in_quotes,
b',' if !in_quotes => {
parts.push(&value[start..i]);
start = i + 1;
}
_ => {}
}
}
parts.push(&value[start..]);
parts
}
fn parse_quoted_string(s: &str) -> Option<(String, &str)> {
let bytes = s.as_bytes();
if bytes.first() != Some(&b'"') {
return None;
}
let mut out = String::new();
let mut i = 1usize;
while i < bytes.len() {
match bytes[i] {
b'\\' => {
i += 1;
if i >= bytes.len() {
return None;
}
let c = bytes[i];
if c != b'"' && c != b'\\' {
return None;
}
if out.len() >= 512 {
return None;
}
out.push(c as char);
i += 1;
}
b'"' => {
return Some((out, &s[i + 1..]));
}
c if c < 0x20 || c == 0x7f => return None,
c => {
if out.len() >= 512 {
return None;
}
out.push(c as char);
i += 1;
}
}
}
None
}
fn is_token(s: &str) -> bool {
!s.is_empty()
&& s.bytes().all(|b| {
b > 0x20
&& b < 0x7f
&& !matches!(
b,
b'(' | b')'
| b'<'
| b'>'
| b'@'
| b','
| b';'
| b':'
| b'\\'
| b'"'
| b'/'
| b'['
| b']'
| b'?'
| b'='
| b'{'
| b'}'
| b' '
| b'\t'
)
})
}
fn parse_authority(authority: &str) -> Option<(String, u16)> {
if authority.is_empty() || authority.len() > 512 {
return None;
}
if authority.contains('@') {
return None;
}
if let Some(rest) = authority.strip_prefix('[') {
let end = rest.find(']')?;
let host = &rest[..end];
let after = &rest[end + 1..];
let port_str = after.strip_prefix(':')?;
if host.is_empty() || port_str.is_empty() {
return None;
}
let port: u16 = port_str.parse().ok()?;
if port == 0 {
return None;
}
return Some((host.to_ascii_lowercase(), port));
}
let colon = authority.rfind(':')?;
let (host, port_str) = authority.split_at(colon);
let port_str = &port_str[1..];
if port_str.is_empty() {
return None;
}
let port: u16 = port_str.parse().ok()?;
if port == 0 {
return None;
}
if host.is_empty() {
return Some((String::new(), port));
}
if host.contains([' ', '\t', '\r', '\n', '/', '?', '#']) {
return None;
}
Some((host.to_ascii_lowercase(), port))
}
pub struct AltSvcCache {
entries: RwLock<HashMap<AltSvcOrigin, AltSvcEntry>>,
sequence: AtomicU64,
}
impl Default for AltSvcCache {
fn default() -> Self {
Self::new()
}
}
impl AltSvcCache {
#[must_use]
pub fn new() -> Self {
Self {
entries: RwLock::new(HashMap::new()),
sequence: AtomicU64::new(1),
}
}
fn read_entries(&self) -> std::sync::RwLockReadGuard<'_, HashMap<AltSvcOrigin, AltSvcEntry>> {
self.entries
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn write_entries(&self) -> std::sync::RwLockWriteGuard<'_, HashMap<AltSvcOrigin, AltSvcEntry>> {
self.entries
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[must_use]
pub fn len(&self) -> usize {
self.read_entries().len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.read_entries().is_empty()
}
#[cfg(any(test, feature = "test-util"))]
#[must_use]
pub fn contains_origin(&self, origin: &AltSvcOrigin) -> bool {
self.read_entries().contains_key(origin)
}
#[must_use]
pub fn get_fresh(&self, origin: &AltSvcOrigin, now: Instant) -> Option<AltSvcEntry> {
let entry = self.read_entries().get(origin).cloned()?;
if entry.is_expired(now) {
self.write_entries().remove(origin);
return None;
}
Some(entry)
}
pub fn get_fresh_counted(
&self,
origin: &AltSvcOrigin,
now: Instant,
) -> (Option<AltSvcEntry>, bool) {
let Some(entry) = self.read_entries().get(origin).cloned() else {
return (None, false);
};
if entry.is_expired(now) {
self.write_entries().remove(origin);
return (None, true);
}
(Some(entry), false)
}
pub fn clear(&self, origin: &AltSvcOrigin) -> bool {
self.write_entries().remove(origin).is_some()
}
pub fn learn(
&self,
origin: &AltSvcOrigin,
values: &[String],
now: Instant,
) -> AltSvcLearnOutcome {
self.learn_counted(origin, values, now).0
}
pub fn learn_counted(
&self,
origin: &AltSvcOrigin,
values: &[String],
now: Instant,
) -> (AltSvcLearnOutcome, bool) {
if values.is_empty() {
return (AltSvcLearnOutcome::Absent, false);
}
let combined = values.join(", ");
if combined.len() > ALTSVC_MAX_HEADER_BYTES {
return (AltSvcLearnOutcome::Rejected, false);
}
if is_clear_value(combined.trim()) {
let had = self.clear(origin);
return (AltSvcLearnOutcome::Cleared, had);
}
let parsed = parse_alternatives(&combined);
let mut best: Option<(String, u16, Instant)> = None;
for alt in parsed {
if !alt.protocol.eq_ignore_ascii_case("h3") {
continue;
}
let Some((host, port)) = parse_authority(&alt.authority) else {
continue;
};
let ma_secs = alt.ma.unwrap_or(ALTSVC_DEFAULT_MA_SECS);
if ma_secs == 0 {
continue;
}
let Some(expires_at) = now.checked_add(Duration::from_secs(ma_secs)) else {
continue;
};
let resolved_host = if host.is_empty() {
origin.host().to_owned()
} else {
host
};
if best.is_none() {
best = Some((resolved_host, port, expires_at));
}
}
let Some((alt_host, alt_port, expires_at)) = best else {
let had = self.clear(origin);
if had {
return (AltSvcLearnOutcome::Cleared, true);
}
return (AltSvcLearnOutcome::Absent, false);
};
let mut table = self.write_entries();
if let Some(existing) = table.get(origin).cloned() {
if existing.alt_host == alt_host && existing.alt_port == alt_port {
let new_expiry = expires_at.max(existing.expires_at);
if new_expiry != existing.expires_at {
table.insert(
origin.clone(),
AltSvcEntry {
alt_host,
alt_port,
expires_at: new_expiry,
generation: existing.generation,
},
);
}
return (AltSvcLearnOutcome::Learned, false);
}
}
Self::ensure_bound_locked(&mut table, origin);
let generation = self.sequence.fetch_add(1, Ordering::Relaxed);
table.insert(
origin.clone(),
AltSvcEntry {
alt_host,
alt_port,
expires_at,
generation,
},
);
(AltSvcLearnOutcome::Learned, false)
}
#[cfg(any(test, feature = "test-util"))]
pub fn insert_for_test(&self, origin: AltSvcOrigin, entry: AltSvcEntry) {
let mut table = self.write_entries();
Self::ensure_bound_locked(&mut table, &origin);
table.insert(origin, entry);
}
fn ensure_bound_locked(table: &mut HashMap<AltSvcOrigin, AltSvcEntry>, except: &AltSvcOrigin) {
if table.len() < ALTSVC_CACHE_MAX_ENTRIES {
return;
}
let victim = table.keys().find(|k| *k != except).cloned();
if let Some(victim) = victim {
table.remove(&victim);
}
}
}
impl std::fmt::Debug for AltSvcCache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let len = self.entries.try_read().map(|t| t.len()).ok();
f.debug_struct("AltSvcCache")
.field("len", &len)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum H3FailureClass {
Connectivity,
Protocol,
Closed,
Other,
}
impl H3FailureClass {
#[must_use]
pub fn from_error(err: &crate::error::Error) -> Self {
match err {
crate::error::Error::Connect(_) | crate::error::Error::H3Connect(_) => {
Self::Connectivity
}
crate::error::Error::Timeout {
phase: crate::timeout::TimeoutPhase::Connect,
..
} => Self::Connectivity,
crate::error::Error::H3Protocol(_) | crate::error::Error::H3Stream(_) => Self::Protocol,
crate::error::Error::H3ConnectionClosed(_) => Self::Closed,
_ => Self::Other,
}
}
}
pub struct BrokenRouteSuppressor {
entries: RwLock<HashMap<AltSvcOrigin, SuppressionEntry>>,
}
#[derive(Debug, Clone)]
struct SuppressionEntry {
generation: u64,
failures: u32,
suppressed_until: Instant,
#[allow(
dead_code,
reason = "retained for diagnostics; backoff is uniform across classes"
)]
reason: H3FailureClass,
}
impl Default for BrokenRouteSuppressor {
fn default() -> Self {
Self::new()
}
}
impl BrokenRouteSuppressor {
#[must_use]
pub fn new() -> Self {
Self {
entries: RwLock::new(HashMap::new()),
}
}
fn read_entries(
&self,
) -> std::sync::RwLockReadGuard<'_, HashMap<AltSvcOrigin, SuppressionEntry>> {
self.entries
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn write_entries(
&self,
) -> std::sync::RwLockWriteGuard<'_, HashMap<AltSvcOrigin, SuppressionEntry>> {
self.entries
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[must_use]
pub fn is_suppressed(&self, origin: &AltSvcOrigin, generation: u64, now: Instant) -> bool {
let Some(entry) = self.read_entries().get(origin).cloned() else {
return false;
};
if entry.generation != generation {
return false;
}
now < entry.suppressed_until
}
pub fn record_failure(
&self,
origin: &AltSvcOrigin,
generation: u64,
now: Instant,
reason: H3FailureClass,
) {
let mut table = self.write_entries();
if let Some(entry) = table.get_mut(origin) {
if entry.generation != generation {
entry.generation = generation;
entry.failures = 1;
entry.reason = reason;
entry.suppressed_until = now + SUPPRESSION_BASE.min(SUPPRESSION_MAX);
return;
}
let next = entry.failures.saturating_add(1);
entry.failures = next;
entry.reason = reason;
let shift = next.saturating_sub(1).min(10);
let backoff = SUPPRESSION_BASE
.checked_mul(1u32 << shift)
.unwrap_or(SUPPRESSION_MAX)
.min(SUPPRESSION_MAX);
entry.suppressed_until = now + backoff;
return;
}
Self::ensure_bound_locked(&mut table, origin);
table.insert(
origin.clone(),
SuppressionEntry {
generation,
failures: 1,
suppressed_until: now + SUPPRESSION_BASE.min(SUPPRESSION_MAX),
reason,
},
);
}
pub fn record_success(&self, origin: &AltSvcOrigin) {
self.write_entries().remove(origin);
}
pub fn note_new_advertisement(&self, origin: &AltSvcOrigin, generation: u64) {
let stale = self
.read_entries()
.get(origin)
.is_some_and(|e| e.generation != generation);
if stale {
self.write_entries().remove(origin);
}
}
#[cfg(any(test, feature = "test-util"))]
#[must_use]
pub fn len(&self) -> usize {
self.read_entries().len()
}
#[cfg(any(test, feature = "test-util"))]
#[must_use]
pub fn is_empty(&self) -> bool {
self.read_entries().is_empty()
}
fn ensure_bound_locked(
table: &mut HashMap<AltSvcOrigin, SuppressionEntry>,
except: &AltSvcOrigin,
) {
if table.len() < SUPPRESSION_MAX_ENTRIES {
return;
}
let victim = table.keys().find(|k| *k != except).cloned();
if let Some(victim) = victim {
table.remove(&victim);
}
}
}
impl std::fmt::Debug for BrokenRouteSuppressor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let len = self.entries.try_read().map(|t| t.len()).ok();
f.debug_struct("BrokenRouteSuppressor")
.field("len", &len)
.finish_non_exhaustive()
}
}
#[derive(Debug, Default)]
pub struct AltSvcState {
cache: AltSvcCache,
suppressor: BrokenRouteSuppressor,
}
impl AltSvcState {
#[must_use]
pub fn new() -> Self {
Self {
cache: AltSvcCache::new(),
suppressor: BrokenRouteSuppressor::new(),
}
}
#[must_use]
pub fn cache(&self) -> &AltSvcCache {
&self.cache
}
#[must_use]
pub fn suppressor(&self) -> &BrokenRouteSuppressor {
&self.suppressor
}
}
#[cfg(test)]
mod tests {
use super::*;
fn origin() -> AltSvcOrigin {
AltSvcOrigin::new("https", "example.com", 443).expect("origin")
}
fn now() -> Instant {
Instant::now()
}
#[test]
fn origin_normalizes_case_and_rejects_bad() {
let o = AltSvcOrigin::new("HTTPS", "Example.COM", 443).expect("origin");
assert_eq!(o.host(), "example.com");
assert!(AltSvcOrigin::new("https", "", 443).is_none());
assert!(AltSvcOrigin::new("https", "example.com", 0).is_none());
assert!(AltSvcOrigin::new("https", "user@example.com", 443).is_none());
}
#[test]
fn parses_basic_h3_with_ma() {
let alts = parse_alternatives(r#"h3=":443"; ma=86400"#);
assert_eq!(alts.len(), 1);
assert_eq!(alts[0].protocol, "h3");
assert_eq!(alts[0].authority, ":443");
assert_eq!(alts[0].ma, Some(86_400));
}
#[test]
fn ignores_unsupported_protocols() {
let cache = AltSvcCache::new();
let o = origin();
let (outcome, had) = cache.learn_counted(&o, &[r#"h2=":443"; ma=60"#.to_owned()], now());
assert_eq!(outcome, AltSvcLearnOutcome::Absent);
assert!(!had);
assert!(cache.get_fresh(&o, now()).is_none());
}
#[test]
fn learns_supported_h3_and_resolves_same_host() {
let cache = AltSvcCache::new();
let o = origin();
let outcome = cache.learn(&o, &[r#"h3=":8443"; ma=60"#.to_owned()], now());
assert_eq!(outcome, AltSvcLearnOutcome::Learned);
let entry = cache.get_fresh(&o, now()).expect("fresh");
assert_eq!(entry.alt_host, "example.com");
assert_eq!(entry.alt_port, 8443);
}
#[test]
fn learns_alternative_authority() {
let cache = AltSvcCache::new();
let o = origin();
let outcome = cache.learn(
&o,
&[r#"h3="alt.example.com:443"; ma=60"#.to_owned()],
now(),
);
assert_eq!(outcome, AltSvcLearnOutcome::Learned);
let entry = cache.get_fresh(&o, now()).expect("fresh");
assert_eq!(entry.alt_host, "alt.example.com");
}
#[test]
fn clear_removes_entry() {
let cache = AltSvcCache::new();
let o = origin();
assert_eq!(
cache.learn(&o, &[r#"h3=":443"; ma=60"#.to_owned()], now()),
AltSvcLearnOutcome::Learned
);
assert_eq!(
cache.learn(&o, &["clear".to_owned()], now()),
AltSvcLearnOutcome::Cleared
);
assert!(cache.get_fresh(&o, now()).is_none());
}
#[test]
fn zero_ma_never_caches() {
let cache = AltSvcCache::new();
let o = origin();
let (outcome, had) = cache.learn_counted(&o, &[r#"h3=":443"; ma=0"#.to_owned()], now());
assert_eq!(outcome, AltSvcLearnOutcome::Absent);
assert!(!had);
assert!(cache.get_fresh(&o, now()).is_none());
}
#[test]
fn malformed_values_fail_closed() {
let cache = AltSvcCache::new();
let o = origin();
for bad in [
r#"h3=":443"#.to_owned(), r"h3=:443; ma=60".to_owned(), r#"h3="user@:443"; ma=60"#.to_owned(), r#"h3=":0"; ma=60"#.to_owned(), r#"h3=":443"; ma=abc"#.to_owned(), r#"h3=":443"; ma=99999999999999999999999"#.to_owned(), ] {
let outcome = cache.learn(&o, &[bad], now());
assert!(
matches!(
outcome,
AltSvcLearnOutcome::Cleared | AltSvcLearnOutcome::Absent
),
"bad value must not learn: {outcome:?}"
);
assert!(cache.get_fresh(&o, now()).is_none());
}
}
#[test]
fn oversized_header_rejected_without_allocation() {
let cache = AltSvcCache::new();
let o = origin();
let big = format!(
"h3=\":443\"; ma=60, {}",
"x".repeat(ALTSVC_MAX_HEADER_BYTES + 1)
);
assert_eq!(cache.learn(&o, &[big], now()), AltSvcLearnOutcome::Rejected);
}
#[test]
fn expiry_is_lazy() {
let cache = AltSvcCache::new();
let o = origin();
assert_eq!(
cache.learn(&o, &[r#"h3=":443"; ma=60"#.to_owned()], now()),
AltSvcLearnOutcome::Learned
);
let future = now() + Duration::from_secs(61);
assert!(cache.get_fresh(&o, future).is_none());
assert!(!cache.contains_origin(&o));
}
#[test]
fn cache_stays_bounded() {
let cache = AltSvcCache::new();
for i in 0..(ALTSVC_CACHE_MAX_ENTRIES + 10) {
let o = AltSvcOrigin::new("https", &format!("host-{i}.example"), 443).expect("origin");
let _ = cache.learn(&o, &[r#"h3=":443"; ma=60"#.to_owned()], now());
}
assert!(cache.len() <= ALTSVC_CACHE_MAX_ENTRIES);
}
#[test]
fn duplicate_alternatives_first_wins_deterministically() {
let cache = AltSvcCache::new();
let o = origin();
let _ = cache.learn(
&o,
&[r#"h3="a.example:443"; ma=60, h3="b.example:443"; ma=60"#.to_owned()],
now(),
);
let entry = cache.get_fresh(&o, now()).expect("fresh");
assert_eq!(entry.alt_host, "a.example");
}
#[test]
fn suppression_backoff_and_expiry() {
let s = BrokenRouteSuppressor::new();
let o = origin();
let t0 = now();
assert!(!s.is_suppressed(&o, 1, t0));
s.record_failure(&o, 1, t0, H3FailureClass::Connectivity);
assert!(s.is_suppressed(&o, 1, t0));
assert!(!s.is_suppressed(&o, 1, t0 + SUPPRESSION_BASE + Duration::from_secs(1)));
s.record_failure(&o, 1, t0, H3FailureClass::Connectivity);
assert!(s.is_suppressed(&o, 1, t0 + SUPPRESSION_BASE + Duration::from_secs(1)));
s.record_success(&o);
assert!(!s.is_suppressed(&o, 1, t0));
}
#[test]
fn new_generation_reenables_without_waiting() {
let s = BrokenRouteSuppressor::new();
let o = origin();
let t0 = now();
s.record_failure(&o, 1, t0, H3FailureClass::Connectivity);
assert!(s.is_suppressed(&o, 1, t0));
assert!(!s.is_suppressed(&o, 2, t0));
s.note_new_advertisement(&o, 2);
assert!(!s.is_suppressed(&o, 2, t0));
}
#[test]
fn failure_class_uses_variants_not_strings() {
use crate::error::Error;
assert_eq!(
H3FailureClass::from_error(&Error::H3Connect("x".into())),
H3FailureClass::Connectivity
);
assert_eq!(
H3FailureClass::from_error(&Error::H3Protocol("x".into())),
H3FailureClass::Protocol
);
assert_eq!(
H3FailureClass::from_error(&Error::H3ConnectionClosed("x".into())),
H3FailureClass::Closed
);
}
#[test]
fn learn_context_trust_rules() {
let good = AltSvcLearnContext {
is_https: true,
tls_authenticated: true,
via_proxy: false,
origin_matches_hop: true,
};
assert!(good.trustworthy());
for bad in [
AltSvcLearnContext {
is_https: false,
..good
},
AltSvcLearnContext {
tls_authenticated: false,
..good
},
AltSvcLearnContext {
via_proxy: true,
..good
},
AltSvcLearnContext {
origin_matches_hop: false,
..good
},
] {
assert!(!bad.trustworthy());
}
}
#[test]
fn quoted_string_enforces_512_byte_cap() {
let ok = format!("\"{}\"", "a".repeat(512));
let (value, rest) = parse_quoted_string(&ok).expect("512-byte value parses");
assert_eq!(value.len(), 512);
assert_eq!(rest, "");
let too_long = format!("\"{}\"", "a".repeat(513));
assert!(parse_quoted_string(&too_long).is_none());
}
}