footing 0.6.1

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! Cookie transport and validated browser attributes, enabled by `http-cookie`.
//!
//! [`CookieOptions`] builds a reusable [`CookiePolicy`] for one cookie name.
//! Defaults are `path: "/"`, no `domain`, `secure: true`, `http_only: true`,
//! `same_site: SameSite::Lax`, no `max_age`, and `partitioned: false`. Configure
//! selected fields with struct update syntax. Serde uses lowercase `same_site`
//! values (`"strict"`, `"lax"`, `"none"`) and human-readable `max_age` durations
//! such as `"30m"`; `None` leaves the cookie without an explicit lifetime.
//!
//! Use an opaque, cryptographically random credential issued by your application
//! and a name such as `__Host-session` over HTTPS. This module does not generate,
//! sign, encrypt, authenticate, or persist credentials.
//!
//! ```no_run
//! use std::time::Duration;
//! use axum::{
//!     http::{StatusCode, header::{CACHE_CONTROL, SET_COOKIE}},
//!     response::{AppendHeaders, IntoResponse},
//! };
//! use footing::http::cookie::{CookieError, CookieOptions, CookiePolicy};
//!
//! let policy = CookieOptions {
//!     max_age: Some(Duration::from_secs(30 * 60)),
//!     ..CookieOptions::default()
//! }.build("__Host-session")?;
//! assert_eq!(policy.name(), "__Host-session");
//!
//! // Call after the application has issued and stored the credential.
//! fn issued_cookie(
//!     policy: &CookiePolicy,
//!     credential: &str,
//! ) -> Result<impl IntoResponse, CookieError> {
//!     Ok((
//!         AppendHeaders([(SET_COOKIE, policy.set(credential)?)]),
//!         [(CACHE_CONTROL, "no-store")],
//!         StatusCode::NO_CONTENT,
//!     ))
//! }
//!
//! // Call after the application has revoked the credential.
//! fn cleared_cookie(policy: &CookiePolicy) -> impl IntoResponse {
//!     (
//!         AppendHeaders([(SET_COOKIE, policy.remove())]),
//!         [(CACHE_CONTROL, "no-store")],
//!         StatusCode::NO_CONTENT,
//!     )
//! }
//! # Ok::<(), CookieError>(())
//! ```
//!
//! `set` and `remove` return sensitive [`axum::http::HeaderValue`] values, which
//! redact their `Debug` output. Use [`axum::response::AppendHeaders`] so other
//! `Set-Cookie` fields survive; each cookie needs its own field. Values must use
//! cookie wire syntax. Names and values are not percent-encoded or decoded.
//! The 4096-byte limit on a generated `Set-Cookie` value is a conservative library
//! policy, not a guarantee that every browser will accept or retain the cookie.
//!
//! `build` validates the name, scope syntax, and attribute combinations.
//! `SameSite::None` and `Partitioned` require `Secure`. Prefix checks also cover
//! ASCII case variants: `__Secure-` requires `Secure`; `__Host-` additionally
//! requires `Path=/` and no `Domain`; `__Http-` requires `Secure` and `HttpOnly`;
//! `__Host-Http-` requires all four constraints. Scope validation does not verify
//! domain ownership, public suffixes, or the deployment's HTTPS configuration.
//! For local HTTP development, explicitly set `secure: false` with an ordinary
//! name; prefix, `SameSite::None`, and `Partitioned` constraints still apply.
//!
//! [`CookiePolicy::read`] examines every `Cookie` request field and matches the
//! configured name exactly, including case. It preserves raw name/value
//! semantics and removes one valid pair of surrounding value quotes. A target
//! name appearing more than once is an error, even if its values are equal.
//! Repetition of another name alone is allowed. The underlying parser tolerates
//! empty semicolon-separated fragments and surrounding whitespace; parser errors
//! and invalid name/value bytes are rejected. No match returns `Ok(None)`.
//! The target name and value together are limited to 4096 bytes; aggregate header
//! limits belong to the HTTP server. A matching value is returned as
//! [`crate::secret::SecretString`], whose debug and display output is redacted.
//! The original request headers still contain
//! the credential and must not be logged as plaintext.
//!
//! A parsed cookie remains an unverified credential. Pass it to the application's
//! validator before creating a principal or authenticated idempotency scope.
//! With `http-stack` enabled, integrate it through `HttpAuthenticationHook`.
//! The application supplies an applicable `WWW-Authenticate` challenge for `401`
//! responses using `ApiProblem::unauthorized`; the library never invents a Cookie
//! authentication scheme. Verifiers returning `Err(ApiProblem)` use that constructor too.
//!
//! ```no_run
//! # #[cfg(feature = "http-stack")]
//! # {
//! use std::sync::Arc;
//! use async_trait::async_trait;
//! use axum::http::request::Parts;
//! use footing::{
//!     http::{
//!         ApiProblem, AuthenticationChallenge, HttpAuthenticationHook, HttpMiddlewareConfig,
//!         HttpMiddlewareError, HttpMiddlewareStack, ProblemCode,
//!         VerifiedAuthentication,
//!         cookie::CookiePolicy,
//!     },
//!     secret::ExposeSecret,
//! };
//!
//! // The application implements this using its credential store and current
//! // expiry/revocation checks. Only verified identities may produce Some(...).
//! #[async_trait]
//! trait CredentialVerifier: Send + Sync + 'static {
//!     async fn verify(&self, credential: &str)
//!         -> Result<Option<VerifiedAuthentication>, ApiProblem>;
//! }
//!
//! struct CookieAuthentication {
//!     policy: CookiePolicy,
//!     verifier: Arc<dyn CredentialVerifier>,
//!     challenge: AuthenticationChallenge,
//! }
//!
//! #[async_trait]
//! impl HttpAuthenticationHook for CookieAuthentication {
//!     async fn authenticate(
//!         &self,
//!         request: &Parts,
//!     ) -> Result<Option<VerifiedAuthentication>, ApiProblem> {
//!         let credential = self.policy.read(&request.headers).map_err(|_| {
//!             ApiProblem::bad_request(
//!                 ProblemCode::from_static("invalid_cookie"),
//!                 "cookie header is invalid",
//!             )
//!         })?;
//!         let Some(credential) = credential else {
//!             return Ok(None);
//!         };
//!         self.verifier.verify(credential.expose_secret()).await?
//!             .map(Some)
//!             .ok_or_else(|| {
//!                 ApiProblem::unauthorized(
//!                     ProblemCode::from_static("invalid_session"),
//!                     "session credential is invalid or expired",
//!                     &self.challenge,
//!                 )
//!             })
//!     }
//! }
//!
//! fn authenticated_stack(
//!     policy: CookiePolicy,
//!     verifier: Arc<dyn CredentialVerifier>,
//!     challenge: AuthenticationChallenge,
//! ) -> Result<HttpMiddlewareStack, HttpMiddlewareError> {
//!     HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
//!         .with_authentication_hook(Arc::new(CookieAuthentication { policy, verifier, challenge }))
//!         .build()
//! }
//! # }
//! ```
//!
//! Session lifetime, rotation, revocation, and CSRF defenses belong to the host
//! application. The default `SameSite=Lax` is not a complete CSRF defense.
//! Removing a browser cookie does not revoke its credential on the server.
//!
//! `remove` emits an expired cookie even when the request contains no matching
//! cookie. Reuse the same policy that issued it: deletion must preserve the
//! original name, `Domain`/host-only choice, `Path`, and `Partitioned` setting.
//! Request cookies do not contain those attributes, so `read` cannot recover
//! them. A partitioned deletion affects the browser's current partition only;
//! it cannot clear the cookie from every top-level site partition.

