From b101065bad2c2e451c531ff59b0d7884f6a1e7d6 Mon Sep 17 00:00:00 2001
From: David Taylor <david@taylorhq.com>
Date: Fri, 8 Mar 2019 08:58:06 +0000
Subject: [PATCH] FIX: Sanitize theme settings properly before injecting into
 stylesheets (#7031)

---
 lib/stylesheet/importer.rb |  5 ++---
 spec/models/theme_spec.rb  | 12 ++++++++++++
 2 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/lib/stylesheet/importer.rb b/lib/stylesheet/importer.rb
index 49ff26d8e70..19d9676120f 100644
--- a/lib/stylesheet/importer.rb
+++ b/lib/stylesheet/importer.rb
@@ -144,9 +144,8 @@ COMMENT
     end
 
     def to_scss_variable(name, value)
-      escaped = value.to_s.gsub('"', "\\22")
-      escaped.gsub!("\n", "\\A")
-      "$#{name}: unquote(\"#{escaped}\");\n"
+      escaped = SassC::Script::Value::String.quote(value, sass: true)
+      "$#{name}: unquote(#{escaped});\n"
     end
 
     def imports(asset, parent_path)
diff --git a/spec/models/theme_spec.rb b/spec/models/theme_spec.rb
index 0b4a332c9a7..3b0b442e697 100644
--- a/spec/models/theme_spec.rb
+++ b/spec/models/theme_spec.rb
@@ -310,6 +310,18 @@ HTML
 
       scss, _map = Stylesheet::Compiler.compile('@import "theme_variables"; @import "desktop_theme"; ', "theme.scss", theme_id: theme.id)
       expect(scss).to include("font-size:30px")
+
+      # Escapes correctly. If not, compiling this would throw an exception
+      setting.value = <<~MULTILINE
+          \#{$fakeinterpolatedvariable}
+          andanothervalue 'withquotes'; margin: 0;
+      MULTILINE
+
+      theme.set_field(target: :common, name: :scss, value: 'body {font-size: quote($font-size)}')
+      theme.save!
+
+      scss, _map = Stylesheet::Compiler.compile('@import "theme_variables"; @import "desktop_theme"; ', "theme.scss", theme_id: theme.id)
+      expect(scss).to include('font-size:"#{$fakeinterpolatedvariable}\a andanothervalue \'withquotes\'; margin: 0;\a"')
     end
 
     it "allows values to be used in JS" do