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
//! Documentation pages and their supporting routes.

mod assets;
mod options;
mod page;

use axum::{
    Router,
    body::{Body, Bytes},
    http::{HeaderMap, HeaderValue, StatusCode, Uri, header},
    response::{IntoResponse, Redirect},
    routing::{MethodRouter, get},
};
use serde_json::Value;
use sha2::{Digest, Sha256};
use thiserror::Error;
use utoipa::openapi::OpenApi;

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

#[cfg(feature = "rapidoc-embedded")]
pub use assets::EMBEDDED_RAPIDOC_VERSION;
#[cfg(feature = "redoc-embedded")]
pub use assets::EMBEDDED_REDOC_VERSION;
pub use assets::{DocsAssets, DocsUi};

/// Invalid documentation route, options, or template.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DocsError {
    /// A mount path is not an absolute, literal URL path.
    #[error("invalid documentation mount path: {0}")]
    InvalidPath(String),
    /// A script URL is neither an HTTP(S) URL nor a relative URL.
    #[error("invalid documentation script URL: {0}")]
    InvalidAssetUrl(String),
    /// Native options have an invalid container type.
    #[error("invalid documentation options: {0}")]
    InvalidOptions(&'static str),
    /// A required template slot is missing or repeated.
    #[error("documentation template must contain exactly one {0} slot")]
    InvalidTemplate(&'static str),
    /// The OpenAPI document could not be serialized.
    #[error("cannot serialize the OpenAPI document: {0}")]
    Serialize(#[from] serde_json::Error),
}

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

    fn error_code(&self) -> ErrorCode {
        ErrorCode::internal(match self {
            Self::InvalidPath(_) => "docs_invalid_path",
            Self::InvalidAssetUrl(_) => "docs_invalid_asset_url",
            Self::InvalidOptions(_) => "docs_invalid_options",
            Self::InvalidTemplate(_) => "docs_invalid_template",
            Self::Serialize(_) => "docs_serialization_failed",
        })
    }
}

/// Builds a ReDoc or RapiDoc page and all supporting routes.
///
/// Available with `openapi`; nothing is mounted until explicitly merged into
/// the application. Select the renderer and resource source with [`DocsUi`].
/// Its feature/constructor table covers bundled, caller-supplied and URL assets.
/// Native [`super::redoc::Redoc`] integration also remains available.
/// Set the main page's HTML language with [`Self::with_lang`], which also shows
/// how to mount separate translated documents.
///
/// # Routes and access control
///
/// Mounting at `/docs` serves the page at `/docs/`, redirects `/docs`, and
/// serves `openapi.json`, `options.json`, `init.js`, `page.css`, and local
/// assets (`ui.js`, plus `ui.LICENSE.txt` for embedded bundles) below it.
/// RapiDoc also serves `oauth-receiver.html` and `oauth-receiver.js` for OAuth
/// callbacks. Register the callback page's full public URL with the provider;
/// it uses the same application access control as the other documentation routes.
/// All generated URLs are page-relative, including redirects, so nesting and
/// reverse proxies work when they preserve this layout. Forwarded headers are
/// not consulted.
/// Prefer mounting at `/docs` and nesting that router at `/api`. When mounting
/// at `/`, nest at `/api/docs/` with the trailing slash so relative resource URLs
/// resolve correctly. Axum then serves `/api/docs/`; the slashless `/api/docs`
/// entry does not match and is not redirected automatically.
///
/// Apply application authentication to the returned router **before** merging.
/// Page, JSON and local resources then share the same middleware. A bearer
/// header on the HTML request alone does not authenticate browser subrequests;
/// use a suitable cookie or HTTP authentication policy. Nothing enforces an
/// administrator role automatically. Responses default to
/// `Cache-Control: private, no-cache`; middleware can override it. Resources
/// include content-based weak ETags and support conditional GET/HEAD requests.
/// A matching `If-None-Match` returns 304 after application middleware runs.
/// Only `If-Match: *` satisfies a strong precondition: specific entity tags
/// cannot strongly match a weak validator and return 412 with `no-store`.
/// `If-Match` is evaluated before `If-None-Match`.
///
/// # Resources and CSP
///
/// Embedded bundles are version-pinned and require no build-time downloads.
/// Presets use system fonts; RapiDoc's preset disables CDN font loading.
/// Applications must localize any external references, images, CSS or URLs in
/// their own documents, overrides and templates for fully offline deployment.
/// Turning off presets restores each renderer's native defaults, including
/// RapiDoc's external fonts. OpenAPI content and native options are trusted
/// application input; neither renderer is an HTML sanitizer for arbitrary specs.
///
/// The generated page contains no inline scripts or interpolated JavaScript.
/// An external initializer fetches JSON options, then starts the selected UI.
/// Renderers create runtime styles; ReDoc additionally uses a Blob search worker.
/// `HttpMiddlewareConfig::documentation()` (`http-stack`) supplies a CSP for these
/// same-origin resources while forbidding inline scripts and framing. Customize
/// it through `HttpMiddlewareSettings::documentation()` (`http-stack`) when using
/// external assets, API servers or token endpoints. Authorization remains
/// application policy.
///
/// RapiDoc popup OAuth needs to retain `window.opener` across a cross-origin
/// provider and back to the callback. The standard HTTP stack's
/// `Cross-Origin-Opener-Policy: same-origin` breaks that flow. Configure a separate
/// stack using `HttpMiddlewareConfig::documentation()` (`http-stack`), then merge
/// it with the separately layered API router, as shown below and in
/// `examples/docs.rs`. Outer middleware and reverse proxies must preserve this
/// policy. For finer control, the documentation HTML can use
/// `same-origin-allow-popups`, while `oauth-receiver.html` must use `unsafe-none`
/// or omit COOP; setting `same-origin-allow-popups` on both pages also breaks the
/// return navigation. Add trusted API and token origins to CSP `connect-src`.
///
/// # Example
///
/// ```rust
/// # #[cfg(feature = "http-stack")]
/// # {
/// use footing::http::{HttpMiddlewareConfig, HttpMiddlewareStack,
///     openapi::{DocsAssets, DocsUi, OpenApiDocs, utoipa}};
/// use utoipa::openapi::{OpenApi, Info, path::Paths};
///
/// let document = OpenApi::new(Info::new("Inventory API", "1"), Paths::new());
/// // The application must also serve this script URL.
/// let ui = DocsUi::RapiDoc(DocsAssets::url("/static/rapidoc-min.js"));
/// let docs = OpenApiDocs::new(document, "/docs", ui)
///     .with_options(serde_json::json!({"theme": "dark", "primary-color": "#8b2252"}))
///     .into_router::<()>()?;
/// let docs = HttpMiddlewareStack::builder(HttpMiddlewareConfig::documentation())
///     .build()?.apply(docs);
/// // Apply application authentication to docs before merging into the app.
/// let api = HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
///     .build()?.apply(axum::Router::new());
/// let app = api.merge(docs);
/// # let _: axum::Router = app;
/// # }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[must_use]
pub struct OpenApiDocs {
    document: OpenApi,
    path: String,
    ui: DocsUi,
    title: String,
    lang: String,
    options: Value,
    preset: bool,
    template: String,
}

impl std::fmt::Debug for OpenApiDocs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OpenApiDocs")
            .field("path", &self.path)
            .field("ui", &self.ui)
            .field("title", &self.title)
            .field("lang", &self.lang)
            .field("preset", &self.preset)
            .finish_non_exhaustive()
    }
}

