safehtml 0.2.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation
//! Borrowed, `no_std` counterparts of the owned safe types.
//!
//! Each `*Str` type is a `#[repr(transparent)]` wrapper around `str` carrying
//! the same safety contract as its owned counterpart, playing the role `str`
//! plays for `String` (or `Path` for `PathBuf`). Because they hold no
//! allocation, they extend type-driven security to `no_std` / zero-allocation
//! environments:
//!
//! - `const` construction from vetted literals via `from_constant`, usable in
//!   `const`/`static` items.
//! - With the `alloc` feature, the owned types [`Deref`](core::ops::Deref) to
//!   their borrowed counterparts, and
//!   [`ToOwned`](alloc::borrow::ToOwned)/[`From`] convert back, so APIs can
//!   accept `&SafeHtmlStr` and callers may pass either form (including
//!   `Cow<SafeHtmlStr>`).
//!
//! Escaping into a fixed buffer and wrapping the result requires the `unsafe`
//! `from_str_unchecked` constructor, since the buffer's contents cannot be
//! proven safe at compile time:
//!
//! ```rust
//! use safehtml::{SafeHtmlStr, escape_html_and_coerce_to};
//!
//! let mut buf = heapless_buf(); // e.g. heapless::String<64>, or any fmt::Write
//! escape_html_and_coerce_to("<script>", &mut buf).unwrap();
//! // SAFETY: `buf` holds only output of the HTML escaper.
//! let safe: &SafeHtmlStr = unsafe { SafeHtmlStr::from_str_unchecked(&buf) };
//! assert_eq!(safe.as_str(), "&lt;script&gt;");
//! # fn heapless_buf() -> String { String::new() }
//! ```