use std::time::Duration;

use axum::http::{HeaderMap, HeaderValue, header};
use cookie::Cookie;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{
    result::{ClassifyError, ErrorCode, ErrorKind},
    secret::SecretString,
};

pub use cookie::SameSite;

/// Conservative maximum size of one complete `Set-Cookie` field, in bytes.
///
/// Includes its name, value and attributes. Browsers also impose total cookie
/// counts and storage limits; successfully generating a header does not guarantee
/// browser acceptance. Request reads limit the target name and value to this size;
/// the HTTP server remains responsible for aggregate request-header limits.
pub const MAX_COOKIE_HEADER_BYTES: usize = 4096;

/// Reusable cookie attributes, validated when bound to a name with [`Self::build`].
///
/// Defaults to `Secure`, `HttpOnly`, `SameSite=Lax`, `Path=/`, no `Domain`, and no
/// persistent lifetime. Changing a public field never silently fixes another:
/// incompatible security attributes fail validation at build time.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CookieOptions {
    /// Absolute ASCII path of at most 1024 bytes, without whitespace or semicolons.
    /// Defaults to `/`. Cookie paths are routing scopes, not authorization boundaries.
    pub path: String,
    /// ASCII DNS domain, without a leading/trailing dot, port, or IP address.
    ///
    /// Defaults to `None`, giving a host-only cookie. Domain names are normalized
    /// to lowercase. Applications must ensure ownership and browser acceptability;
    /// this library does not consult the Public Suffix List or the request host.
    pub domain: Option<String>,
    /// Whether the browser should send this cookie only over HTTPS. Defaults to `true`.
    pub secure: bool,
    /// Whether the browser hides this cookie from JavaScript. Defaults to `true`.
    pub http_only: bool,
    /// Cross-site sending policy. Defaults to `Lax`; `None` requires `secure=true`.
    #[serde(with = "SameSiteSerde")]
    pub same_site: SameSite,
    /// Optional persistent lifetime, expressed as positive whole seconds.
    ///
    /// `None` omits `Max-Age` and `Expires`. Browser session restoration can retain
    /// such cookies, so this is not a server-side credential-expiration guarantee.
    /// Serialized using human-readable durations such as `"30m"`.
    #[serde(with = "crate::settings::human_duration::option")]
    pub max_age: Option<Duration>,
    /// Whether to opt into partitioned browser storage. Requires `secure=true`.
    ///
    /// Defaults to `false`. Browser support varies; removing a partitioned cookie
    /// only affects the current partition, not all sites that have embedded it.
    pub partitioned: bool,
}