impl OpenApiDocs {
    /// Configures a page with the selected renderer, assets, and presentation preset.
    ///
    /// `ui` selects both the renderer and its asset source for this page. Enabling
    /// an embedded feature makes its [`DocsUi`] constructor available; it does not
    /// select the UI automatically. Call [`Self::into_router`] and merge the result
    /// into the application to serve the page.
    ///
    /// The title defaults to the document's `info.title`. Paths are validated by
    /// [`Self::into_router`]; `/`, `/docs`, and `/docs/` are supported. Parameters,
    /// wildcards, percent escapes, dot segments, and empty segments are rejected.
    pub fn new(document: OpenApi, path: impl Into<String>, ui: DocsUi) -> Self {
        Self {
            title: document.info.title.clone(),
            document,
            path: path.into(),
            ui,
            lang: "en".to_owned(),
            options: serde_json::json!({}),
            preset: true,
            template: include_str!("template.html").to_owned(),
        }
    }

    /// Replaces the page title. Text is HTML-escaped, never interpreted as markup.
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Sets the main documentation page's HTML `lang` attribute; defaults to `en`.
    ///
    /// Supply a BCP 47 language tag such as `zh-CN`, `zh-Hans` or `en`, or an
    /// empty string to declare an unknown language, following the
    /// [HTML language rules](https://html.spec.whatwg.org/multipage/dom.html#the-lang-and-xml:lang-attributes).
    /// The value is HTML-escaped without validation or normalization. Custom
    /// templates must place `{{lang}}` in a quoted `<html lang="{{lang}}">`
    /// attribute; see [`Self::with_template`].
    ///
    /// This declares the content's language for browsers and assistive technology.
    /// It does not translate document text or renderer controls, select a UI
    /// locale, or negotiate `Accept-Language`. The separate OAuth callback page
    /// retains its English language declaration.
    ///
    /// Applications can mount a translated OpenAPI document for each language:
    ///
    /// ```rust
    /// use axum::Router;
    /// use footing::http::openapi::{DocsAssets, DocsUi, OpenApiDocs, utoipa};
    /// use utoipa::openapi::{Info, OpenApi, path::Paths};
    ///
    /// let mut app = Router::<()>::new();
    /// for (path, lang, title) in [
    ///     ("/docs/zh", "zh-CN", "库存 API"),
    ///     ("/docs/en", "en", "Inventory API"),
    /// ] {
    ///     // Supply translated summaries and descriptions in each document too.
    ///     let document = OpenApi::new(Info::new(title, "1"), Paths::new());
    ///     // The application must also serve this script URL.
    ///     let ui = DocsUi::RapiDoc(DocsAssets::url("/static/rapidoc-min.js"));
    ///     let docs = OpenApiDocs::new(document, path, ui)
    ///         .with_lang(lang)
    ///         .into_router()?;
    ///     app = app.merge(docs);
    /// }
    /// // Apply the application's documentation access control to `app`.
    /// # let _ = app;
    /// # Ok::<(), footing::http::openapi::DocsError>(())
    /// ```
    pub fn with_lang(mut self, lang: impl Into<String>) -> Self {
        self.lang = lang.into();
        self
    }

