Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.references.safe_badges

Requirements index · View definition

evidence Valid

Requirement

The book preprocessor MUST escape requirement names and link targets when inserting badge HTML. It MUST encode badge label and message text in Shields.io URL path components so punctuation cannot change the badge URL structure.

Rationale

The code meets requirements.references.safe_badges, and each obligation has a test that asserts its outcome.

Obligations

  1. The preprocessor MUST escape requirement names when inserting badge HTML.
  2. The preprocessor MUST escape link targets when inserting badge HTML.
  3. The preprocessor MUST percent-encode badge label text in Shields.io URL path components.
  4. The preprocessor MUST percent-encode badge message text in Shields.io URL path components.

Code

  • Names in HTML (obligation 1):
    • src/lib.rs#fn[replace_definitions] runs the full name through escape_html as escaped_name. It uses escaped_name in the anchor id and in the aria-label.
    • The badge image goes through shield_badge, which calls escape_html on the label and message for the alt text and on the whole URL.
    • src/lib.rs#fn[reference_badge] builds its badge through the same shield_badge call.
  • Link targets (obligation 2):
    • replace_definitions wraps the detail-page href in escape_html(&chapter_href(...)).
    • reference_badge wraps the reference href in escape_html(&chapter_href(...)).
    • reference_badge also escapes the built-in’s hover title.
  • URL path encoding (obligations 3 and 4): src/lib.rs#fn[shield_badge] passes both the label and the message through shield_path_component. That function keeps only ASCII letters, digits and .. It maps space to _, _ to __ and - to --, and percent-encodes every other byte.
  • Reachability: shield_badge, escape_html, shield_path_component and chapter_href are all reached from the two {impl} items. replace_query_directives also uses shield_badge, so query badges get the same encoding.

Tests

  • src/lib.rs#mod[tests]/fn[badge_urls_percent_encode_punctuation_and_html_is_escaped] checks the exact encoded URL for / ? # % & < > " ' and a non-ASCII character. It also checks the escaped alt text, so it covers obligations 1, 3 and 4.
  • src/lib.rs#mod[tests]/fn[shields_badge_urls_escape_requirement_names] checks _ → __, - → -- and space → _, plus the alt text.
  • src/lib.rs#mod[tests]/fn[reference_link_targets_are_escaped] uses a chapter path containing &, ", < and >. It asserts that the reference badge href is escaped (obligation 2).
  • src/lib.rs#mod[tests]/fn[definition_evidence_link_targets_are_escaped] makes the same check for the detail-icon href and also checks the aria-label (obligations 1 and 2).

Gaps

  • None found.
  • Valid requirement names contain no HTML-special characters, so no test feeds a special-character name through the escaped_name calls in replace_definitions. A code comment says as much. The alt-text assertions exercise the same escape_html function on special characters.
  • No {fixme} references apply.

Inputs

Implementation

