Skip to content

Commit 2c7837c

Browse files
committed
Fail if metadata.json contains invalid escape sequence
This is an enhancement of voxpupuli#120 We now use a regex to identify invalid escape sequences. `JSON.parse()` has no built-in way to detect this. Even in strict mode it ignores it: ``` irb(main):002> require 'json' => true irb(main):003> JSON.parser = JSON::Ext::Parser => JSON::Ext::Parser irb(main):004> JSON.parse('{"summary": "A description with an invalid \( escape sequence"}') => {"summary"=>"A description with an invalid ( escape sequence"} irb(main):005> JSON.parse("{\"summary\": \"A description with an invalid \( escape sequence\"}") => {"summary"=>"A description with an invalid ( escape sequence"} irb(main):006> ```
1 parent 9cbe5b5 commit 2c7837c

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

lib/metadata_json_lint.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88

99
module MetadataJsonLint
1010
MIN_PUPPET_VER = '4.10.0'.freeze
11+
# Regex looks for:
12+
# 1. Invalid escape sequences (\x or incomplete \u)
13+
INVALID_ESCAPE_REGEX = %r{\\[^"/bfnrtu]|\\u(?![0-9a-fA-F]{4})}.freeze
1114

1215
def options
1316
@options ||= Struct.new(
@@ -69,6 +72,11 @@ def run
6972
end
7073
module_function :run
7174

75+
def contains_invalid_escape?(content)
76+
content.match?(INVALID_ESCAPE_REGEX)
77+
end
78+
module_function :contains_invalid_escape?
79+
7280
def parse(metadata)
7381
@errors = []
7482
@warnings = []
@@ -83,6 +91,8 @@ def parse(metadata)
8391
abort("Error: Unable to read metadata file: #{e.exception}")
8492
end
8593

94+
abort('Error: Unable to parse metadata.json: Invalid escape character in string') if contains_invalid_escape?(f)
95+
8696
begin
8797
parsed = JSON.parse(f)
8898
rescue Exception => e

0 commit comments

Comments
 (0)