    /// Sets native options, replacing any previous caller overrides.
    ///
    /// Precedence: renderer defaults, footing preset, then caller options.
    /// ReDoc takes its native JSON object: objects merge recursively, while
    /// arrays, scalars and null replace previous values. The root and `theme`
    /// must be objects. Use `sanitize`, `hideDownloadButtons`,
    /// `schemasExpansionLevel` and `jsonSamplesExpandLevel`; their legacy aliases
    /// are rejected, even without presets or alongside a canonical name.
    /// Existing upstream `redoc::Config` values can be passed with
    /// `with_options(config.load())` after importing that trait.
    ///
    /// RapiDoc takes native kebab-case attribute names, with string, boolean or
    /// number values. Values are passed as strings; overrides
    /// replace preset attributes. For example `{"theme":"dark","allow-try":false}`.
    /// Event handlers and `spec-url` are rejected; the component owns the spec URL.
    /// Unknown attributes pass through for newer compatible bundles.
    ///
    /// Both presets enable search/downloads and use system fonts. ReDoc expands
    /// one schema level and two sample levels. RapiDoc uses focused mode with
    /// table schemas, expanded descriptions, the schema tab, colored method
    /// labels, method sorting and a blue primary color. It disables CDN fonts
    /// and keeps native theme selection, schema expansion and document loaders.
    /// RapiDoc keeps authentication in memory by default. Setting `persist-auth`
    /// to `true` opts into browser localStorage shared by RapiDoc pages on the
    /// same origin; only enable it when that credential sharing is intended.
    /// Its try-it console remains available; disabling it is a UI preference,
    /// not an authorization boundary.
    pub fn with_options(mut self, options: Value) -> Self {
        self.options = options;
        self
    }

    /// Disables footing's preset while preserving the caller's native options.
    pub fn without_preset(mut self) -> Self {
        self.preset = false;
        self
    }

