Skip to content

A platform for community discussion. Free, open, simple.

DEV: Validate JSON:API documents before processing writes

Loïc Guitaut38990c8fce5f
diff --git a/app/controllers/json_api_kit/base_controller.rb b/app/controllers/json_api_kit/base_controller.rb
index eaec020a32d..e3a7348e2dd 100644
--- a/app/controllers/json_api_kit/base_controller.rb
+++ b/app/controllers/json_api_kit/base_controller.rb
@@ -13,5 +13,6 @@ module JsonApiKit
include Versioning
include Serving
include Fetching
+ include RequestInput
end
end
diff --git a/app/controllers/json_api_kit/base_controller/rendering.rb b/app/controllers/json_api_kit/base_controller/rendering.rb
index 7660a3c81f8..e3764faf2d1 100644
--- a/app/controllers/json_api_kit/base_controller/rendering.rb
+++ b/app/controllers/json_api_kit/base_controller/rendering.rb
@@ -11,6 +11,12 @@ module JsonApiKit
rescue_from(Discourse::InvalidAccess) do
render_document(Document::Errors.new(Forbidden.new))
end
+
+ rescue_from(Request::Invalid) do |error|
+ render_document(Document::Errors.new(*error.refusals))
+ end
+
+ rescue_from(Error) { |error| render_document(Document::Errors.new(error)) }
end
def rescue_with_handler(*)
diff --git a/app/controllers/json_api_kit/base_controller/request_input.rb b/app/controllers/json_api_kit/base_controller/request_input.rb
new file mode 100644
index 00000000000..a9b9830f28f
--- /dev/null
+++ b/app/controllers/json_api_kit/base_controller/request_input.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class BaseController
+ module RequestInput
+ extend ActiveSupport::Concern
+
+ private
+
+ def request_body
+ @request_body ||=
+ begin
+ verify_input(request_query)
+ verify_input(Request::Body.parse(request.raw_post, resource: request_resource))
+ end
+ end
+
+ def request_query
+ @request_query ||=
+ Request::Input::Individual.new(
+ request.query_parameters,
+ resource: request_resource,
+ edition:,
+ )
+ end
+
+ def request_resource = @request_resource ||= resource.new(guardian:, edition:)
+
+ def verify_input(input)
+ raise Request::Invalid.new(input.refusals) if input.invalid?
+ input
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/body.rb b/lib/json_api_kit/request/body.rb
new file mode 100644
index 00000000000..38d794c5b5d
--- /dev/null
+++ b/lib/json_api_kit/request/body.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Body
+ class Unreadable < BadRequest
+ def title = "Invalid request body"
+
+ def detail = "The request body must contain valid JSON."
+ end
+
+ def self.parse(json, resource:)
+ new(JSON.parse(json), resource:)
+ rescue JSON::ParserError
+ raise Unreadable
+ end
+
+ def initialize(document, resource:)
+ @document = document
+ @resource = resource
+ end
+
+ delegate :invalid?, to: :contract
+
+ def to_h = document
+
+ def refusals = contract.errors.map { Error.new(it, document:) }
+
+ private
+
+ attr_reader :document, :resource
+
+ delegate :edition, :type, to: :resource
+ delegate :glossary, to: :edition
+
+ def contract = @contract ||= Contract.new(document, type: glossary.member_type(type))
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/body/contract.rb b/lib/json_api_kit/request/body/contract.rb
new file mode 100644
index 00000000000..c4135452e20
--- /dev/null
+++ b/lib/json_api_kit/request/body/contract.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Body
+ class Contract
+ include ActiveModel::Validations
+
+ validates :base, json_type: :object
+ validates :data, json_type: :object, if: :document_object?
+ validates :"data.type", json_type: :string, if: :resource_object?
+ validates :"data.type", comparison: { equal_to: :expected_type }, if: :string_type?
+ validates :"data.attributes", json_type: :object, if: :attributes_supplied?
+
+ validate :check_id, if: :resource_object?
+ validate :check_errors, if: :document_object?
+
+ def initialize(document, type:)
+ @locations =
+ Hash.new do |locations, attribute|
+ locations[attribute] = Location.for(attribute, document:)
+ end
+ @expected_type = type
+ end
+
+ attr_reader :expected_type
+
+ def read_attribute_for_validation(attribute) = location(attribute).value
+
+ private
+
+ attr_reader :locations
+
+ def location(attribute) = locations[attribute]
+
+ def document_object? = location(:base).object?
+
+ def resource_object? = location(:data).object?
+
+ def string_type? = location(:"data.type").string?
+
+ def attributes_supplied? = location(:"data.attributes").supplied?
+
+ def check_id
+ errors.add(:"data.id", :unsupported) if location(:"data.id").supplied?
+ end
+
+ def check_errors
+ if location(:data).supplied? && location(:errors).supplied?
+ errors.add(:errors, :incompatible)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/body/contract/json_type_validator.rb b/lib/json_api_kit/request/body/contract/json_type_validator.rb
new file mode 100644
index 00000000000..fbc745f9243
--- /dev/null
+++ b/lib/json_api_kit/request/body/contract/json_type_validator.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Body
+ class Contract
+ class JsonTypeValidator < ActiveModel::EachValidator
+ TYPES = { object: Hash, string: String }.freeze
+
+ def check_validity! = TYPES.fetch(options.fetch(:with))
+
+ def validate_each(record, attribute, value)
+ return if TYPES.fetch(options[:with]) === value
+ record.errors.add(attribute, :json_type, expected: options[:with])
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/body/error.rb b/lib/json_api_kit/request/body/error.rb
new file mode 100644
index 00000000000..9fdcab9a258
--- /dev/null
+++ b/lib/json_api_kit/request/body/error.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Body
+ class Error < JsonApiKit::Error
+ Rule =
+ Data.define(:status, :description) do
+ def detail(error, location) = description.call(error, location)
+ end
+
+ JSON_TYPES = { object: "an object", string: "a string" }.freeze
+ DEFAULT_RULE = Rule.new("400", ->(error, _) { error.message })
+ RULES = {
+ :json_type =>
+ Rule.new(
+ "400",
+ ->(error, location) do
+ "#{location.name} must be #{JSON_TYPES.fetch(error.options[:expected])}."
+ end,
+ ),
+ [:"data.type", :equal_to] =>
+ Rule.new(
+ "409",
+ ->(error, _) { "type must be #{error.options[:count]} for this endpoint." },
+ ),
+ [:"data.id", :unsupported] =>
+ Rule.new("403", ->(*) { "This endpoint does not accept client-generated IDs." }),
+ %i[errors incompatible] =>
+ Rule.new("400", ->(*) { "data and errors must not appear in the same document." }),
+ }.freeze
+
+ def initialize(error, document:)
+ @error = error
+ @location = Location.for(error.attribute, document:)
+ @rule =
+ RULES.fetch([error.attribute, error.type]) { RULES.fetch(error.type, DEFAULT_RULE) }
+ super()
+ end
+
+ delegate :status, to: :rule
+
+ def title = "Invalid request body"
+
+ def detail = rule.detail(error, location)
+
+ def source = { pointer: location.nearest_existing.pointer }
+
+ private
+
+ attr_reader :error, :location, :rule
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/body/location.rb b/lib/json_api_kit/request/body/location.rb
new file mode 100644
index 00000000000..9b12d56f12a
--- /dev/null
+++ b/lib/json_api_kit/request/body/location.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Body
+ class Location
+ def self.for(attribute, document:)
+ new(document, attribute == :base ? [] : attribute.to_s.split("."))
+ end
+
+ def initialize(document, path)
+ @document = document
+ @path = path
+ end
+
+ def value
+ return document if root?
+ parent.value[path.last] if parent.object?
+ end
+
+ def supplied? = root? || (parent.object? && parent.value.key?(path.last))
+
+ def object? = value.is_a?(Hash)
+
+ def string? = value.is_a?(String)
+
+ def name = root? ? "The document" : path.last
+
+ def nearest_existing
+ return self if supplied?
+ parent.nearest_existing
+ end
+
+ def pointer = path.map { "/#{it.gsub("~", "~0").gsub("/", "~1")}" }.join
+
+ private
+
+ attr_reader :document, :path
+
+ def root? = path.empty?
+
+ def parent = @parent ||= self.class.new(document, path[...-1])
+ end
+ end
+ end
+end
diff --git a/lib/json_api_kit/request/contract.rb b/lib/json_api_kit/request/contract.rb
index 483e099a263..1a4e970293c 100644
--- a/lib/json_api_kit/request/contract.rb
+++ b/lib/json_api_kit/request/contract.rb
@@ -70,17 +70,30 @@ module JsonApiKit
def check_parameters(parameters, contract, prefix = nil)
(parameters.keys - contract.attribute_names).each do |name|
- errors.add(
- [prefix, name].compact.join(".").to_sym,
- :unknown_parameter,
- message: "unknown parameter",
- )
+ unknown_parameter_members(name, parameters[name]).each do |members|
+ errors.add(
+ [prefix, name].compact.join(".").to_sym,
+ :unknown_parameter,
+ members:,
+ message: "unknown parameter",
+ )
+ end
end
contract.attribute_types.each do |name, type|
next unless type.is_a?(Service::NestedContractType) && attributes[name]
check_parameters(parameters[name], type.contract_class, name)
end
end
+
+ def unknown_parameter_members(name, value)
+ return [[]] if Parameters::FAMILIES.key?(name)
+ enum_for(:each_parameter_member, value)
+ end
+
+ def each_parameter_member(value, members = [], &block)
+ return yield(members) unless value.is_a?(Hash) && value.present?
+ value.each { |name, member| each_parameter_member(member, [*members, name], &block) }
+ end
end
end
end
diff --git a/lib/json_api_kit/request/contract/error.rb b/lib/json_api_kit/request/contract/error.rb
index f24087e8234..de39e111110 100644
--- a/lib/json_api_kit/request/contract/error.rb
+++ b/lib/json_api_kit/request/contract/error.rb
@@ -26,7 +26,10 @@ module JsonApiKit
def meta = @meta&.call(self) || {}
def parameter
- ParameterName.new(*error.attribute.to_s.split(".").map { member_value(member(it)) })
+ ParameterName.new(
+ *error.attribute.to_s.split(".").map { member_value(member(it)) },
+ *options.fetch(:members, []),
+ )
end
def name = member_value(options[:name])
diff --git a/lib/json_api_kit/request/invalid.rb b/lib/json_api_kit/request/invalid.rb
new file mode 100644
index 00000000000..7cffa62d1c0
--- /dev/null
+++ b/lib/json_api_kit/request/invalid.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+module JsonApiKit
+ class Request
+ class Invalid < StandardError
+ def initialize(refusals)
+ @refusals = refusals
+ super(refusals.map(&:detail).join(" "))
+ end
+
+ attr_reader :refusals
+ end
+ end
+end
diff --git a/spec/integration/json_api_kit/errors_spec.rb b/spec/integration/json_api_kit/errors_spec.rb
index 7b3007059da..de68d9c04bd 100644
--- a/spec/integration/json_api_kit/errors_spec.rb
+++ b/spec/integration/json_api_kit/errors_spec.rb
@@ -332,8 +332,8 @@ RSpec.describe "a refused request" do
errors: [
refusal(
title: "No such parameter",
- detail: "There is no parameter named sorts.",
- parameter: "sorts",
+ detail: "There is no parameter named sorts[createdAt].",
+ parameter: "sorts[createdAt]",
),
],
)
diff --git a/spec/integration/json_api_kit/request_body_spec.rb b/spec/integration/json_api_kit/request_body_spec.rb
new file mode 100644
index 00000000000..aff238980a8
--- /dev/null
+++ b/spec/integration/json_api_kit/request_body_spec.rb
@@ -0,0 +1,274 @@
+# frozen_string_literal: true
+
+require_relative "support"
+
+module JsonApiKitSpec
+ class RequestBodyTopicsController < JsonApiKit::BaseController
+ resource :topics
+
+ def create
+ render json: request_body.to_h, content_type: JsonApiKit::MediaType::JSON_API
+ end
+ end
+
+ class RenameRequestBodyTopics < JsonApiKit::VersionChange
+ version "2026-09-01"
+ description "Discussion threads become topics."
+
+ renamed_type from: :discussion_threads, to: :topics
+
+ resource :topics do
+ renamed_attribute from: :heading, to: :title
+ end
+ end
+end
+
+RSpec.describe JsonApiKitSpec::RequestBodyTopicsController, type: :request do
+ describe "#create" do
+ let(:path) { "/api/request-body-topics" }
+ let(:document) { { "data" => primary } }
+ let(:primary) { { "type" => "topics", "attributes" => attributes } }
+ let(:attributes) { { "title" => "A new topic" } }
+ let(:body) { document.to_json }
+ let(:version) { "2026-09-01" }
+ let(:version_changes) do
+ JsonApiKit::VersionChanges.new([JsonApiKitSpec::RenameRequestBodyTopics.new(__FILE__)])
+ end
+ let(:parsed_body) { JSON.parse(response.body) }
+ let(:status) { 400 }
+
+ before do
+ freeze_time(Date.new(2026, 9, 2))
+ allow(JsonApiKit::VersionChanges).to receive(:core).and_return(version_changes)
+ Rails.application.routes.disable_clear_and_finalize = true
+ Rails.application.routes.draw do
+ post "/api/request-body-topics" => "json_api_kit_spec/request_body_topics#create"
+ end
+ Rails.application.routes.disable_clear_and_finalize = false
+ post path,
+ params: body,
+ headers: {
+ "HTTP_API_VERSION" => version,
+ "CONTENT_TYPE" => JsonApiKit::MediaType::JSON_API,
+ }
+ end
+
+ after { Rails.application.reload_routes! }
+
+ shared_examples "a refused request body" do
+ it "returns the refusal at the submitted location", :aggregate_failures do
+ expect(response).to have_http_status(status)
+ expect(parsed_body.fetch("errors")).to contain_exactly(
+ a_hash_including("status" => status.to_s, "source" => { "pointer" => pointer }),
+ )
+ end
+ end
+
+ it "supplies the document to the action", :aggregate_failures do
+ expect(response).to have_http_status(:ok)
+ expect(parsed_body).to eq(document)
+ end
+
+ context "when attributes are omitted" do
+ let(:primary) { super().except("attributes") }
+
+ it "preserves their absence" do
+ expect(parsed_body).to eq(document)
+ end
+ end
+
+ context "when attributes are empty" do
+ let(:attributes) { {} }
+
+ it "supplies the empty object to the action" do
+ expect(parsed_body).to eq(document)
+ end
+ end
+
+ context "when an attribute is null" do
+ let(:attributes) { super().merge("title" => nil) }
+
+ it "preserves the explicit null" do
+ expect(parsed_body).to eq(document)
+ end
+ end
+
+ context "when attributes are undeclared" do
+ let(:attributes) do
+ {
+ "unknownField" => "something",
+ "enabled" => false,
+ "count" => 0,
+ "settings" => {
+ "labels" => ["one", nil, "two"],
+ },
+ }
+ end
+
+ it "supplies their names and values to the action" do
+ expect(parsed_body).to eq(document)
+ end
+ end
+
+ context "when the query supplies conflicting data" do
+ let(:path) { "#{super()}?data[type]=users" }
+
+ it "refuses the unsupported query parameter", :aggregate_failures do
+ expect(response).to have_http_status(:bad_request)
+ expect(parsed_body.fetch("errors")).to contain_exactly(
+ a_hash_including("status" => "400", "source" => { "parameter" => "data[type]" }),
+ )
+ end
+ end
+
+ context "when the document contains an additional member" do
+ let(:document) { super().merge("extra" => true) }
+
+ it "accepts the resource object", :aggregate_failures do
+ expect(response).to have_http_status(:ok)
+ expect(parsed_body.fetch("data")).to eq(primary)
+ end
+ end
+
+ context "when the document contains data and errors" do
+ let(:document) { super().merge("errors" => []) }
+ let(:pointer) { "/errors" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when the document is an array" do
+ let(:document) { [super()] }
+ let(:pointer) { "" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when the document is null" do
+ let(:document) { nil }
+ let(:pointer) { "" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when data is omitted" do
+ let(:document) { {} }
+ let(:pointer) { "" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when only the query supplies data" do
+ let(:path) { "#{super()}?data[type]=topics" }
+ let(:document) { {} }
+
+ it "refuses the unsupported query parameter", :aggregate_failures do
+ expect(response).to have_http_status(:bad_request)
+ expect(parsed_body.fetch("errors")).to include(
+ a_hash_including("status" => "400", "source" => { "parameter" => "data[type]" }),
+ )
+ end
+ end
+
+ context "when data is an array" do
+ let(:primary) { [super()] }
+ let(:pointer) { "/data" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when data is null" do
+ let(:primary) { nil }
+ let(:pointer) { "/data" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when the type is omitted" do
+ let(:primary) { super().except("type") }
+ let(:pointer) { "/data" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when the type is a number" do
+ let(:primary) { super().merge("type" => 123) }
+ let(:pointer) { "/data/type" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when the type is null" do
+ let(:primary) { super().merge("type" => nil) }
+ let(:pointer) { "/data/type" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when the type belongs to another resource" do
+ let(:primary) { super().merge("type" => "users") }
+ let(:status) { 409 }
+ let(:pointer) { "/data/type" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when attributes are null" do
+ let(:attributes) { nil }
+ let(:pointer) { "/data/attributes" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when attributes are an array" do
+ let(:attributes) { [] }
+ let(:pointer) { "/data/attributes" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when the client supplies an id" do
+ let(:primary) { super().merge("id" => "550e8400-e29b-41d4-a716-446655440000") }
+ let(:status) { 403 }
+ let(:pointer) { "/data/id" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when the client uses a historical version" do
+ let(:version) { JsonApiKit::Timeline::FIRST_RELEASE.to_s }
+ let(:primary) { super().merge("type" => "discussionThreads") }
+ let(:attributes) { { "heading" => "A new topic" } }
+
+ it "accepts the historical type", :aggregate_failures do
+ expect(response).to have_http_status(:ok)
+ expect(parsed_body).to eq(document)
+ end
+
+ context "when the client supplies the current type" do
+ let(:primary) { super().merge("type" => "topics") }
+ let(:status) { 409 }
+ let(:pointer) { "/data/type" }
+
+ it_behaves_like "a refused request body"
+ end
+ end
+
+ context "when the client supplies a historical type in the current version" do
+ let(:primary) { super().merge("type" => "discussionThreads") }
+ let(:status) { 409 }
+ let(:pointer) { "/data/type" }
+
+ it_behaves_like "a refused request body"
+ end
+
+ context "when the body contains malformed JSON" do
+ let(:body) { '{"data":' }
+
+ it "returns a JSON:API error", :aggregate_failures do
+ expect(response).to have_http_status(:bad_request)
+ expect(parsed_body.fetch("errors")).to contain_exactly(a_hash_including("status" => "400"))
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/request/body/error_spec.rb b/spec/lib/json_api_kit/request/body/error_spec.rb
new file mode 100644
index 00000000000..491d7af6532
--- /dev/null
+++ b/spec/lib/json_api_kit/request/body/error_spec.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Request::Body::Error do
+ subject(:refusal) { described_class.new(error, document:) }
+
+ let(:document) { { "data" => { "type" => "users", "attributes" => {} } } }
+ let(:contract) { JsonApiKit::Request::Body::Contract.new(document, type: "topics") }
+ let(:error) { contract.errors.add(attribute, reason, **options) }
+ let(:attribute) { :"data.type" }
+ let(:reason) { :equal_to }
+ let(:options) { { count: "topics" } }
+
+ describe "#status" do
+ it "reports an endpoint type conflict" do
+ expect(refusal.status).to eq("409")
+ end
+
+ context "when a different member fails a comparison" do
+ let(:attribute) { :"data.attributes" }
+
+ it "reports invalid input" do
+ expect(refusal.status).to eq("400")
+ end
+ end
+
+ context "when the client supplies an id" do
+ let(:attribute) { :"data.id" }
+ let(:reason) { :unsupported }
+ let(:options) { {} }
+
+ it "reports an unsupported client-generated id" do
+ expect(refusal.status).to eq("403")
+ end
+ end
+
+ context "when a different member is unsupported" do
+ let(:attribute) { :"data.attributes" }
+ let(:reason) { :unsupported }
+ let(:options) { { message: "Unsupported attributes." } }
+
+ it "reports invalid input" do
+ expect(refusal.status).to eq("400")
+ end
+ end
+ end
+
+ describe "#detail" do
+ it "describes the endpoint type conflict" do
+ expect(refusal.detail).to eq("type must be topics for this endpoint.")
+ end
+
+ context "when an error has no presentation rule" do
+ let(:attribute) { :"data.attributes" }
+ let(:reason) { :unsupported }
+ let(:options) { { message: "Unsupported attributes." } }
+
+ it "preserves the validation message" do
+ expect(refusal.detail).to eq("Unsupported attributes.")
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/request/body/location_spec.rb b/spec/lib/json_api_kit/request/body/location_spec.rb
new file mode 100644
index 00000000000..c2e86ee2ac1
--- /dev/null
+++ b/spec/lib/json_api_kit/request/body/location_spec.rb
@@ -0,0 +1,113 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Request::Body::Location do
+ subject(:location) { described_class.new(document, path) }
+
+ let(:document) { { "data" => { "type" => "topics", "attributes" => { "title" => nil } } } }
+ let(:path) { %w[data type] }
+
+ describe ".for" do
+ subject(:location) { described_class.for(attribute, document:) }
+
+ let(:attribute) { :"data.type" }
+
+ it "locates the contract attribute" do
+ expect(location.value).to eq("topics")
+ end
+
+ context "when the attribute is base" do
+ let(:attribute) { :base }
+
+ it "locates the whole document" do
+ expect(location.value).to equal(document)
+ end
+ end
+ end
+
+ describe "#value" do
+ it "reads the submitted value" do
+ expect(location.value).to eq("topics")
+ end
+
+ context "when a parent is a scalar" do
+ let(:document) { { "data" => false } }
+
+ it "returns no value" do
+ expect(location.value).to be_nil
+ end
+ end
+ end
+
+ describe "#supplied?" do
+ it { is_expected.to be_supplied }
+
+ context "when the value is null" do
+ let(:path) { %w[data attributes title] }
+
+ it { is_expected.to be_supplied }
+ end
+
+ context "when the member is omitted" do
+ let(:path) { %w[data id] }
+
+ it { is_expected.not_to be_supplied }
+ end
+
+ context "when a parent is omitted" do
+ let(:document) { {} }
+
+ it { is_expected.not_to be_supplied }
+ end
+
+ context "when the document is null" do
+ let(:document) { nil }
+ let(:path) { [] }
+
+ it { is_expected.to be_supplied }
+ end
+ end
+
+ describe "#nearest_existing" do
+ it "retains a supplied location" do
+ expect(location.nearest_existing).to equal(location)
+ end
+
+ context "when the member is omitted" do
+ let(:path) { %w[data id] }
+
+ it "locates the parent" do
+ expect(location.nearest_existing.pointer).to eq("/data")
+ end
+ end
+
+ context "when a parent is null" do
+ let(:document) { { "data" => nil } }
+
+ it "locates the explicit null" do
+ expect(location.nearest_existing.pointer).to eq("/data")
+ end
+ end
+
+ context "when data is omitted" do
+ let(:document) { {} }
+
+ it "locates the document" do
+ expect(location.nearest_existing.pointer).to eq("")
+ end
+ end
+ end
+
+ describe "#pointer" do
+ it "encodes the member path" do
+ expect(location.pointer).to eq("/data/type")
+ end
+
+ context "when member names contain pointer characters" do
+ let(:path) { %w[data attributes a~/b.c] }
+
+ it "escapes each complete member name" do
+ expect(location.pointer).to eq("/data/attributes/a~0~1b.c")
+ end
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/request/body_spec.rb b/spec/lib/json_api_kit/request/body_spec.rb
new file mode 100644
index 00000000000..187260dfb6e
--- /dev/null
+++ b/spec/lib/json_api_kit/request/body_spec.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+RSpec.describe JsonApiKit::Request::Body do
+ subject(:body) { described_class.parse(document.to_json, resource:) }
+
+ let(:document) { { "data" => { "type" => "topics", "attributes" => { "title" => nil } } } }
+ let(:resource) do
+ Class
+ .new(JsonApiKit::Resource) do
+ model Topic
+ type :topics
+ end
+ .new(guardian: Guardian.new)
+ end
+
+ describe "#to_h" do
+ before { body.invalid? }
+
+ it "preserves the supplied document" do
+ expect(body.to_h).to eq(document)
+ end
+ end
+
+ describe "#refusals" do
+ subject(:refusals) { body.refusals }
+
+ let(:document) { { "data" => { "type" => 123, "attributes" => [] } } }
+
+ before { body.invalid? }
+
+ it "reports each invalid member" do
+ expect(refusals.map(&:source)).to contain_exactly(
+ { pointer: "/data/type" },
+ { pointer: "/data/attributes" },
+ )
+ end
+
+ it "explains the invalid type" do
+ expect(refusals.map(&:detail)).to include("type must be a string.")
+ end
+ end
+
+ describe "#invalid?" do
+ context "when the type is an empty array" do
+ let(:document) { { "data" => { "type" => [] } } }
+
+ it { is_expected.to be_invalid }
+ end
+
+ context "when the type is an array containing the expected type" do
+ let(:document) { { "data" => { "type" => ["topics"] } } }
+
+ it { is_expected.to be_invalid }
+ end
+ end
+end
diff --git a/spec/lib/json_api_kit/request/contract/individual_spec.rb b/spec/lib/json_api_kit/request/contract/individual_spec.rb
index f8310c03787..78ec26f9590 100644
--- a/spec/lib/json_api_kit/request/contract/individual_spec.rb
+++ b/spec/lib/json_api_kit/request/contract/individual_spec.rb
@@ -23,6 +23,21 @@ RSpec.describe JsonApiKit::Request::Contract::Individual, type: :model do
end
end
+ describe "#refusals" do
+ subject(:refusals) { contract.refusals }
+
+ let(:params) { { data: { type: "users", attributes: { "unknown_field" => "value" } } } }
+
+ before { contract.invalid? }
+
+ it "identifies each unknown query parameter" do
+ expect(refusals.map(&:source)).to contain_exactly(
+ { parameter: "data[type]" },
+ { parameter: "data[attributes][unknown_field]" },
+ )
+ end
+ end
+
describe "Unknown parameters" do
context "when a parameter is unknown" do
let(:params) { { fieldsets: { topics: %w[title] } } }