Input 2: outline src/lib.rs fn[replace_definitions]
// {impl}`requirements.index.navigation`
// {impl}`requirements.references.book_badges`
// {impl}`requirements.examples.definition`
// {impl}`requirements.examples.index`
fn replace_definitions(
    content: &str,
    namespace: &str,
    current_path: Option<&Path>,
    plan: Option<&index::DetailPlan>,
) -> String {
    let mut result = String::with_capacity(content.len());
    let mut cursor = 0;

    // A directive whose full name is invalid remains literal.
    for block in definition_blocks(content)
        .into_iter()
        .filter(|block| block.closed && valid_name(&full_requirement_name(namespace, &block.name)))
    {
        if block.start < cursor {
            continue;
        }
        result.push_str(&content[cursor..block.start]);
        let full_name = full_requirement_name(namespace, &block.name);
        // Valid names contain no HTML-special characters, so this escaping
        // only guards the inserted HTML against future name rules.
        // {impl}`requirements.references.safe_badges`
        let escaped_name = escape_html(&full_name);
        if block.kind == DefinitionKind::Term {
            if let Ok((phrase, body)) =
                terms::declaration(&content[block.body_start..block.body_end])
            {
                result.push_str(&format!(
                    "<strong id=\"{}\">{}</strong>\n\n",
                    escape_html(&block.kind.anchor(&full_name)),
                    terms::escaped_phrase(phrase)
                ));
                result.push_str(body);
                result.push('\n');
            } else {
                result.push_str(&content[block.start..block.end]);
            }
            cursor = block.end;
            continue;
        }
        let color = if block.kind == DefinitionKind::Example {
            "5b62a8"
        } else {
            "006ba8"
        };
        let badge = shield_badge(block.kind.badge(), &full_name, color);
        let detail_href = current_path
            .zip(plan)
            .and_then(|(current, plan)| plan.detail_path(&full_name).map(|path| (current, path)))
            .map(|(current, path)| escape_html(&chapter_href(current, path, None)));
        let anchor = format!("habeas-{}-{escaped_name}", block.kind.badge());
        let permalink = format!("#{anchor}").replace(".md", "%2Emd");
        result.push_str(&format!(
            "<span class=\"habeas-definition-badge\"><a class=\"habeas-req-badge\" id=\"{anchor}\" href=\"{permalink}\" title=\"Link to this definition\">{badge}</a>"
        ));
        if let Some(href) = &detail_href {
            result.push_str(&format!(
                "<a class=\"habeas-detail-icon\" href=\"{href}\" style=\"background-color: #{color}\" title=\"View evidence\" aria-label=\"View evidence for {escaped_name}\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"#fff\" stroke-width=\"1.5\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M3 8h10M8 3l5 5-5 5\"/></svg></a>"
            ));
        }
        result.push_str("</span>\n\n");
        // Option lines such as anchors are metadata, not body text.
        let body = &content[block.text_start..block.body_end];
        let body = if block.kind == DefinitionKind::Requirement {
            replace_query_directives(body)
        } else {
            body.to_owned()
        };
        result.push_str(&replace_definitions(&body, namespace, current_path, plan));
        result.push('\n');
        cursor = block.end;
    }

    result.push_str(&content[cursor..]);
    result
}
Input 3: outline src/lib.rs fn[reference_badge]
/// The badge for a valid `{impl}`, `{cite}`, or `{test}` reference: a link to
/// a project definition, or an unlinked badge whose hover text gives a
/// built-in's text. Returns `None` for a reference that must remain literal.
// {impl}`requirements.references.safe_badges`
// {impl}`requirements.index.navigation`
// {impl}`requirements.examples.index`
fn reference_badge(
    kind: ReferenceKind,
    name: &str,
    current_path: &Path,
    definitions: &BTreeMap<String, Definition>,
) -> Option<String> {
    // A `{fixme}` has no badge; a named one is invalid in the book and an
    // unnamed one is not a reference.
    if kind == ReferenceKind::Fixme {
        return None;
    }
    let label = kind.label();
    let badge = shield_badge(label, name, kind.color());
    if let Some(builtin) = builtins::builtin(name) {
        builtin.check(kind).ok()?;
        return Some(format!(
            "<span class=\"habeas-req-badge habeas-req-ref-{label} habeas-builtin\" title=\"{}\">{badge}</span>",
            escape_html(builtin.text())
        ));
    }
    let target = definitions.get(name)?;
    if target.kind == DefinitionKind::Term {
        return None;
    }
    let href = escape_html(&chapter_href(
        current_path,
        &target.path,
        Some(&target.kind.anchor(name)),
    ));
    Some(format!(
        "<a class=\"habeas-req-badge habeas-req-ref-{label}\" href=\"{href}\">{badge}</a>"
    ))
}

Tests

