Class: Aspera::Schema::Validator

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/aspera/schema/validator.rb

Overview

Validate values against the JSON schemas of the registry. Only schemas owned by ascli are validated: vendor API schemas are checked by the API itself.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize ⇒ Validator

Returns a new instance of Validator.



20
21
22
23
# File 'lib/aspera/schema/validator.rb', line 20

def initialize
  # Compiled documents, key: [registry key, partial], value: [document of the registry, compiled document]
  @documents = {}
end

Class Method Details

.instance ⇒ Validator

Returns the singleton instance of Validator

Returns:



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/aspera/schema/validator.rb', line 17

class Validator
  include Singleton

  def initialize
    # Compiled documents, key: [registry key, partial], value: [document of the registry, compiled document]
    @documents = {}
  end

  # Validate a value against a schema.
  # @param value   [Object]  value to validate
  # @param path    [String]  schema path, e.g. `opts:components.schemas.HttpOptions`
  # @param partial [Boolean] `true`: value may be incomplete, `required` is not enforced, the selector of variants (`discriminator`) may be missing
  # @param ignore_null [Boolean] `true`: `null` values (removal of an entry) are ignored, as if absent
  # @return [Array<String>] error messages, empty if valid or schema not validated
  def errors(value, path, partial: false, ignore_null: partial)
    return [] unless path.is_a?(String) && Registry.owned?(path)
    key, dotted = path.split(':', 2)
    schema = document(key, partial)
    schema = schema.ref("#/#{dotted.split('.').map { |s| s.gsub('~', '~0').gsub('/', '~1') }.join('/')}") if dotted
    # JSON view of value: symbol keys and values become strings
    data = JSON.parse(JSON.generate(value))
    data = without_null(data) if ignore_null
    results = schema.validate(data).to_a
    # Only an error that is reported cancels the unknown-key error (not the missing selector of a partial value)
    reported = results.select { |error| message(error, partial) }
    results.reject { |error| unreliable_unevaluated?(error, reported, results, key, partial) }.filter_map { |error| message(error, partial) }
  end

  private

  # @param key     [String]  registry key
  # @param partial [Boolean] remove `required` from schema
  # @return [JSONSchemer::Schema] compiled schema document, compiled again when the registry reads the document again (see `Registry#reader`)
  def document(key, partial)
    source = Registry.instance.reader(key).current
    compiled_source, compiled = @documents[[key, partial]]
    return compiled if compiled_source.equal?(source)
    require 'json_schemer'
    root = partial ? without_required(source) : source
    meta =
      case root['openapi']
      when /^3\.0\./ then JSONSchemer.openapi30
      when /^3\.1\./ then JSONSchemer.openapi31
      end
    compiled = meta ? JSONSchemer.schema(root, meta_schema: meta) : JSONSchemer.schema(root)
    @documents[[key, partial]] = [source, compiled]
    compiled
  end

  # @param node [Object] schema node
  # @return [Object] copy of node without `required` lists
  def without_required(node)
    case node
    when Hash then node.each_with_object({}) { |(k, v), h| h[k] = without_required(v) unless k.eql?('required') && v.is_a?(Array) }
    when Array then node.map { |e| without_required(e) }
    else node
    end
  end

  # @param node [Object] JSON value
  # @return [Object] copy of node without Hash entries whose value is `null` (entry removal requested by user)
  def without_null(node)
    case node
    when Hash then node.each_with_object({}) { |(k, v), h| h[k] = without_null(v) unless v.nil? }
    when Array then node.map { |e| without_null(e) }
    else node
    end
  end

  # A key refused by `unevaluatedProperties` is unknown only if the variants of the object are evaluated without error.
  # Else (selector of variants invalid, or error in the variant), no key of the variant is evaluated, and all are refused.
  # With the selector missing in a partial value (ignored error), the variant is not known: a key of any variant is accepted.
  # @param error    [Hash]        json_schemer error
  # @param reported [Array<Hash>] Errors of the validation that are reported
  # @param results  [Array<Hash>] All errors of the validation
  # @param key      [String]      registry key
  # @param partial  [Boolean]     partial validation
  # @return [Boolean] `true` if the error is a key refused by `unevaluatedProperties`, that is not a real unknown key
  def unreliable_unevaluated?(error, reported, results, key, partial)
    return false unless error['schema_pointer'].end_with?('/unevaluatedProperties')
    object = error['data_pointer'].sub(%r{/[^/]*\z}, '')
    inside = lambda do |other|
      !other['schema_pointer'].eql?(error['schema_pointer']) &&
        (other['data_pointer'].eql?(object) || other['data_pointer'].start_with?("#{object}/"))
    end
    return true if reported.any?(&inside)
    return false unless partial && results.any? { |other| inside.call(other) && other['type'].eql?('discriminator') }
    variant_key?(key, error['schema_pointer'].delete_suffix('/unevaluatedProperties'), error['data_pointer'].split('/').last)
  end

  # @param key     [String] registry key
  # @param pointer [String] JSON pointer of a schema node with `oneOf` variants
  # @param name    [String] property name
  # @return [Boolean] `true` if a variant of the node has a property of that name
  def variant_key?(key, pointer, name)
    source = Registry.instance.reader(key).current
    node = source.dig(*pointer.split('/').drop(1).map { |s| s.gsub('~1', '/').gsub('~0', '~') })
    return false unless node.is_a?(Hash)
    node.fetch('oneOf', []).any? do |variant|
      ref = variant['$ref']
      variant = source.dig(*ref.delete_prefix('#/').split('/')) if ref
      variant.is_a?(Hash) && variant.fetch('properties', {}).key?(name)
    end
  end

  # @param error   [Hash]    json_schemer error
  # @param partial [Boolean] partial validation
  # @return [String, nil] message, or nil if error is ignored
  def message(error, partial)
    # Same message for both ways of refusing other keys
    return "object property at `#{error['data_pointer']}` is a disallowed additional property" if error['schema_pointer'].end_with?('/unevaluatedProperties')
    return error['error'] unless error['type'].eql?('discriminator')
    property = error['schema'].dig('discriminator', 'propertyName')
    object = error['data']
    # Partial value: selector may come from another source or a default
    return if partial && object.is_a?(Hash) && !object.key?(property)
    # Value of an agent of a bundle that is unavailable: tell why, instead of listing the available ones
    reason = error['schema'][Registry::UNAVAILABLE]&.[](object[property]) if object.is_a?(Hash) && object[property].is_a?(String)
    return reason unless reason.nil?
    allowed = error['schema'].dig('discriminator', 'mapping')&.keys
    "value at `#{error['data_pointer']}/#{property}` is not one of: #{allowed}"
  end