impl Default for CookieOptions {
    fn default() -> Self {
        Self {
            path: "/".to_owned(),
            domain: None,
            secure: true,
            http_only: true,
            same_site: SameSite::Lax,
            max_age: None,
            partitioned: false,
        }
    }
}

#[derive(Serialize, Deserialize)]
#[serde(remote = "SameSite", rename_all = "lowercase")]
enum SameSiteSerde {
    Strict,
    Lax,
    None,
}

impl CookieOptions {
    /// Binds these attributes to a case-sensitive cookie name and validates them.
    ///
    /// The name must be a nonempty HTTP token. Security-prefix constraints are
    /// checked case-insensitively: `__Secure-` requires HTTPS, `__Host-` also
    /// requires `Path=/` and no `Domain`, and `__Http-`/`__Host-Http-` additionally
    /// require `HttpOnly`. Prefix support in browsers does not authenticate a value.
    ///
    /// No I/O is performed, and invalid input is rejected without trimming it or
    /// silently changing security flags. The resulting policy can be shared by
    /// credential-setting, authentication, and logout handlers.
    pub fn build(self, name: impl Into<String>) -> Result<CookiePolicy, CookieError> {
        let name = name.into();
        if !valid_name(&name) {
            return Err(CookieError::InvalidName);
        }
        if !self.path.starts_with('/')
            || self.path.len() > 1024
            || !self
                .path
                .bytes()
                .all(|byte| byte.is_ascii_graphic() && byte != b';')
        {
            return Err(CookieError::InvalidPath);
        }
        if self
            .domain
            .as_deref()
            .is_some_and(|domain| !valid_domain(domain))
        {
            return Err(CookieError::InvalidDomain);
        }
        if self.same_site == SameSite::None && !self.secure {
            return Err(CookieError::InsecureSameSiteNone);
        }
        if self.partitioned && !self.secure {
            return Err(CookieError::InsecurePartitioned);
        }
        let host_prefix = has_prefix(&name, "__Host-");
        let http_prefix = has_prefix(&name, "__Http-") || has_prefix(&name, "__Host-Http-");
        if (host_prefix || http_prefix || has_prefix(&name, "__Secure-")) && !self.secure {
            return Err(CookieError::InsecurePrefix);
        }
        if host_prefix && (self.path != "/" || self.domain.is_some()) {
            return Err(CookieError::InvalidHostPrefix);
        }
        if http_prefix && !self.http_only {
            return Err(CookieError::NonHttpOnlyPrefix);
        }
        let max_age = self
            .max_age
            .map(|age| {
                if age.is_zero() || age.subsec_nanos() != 0 {
                    return Err(CookieError::InvalidMaxAge);
                }
                i64::try_from(age.as_secs())
                    .map(cookie::time::Duration::seconds)
                    .map_err(|_| CookieError::InvalidMaxAge)
            })
            .transpose()?;

        let mut template = Cookie::new(name, "");
        template.set_path(self.path);
        if let Some(domain) = self.domain {
            template.set_domain(domain.to_ascii_lowercase());
        }
        template.set_secure(self.secure);
        template.set_http_only(self.http_only);
        template.set_same_site(self.same_site);
        template.set_partitioned(self.partitioned);
        template.set_max_age(max_age);

        // Validate both forms once. Logout never needs a fallible rendering step
        // or the presence of a request cookie, and does not consult the clock.
        let empty_header = render(&template)?;
        let mut removal = template.clone();
        removal.set_max_age(cookie::time::Duration::ZERO);
        removal.set_expires(cookie::time::OffsetDateTime::UNIX_EPOCH);
        let removal = render(&removal)?;
        Ok(CookiePolicy {
            template,
            removal,
            max_value_bytes: MAX_COOKIE_HEADER_BYTES - empty_header.as_bytes().len(),
        })
    }
}