Input 4: outline src/lib.rs mod[tests]/fn[definition_evidence_link_targets_are_escaped]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[definition_evidence_link_targets_are_escaped]
  • Kind: fn
  • src/lib.rs:1392–1427
    // {test}`requirements.references.safe_badges`
    // {test}`requirements.index.navigation`
    #[test]
    fn definition_evidence_link_targets_are_escaped() {
        let mut book = Book::new();
        book.push_item(Chapter::new(
            "Rules",
            ":::{req} ready\nReady.\n:::\n".into(),
            "rules.md",
            vec![],
        ));
        book.push_item(Chapter::new(
            "Index",
            ":::{requirements-index}\n:::\n".into(),
            "a&b \"q\" <x>.md",
            vec![],
        ));
        let root = book_root();
        preprocess_book(&mut book, root.path()).unwrap();
        let content = &book.chapters().next().unwrap().content;
        let icon = content
            .split("<a class=\"habeas-detail-icon\"")
            .nth(1)
            .unwrap()
            .split("</a>")
            .next()
            .unwrap();
        assert!(
            icon.contains("href=\"a&amp;b &quot;q&quot; &lt;x&gt;/rules.ready.html\""),
            "{icon}"
        );
        assert!(icon.contains("aria-label=\"View evidence for rules.ready\""));
        assert!(!icon.contains("a&b"));
        assert!(!icon.contains("\"q\""));
        assert!(!icon.contains("<x>"));
    }
Input 5: outline src/lib.rs mod[tests]/fn[badge_urls_percent_encode_punctuation_and_html_is_escaped]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[badge_urls_percent_encode_punctuation_and_html_is_escaped]
  • Kind: fn
  • src/lib.rs:1567–1584
    // {test}`requirements.references.safe_badges`
    #[test]
    fn badge_urls_percent_encode_punctuation_and_html_is_escaped() {
        let badge = shield_badge("a/b?c", "x#y%z&w<v>\"u' caf\u{e9}", "006ba8");
        let url = badge
            .split("src=\"")
            .nth(1)
            .and_then(|rest| rest.split('"').next())
            .unwrap();
        assert_eq!(
            url,
            "https://img.shields.io/badge/a%2Fb%3Fc-x%23y%25z%26w%3Cv%3E%22u%27_caf%C3%A9-006ba8?style=flat-square&amp;labelColor=555"
        );
        assert!(
            badge.contains("alt=\"a/b?c x#y%z&amp;w&lt;v&gt;&quot;u&#39; caf\u{e9}\""),
            "{badge}"
        );
    }
Input 6: outline src/lib.rs mod[tests]/fn[reference_link_targets_are_escaped]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[reference_link_targets_are_escaped]
  • Kind: fn
  • src/lib.rs:1586–1621
    // {test}`requirements.references.safe_badges`
    #[test]
    fn reference_link_targets_are_escaped() {
        let mut book = Book::new();
        let mut target = Chapter::new(
            "Rules",
            ":::{req} ready\nReady.\n:::".to_owned(),
            "rules.md",
            Vec::new(),
        );
        // The rendered path, unlike the source path, may contain characters
        // that are special in HTML.
        target.path = Some("a&b \"q\" <x>.md".into());
        book.push_item(target);
        book.push_item(Chapter::new(
            "Guide",
            "See {cite}`rules.ready`.".to_owned(),
            "guide.md",
            Vec::new(),
        ));
        let root = book_root();
        preprocess_book(&mut book, root.path()).unwrap();
        let guide = book
            .chapters()
            .find(|chapter| chapter.name == "Guide")
            .unwrap();
        assert!(
            guide
                .content
                .contains("href=\"a&amp;b &quot;q&quot; &lt;x&gt;.html#habeas-req-rules.ready\""),
            "{}",
            guide.content
        );
        assert!(!guide.content.contains("\"q\""), "{}", guide.content);
        assert!(!guide.content.contains("<x>"), "{}", guide.content);
    }
