Commit 5e0a7e52 authored by Alan (Maciej) Paruszewski's avatar Alan (Maciej) Paruszewski Committed by Kerri Miller

Add validating jsonb fields with json schema draft-07

parent b5aee638
......@@ -12,6 +12,7 @@
class JsonSchemaValidator < ActiveModel::EachValidator
FILENAME_ALLOWED = /\A[a-z0-9_-]*\Z/.freeze
FilenameError = Class.new(StandardError)
JSON_VALIDATOR_MAX_DRAFT_VERSION = 4
def initialize(options)
raise ArgumentError, "Expected 'filename' as an argument" unless options[:filename]
......@@ -29,10 +30,18 @@ class JsonSchemaValidator < ActiveModel::EachValidator
private
def valid_schema?(value)
if draft_version > JSON_VALIDATOR_MAX_DRAFT_VERSION
JSONSchemer.schema(Pathname.new(schema_path)).valid?(value)
else
JSON::Validator.validate(schema_path, value)
end
end
def schema_path
Rails.root.join('app', 'validators', 'json_schemas', "#{options[:filename]}.json").to_s
end
def draft_version
options[:draft] || JSON_VALIDATOR_MAX_DRAFT_VERSION
end
end
---
title: Add validating jsonb fields with json schema draft-07
merge_request: 49451
author:
type: added
......@@ -92,7 +92,7 @@ module Vulnerabilities
validates :metadata_version, presence: true
validates :raw_metadata, presence: true
validates :details, json_schema: { filename: 'vulnerability_finding_details' }
validates :details, json_schema: { filename: 'vulnerability_finding_details', draft: 7 }
delegate :name, :external_id, to: :scanner, prefix: true, allow_nil: true
......
......@@ -29,6 +29,36 @@ RSpec.describe JsonSchemaValidator do
expect(build_report_result.errors.full_messages).to eq(["Data must be a valid json schema"])
end
end
context 'when draft is > 4' do
let(:validator) { described_class.new(attributes: [:data], filename: "build_report_result_data", draft: 6) }
it 'uses JSONSchemer to perform validations' do
expect(JSONSchemer).to receive(:schema).with(Pathname.new(Rails.root.join('app', 'validators', 'json_schemas', 'build_report_result_data.json').to_s)).and_call_original
subject
end
end
context 'when draft is <= 4' do
let(:validator) { described_class.new(attributes: [:data], filename: "build_report_result_data", draft: 4) }
it 'uses JSON::Validator to perform validations' do
expect(JSON::Validator).to receive(:validate).with(Rails.root.join('app', 'validators', 'json_schemas', 'build_report_result_data.json').to_s, build_report_result.data)
subject
end
end
context 'when draft value is not provided' do
let(:validator) { described_class.new(attributes: [:data], filename: "build_report_result_data") }
it 'uses JSON::Validator to perform validations' do
expect(JSON::Validator).to receive(:validate).with(Rails.root.join('app', 'validators', 'json_schemas', 'build_report_result_data.json').to_s, build_report_result.data)
subject
end
end
end
context 'when filename is not set' do
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment