Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions lib/committee/request_unpacker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ def initialize(options = {})
@allow_get_body = options[:allow_get_body]
@allow_raw_body = options[:allow_raw_body]
@allow_json_array = options[:allow_json_array]
@allow_sequential_json = options[:allow_sequential_json]
@allow_query_params = options[:allow_query_params]
@allow_non_get_query_params = options[:allow_non_get_query_params]
@optimistic_json = options[:optimistic_json]
Expand All @@ -54,8 +55,10 @@ def unpack_request_params(request)
# if Content-Type is empty or JSON, and there was a request body, try to
# interpret it as JSON
json_body = !request.media_type || Committee::SchemaValidator.json_media_type?(request.media_type)
params = if json_body
parse_json(request)
params = if @allow_sequential_json && Committee::SchemaValidator.sequential_json_media_type?(request.media_type)
parse_sequential_json(request)
elsif json_body
parse_json(request)
elsif @optimistic_json
begin
parse_json(request)
Expand Down Expand Up @@ -115,6 +118,15 @@ def unpack_headers(request)

private

def parse_sequential_json(request)
return nil if request.get? && !@allow_get_body

input = request.body
body = input ? input.read : ""
input.rewind if input.respond_to?(:rewind)
self.class.indifferent_params(Committee::SchemaValidator.parse_sequential_json(body, request.media_type))
end

def parse_json(request)
return nil if request.request_method == "GET" && !@allow_get_body

Expand Down
25 changes: 25 additions & 0 deletions lib/committee/schema_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
module Committee
module SchemaValidator
JSON_MEDIA_TYPE_PATTERN = %r{\Aapplication/(?:.+\+)?json\z}.freeze
SEQUENTIAL_JSON_MEDIA_TYPE_PATTERN = %r{\A(?:application/(?:jsonl|x-ndjson|json-seq)|[^/]+/[^/]+\+json-seq)\z}.freeze

class << self
def request_media_type(request)
Expand All @@ -14,6 +15,30 @@ def json_media_type?(content_type)
normalized_content_type&.match?(JSON_MEDIA_TYPE_PATTERN) || false
end

def sequential_json_media_type?(content_type)
Rack::MediaType.type(content_type)&.match?(SEQUENTIAL_JSON_MEDIA_TYPE_PATTERN) || false
end

def parse_sequential_json(body, content_type)
unless Rack::MediaType.type(content_type).end_with?('json-seq')
return body.each_line("\n").map { |line| JSON.parse(line) }
end

unless body.empty? || body.start_with?("\x1e")
raise JSON::ParserError, 'JSON sequence must start with a record separator'
end

body.split("\x1e").reject(&:empty?).map do |record|
value = JSON.parse(record)
# RFC 7464 requires trailing whitespace to detect truncated numbers and literals.
case value
when Numeric, TrueClass, FalseClass, NilClass
raise JSON::ParserError, 'JSON sequence scalar is not terminated by whitespace' unless record.match?(/[ \t\r\n]\z/)
end
value
end
end