macro_rules! borrowed_safe_type {
    (
        $(#[$attr:meta])*
        $Str:ident, $Owned:ident
    ) => {
        $(#[$attr])*
        #[must_use]
        #[repr(transparent)]
        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct $Str(str);

        impl $Str {
            /// The empty value.
            pub const EMPTY: &'static $Str = $Str::from_constant("");

            /// Wraps a compile-time constant or heavily vetted static string.
            ///
            /// Allocation-free and `const`: usable in `const` and `static`
            /// items.
            ///
            /// # Security
            ///
            /// The `&'static str` bound is intended for string literals
            /// reviewed alongside the code. Do not pass leaked runtime
            /// strings.
            pub const fn from_constant(val: &'static str) -> &'static $Str {
                // SAFETY: static strings are vetted by the developer, the
                // same trust model as the owned `from_constant`.
                unsafe { $Str::from_str_unchecked(val) }
            }

            /// Wraps a raw string without validation.
            ///
            /// Part of the `from_string_unchecked` constructor family.
            ///
            /// # Safety
            ///
            /// The caller must ensure the string satisfies this type's
            /// safety contract (e.g. it is the output of one of this
            /// crate's escapers or sanitizers).
            pub const unsafe fn from_str_unchecked(val: &str) -> &$Str {
                // SAFETY: `$Str` is `repr(transparent)` over `str`, so the
                // pointer cast preserves layout and provenance.
                unsafe { &*(val as *const str as *const $Str) }
            }

            /// Returns the underlying string.
            pub const fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl core::ops::Deref for $Str {
            type Target = str;
            fn deref(&self) -> &str {
                &self.0
            }
        }

        impl AsRef<str> for $Str {
            fn as_ref(&self) -> &str {
                &self.0
            }
        }

        impl core::fmt::Display for $Str {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                f.write_str(&self.0)
            }
        }

        impl<'a> Default for &'a $Str {
            fn default() -> Self {
                $Str::EMPTY
            }
        }

        #[cfg(feature = "alloc")]
        #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
        impl core::borrow::Borrow<$Str> for crate::types::$Owned {
            fn borrow(&self) -> &$Str {
                self
            }
        }

        #[cfg(feature = "alloc")]
        #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
        impl alloc::borrow::ToOwned for $Str {
            type Owned = crate::types::$Owned;
            fn to_owned(&self) -> crate::types::$Owned {
                // SAFETY: this value already satisfies the contract.
                unsafe {
                    crate::types::$Owned::from_string_unchecked(alloc::string::String::from(
                        &self.0,
                    ))
                }
            }
        }

        #[cfg(feature = "alloc")]
        #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
        impl From<&$Str> for crate::types::$Owned {
            fn from(value: &$Str) -> Self {
                alloc::borrow::ToOwned::to_owned(value)
            }
        }

        #[cfg(feature = "alloc")]
        #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
        impl PartialEq<$Str> for crate::types::$Owned {
            fn eq(&self, other: &$Str) -> bool {
                self.as_str() == other.as_str()
            }
        }

        #[cfg(feature = "alloc")]
        #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
        impl PartialEq<crate::types::$Owned> for &$Str {
            fn eq(&self, other: &crate::types::$Owned) -> bool {
                self.as_str() == other.as_str()
            }
        }
    };
}

borrowed_safe_type!(
    /// A borrowed string slice that is safe to use in HTML contexts, the
    /// `no_std`-friendly counterpart of [`SafeHtml`](crate::SafeHtml).
    ///
    /// Carries the same contract: the value will not cause untrusted script
    /// execution (XSS) when evaluated as HTML in a browser.
    SafeHtmlStr,
    SafeHtml
);

borrowed_safe_type!(
    /// A borrowed string slice that is safe to use as a hyperlink URL, the
    /// `no_std`-friendly counterpart of [`SafeUrl`](crate::SafeUrl).
    SafeUrlStr,
    SafeUrl
);

borrowed_safe_type!(
    /// A borrowed string slice of trusted JavaScript, the `no_std`-friendly
    /// counterpart of [`SafeScript`](crate::SafeScript).
    SafeScriptStr,
    SafeScript
);

borrowed_safe_type!(
    /// A borrowed URL of a trusted, developer-controlled resource, the
    /// `no_std`-friendly counterpart of
    /// [`TrustedResourceUrl`](crate::TrustedResourceUrl).
    TrustedResourceUrlStr,
    TrustedResourceUrl
);

borrowed_safe_type!(
    /// A borrowed sequence of safe CSS declarations, the `no_std`-friendly
    /// counterpart of [`SafeStyle`](crate::SafeStyle).
    SafeStyleStr,
    SafeStyle
);

borrowed_safe_type!(
    /// A borrowed safe CSS style sheet, the `no_std`-friendly counterpart of
    /// [`SafeStyleSheet`](crate::SafeStyleSheet).
    SafeStyleSheetStr,
    SafeStyleSheet
);

impl SafeUrlStr {
    /// The innocuous placeholder URL ([`INNOCUOUS_URL`](crate::INNOCUOUS_URL))
    /// produced by the sanitizers when validation fails.
    pub const INNOCUOUS: &'static SafeUrlStr = SafeUrlStr::from_constant(crate::INNOCUOUS_URL);
}

// -----------------------------------------------------------------------------
// Safe zero-allocation construction: escape/sanitize into caller buffers
// (no `unsafe` needed by the caller) and borrowing sanitizers.
// -----------------------------------------------------------------------------

use crate::writer::{CapacityError, SliceWriter};

impl SafeHtmlStr {
    /// Escapes `text` into `buf` and returns the result as a borrowed safe
    /// type — the `no_std`, zero-allocation counterpart of
    /// [`SafeHtml::escape`](crate::SafeHtml::escape).
    ///
    /// Returns [`CapacityError`] if `buf` is too small (worst case is
    /// `6 * text.len()` bytes).
    ///
    /// ```rust
    /// use safehtml::SafeHtmlStr;
    ///
    /// let mut buf = [0u8; 32];
    /// let safe = SafeHtmlStr::escape_into("<b>", &mut buf).unwrap();
    /// assert_eq!(safe.as_str(), "&lt;b&gt;");
    /// ```
    pub fn escape_into<'a>(
        text: &str,
        buf: &'a mut [u8],
    ) -> Result<&'a SafeHtmlStr, CapacityError> {
        let mut w = SliceWriter::new(buf);
        crate::escape_html_and_coerce_to(text, &mut w).map_err(|_| CapacityError)?;
        // SAFETY: the buffer holds exactly the output of the HTML escaper.
        Ok(unsafe { SafeHtmlStr::from_str_unchecked(w.finish()) })
    }

    /// Like [`SafeHtmlStr::escape_into`], but preserves existing valid
    /// character references (the counterpart of
    /// [`SafeHtml::escape_allow_character_references`](crate::SafeHtml::escape_allow_character_references)).
    pub fn escape_allow_character_references_into<'a>(
        text: &str,
        buf: &'a mut [u8],
    ) -> Result<&'a SafeHtmlStr, CapacityError> {
        let mut w = SliceWriter::new(buf);
        crate::escape_allow_character_references_to(text, &mut w).map_err(|_| CapacityError)?;
        // SAFETY: the buffer holds exactly the output of the escaper.
        Ok(unsafe { SafeHtmlStr::from_str_unchecked(w.finish()) })
    }
}