    /// Replaces the page template with trusted application HTML.
    ///
    /// Include exactly one of each slot: `{{lang}}` in a quoted
    /// `<html lang="{{lang}}">` attribute, `{{title}}` in an HTML text context,
    /// `{{head}}` in `<head>`, and `{{body}}` in `<body>`. Language and title values
    /// are escaped; head and body contain the component's generated elements.
    /// Slots are substituted once, so slot-like text inside a language, title or
    /// URL is not interpreted a second time.
    ///
    /// Applications own additional markup/scripts and their CSP, resource and
    /// trust requirements. This is not a sanitizer for arbitrary HTML. Custom
    /// templates must not change URL resolution with a `<base>` element.
    ///
    /// ```rust
    /// # use footing::http::openapi::{DocsAssets, DocsUi, OpenApiDocs};
    /// # use footing::http::openapi::utoipa::openapi::{OpenApi, Info, path::Paths};
    /// # let document = OpenApi::new(Info::new("Inventory API", "1"), Paths::new());
    /// # let docs = OpenApiDocs::new(document, "/docs", DocsUi::Redoc(DocsAssets::url("/static/redoc.js")));
    /// let docs = docs.with_title("Developer reference").with_template(r#"<!doctype html>
    /// <html lang="{{lang}}">
    /// <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
    /// <title>{{title}}</title>{{head}}</head>
    /// <body><header>Developer reference</header>{{body}}</body>
    /// </html>"#);
    /// # let _: axum::Router = docs.into_router()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn with_template(mut self, template: impl Into<String>) -> Self {
        self.template = template.into();
        self
    }

    /// Validates configuration and creates the complete, composable route set.
    ///
    /// The document and options are serialized once and shared across requests.
    /// The state type is left to the application. Conflicts when merging this
    /// router with application routes follow Axum's normal panic behavior.
    ///
    /// Protect the complete route set using an application's authentication
    /// middleware. For applications that install `VerifiedAuthentication` (`http-stack`)
    /// in an outer layer, [`crate::http::CurrentPrincipal`] rejects requests
    /// without a verified principal. Local assets share the same guard:
    ///
    /// ```no_run
    /// use axum::{Router, middleware};
    /// use footing::http::{AuthenticationChallenge, CurrentPrincipal, openapi::{DocsAssets, DocsUi, OpenApiDocs}};
    /// # use footing::http::openapi::utoipa::openapi::{OpenApi, Info, path::Paths};
    /// # let document = OpenApi::new(Info::new("Inventory API", "1"), Paths::new());
    ///
    /// let assets = DocsAssets::local(std::fs::read("assets/redoc.standalone.js")?);
    /// let challenge = AuthenticationChallenge::try_new("Basic realm=\"docs\"")?;
    /// let docs = OpenApiDocs::new(document, "/docs", DocsUi::Redoc(assets))
    ///     .into_router::<()>()?
    ///     .route_layer(middleware::from_extractor_with_state::<CurrentPrincipal, _>(challenge));
    /// let app = Router::new().merge(docs);
    /// // The outer authentication layer must validate credentials before this guard.
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn into_router<S: Clone + Send + Sync + 'static>(self) -> Result<Router<S>, DocsError> {
        let mount = mount_path(&self.path)?;
        let options = options::resolve(self.options, self.preset, &self.ui)?;
        let script_url = self.ui.assets().script_url()?;
        let html = page::render(
            &self.template,
            &self.title,
            &self.lang,
            script_url,
            self.ui.name(),
        )?;
        let mut router = Router::new()
            .route(
                &format!("{mount}/"),
                resource("text/html; charset=utf-8", html),
            )
            .route(
                &format!("{mount}/openapi.json"),
                resource("application/json", serde_json::to_vec(&self.document)?),
            )
            .route(
                &format!("{mount}/options.json"),
                resource("application/json", serde_json::to_vec(&options)?),
            )
            .route(
                &format!("{mount}/init.js"),
                resource(
                    "text/javascript; charset=utf-8",
                    include_bytes!("init.js").as_slice(),
                ),
            )
            .route(
                &format!("{mount}/page.css"),
                resource(
                    "text/css; charset=utf-8",
                    include_bytes!("page.css").as_slice(),
                ),
            );
        if matches!(&self.ui, DocsUi::RapiDoc(_)) {
            router = router
                .route(
                    &format!("{mount}/oauth-receiver.html"),
                    resource(
                        "text/html; charset=utf-8",
                        include_bytes!("oauth-receiver.html").as_slice(),
                    )
                    .layer(axum::middleware::map_response(
                        |mut response: axum::response::Response| async move {
                            response.headers_mut().insert(
                                header::CACHE_CONTROL,
                                HeaderValue::from_static("no-store"),
                            );
                            response.headers_mut().insert(
                                header::REFERRER_POLICY,
                                HeaderValue::from_static("no-referrer"),
                            );
                            response
                        },
                    )),
                )
                .route(
                    &format!("{mount}/oauth-receiver.js"),
                    resource(
                        "text/javascript; charset=utf-8",
                        include_bytes!("oauth-receiver.js").as_slice(),
                    ),
                );
        }
        if !mount.is_empty() {
            let leaf = mount.rsplit('/').next().unwrap_or_default().to_owned();
            router = router.route(
                mount,
                get(move |uri: Uri| {
                    let mut location = format!("{leaf}/");
                    if let Some(query) = uri.query() {
                        location.push('?');
                        location.push_str(query);
                    }
                    async move {
                        (
                            [(header::CACHE_CONTROL, "private, no-cache")],
                            Redirect::permanent(&location),
                        )
                    }
                }),
            );
        }
        Ok(self.ui.into_assets().mount(router, mount))
    }
}