# @param [String] prefix
# @return [Regexp]
def build_prefix_regexp(prefix)
Expand Down
13 changes: 10 additions & 3 deletions lib/committee/schema_validator/open_api_3.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,18 @@ def response_validate(status, headers, response, test_method = false, custom_bod
response.each_with_object(String.new(encoding: Encoding::BINARY)) { |chunk, body| body << chunk.b }.force_encoding(Encoding::UTF_8)
end

content_type_key = headers.keys.detect { |k| k.casecmp?('Content-Type') }
content_type = headers.fetch(content_type_key, nil)
parse_to_json = if validator_option.parse_response_by_content_type
content_type_key = headers.keys.detect { |k| k.casecmp?('Content-Type') }
Committee::SchemaValidator.json_media_type?(headers.fetch(content_type_key, nil))
Committee::SchemaValidator.json_media_type?(content_type)
else
true
end

data = if custom_body_parser
custom_body_parser.call(full_body)
elsif use_3_2_features? && Committee::SchemaValidator.sequential_json_media_type?(content_type)
Committee::SchemaValidator.parse_sequential_json(full_body, content_type)
elsif parse_to_json
# HEAD responses have no body, but still require header validation.
full_body.empty? && @request.head? ? {} : JSON.parse(full_body)
Expand All @@ -60,6 +63,10 @@ def link_exist?

attr_reader :validator_option

def use_3_2_features?
@operation_object.request_operation.operation_object.root.use_3_2_features?
end

def coerce_path_params(deserializer)
path_params = deserializer&.deserialize_path_params(@operation_object.path_params)
Committee::RequestUnpacker.indifferent_params(@operation_object.coerce_path_parameter(@validator_option, path_params))
Expand Down Expand Up @@ -91,7 +98,7 @@ def header(request)
def request_unpack(request)
media_type = @operation_object.request_operation.operation_object.request_body&.select_media_type(request.media_type)
allow_json_array = media_type&.schema&.type == 'array'
unpacker = Committee::RequestUnpacker.new(allow_empty_date_and_datetime: validator_option.allow_empty_date_and_datetime, allow_form_params: validator_option.allow_form_params, allow_get_body: validator_option.allow_get_body, allow_raw_body: true, allow_json_array: allow_json_array, allow_query_params: validator_option.allow_query_params, allow_non_get_query_params: validator_option.allow_non_get_query_params, optimistic_json: validator_option.optimistic_json,)
unpacker = Committee::RequestUnpacker.new(allow_empty_date_and_datetime: validator_option.allow_empty_date_and_datetime, allow_form_params: validator_option.allow_form_params, allow_get_body: validator_option.allow_get_body, allow_raw_body: true, allow_json_array: allow_json_array, allow_sequential_json: use_3_2_features?, allow_query_params: validator_option.allow_query_params, allow_non_get_query_params: validator_option.allow_non_get_query_params, optimistic_json: validator_option.optimistic_json,)

request.env[validator_option.headers_key] = unpacker.unpack_headers(request)

Expand Down
89 changes: 89 additions & 0 deletions test/middleware/request_validation_open_api_3_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,84 @@ def app
assert_equal 200, last_response.status
end

describe "sequential JSON request bodies" do
[
['application/jsonl', '', "\n"],
['application/x-ndjson', '', "\r\n"],
['application/json-seq', "\x1e", "\n\x1e"],
['application/geo+json-seq', "\x1e", "\n\x1e"],
].each do |content_type, prefix, separator|
it "validates each #{content_type} record and the complete array" do
encode = ->(records) { "#{prefix}#{records.join(separator)}\n" }
first = prefix.empty? ? '{"a":1}' : JSON.pretty_generate('a' => 1)
body = encode.call([first, '{"a":2}'])
check_body = lambda { |env|
assert_equal [{ 'a' => 1 }, { 'a' => 2 }], env['committee.request_body_hash']
assert_equal body, env['rack.input'].read
[200, {}, []]
}
@app = new_rack_app_with_lambda(check_body, schema: sequential_request_schema(content_type))
header 'Content-Type', "#{content_type}; charset=utf-8"

post '/numbers', body
assert_equal 200, last_response.status, last_response.body

post '/numbers', encode.call([first, '{}'])
assert_equal 400, last_response.status
assert_match(/required.*a/i, last_response.body)

post '/numbers', encode.call([first, '{'])
assert_equal 400, last_response.status
assert_equal "Request body wasn't valid JSON.", JSON.parse(last_response.body)['message']

post '/numbers', encode.call([first, '{"a":2}', '{"a":3}'])
assert_equal 400, last_response.status
end
end

it "treats an empty sequential JSON request as an empty array" do
check_body = lambda { |env|
assert_equal [], env['committee.request_body_hash']
[200, {}, []]
}
@app = new_rack_app_with_lambda(check_body, schema: sequential_request_schema('application/jsonl'))
header 'Content-Type', 'application/jsonl'

post '/numbers', ''

assert_equal 200, last_response.status, last_response.body
end

it "keeps sequential JSON request bodies raw before OpenAPI 3.2" do
body = "{\"a\":1}\n{\"a\":2}\n"
check_body = lambda { |env|
assert_equal body, env['committee.request_body_hash']
assert_equal body, env['rack.input'].read
[200, {}, []]
}
@app = new_rack_app_with_lambda(check_body, schema: sequential_request_schema('application/jsonl', version: '3.1.0', type: 'string'))
header 'Content-Type', 'application/jsonl'

post '/numbers', body

assert_equal 200, last_response.status, last_response.body
end

it "respects allow_get_body for sequential JSON requests" do
body = "{\"a\":1}\n"
check_body = lambda { |env|
assert_equal({}, env['committee.request_body_hash'])
assert_equal body, env['rack.input'].read
[200, {}, []]
}
@app = new_rack_app_with_lambda(check_body, schema: sequential_request_schema('application/jsonl', method: 'get'))

get '/numbers', {}, { input: body, 'CONTENT_TYPE' => 'application/jsonl' }

assert_equal 200, last_response.status, last_response.body
end
end

describe "DELETE request bodies" do
%w[3.1.0 3.2.0].each do |version|
describe "OpenAPI #{version}" do
Expand Down Expand Up @@ -1576,6 +1654,17 @@ def array_body_schema
Committee::Drivers.load_from_data(array_body_document, nil, parser_options: { strict_reference_validation: true })
end

def sequential_request_schema(content_type, version: '3.2.0', type: 'array', method: 'post')
document = array_body_document
document['openapi'] = version
operation = document['paths']['/numbers'].delete('post')
document['paths']['/numbers'][method] = operation
body_schema = { 'type' => type }
body_schema.merge!('maxItems' => 2, 'items' => { 'type' => 'object', 'required' => ['a'] }) if type == 'array'
operation['requestBody']['content'] = { content_type => { 'schema' => body_schema } }
Committee::Drivers.load_from_data(document, nil, parser_options: { strict_reference_validation: true })
end

def array_body_document
{
'openapi' => '3.0.3',
Expand Down
85 changes: 85 additions & 0 deletions test/middleware/response_validation_open_api_3_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,84 @@ def app
assert_equal 200, last_response.status
end

describe "sequential JSON response bodies" do
[
['application/jsonl', '', "\n"],
['application/x-ndjson', '', "\r\n"],
['application/json-seq', "\x1e", "\n\x1e"],
['application/geo+json-seq', "\x1e", "\n\x1e"],
].each do |content_type, prefix, separator|
it "validates each #{content_type} record and the complete array" do
encode = ->(records) { "#{prefix}#{records.join(separator)}\n" }
first = prefix.empty? ? '{"a":1}' : JSON.pretty_generate('a' => 1)
body = encode.call([first, '{"a":2}'])
chunks = [body[0, 5].freeze, body[5..].b.freeze]
schema = sequential_response_schema(content_type)
@app = Rack::Builder.new {
use Committee::Middleware::ResponseValidation, schema: schema
run ->(_) { [200, { 'content-type' => "#{content_type}; charset=utf-8" }, chunks] }
}

status, _headers, response = @app.call(Rack::MockRequest.env_for('/records'))
assert_equal 200, status
response.each_with_index { |chunk, index| assert_same chunks[index], chunk }

chunks.replace([encode.call([first, '{}'])])
status, _headers, response = @app.call(Rack::MockRequest.env_for('/records'))
assert_equal 500, status
assert_match(/required.*a/i, response.join)

chunks.replace([encode.call([first, '{'])])
status, _headers, response = @app.call(Rack::MockRequest.env_for('/records'))
assert_equal 500, status
assert_equal "Response wasn't valid JSON.", JSON.parse(response.join)['message']

chunks.replace([encode.call([first, '{"a":2}', '{"a":3}'])])
status, _headers, _response = @app.call(Rack::MockRequest.env_for('/records'))
assert_equal 500, status
end
end

it "treats an empty sequential JSON response as an empty array" do
@app = new_response_rack('', {}, { schema: sequential_response_schema('application/jsonl') }, { content_type: 'application/jsonl' })

get '/records'

assert_equal 200, last_response.status, last_response.body
end

it "keeps sequential JSON response bodies raw before OpenAPI 3.2" do
body = "{\"a\":1}\n{\"a\":2}\n"
@app = new_response_rack(body, {}, { schema: sequential_response_schema('application/jsonl', version: '3.1.0', type: 'string') }, { content_type: 'application/jsonl' })

get '/records'

assert_equal 200, last_response.status, last_response.body
assert_equal body, last_response.body
end

it "uses sequential JSON mapping when parse_response_by_content_type is false" do
body = "{\"a\":1}\n{\"a\":2}\n"
@app = new_response_rack(body, {}, { schema: sequential_response_schema('application/jsonl'), parse_response_by_content_type: false }, { content_type: 'application/jsonl' })

get '/records'

assert_equal 200, last_response.status, last_response.body
end

it "lets custom parsers handle sequential JSON responses" do
parsed_body = nil
parser = ->(body) { parsed_body = body; [{ 'a' => 1 }] }
@app = new_response_rack('custom format', {}, { schema: sequential_response_schema('application/jsonl'), streaming_content_parsers: { 'application/jsonl' => parser } }, { content_type: 'application/jsonl' })

get '/records'

assert_equal 200, last_response.status
assert_equal 'custom format', last_response.body
assert_equal 'custom format', parsed_body
end
end

it "passes through mixed encoding chunks" do
chunks = ['{"Otonokizaka":["あ'.freeze, "い".b.freeze, 'う"]}'.freeze]
@app = Rack::Builder.new {
Expand Down Expand Up @@ -489,6 +567,13 @@ def app

private

def sequential_response_schema(content_type, version: '3.2.0', type: 'array')
body_schema = { 'type' => type }
body_schema.merge!('maxItems' => 2, 'items' => { 'type' => 'object', 'required' => ['a'] }) if type == 'array'
document = { 'openapi' => version, 'info' => { 'title' => 'test', 'version' => '1.0.0' }, 'paths' => { '/records' => { 'get' => { 'responses' => { '200' => { 'description' => 'ok', 'content' => { content_type => { 'schema' => body_schema } } } } } } } }
Committee::Drivers.load_from_data(document, nil, parser_options: { strict_reference_validation: true })
end

def new_response_rack(response, headers = {}, options = {}, rack_options = {})
status = rack_options[:status] || 200
content_type = rack_options[:content_type] || "application/json"
Expand Down
9 changes: 9 additions & 0 deletions test/request_unpacker_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,15 @@
assert_equal([{}, false], unpacker.unpack_request_params(request))
end

it "rewinds sequential JSON bodies before parsing errors" do
body = "{\"a\":1}\n{\n"
request = Rack::Request.new({ 'REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'application/jsonl', 'rack.input' => StringIO.new(body) })
unpacker = Committee::RequestUnpacker.new(allow_sequential_json: true)

assert_raises(JSON::ParserError) { unpacker.unpack_request_params(request) }
assert_equal body, request.body.read
end

it "doesn't unpack form params" do
%w[application/x-www-form-urlencoded multipart/form-data].each do |content_type|
env = { "CONTENT_TYPE" => content_type, "rack.input" => StringIO.new("x=y"), }
Expand Down
55 changes: 55 additions & 0 deletions test/schema_validator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,61 @@
assert_equal false, Committee::SchemaValidator.json_media_type?(nil)
end

describe "sequential JSON" do
it "recognizes complete media types and structured suffixes" do
%w[application/jsonl application/x-ndjson application/json-seq application/geo+json-seq model/example+json-seq].each do |content_type|
assert Committee::SchemaValidator.sequential_json_media_type?("#{content_type}; charset=utf-8")
end
[nil, 'application/json', 'x-application/jsonl', 'application/jsonl-extra', 'application/json-sequence', 'text/event-stream'].each do |content_type|
refute Committee::SchemaValidator.sequential_json_media_type?(content_type)
end
end

it "parses every newline-delimited JSON value in order" do
values = [{ 'a' => 1 }, nil, false, 3, 'text', [1]]
body = values.map { |value| JSON.generate(value) }.join("\r\n") + "\r\n"

assert_equal values, Committee::SchemaValidator.parse_sequential_json(body, 'application/jsonl')
assert_equal values, Committee::SchemaValidator.parse_sequential_json(body, 'application/x-ndjson')
end

it "rejects blank JSON Lines records" do
["{}\n\n{}\n", "{}\n\n", " \n"].each do |body|
assert_raises(JSON::ParserError) { Committee::SchemaValidator.parse_sequential_json(body, 'application/jsonl') }
end
end

it "parses RS-delimited pretty JSON and scalar values" do
body = "\x1e#{JSON.pretty_generate('a' => 1)}\n\x1enull\n\x1efalse\n\x1e1\n\x1e\"text\""

assert_equal [{ 'a' => 1 }, nil, false, 1, 'text'], Committee::SchemaValidator.parse_sequential_json(body, 'application/geo+json-seq')
end

it "ignores consecutive record separators rather than creating empty values" do
assert_equal [{}, false], Committee::SchemaValidator.parse_sequential_json("\x1e\x1e{}\n\x1e\x1efalse\n", 'application/json-seq')
end

it "rejects JSON sequences without a leading record separator" do
["{}\n", "{}\x1e{}\n", " \x1e{}\n"].each do |body|
assert_raises(JSON::ParserError) { Committee::SchemaValidator.parse_sequential_json(body, 'application/json-seq') }
end
end

it "rejects potentially truncated scalar sequence records" do
%w[1 1e1 true false null].each do |value|
assert_raises(JSON::ParserError) { Committee::SchemaValidator.parse_sequential_json("\x1e#{value}", 'application/json-seq') }
end
assert_raises(JSON::ParserError) { Committee::SchemaValidator.parse_sequential_json("\x1e1\x1e{}\n", 'application/json-seq') }
assert_equal [1, true, nil], Committee::SchemaValidator.parse_sequential_json("\x1e1\n\x1etrue \x1enull\t", 'application/json-seq')
end

it "maps empty sequential JSON bodies to empty arrays" do
%w[application/jsonl application/x-ndjson application/json-seq application/geo+json-seq].each do |content_type|
assert_equal [], Committee::SchemaValidator.parse_sequential_json('', content_type)
end
end
end

it "parses +json responses in the HyperSchema validator" do
schema = Committee::Drivers::OpenAPI2::Driver.new.parse(open_api_2_data)
validator_option = Committee::SchemaValidator::Option.new({ parse_response_by_content_type: true }, schema, :hyper_schema)
Expand Down