Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_steel/tests/confirm_carries_no_script.rs

7.0 KiB, 1 run

created by r567599779:77720, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! A form's "are you sure?" carries its question as data, never as script.
2//!
3//! Every confirmation in the site console and the Steel admin is asked by one delegated listener that
4//! reads the form's `data-confirm` attribute. Before this, each was an inline `onsubmit` with the
5//! question formatted into it, and an HTML attribute is decoded before its script is parsed: an
6//! escaped `'` in a subscriber's address became a real one and ended the string. A hostile value is
7//! rendered through each such form here and must arrive as escaped text in an attribute only.
8
9use oxedyne_fe2o3_steel::srv::{
10 admin::{
11 AdminPrincipal,
12 assets::{
13 html_escape,
14 render_layout,
15 },
16 handler::admin_row,
17 },
18 console::{
19 SiteAdmin,
20 Theme,
21 page,
22 publish::{
23 comment_card,
24 comments_switch,
25 dest_panel,
26 post_actions,
27 subscriber_actions,
28 },
29 },
30 publish::{
31 comment::Comment,
32 subscribe::{
33 SubState,
34 Subscriber,
35 },
36 },
37};
38
39use std::path::Path;
40
41const EVIL_ADDR: &str = "a');alert(1);('@x.io";
42const EVIL: &str = "x');alert(1);('";
43
44/// The `on…=` attribute names in some HTML, in the order found.
45fn inline_handlers(html: &str) -> Vec<String> {
46 let b = html.as_bytes();
47 let mut found = Vec::new();
48 let mut i = 0;
49 while let Some(off) = html[i..].find('=') {
50 let eq = i + off;
51 let mut j = eq;
52 while j > 0 && b[j - 1].is_ascii_lowercase() {
53 j -= 1;
54 }
55 let name = &html[j..eq];
56 let bounded = j == 0 || !(b[j - 1].is_ascii_alphanumeric() || b[j - 1] == b'-' || b[j - 1] == b'_');
57 if bounded && name.len() > 2 && name.starts_with("on") {
58 found.push(name.to_string());
59 }
60 i = eq + 1;
61 }
62 found
63}
64
65/// The values of every `name="…"` attribute.
66fn attr_values(html: &str, name: &str) -> Vec<String> {
67 let key = format!("{}=\"", name);
68 let mut out = Vec::new();
69 let mut rest = html;
70 while let Some(at) = rest.find(&key) {
71 let tail = &rest[at + key.len()..];
72 match tail.find('"') {
73 Some(end) => { out.push(tail[..end].to_string()); rest = &tail[end..]; },
74 None => break,
75 }
76 }
77 out
78}
79
80/// The fragment runs no script of its own, and the value is in it only escaped, as data.
81fn assert_inert(html: &str, raw: &str) {
82 let esc = html_escape(raw);
83 assert!(inline_handlers(html).is_empty(), "an inline handler: {:?} in {}", inline_handlers(html), html);
84 assert!(!html.contains("<script"), "a script element in a fragment: {}", html);
85 assert!(!html.contains(raw), "the value reached the page unescaped: {}", html);
86 let asks = attr_values(html, "data-confirm");
87 assert!(!asks.is_empty(), "no form here asks before it submits: {}", html);
88 assert!(asks.iter().any(|q| q.contains(&esc)), "no question names {}: {:?}", esc, asks);
89 assert!(html.contains(&format!("value=\"{}\"", esc)), "the hidden input does not carry the escaped value: {}", html);
90}
91
92#[test]
93fn test_a_hostile_address_is_only_data_in_the_erase_form() {
94 let sub = Subscriber {
95 email: EVIL_ADDR.to_string(),
96 state: SubState::Confirmed,
97 ..Default::default()
98 };
99 let html = subscriber_actions("tok", &sub);
100 assert_inert(&html, EVIL_ADDR);
101}
102
103#[test]
104fn test_a_hostile_slug_is_only_data_in_the_delete_form() {
105 let html = post_actions("tok", EVIL);
106 assert_inert(&html, EVIL);
107}
108
109#[test]
110fn test_a_hostile_provider_title_is_only_data_in_the_clear_form() {
111 let html = dest_panel(EVIL, "mastodon", "tok", true, false, "");
112 let esc = html_escape(EVIL);
113 assert!(inline_handlers(&html).is_empty(), "an inline handler in {}", html);
114 assert!(!html.contains(EVIL), "the title reached the page unescaped: {}", html);
115 let asks = attr_values(&html, "data-confirm");
116 assert!(asks.iter().any(|q| q.contains(&esc)), "the clear form does not ask about {}: {}", esc, html);
117}
118
119#[test]
120fn test_a_comment_card_and_the_switch_ask_without_script() {
121 let c = Comment {
122 id: "c1".to_string(),
123 slug: EVIL.to_string(),
124 ..Default::default()
125 };
126 let html = comment_card(&c, "tok");
127 assert!(inline_handlers(&html).is_empty(), "an inline handler in {}", html);
128 assert!(!html.contains(EVIL), "the slug reached the card unescaped: {}", html);
129 assert_eq!(attr_values(&html, "data-confirm").len(), 1, "only erase asks first: {}", html);
130 let open = comments_switch(true, "tok");
131 assert!(inline_handlers(&open).is_empty(), "an inline handler in {}", open);
132 assert_eq!(attr_values(&open, "data-confirm").len(), 1, "closing comments asks first: {}", open);
133 assert!(attr_values(&comments_switch(false, "tok"), "data-confirm").is_empty(), "opening asks nothing");
134}
135
136#[test]
137fn test_a_hostile_admin_name_is_only_data_in_the_remove_form() {
138 let html = admin_row(EVIL, 0, &[]);
139 assert_inert(&html, EVIL);
140}
141
142#[test]
143fn test_both_shells_carry_the_one_listener() {
144 let theme = Theme { site_name: "S".to_string(), css: Vec::new(), home: "/".to_string() };
145 let admin = SiteAdmin { username: "0".repeat(64) };
146 let console = page(&theme, &admin, "T", "").body_as_string().to_string();
147 let principal = AdminPrincipal { name: "n".to_string(), scopes: Vec::new(), expires_at: 0 };
148 let steel = render_layout("T", "/admin", &principal, "", "");
149 for (which, html) in [("console", &console), ("admin", &steel)] {
150 assert!(html.contains("'data-confirm'"), "the {} page has no confirm listener", which);
151 assert!(inline_handlers(html).is_empty(), "an inline handler in the {} shell", which);
152 }
153}
154
155/// The class, held at the source: no Rust string literal in the crate writes an inline handler.
156#[test]
157fn test_no_source_writes_an_inline_event_handler() {
158 let mut hits = Vec::new();
159 let mut dirs = vec![Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
160 while let Some(d) = dirs.pop() {
161 let entries = match std::fs::read_dir(&d) {
162 Ok(r) => r,
163 Err(e) => panic!("reading {}: {}", d.display(), e),
164 };
165 for e in entries.flatten() {
166 let p = e.path();
167 if p.is_dir() {
168 dirs.push(p);
169 } else if p.extension().map_or(false, |x| x == "rs") {
170 let text = match std::fs::read_to_string(&p) {
171 Ok(t) => t,
172 Err(e) => panic!("reading {}: {}", p.display(), e),
173 };
174 for (n, line) in text.lines().enumerate() {
175 // The escaped quote is the mark of an attribute inside a Rust string literal.
176 for name in inline_handlers(line) {
177 if line.contains(&format!("{}=\\\"", name)) {
178 hits.push(format!("{}:{}: {}", p.display(), n + 1, name));
179 }
180 }
181 }
182 }
183 }
184 }
185 assert!(hits.is_empty(), "inline event handlers in source:\n{}", hits.join("\n"));
186}