fn mount_path(path: &str) -> Result<&str, DocsError> {
    let mount = path.strip_suffix('/').unwrap_or(path);
    if !path.starts_with('/')
        || !path
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"/-._~".contains(&b))
        || (!mount.is_empty()
            && mount[1..]
                .split('/')
                .any(|s| s.is_empty() || s == "." || s == ".."))
    {
        return Err(DocsError::InvalidPath(path.to_owned()));
    }
    Ok(mount)
}

fn resource<S: Clone + Send + Sync + 'static>(
    content_type: &'static str,
    bytes: impl Into<Bytes>,
) -> MethodRouter<S> {
    let bytes = bytes.into();
    let digest = Sha256::digest(&bytes);
    let hex = crate::http::to_lower_hex(&digest);
    // Weak validators remain valid when outer middleware compresses the body.
    let etag = format!("W/\"{hex}\"");
    get(move |headers: HeaderMap| {
        // The selected representation exists, but its weak validator cannot
        // satisfy a concrete If-Match. The wildcard is valid only on its own.
        let mut if_match = headers.get_all(header::IF_MATCH).iter();
        let precondition_failed = if_match.next().is_some_and(|value| {
            value.as_bytes().trim_ascii() != b"*" || if_match.next().is_some()
        });
        let not_modified = headers
            .get_all(header::IF_NONE_MATCH)
            .iter()
            .any(|value| matches_etag(value.as_bytes(), hex.as_bytes()));
        let bytes = bytes.clone();
        let etag = etag.clone();
        async move {
            let (status, body) = if precondition_failed {
                (StatusCode::PRECONDITION_FAILED, Body::empty())
            } else if not_modified {
                // An unspecified size prevents Axum from adding Content-Length: 0
                // to a 304, where that header would describe the original resource.
                (
                    StatusCode::NOT_MODIFIED,
                    Body::from_stream(Body::empty().into_data_stream()),
                )
            } else {
                (StatusCode::OK, Body::from(bytes))
            };
            (
                status,
                [
                    (header::CONTENT_TYPE, content_type),
                    (
                        header::CACHE_CONTROL,
                        if precondition_failed {
                            "no-store"
                        } else {
                            "private, no-cache"
                        },
                    ),
                    (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
                    // Keep the validator response consistent with representations
                    // compressed by an outer HTTP middleware stack.
                    (header::VARY, "accept-encoding"),
                ],
                [(header::ETAG, etag)],
                body,
            )
                .into_response()
        }
    })
}

// If-None-Match uses weak comparison. Parse quoted values so commas inside an
// opaque tag cannot be mistaken for separators or a wildcard.
fn matches_etag(mut value: &[u8], expected: &[u8]) -> bool {
    if value.trim_ascii() == b"*" {
        return true;
    }
    let mut matched = false;
    loop {
        value = value.trim_ascii_start();
        if value.is_empty() {
            return matched;
        }
        if let Some(rest) = value.strip_prefix(b",") {
            value = rest;
            continue;
        }
        let Some(tag) = value
            .strip_prefix(b"W/")
            .unwrap_or(value)
            .strip_prefix(b"\"")
        else {
            return false;
        };
        let Some(end) = tag.iter().position(|byte| *byte == b'"') else {
            return false;
        };
        let opaque = &tag[..end];
        if !opaque
            .iter()
            .all(|byte| *byte == 0x21 || *byte >= 0x23 && *byte != 0x7f)
        {
            return false;
        }
        matched |= opaque == expected;
        value = tag[end + 1..].trim_ascii_start();
        if !value.is_empty() && !value.starts_with(b",") {
            return false;
        }
    }
}