rumtk-sanitize 0.2.0

HTML input sanitizer for RUMTK.
/*
 *     rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
 *     This toolkit aims to be reliable, simple, performant, and standards compliant.
 *     Copyright (C) 2026  Ian McDonald
 *     Copyright (C) 2026  Luis M. Santos, MD
 *     Copyright (C) 2026  MedicalMasses L.L.C.
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
///
/// # CLI Sanitize Utility
///
/// ## Usage:
///
///
///     cat BUILD_injectionDemo.html | .\target\debug\rumtk-sanitize --mode html
///
///
///  TODO:  Revisit macro's on September 25th (if it is not the 25th still do this)
///  TODO:  Rebuild the interface args
///

use rumtk_core::base::{RUMResult, RUMVec};
use rumtk_core::buffers::buffer_to_str;
use rumtk_core::regex::filter_ansi_escape_sequences;
use rumtk_core::rumtk_cli_process;
use rumtk_core::strings::RUMArrayConversions;

use rumtk_hl7_v2::hl7_v2_sanitize::hl7_v2_sanitize;
use rumtk_web::utils::sanitize_html;

fn sanitize_input(mut data: RUMVec<u8>, mode: &str) -> RUMResult<RUMVec<u8>> {
    let r = match mode.to_lowercase().as_str() {
        "html" => sanitize_html(buffer_to_str(data.as_slice())?, false).into(),
        "html_relaxed" => sanitize_html(&data.as_slice().to_string()?, true).into(),
        "ansi" => filter_ansi_escape_sequences(buffer_to_str(data.as_slice())?)?.into_owned().into(), //ANSI Escape Sequences can be weaponized!
        "hl7" => hl7_v2_sanitize(&mut data)?.into(),
        _ => return Err("Invalid mode".into()),
    };
    Ok(r)
}

fn main() {
    rumtk_cli_process!(
        ///
        /// Specifies command line script to execute on message.
        ///
        /// The `ansi` option filters out ANSI escape sequences from the message. It can be weaponized per this DefCon recording!
        /// [DEF CON 31 - Weaponizing Plain Text ANSI Escape Sequences as a Forensic Nightmare - STÖK](https://www.youtube.com/watch?v=3T2Al3jdY38)
        ///
        #[arg(short, long, value_parser = clap::builder::PossibleValuesParser::new(["html", "html_relaxed", "ansi", "hl7", ""]))]
        mode: Option<String>,
        Message(|data: RUMVec<u8>, args: &RUMTKInterfaceArgs| -> RUMResult<RUMVec<u8>> {
            match &args.mode {
                Some(mode) => sanitize_input(data, mode),
                None => Ok(sanitize_html(&data.as_slice().to_string()?, false).into()),
            }
        })
    );
}

#[cfg(test)]
mod tests {
    use crate::sanitize_input;
    use rumtk_core::base::RUMVec;
    use rumtk_core::strings::RUMArrayConversions;


    const V2_TEST_LARGE_MESSAGE: &str = include_str!("../../../examples/hl7/large_message.v2");

    #[test]
    fn test_sanitize_input_html() {
        let input = RUMVec::from(r#"
        <html>
        <head>
                <script>alert('XSS Attack!');</script>
        </head>
        <body><h1>Hello World!</h1></body>
        </html>
        "#);
        let expected = RUMVec::from("<h1>Hello World!</h1>");
        let mode = "html";
        let result = sanitize_input(input, mode).unwrap();

        assert_eq!(&result, &expected, "Unexpected sanitization output => {}", result.to_string().unwrap());
    }

    #[test]
    fn test_sanitize_input_html_relaxed() {
        let input = RUMVec::from(r#"
        <html>
        <head>
                <script>alert('XSS Attack!');</script>
        </head>
        <body><h1>Hello World!</h1></body>
        </html>
        "#);
        let expected = RUMVec::from("<script>alert('XSS Attack!');</script>\n        \n        <h1>Hello World!</h1>");
        let mode = "html_relaxed";
        let result = sanitize_input(input, mode).unwrap();

        assert_eq!(&result, &expected, "Unexpected sanitization output => {}", result.to_string().unwrap());
    }

    #[test]
    fn test_sanitize_input_ansi() {
        let input = RUMVec::from("\x1b[36mRunning tests...\x1b[0m\x1b[32m✓ test_login passed\x1b[0m\x1b[31m✗ test_signup failed:\x1b[0m expected 200, got 500   ");
        let expected = RUMVec::from("Running tests...✓ test_login passed✗ test_signup failed: expected 200, got 500   ");
        let mode = "ansi";
        let result = sanitize_input(input, mode).unwrap();

        assert_eq!(&result, &expected, "Unexpected sanitization output => {:?}", result.to_string().unwrap());
    }

    #[test]
    fn test_sanitize_input_hl7() {
        let input = V2_TEST_LARGE_MESSAGE;
        let expected = RUMVec::from(V2_TEST_LARGE_MESSAGE.replace("\n", "\r"));
        let mode = "hl7";
        let result = sanitize_input(RUMVec::from(input.as_bytes()), mode).unwrap();

        assert_eq!(&result, &expected, "Unexpected sanitization output => {:?} vs. {:?}", (&result[0..1024]).to_string().unwrap(), (&expected[0..1024]).to_string());
    }
}