end

Instance Method Details

#errors(value, path, partial: false, ignore_null: partial) ⇒ Array<String>

Validate a value against a schema.

Parameters:

  • value (Object) —

    value to validate

  • path (String) —

    schema path, e.g. opts:components.schemas.HttpOptions

  • partial (Boolean) (defaults to: false) —

    true: value may be incomplete, required is not enforced, the selector of variants (discriminator) may be missing

  • ignore_null (Boolean) (defaults to: partial) —

    true: null values (removal of an entry) are ignored, as if absent

Returns:

  • (Array<String>) —

    error messages, empty if valid or schema not validated



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/aspera/schema/validator.rb', line 31

def errors(value, path, partial: false, ignore_null: partial)
  return [] unless path.is_a?(String) && Registry.owned?(path)
  key, dotted = path.split(':', 2)
  schema = document(key, partial)
  schema = schema.ref("#/#{dotted.split('.').map { |s| s.gsub('~', '~0').gsub('/', '~1') }.join('/')}") if dotted
  # JSON view of value: symbol keys and values become strings
  data = JSON.parse(JSON.generate(value))
  data = without_null(data) if ignore_null
  results = schema.validate(data).to_a
  # Only an error that is reported cancels the unknown-key error (not the missing selector of a partial value)
  reported = results.select { |error| message(error, partial) }
  results.reject { |error| unreliable_unevaluated?(error, reported, results, key, partial) }.filter_map { |error| message(error, partial) }
end