/// A validated cookie name and scope shared by issuance, reading, and removal.
///
/// This type contains no credential values. Generated headers are marked
/// sensitive, and reads return a [`SecretString`] with redacted diagnostics.
#[derive(Clone, Debug)]
pub struct CookiePolicy {
    template: Cookie<'static>,
    removal: HeaderValue,
    max_value_bytes: usize,
}

impl CookiePolicy {
    /// Returns the exact, case-sensitive cookie name.
    #[must_use]
    pub fn name(&self) -> &str {
        self.template.name()
    }

    /// Creates one sensitive `Set-Cookie` value using this policy's attributes.
    ///
    /// Accepts raw cookie-octet values, including the empty string. Whitespace,
    /// quotes, commas, semicolons, backslashes, control characters, and non-ASCII
    /// input are rejected. Nothing is percent-encoded or decoded; applications
    /// can encode structured data explicitly, for example as base64url.
    ///
    /// Append the header instead of replacing other `Set-Cookie` fields. Axum's
    /// [`axum::response::AppendHeaders`] supports this in response tuples.
    pub fn set(&self, value: &str) -> Result<HeaderValue, CookieError> {
        if value.len() > self.max_value_bytes {
            return Err(CookieError::TooLarge);
        }
        if !valid_value(value) {
            return Err(CookieError::InvalidValue);
        }
        let mut cookie = self.template.clone();
        cookie.set_value(value);
        render(&cookie)
    }

    /// Creates a sensitive deletion header with the same name and scope.
    ///
    /// Uses an empty value, `Max-Age=0`, and a fixed past `Expires`. Domain, path,
    /// security attributes, and partitioning are preserved. Always emits a
    /// header, even when the request has no cookie. Applications must separately
    /// revoke server-side credentials and remove any older scopes they issued.
    #[must_use]
    pub fn remove(&self) -> HeaderValue {
        self.removal.clone()
    }

    /// Reads exactly one cookie of this name across all request `Cookie` fields.
    ///
    /// Returns `None` when absent, and an empty secret when explicitly empty.
    /// Repeated target names are rejected even if their values are identical;
    /// unrelated duplicate names are allowed. Empty semicolon-separated fragments
    /// and surrounding whitespace are tolerated by the underlying parser. Invalid
    /// header text, parser errors and invalid name/value bytes are rejected.
    ///
    /// Names are case-sensitive and never percent-decoded. Values retain their
    /// raw cookie-octet representation, with one optional pair of surrounding
    /// quotes removed. Request cookies carry no trusted domain/path attributes:
    /// the result is an **unverified credential**, not an authenticated identity.
    pub fn read(&self, headers: &HeaderMap) -> Result<Option<SecretString>, CookieError> {
        let mut value = None;
        for header in headers.get_all(header::COOKIE) {
            let text = header.to_str().map_err(|_| CookieError::MalformedRequest)?;
            for parsed in Cookie::split_parse(text) {
                let parsed = parsed.map_err(|_| CookieError::MalformedRequest)?;
                let raw = parsed.value_trimmed();
                if !valid_name(parsed.name()) || !valid_value(raw) {
                    return Err(CookieError::MalformedRequest);
                }
                if parsed.name() != self.name() {
                    continue;
                }
                if value.is_some() {
                    return Err(CookieError::Duplicate);
                }
                if self.name().len() + raw.len() > MAX_COOKIE_HEADER_BYTES {
                    return Err(CookieError::TooLarge);
                }
                value = Some(SecretString::new(raw));
            }
        }
        Ok(value)
    }
}