Input 7: outline src/lib.rs mod[tests]/fn[shields_badge_urls_escape_requirement_names]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[shields_badge_urls_escape_requirement_names]
  • Kind: fn
  • src/lib.rs:1741–1753
    // {test}`requirements.references.book_badges`
    // {test}`requirements.references.safe_badges`
    #[test]
    fn shields_badge_urls_escape_requirement_names() {
        let badge = shield_badge("req", "requirements.foo_bar-baz", "006ba8");
        assert!(badge.contains(
            "https://img.shields.io/badge/req-requirements.foo__bar--baz-006ba8?style=flat-square&amp;labelColor=555"
        ));
        assert!(badge.contains("alt=\"req requirements.foo_bar-baz\""));

        let status = shield_badge("evidence", "Determination false", "ae5d14");
        assert!(status.contains("badge/evidence-Determination_false-ae5d14"));
    }

Other sources

Input 1: requirements selection requirements.references.safe_badges
:::{req} safe_badges
The book preprocessor MUST escape requirement names and link targets when inserting badge HTML. It MUST encode badge label and message text in Shields.io URL path components so punctuation cannot change the badge URL structure.
:::
Input 8: outline src/lib.rs fn[shield_badge]
// {impl}`requirements.index.detail_format`
pub(crate) fn shield_badge(label: &str, message: &str, color: &str) -> String {
    let url = format!(
        "https://img.shields.io/badge/{}-{}-{color}?style=flat-square&labelColor=555",
        shield_path_component(label),
        shield_path_component(message)
    );
    format!(
        "<img class=\"habeas-shield\" src=\"{}\" alt=\"{} {}\" loading=\"lazy\">",
        escape_html(&url),
        escape_html(label),
        escape_html(message)
    )
}
Input 9: outline src/lib.rs fn[escape_html]
fn escape_html(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for character in value.chars() {
        match character {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&#39;"),
            _ => escaped.push(character),
        }
    }
    escaped
}
Input 10: outline src/lib.rs fn[chapter_href]
// {impl}`requirements.index.navigation`
// Relative chapter links, including `../` from nested chapters.
pub(crate) fn chapter_href(current: &Path, target: &Path, anchor: Option<&str>) -> String {
    let current_dir = current
        .parent()
        .into_iter()
        .flat_map(Path::components)
        .filter_map(|component| match component {
            Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
            _ => None,
        })
        .collect::<Vec<_>>();
    let target_html = target
        .with_extension("html")
        .components()
        .filter_map(|component| match component {
            Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
            _ => None,
        })
        .collect::<Vec<_>>();
    let shared = current_dir
        .iter()
        .zip(&target_html)
        .take_while(|(left, right)| left == right)
        .count();
    let mut href = "../".repeat(current_dir.len() - shared);
    href.push_str(&target_html[shared..].join("/"));
    if let Some(anchor) = anchor {
        href.push('#');
        href.push_str(anchor);
    }
    // mdBook interprets ".md" inside a generated URL as a chapter suffix.
    href.replace(".md", "%2Emd")
}
Input 11: outline src/lib.rs fn[replace_query_directives]
/// Renders each query directive in a requirement body as a badge naming its
/// kind and name, followed by its code block. Directives in code blocks
/// stay literal.
// {impl}`requirements.references.distributed`
fn replace_query_directives(body: &str) -> String {
    let code = code_block_ranges(body);
    let mut result = String::with_capacity(body.len());
    let mut closing: Option<String> = None;
    let mut offset = 0;
    for line in body.split_inclusive('\n') {
        let start = offset;
        offset += line.len();
        let text = line.trim_end_matches(['\n', '\r']);
        if code.iter().any(|range| range.contains(&start)) {
            result.push_str(line);
            continue;
        }
        if closing.as_deref() == Some(text.trim_end()) {
            closing = None;
            continue;
        }
        if closing.is_none()
            && let Some((fence, kind, name)) = structural::query_fence(text)
        {
            result.push_str("<span class=\"habeas-query-badge\">");
            result.push_str(&shield_badge(kind.label(), name, "6c4f8a"));
            result.push_str("</span>\n\n");
            closing = Some(fence.to_owned());
            continue;
        }
        result.push_str(line);
    }
    result
}