Skip to main content

rumtk_web/
lib.rs

1/*
2 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 * This toolkit aims to be reliable, simple, performant, and standards compliant.
4 * Copyright (C) 2025  Luis M. Santos, M.D. <lsantos@medicalmasses.com>
5 * Copyright (C) 2025  Ethan Dixon
6 * Copyright (C) 2025  MedicalMasses L.L.C. <contact@medicalmasses.com>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
20 */
21#![feature(once_cell_get_mut)]
22#![feature(macro_metavar_expr)]
23#![feature(str_as_str)]
24#![feature(random)]
25extern crate core;
26
27pub mod api;
28pub mod components;
29pub mod css;
30pub mod pages;
31pub mod utils;
32pub mod js;
33
34pub use app::*;
35pub use utils::*;
36
37///
38/// Add utils unit tests here to ensure internal functions work.
39///
40#[cfg(test)]
41mod tests {
42    use crate::components::app::css::css;
43    use crate::components::sanitize::sanitized;
44    use crate::components::title::title;
45    use crate::defaults::{PARAMS_ID, PARAMS_TITLE};
46    use crate::jobs::JobResult;
47    use crate::testdata::data::{create_test_form, RAW_HTML_PREFORMATTED, TESTDATA_EXPECTED_FORMDATA, TESTDATA_EXPECTED_FORMDATA_EMPTY, TESTDATA_FORMDATA_EMPTY_REQUEST, TESTDATA_FORMDATA_EMPTY_REQUEST_WITH_BOUNDARIES, TESTDATA_FORMDATA_REQUEST, TRIMMED_HTML_PREFORMATTED, TRIMMED_HTML_RENDER_CSS, TRIMMED_HTML_TITLE_RENDER};
48    use crate::utils::app::{AppComponents, AppSwitches};
49    use crate::{rumtk_web_get_job_manager, rumtk_web_init_job_manager, rumtk_web_params_map, rumtk_web_post_process, rumtk_web_register_app_components, rumtk_web_register_app_switches, rumtk_web_render, rumtk_web_render_component, rumtk_web_render_redirect, rumtk_web_run_app, rumtk_web_sync_get, rumtk_web_trim_rendered_html, sanitize_html, AppState, RUMWebData, RUMWebRedirect, RenderedPageComponentsResult, SharedAppState};
50    use crate::{RUMWebResponse, RUMWebTemplate};
51    use rand::random;
52    use rumtk_core::buffers::buffer_to_str;
53    use rumtk_core::strings::{rumtk_format, RUMString};
54    use std::thread::spawn;
55
56
57    const EXPECTED_RESPONSE_SIZE: usize = 2012;
58
59    ///////////////////////////////////Main Macro///////////////////////////////////////////////
60    #[test]
61    #[allow(dead_code)]
62    fn components_only() {
63        //Requesting to immediately exit instead of indefinitely serving pages so this example can be used as a unit test.
64        let skip_serve = true;
65        let app_switches = rumtk_web_register_app_switches!(
66            skip_serve //Omit in production code. This is used so that this example can work as a unit test.
67        );
68
69        rumtk_web_run_app!(AppComponents::default(), app_switches);
70    }
71
72    #[test]
73    #[allow(dead_code)]
74    fn overloads() {
75        //Requesting to immediately exit instead of indefinitely serving pages so this example can be used as a unit test.
76        let skip_serve = true;
77        let skip_default_css = false;
78        let app_switches = rumtk_web_register_app_switches!(
79            skip_serve, //Omit in production code. This is used so that this example can work as a unit test.
80            skip_default_css //Omit in production code. This is used so that this example can work as a unit test.
81        );
82
83        rumtk_web_run_app!(AppComponents::default(), app_switches);
84        rumtk_web_run_app!(AppComponents::default(), app_switches, 3001);
85        rumtk_web_run_app!(AppComponents::default(), app_switches, 3001, async || Ok(()));
86        rumtk_web_run_app!([#[arg(long)] extra: bool], AppComponents::default(), app_switches);
87        rumtk_web_run_app!([#[arg(long)] extra: bool], AppComponents::default(), app_switches, 3001);
88        rumtk_web_run_app!([#[arg(long)] extra: bool], AppComponents::default(), app_switches, 3001, async || Ok(()));
89    }
90
91    #[test]
92    fn context_preserves_explicit_options() {
93        let switches = AppSwitches::from([true, true, true]);
94        let context = crate::rumtk_web_register_app_context!(
95        AppComponents::default(),
96        switches.clone(),
97        4321,
98        async || Ok(())
99    );
100        assert_eq!(context.port, Some(4321));
101        assert_eq!(context.switches, switches);
102        assert!(context.logic.is_some());
103    }
104
105    ///////////////////////////////////FormData/////////////////////////////////////////////////
106    #[test]
107    fn test_compile_form() {
108        let expected_form = TESTDATA_EXPECTED_FORMDATA();
109        let form_data = create_test_form(TESTDATA_FORMDATA_REQUEST).expect("Form");
110
111        assert_eq!(form_data, expected_form, "Form results mismatch!");
112    }
113
114    #[test]
115    fn test_compile_empty_form() {
116        let expected_form = TESTDATA_EXPECTED_FORMDATA_EMPTY();
117        let form_data = create_test_form(TESTDATA_FORMDATA_EMPTY_REQUEST).expect("Form");
118
119        assert_eq!(form_data, expected_form, "Form results mismatch!");
120    }
121
122    #[test]
123    fn test_compile_empty_form_with_boundaries() {
124        let expected_form = TESTDATA_EXPECTED_FORMDATA_EMPTY();
125        let form_data = create_test_form(TESTDATA_FORMDATA_EMPTY_REQUEST_WITH_BOUNDARIES).expect("Form");
126
127        assert_eq!(form_data, expected_form, "Form results mismatch!");
128    }
129
130    ///////////////////////////////////Response/////////////////////////////////////////////////
131    #[test]
132    fn test_render_redirect_response() {
133        let url = "http://localhost/redirected";
134        let redirect =
135            rumtk_web_render_redirect!(RUMWebRedirect::Redirect(url.to_string())).unwrap();
136        let redirect_code = redirect.get_code();
137        let redirect_url = redirect.get_url();
138        assert_eq!(redirect_url, url, "Redirect url mismatch!");
139        assert_eq!(redirect_code, 303, "Wrong redirect code!");
140    }
141
142    #[test]
143    fn test_render_redirect_response_temporary() {
144        let url = "http://localhost/redirected";
145        let redirect =
146            rumtk_web_render_redirect!(RUMWebRedirect::RedirectTemporary(url.to_string()))
147                .unwrap();
148        let redirect_code = redirect.get_code();
149        let redirect_url = redirect.get_url();
150        assert_eq!(redirect_url, url, "Redirect url mismatch!");
151        assert_eq!(redirect_code, 307, "Wrong redirect code!");
152    }
153
154    #[test]
155    fn test_render_redirect_response_permanent() {
156        let url = "http://localhost/redirected";
157        let redirect =
158            rumtk_web_render_redirect!(RUMWebRedirect::RedirectPermanent(url.to_string()))
159                .unwrap();
160        let redirect_code = redirect.get_code();
161        let redirect_url = redirect.get_url();
162        assert_eq!(redirect_url, url, "Redirect url mismatch!");
163        assert_eq!(redirect_code, 308, "Wrong redirect code!");
164    }
165
166    #[test]
167    fn test_render_standard_web_component() {
168        let params = rumtk_web_params_map!([(PARAMS_TITLE, "Hello World!")]);
169        let state = SharedAppState::default();
170        let rendered = title(&[], params.get_inner(), state).unwrap().to_string();
171        let rendered_trimmed = rumtk_web_post_process(rendered, RUMWebRedirect::None).unwrap().to_string();
172
173        assert_eq!(
174            rendered_trimmed, TRIMMED_HTML_TITLE_RENDER,
175            "Commponent rendered improperly!"
176        );
177    }
178
179    #[test]
180    fn test_render() {
181        #[derive(RUMWebTemplate)]
182        #[template(source = "<div></div>", ext = "html")]
183        struct Div {}
184
185        let result = rumtk_web_render(Div {}, RUMWebRedirect::None).unwrap();
186        let expected = RUMWebResponse::into_get_response("<div></div>");
187
188        assert_eq!(result, expected, "Test Div template rendered improperly!");
189    }
190
191    #[test]
192    fn test_render_static_component() {
193        let rendered = rumtk_web_render_component!(css);
194        let expected = TRIMMED_HTML_RENDER_CSS;
195
196        assert_eq!(rendered, expected, "Commponent rendered improperly!");
197    }
198
199    #[test]
200    fn test_trim_preformatted_component() {
201        let result = rumtk_web_trim_rendered_html(RAW_HTML_PREFORMATTED.to_string()).unwrap();
202
203        assert_eq!(result, TRIMMED_HTML_PREFORMATTED.to_string(), "Preformatted html string was filtered inappropriately.!");
204    }
205
206    ///////////////////////////////////Jobs/////////////////////////////////////////////////
207    #[test]
208    fn test_job_run() {
209        const HELLO_STR: &str = "Hello World";
210
211        rumtk_web_init_job_manager!(&5);
212
213        async fn basic_processor() -> JobResult {
214            let result = RUMString::from(HELLO_STR);
215            let rendered = sanitized(result);
216            Ok(Some(rendered?))
217        }
218
219        let mut params = RUMWebData::new();
220        let job_id = rumtk_web_get_job_manager!()
221            .expect("Job manager not initialized")
222            .spawn_task(basic_processor())
223            .expect("Failed to spawn job");
224        params.insert(RUMString::from(PARAMS_ID), job_id.to_string());
225
226        let result = rumtk_web_get_job_manager!()
227            .expect("Job manager not initialized")
228            .wait_on(&job_id)
229            .expect("Failed to wait on job")
230            .unwrap()
231            .unwrap()
232            .unwrap();
233        
234        let rendered = result.to_string();
235
236        assert_eq!(&rendered, HELLO_STR, "Job returned the wrong result!");
237    }
238
239    ///////////////////////////////////Endpoint Tests/////////////////////////////////////////////////
240    #[test]
241    fn test_run_app() {
242        let port = random::<u16>();
243        pub fn index(app_state: SharedAppState) -> RenderedPageComponentsResult {
244            let title_params = rumtk_web_params_map!([("title", "Hello World!")]);
245            let title = title(&[], title_params.get_inner(), app_state.clone())?.to_string();
246            Ok(vec![title])
247        }
248
249        let app_components = rumtk_web_register_app_components!(
250            vec![
251                ("index", index),
252            ]
253        );
254        let app_switches = rumtk_web_register_app_switches!(
255            true,
256            true,
257            true
258        );
259        rumtk_web_run_app!(
260            app_components,
261            app_switches,
262            port
263        );
264    }
265    #[test]
266    fn test_request_get() {
267        let port = random::<u16>();
268        let port_copy = port.clone();
269        spawn(move || {
270            pub fn index(app_state: SharedAppState) -> RenderedPageComponentsResult {
271                let title_params = rumtk_web_params_map!([("title", "Hello World!")]);
272                let title = title(&[], title_params.get_inner(), app_state.clone())?.to_string();
273                Ok(vec![title])
274            }
275
276            let app_components = rumtk_web_register_app_components!(
277                vec![
278                    ("index", index),
279                ]
280            );
281            let app_switches = rumtk_web_register_app_switches!(
282                false,
283                true,
284                true
285            );
286            rumtk_web_run_app!(
287                app_components,
288                app_switches,
289                port
290            );
291        });
292        let (code, output) = rumtk_web_sync_get(&rumtk_format!("http://127.0.0.1:{port_copy}/")).unwrap();
293        let output_str = buffer_to_str(&output).unwrap();
294        println!("Output: {}", output_str);
295        //%Abz
296        assert!(output_str.contains(">Hello World!</h1>"), "Applet responded improperly with wrong response content!");
297    }
298    #[test]
299    fn test_fuzzed_request_get() {
300        let port = random::<u16>();
301        let port_copy = port.clone();
302        spawn(move || {
303            pub fn index(app_state: SharedAppState) -> RenderedPageComponentsResult {
304                let title_params = rumtk_web_params_map!([("title", "Hello World!")]);
305                let title = title(&[], title_params.get_inner(), app_state.clone())?.to_string();
306                Ok(vec![title])
307            }
308
309            let app_components = rumtk_web_register_app_components!(
310                vec![
311                    ("index", index),
312                ]
313            );
314            let app_switches = rumtk_web_register_app_switches!(
315                false,
316                true,
317                true
318            );
319            rumtk_web_run_app!(
320                app_components,
321                app_switches,
322                port
323            );
324        });
325
326        let fuzz_get_tests = vec![
327            "%Abz"
328        ];
329
330        for fuzz_itm in fuzz_get_tests {
331            let (code, output) = rumtk_web_sync_get(&rumtk_format!("http://127.0.0.1:{port_copy}/{fuzz_itm}")).unwrap();
332            if output.len() != EXPECTED_RESPONSE_SIZE {
333                match code {
334                    200 => panic!("Applet responded with wrong response size! => {}", output.len()),
335                    _ => {
336                        println!("Applet responded with handled error message!");
337                        continue;
338                    }
339                }
340            }
341            let output_str = buffer_to_str(&output).unwrap();
342            println!("Output: {}", output_str);
343            assert!(output_str.contains(">Hello World!</h1>"), "Applet responded improperly with wrong response content!");
344        }
345    }
346    #[test]
347    fn test_fuzzed_request_get_kills_axum() {
348        let port = random::<u16>();
349        let port_copy = port.clone();
350        spawn(move || {
351            pub fn index(app_state: SharedAppState) -> RenderedPageComponentsResult {
352                let title_params = rumtk_web_params_map!([("title", "Hello World!")]);
353                let title = title(&[], title_params.get_inner(), app_state.clone())?.to_string();
354                Ok(vec![title])
355            }
356
357            let app_components = rumtk_web_register_app_components!(
358                vec![
359                    ("index", index),
360                ]
361            );
362            let app_switches = rumtk_web_register_app_switches!(
363                false,
364                true,
365                true
366            );
367            rumtk_web_run_app!(
368                app_components,
369                app_switches,
370                port
371            );
372        });
373
374        let fuzz_get_tests = vec![
375            "%Abz"
376        ];
377
378        for fuzz_itm in fuzz_get_tests {
379            let request = rumtk_format!("http://127.0.0.1:{port_copy}/{fuzz_itm}");
380            let (code, output) = rumtk_web_sync_get(&request).unwrap();
381            if output.len() != EXPECTED_RESPONSE_SIZE {
382                match rumtk_web_sync_get(&request) {
383                    Ok((c,r)) => {
384                        println!("Request[{}] Does not kill axum listener or tokio runtime so allowing... Output: {}", &request,buffer_to_str(&r).unwrap());
385                    }
386                    Err(e) => {
387                        println!("Request[{}] killed axum listener or tokio runtime... Error: {:?}", &request, &e);
388                    }
389                }
390            }
391        }
392    }
393
394    ///////////////////////////////////Sanitizer Tests///////////////////////////////////////////////
395    #[test]
396    fn test_svg_sanitizer() {
397        let input = "<svg><circle cx=\"50\" cy=\"50\" r=\"40\" stroke=\"black\" stroke-width=\"3\" fill=\"red\" /></svg>";
398        let output = sanitize_html(input, false);
399        assert!(output.to_string().contains("<svg><circle"), "SVG and circle tags filtered");
400    }
401    #[test]
402    fn test_svg_sanitizer_full() {
403        let input = "<svg><circle cx=\"50\" cy=\"50\" r=\"40\" stroke=\"black\" stroke-width=\"3\" fill=\"red\" /></svg>";
404        let expected: &str = "<svg><circle cx=\"50\" cy=\"50\" r=\"40\" stroke=\"black\" stroke-width=\"3\" fill=\"red\"></circle></svg>";
405        let output = sanitize_html(input, false);
406        assert_eq!(&output.to_string(), expected, "Circle tag attributes filtered");
407    }
408
409    #[test]
410    fn test_sanitize_invalid_tag() {
411        let input = "<xml><circle cx=\"50\" cy=\"50\" r=\"40\" stroke=\"black\" stroke-width=\"3\" fill=\"red\" /></xml>";
412        let output = sanitize_html(input, true);
413        assert!(output.to_string().is_empty(), "XML and circle tags filtered");
414    }
415
416    #[test]
417    fn test_sanitize_script_tag() {
418        let input = r#"<script type="text/javascript">alert('hi');</script>"#;;
419        let output = sanitize_html(input, false);
420        assert!(output.is_empty(), "Script tag was not filtered as expected!");
421    }
422
423    #[test]
424    fn test_sanitize_script_tag_relaxed() {
425        let input = r#"<script type="text/javascript">alert('hi');</script>"#;;
426        let output = sanitize_html(input, true);
427        assert_eq!(input, &output, "Script tag was filtered when it shouldn't have or attributes were stripped!");
428    }
429
430    #[test]
431    fn test_sanitize_consecutive_script_tag_relaxed() {
432        let input = r#"<script type="text/javascript">alert('hi');</script><script type="text/javascript">alert('hi2');</script>"#;;
433        let output = sanitize_html(input, true);
434        assert_eq!(input, &output, "Script tag was filtered when it shouldn't have or attributes were stripped!");
435    }
436
437    #[test]
438    fn test_sanitize_module_script_tag_relaxed() {
439        let input = r#"<script type="module">alert('hi');</script><script type="text/javascript">alert('hi2');</script>"#;;
440        let output = sanitize_html(input, true);
441        assert_eq!(input, &output, "Script tag was filtered when it shouldn't have or attributes were stripped!");
442    }
443
444    #[test]
445    fn test_sanitize_consecutive_module_script_tag_relaxed() {
446        let input = r#"<script type="module">alert('hi');</script><script type="module">alert('hi2');</script>"#;;
447        let output = sanitize_html(input, true);
448        assert_eq!(input, &output, "Script tag was filtered when it shouldn't have or attributes were stripped!");
449    }
450}