/// Cookie configuration, rendering, or request-reading failures.
///
/// Errors contain no cookie names, values, raw headers, or source-parser errors.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum CookieError {
    /// A name is empty or contains characters outside the HTTP token grammar.
    #[error("cookie name must be a nonempty HTTP token")]
    InvalidName,
    /// A path is not an absolute ASCII path or contains unsafe attribute bytes.
    #[error(
        "cookie path must be absolute ASCII, at most 1024 bytes, without whitespace or semicolons"
    )]
    InvalidPath,
    /// A domain is not an ASCII DNS domain in the supported form.
    #[error(
        "cookie domain must be an ASCII DNS name without dots at its ends, ports, or IP addresses"
    )]
    InvalidDomain,
    /// A persistent lifetime is zero, fractional, or outside the supported range.
    #[error("cookie max_age must be a positive whole number of seconds fitting in i64")]
    InvalidMaxAge,
    /// Cross-site sending was requested without HTTPS-only delivery.
    #[error("SameSite=None requires Secure")]
    InsecureSameSiteNone,
    /// Partitioned storage was requested without HTTPS-only delivery.
    #[error("Partitioned requires Secure")]
    InsecurePartitioned,
    /// A reserved cookie-name prefix requires HTTPS-only delivery.
    #[error("cookie name prefix requires Secure")]
    InsecurePrefix,
    /// A host-prefixed name has a non-root path or an explicit domain.
    #[error("host-prefixed cookies require Path=/ and no Domain")]
    InvalidHostPrefix,
    /// An HTTP-prefixed name is exposed to JavaScript.
    #[error("HTTP-prefixed cookies require HttpOnly")]
    NonHttpOnlyPrefix,
    /// The generated field or target request cookie exceeds the size limit.
    #[error("cookie exceeds the supported size limit")]
    TooLarge,
    /// A value cannot be represented as raw cookie-octets.
    #[error("cookie value contains invalid bytes")]
    InvalidValue,
    /// A request contains invalid cookie syntax or header text.
    #[error("malformed Cookie request header")]
    MalformedRequest,
    /// A request contains more than one cookie with the policy's exact name.
    #[error("ambiguous duplicate cookie")]
    Duplicate,
}

impl ClassifyError for CookieError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> ErrorCode {
        ErrorCode::internal(match self {
            Self::InvalidName => "cookie_invalid_name",
            Self::InvalidPath => "cookie_invalid_path",
            Self::InvalidDomain => "cookie_invalid_domain",
            Self::InvalidMaxAge => "cookie_invalid_max_age",
            Self::InsecureSameSiteNone => "cookie_insecure_same_site_none",
            Self::InsecurePartitioned => "cookie_insecure_partitioned",
            Self::InsecurePrefix => "cookie_insecure_prefix",
            Self::InvalidHostPrefix => "cookie_invalid_host_prefix",
            Self::NonHttpOnlyPrefix => "cookie_non_http_only_prefix",
            Self::TooLarge => "cookie_too_large",
            Self::InvalidValue => "cookie_invalid_value",
            Self::MalformedRequest => "cookie_malformed_request",
            Self::Duplicate => "cookie_duplicate",
        })
    }
}

fn render(cookie: &Cookie<'_>) -> Result<HeaderValue, CookieError> {
    let encoded = cookie.to_string();
    if encoded.len() > MAX_COOKIE_HEADER_BYTES {
        return Err(CookieError::TooLarge);
    }
    let mut header = HeaderValue::try_from(encoded).map_err(|_| CookieError::InvalidValue)?;
    header.set_sensitive(true);
    Ok(header)
}

fn valid_name(name: &str) -> bool {
    !name.is_empty()
        && name.bytes().all(|byte| {
            byte.is_ascii_alphanumeric()
                || matches!(
                    byte,
                    b'!' | b'#'
                        | b'$'
                        | b'%'
                        | b'&'
                        | b'\''
                        | b'*'
                        | b'+'
                        | b'-'
                        | b'.'
                        | b'^'
                        | b'_'
                        | b'`'
                        | b'|'
                        | b'~'
                )
        })
}

fn valid_value(value: &str) -> bool {
    value
        .bytes()
        .all(|byte| matches!(byte, 0x21 | 0x23..=0x2b | 0x2d..=0x3a | 0x3c..=0x5b | 0x5d..=0x7e))
}

fn valid_domain(domain: &str) -> bool {
    !domain.is_empty()
        && domain.len() <= 253
        && domain.parse::<std::net::IpAddr>().is_err()
        && domain.split('.').all(|label| {
            let bytes = label.as_bytes();
            !bytes.is_empty()
                && bytes.len() <= 63
                && bytes[0].is_ascii_alphanumeric()
                && bytes[bytes.len() - 1].is_ascii_alphanumeric()
                && bytes
                    .iter()
                    .all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-')
        })
}

fn has_prefix(name: &str, prefix: &str) -> bool {
    name.get(..prefix.len())
        .is_some_and(|start| start.eq_ignore_ascii_case(prefix))
}