impl SafeScriptStr {
    /// Escapes an existing JSON string into `buf` for safe embedding inside
    /// an inline `<script>` block — the `no_std` counterpart of
    /// [`SafeScript::from_escaped_json`](crate::SafeScript::from_escaped_json).
    pub fn from_escaped_json_into<'a>(
        json: &str,
        buf: &'a mut [u8],
    ) -> Result<&'a SafeScriptStr, CapacityError> {
        let mut w = SliceWriter::new(buf);
        crate::escape_json_for_script_to(json, &mut w).map_err(|_| CapacityError)?;
        // SAFETY: the buffer holds exactly the output of the JSON escaper.
        Ok(unsafe { SafeScriptStr::from_str_unchecked(w.finish()) })
    }
}

impl SafeUrlStr {
    /// Validates `url` against the default safe schemes, borrowing it on
    /// success — the zero-allocation counterpart of
    /// [`SafeUrl::sanitize`](crate::SafeUrl::sanitize).
    ///
    /// No buffer is needed: the sanitizer never transforms its input, so the
    /// result is either `url` itself or the static
    /// [`SafeUrlStr::INNOCUOUS`] placeholder.
    ///
    /// ```rust
    /// use safehtml::SafeUrlStr;
    ///
    /// assert_eq!(SafeUrlStr::sanitize("https://example.com").as_str(), "https://example.com");
    /// assert_eq!(SafeUrlStr::sanitize("javascript:alert(1)"), SafeUrlStr::INNOCUOUS);
    /// ```
    pub fn sanitize(url: &str) -> &SafeUrlStr {
        if crate::is_safe_url_restrictive(url) {
            // SAFETY: the URL was just validated.
            unsafe { SafeUrlStr::from_str_unchecked(url) }
        } else {
            SafeUrlStr::INNOCUOUS
        }
    }

    /// Zero-allocation counterpart of
    /// [`SafeUrl::sanitize_block_only_javascript`](crate::SafeUrl::sanitize_block_only_javascript).
    pub fn sanitize_block_only_javascript(url: &str) -> &SafeUrlStr {
        if crate::is_safe_url_block_javascript(url) {
            // SAFETY: the URL was just validated.
            unsafe { SafeUrlStr::from_str_unchecked(url) }
        } else {
            SafeUrlStr::INNOCUOUS
        }
    }

    /// Zero-allocation counterpart of
    /// [`SafeUrl::sanitize_with_schemes`](crate::SafeUrl::sanitize_with_schemes).
    pub fn sanitize_with_schemes<'a, S: AsRef<str>>(
        url: &'a str,
        extra_schemes: &[S],
    ) -> &'a SafeUrlStr {
        if crate::is_safe_url_restrictive_with_schemes(url, extra_schemes) {
            // SAFETY: the URL was just validated.
            unsafe { SafeUrlStr::from_str_unchecked(url) }
        } else {
            SafeUrlStr::INNOCUOUS
        }
    }

    /// Validates `url` and CSS-percent-escapes it into `buf` — the `no_std`
    /// counterpart of [`SafeUrl::sanitize_for_css`](crate::SafeUrl::sanitize_for_css).
    pub fn sanitize_for_css_into<'a>(
        url: &str,
        buf: &'a mut [u8],
    ) -> Result<&'a SafeUrlStr, CapacityError> {
        if !crate::is_safe_url_restrictive(url) {
            return Ok(SafeUrlStr::INNOCUOUS);
        }
        let mut w = SliceWriter::new(buf);
        crate::percent_escape_css_url_to(url, &mut w).map_err(|_| CapacityError)?;
        // SAFETY: the URL was validated and then CSS-percent-escaped.
        Ok(unsafe { SafeUrlStr::from_str_unchecked(w.finish()) })
    }
}