|
|
|
@ -11,43 +11,30 @@ class SignatureParser
|
|
|
|
|
# In addition, ignore a `Signature ` string prefix that was added by old versions
|
|
|
|
|
# of `node-http-signatures`
|
|
|
|
|
|
|
|
|
|
class SignatureParamsParser < Parslet::Parser
|
|
|
|
|
rule(:token) { match("[0-9a-zA-Z!#$%&'*+.^_`|~-]").repeat(1).as(:token) }
|
|
|
|
|
rule(:quoted_string) { str('"') >> (qdtext | quoted_pair).repeat.as(:quoted_string) >> str('"') }
|
|
|
|
|
# qdtext and quoted_pair are not exactly according to spec but meh
|
|
|
|
|
rule(:qdtext) { match('[^\\\\"]') }
|
|
|
|
|
rule(:quoted_pair) { str('\\') >> any }
|
|
|
|
|
rule(:bws) { match('\s').repeat }
|
|
|
|
|
rule(:param) { (token.as(:key) >> bws >> str('=') >> bws >> (token | quoted_string).as(:value)).as(:param) }
|
|
|
|
|
rule(:comma) { bws >> str(',') >> bws }
|
|
|
|
|
TOKEN_RE = /[0-9a-zA-Z!#$%&'*+.^_`|~-]+/
|
|
|
|
|
# qdtext and quoted_pair are not exactly according to spec but meh
|
|
|
|
|
QUOTED_STRING_RE = /"([^\\"]|(\\.))*"/
|
|
|
|
|
PARAM_RE = /(?<key>#{TOKEN_RE})\s*=\s*((?<value>#{TOKEN_RE})|(?<quoted_value>#{QUOTED_STRING_RE}))/
|
|
|
|
|
|
|
|
|
|
def self.parse(raw_signature)
|
|
|
|
|
# Old versions of node-http-signature add an incorrect "Signature " prefix to the header
|
|
|
|
|
rule(:buggy_prefix) { str('Signature ') }
|
|
|
|
|
rule(:params) { buggy_prefix.maybe >> (param >> (comma >> param).repeat).as(:params) }
|
|
|
|
|
root(:params)
|
|
|
|
|
end
|
|
|
|
|
raw_signature = raw_signature.delete_prefix('Signature ')
|
|
|
|
|
|
|
|
|
|
class SignatureParamsTransformer < Parslet::Transform
|
|
|
|
|
rule(params: subtree(:param)) do
|
|
|
|
|
(param.is_a?(Array) ? param : [param]).each_with_object({}) { |(key, value), hash| hash[key] = value }
|
|
|
|
|
end
|
|
|
|
|
params = {}
|
|
|
|
|
scanner = StringScanner.new(raw_signature)
|
|
|
|
|
|
|
|
|
|
rule(param: { key: simple(:key), value: simple(:val) }) do
|
|
|
|
|
[key, val]
|
|
|
|
|
end
|
|
|
|
|
# Use `skip` instead of `scan` as we only care about the subgroups
|
|
|
|
|
while scanner.skip(PARAM_RE)
|
|
|
|
|
# This is not actually correct with regards to quoted pairs, but it's consistent
|
|
|
|
|
# with our previous implementation, and good enough in practice.
|
|
|
|
|
params[scanner[:key]] = scanner[:value] || scanner[:quoted_value][1...-1]
|
|
|
|
|
|
|
|
|
|
rule(quoted_string: simple(:string)) do
|
|
|
|
|
string.to_s
|
|
|
|
|
end
|
|
|
|
|
scanner.skip(/\s*/)
|
|
|
|
|
return params if scanner.eos?
|
|
|
|
|
|
|
|
|
|
rule(token: simple(:string)) do
|
|
|
|
|
string.to_s
|
|
|
|
|
raise ParsingError unless scanner.skip(/\s*,\s*/)
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
def self.parse(raw_signature)
|
|
|
|
|
tree = SignatureParamsParser.new.parse(raw_signature)
|
|
|
|
|
SignatureParamsTransformer.new.apply(tree)
|
|
|
|
|
rescue Parslet::ParseFailed
|
|
|
|
|
raise ParsingError
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|