A platform for community discussion. Free, open, simple.
DEV: Require a version header on JSON:API requests (#43084)
Loïc Guitaut80692ebba5e3
diff --git a/app/controllers/json_api_kit/base_controller.rb b/app/controllers/json_api_kit/base_controller.rbindex d7cdd6eff35..beb53cf695a 100644--- a/app/controllers/json_api_kit/base_controller.rb+++ b/app/controllers/json_api_kit/base_controller.rb@@ -2,107 +2,16 @@module JsonApiKitclass BaseController < ::ApplicationController- MissingDeclaration = Class.new(StandardError)-- ROOT = "/api"- OTHER_PARAMETER = "Content-Type accepts the ext and profile parameters only."- NO_EXTENSION = "This API applies no extension."- UNREADABLE_ACCEPT =- "Accept must allow #{MediaType::JSON_API} with the ext and profile parameters only."-skip_before_action :check_xhr,:redirect_to_login_if_required,:verify_authenticity_token,raise: false- class_attribute :declared_resource, instance_accessor: false-- before_action :set_json_format- before_action :set_vary_header- before_action :negotiate-- rescue_from(Discourse::InvalidAccess) { render_document(Document::Errors.new(Forbidden.new)) }-- class << self- def resource(declaration)- self.declared_resource = ResourceLookup.resource(declaration, within: self)- end- end-- def rescue_with_handler(*)- super || render_server_error(*)- end-- def index- render_document(- Document::Collection.for(request.query_parameters, resource:, guardian:, urls:),- )- end-- def show- render_document(- Document::Individual.for(- params[:id],- request.query_parameters,- resource:,- guardian:,- urls:,- ),- )- end-- private-- def resource- self.class.declared_resource or- raise MissingDeclaration,- "#{self.class}: declare the resource it serves with `resource :things`"- end-- def urls- Urls.new(- base: "#{request.base_url}#{ROOT}",- current: "#{request.base_url}#{request.path}",- parameters: request.query_parameters,- )- end-- def set_json_format = request.format = :json-- def set_vary_header = response.headers["Vary"] ||= "Accept"-- def render_server_error(error)- Discourse.warn_exception(error, message: "JSON:API request failed")- render_document(Document::Errors.new(InternalServerError.new))- end-- def render_document(document)- render json: document.to_h,- status: document.status,- content_type: Pagination::Profile::MEDIA_TYPE- end-- def negotiate- (content_type_refusal || accept_refusal).try { render_document(Document::Errors.new(it)) }- end-- def content_type_refusal- return unless request_media_type&.json_api?- return UnsupportedMediaType.new(OTHER_PARAMETER) if request_media_type.modified?- UnsupportedMediaType.new(NO_EXTENSION) if request_media_type.extended?- end-- def accept_refusal- return if accepted_media_types.empty? || accepted_media_types.any? { !it.modified? }- NotAcceptable.new(UNREADABLE_ACCEPT)- end-- def request_media_type- @request_media_type ||= MediaType.parse(request.headers["Content-Type"]).first- end-- def accepted_media_types- @accepted_media_types ||= MediaType.parse(request.headers["Accept"]).select(&:json_api?)- end+ # Order matters here+ include Rendering+ include Negotiating+ include Versioning+ include Serving+ include Readingendenddiff --git a/app/controllers/json_api_kit/base_controller/negotiating.rb b/app/controllers/json_api_kit/base_controller/negotiating.rbnew file mode 100644index 00000000000..957ce4d302d--- /dev/null+++ b/app/controllers/json_api_kit/base_controller/negotiating.rb@@ -0,0 +1,46 @@+# frozen_string_literal: true++module JsonApiKit+ class BaseController+ module Negotiating+ extend ActiveSupport::Concern++ OTHER_PARAMETER = "Content-Type accepts the ext and profile parameters only."+ NO_EXTENSION = "This API applies no extension."+ UNREADABLE_ACCEPT =+ "Accept must allow #{MediaType::JSON_API} with the ext and profile parameters only."++ included do+ before_action :set_vary_header+ before_action :negotiate+ end++ private++ def set_vary_header = response.headers["Vary"] ||= "Accept"++ def negotiate+ (content_type_refusal || accept_refusal).try { render_document(Document::Errors.new(it)) }+ end++ def content_type_refusal+ return unless request_media_type&.json_api?+ return UnsupportedMediaType.new(OTHER_PARAMETER) if request_media_type.modified?+ UnsupportedMediaType.new(NO_EXTENSION) if request_media_type.extended?+ end++ def accept_refusal+ return if accepted_media_types.empty? || accepted_media_types.any? { !it.modified? }+ NotAcceptable.new(UNREADABLE_ACCEPT)+ end++ def request_media_type+ @request_media_type ||= MediaType.parse(request.headers["Content-Type"]).first+ end++ def accepted_media_types+ @accepted_media_types ||= MediaType.parse(request.headers["Accept"]).select(&:json_api?)+ end+ end+ end+enddiff --git a/app/controllers/json_api_kit/base_controller/reading.rb b/app/controllers/json_api_kit/base_controller/reading.rbnew file mode 100644index 00000000000..ba1a0b74c0e--- /dev/null+++ b/app/controllers/json_api_kit/base_controller/reading.rb@@ -0,0 +1,39 @@+# frozen_string_literal: true++module JsonApiKit+ class BaseController+ module Reading+ extend ActiveSupport::Concern++ ROOT = "/api"++ def index+ render_document(+ Document::Collection.for(request.query_parameters, resource:, guardian:, urls:),+ )+ end++ def show+ render_document(+ Document::Individual.for(+ params[:id],+ request.query_parameters,+ resource:,+ guardian:,+ urls:,+ ),+ )+ end++ private++ def urls+ Urls.new(+ base: "#{request.base_url}#{ROOT}",+ current: "#{request.base_url}#{request.path}",+ parameters: request.query_parameters,+ )+ end+ end+ end+enddiff --git a/app/controllers/json_api_kit/base_controller/rendering.rb b/app/controllers/json_api_kit/base_controller/rendering.rbnew file mode 100644index 00000000000..7660a3c81f8--- /dev/null+++ b/app/controllers/json_api_kit/base_controller/rendering.rb@@ -0,0 +1,36 @@+# frozen_string_literal: true++module JsonApiKit+ class BaseController+ module Rendering+ extend ActiveSupport::Concern++ included do+ before_action :set_json_format++ rescue_from(Discourse::InvalidAccess) do+ render_document(Document::Errors.new(Forbidden.new))+ end+ end++ def rescue_with_handler(*)+ super || render_server_error(*)+ end++ private++ def set_json_format = request.format = :json++ def render_document(document)+ render json: document.to_h,+ status: document.status,+ content_type: Pagination::Profile::MEDIA_TYPE+ end++ def render_server_error(error)+ Discourse.warn_exception(error, message: "JSON:API request failed")+ render_document(Document::Errors.new(InternalServerError.new))+ end+ end+ end+enddiff --git a/app/controllers/json_api_kit/base_controller/serving.rb b/app/controllers/json_api_kit/base_controller/serving.rbnew file mode 100644index 00000000000..8539c437040--- /dev/null+++ b/app/controllers/json_api_kit/base_controller/serving.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++module JsonApiKit+ class BaseController+ module Serving+ extend ActiveSupport::Concern++ MissingDeclaration = Class.new(StandardError)++ included { class_attribute :declared_resource, instance_accessor: false }++ class_methods do+ def resource(declaration)+ self.declared_resource = ResourceLookup.resource(declaration, within: self)+ end+ end++ private++ def resource+ self.class.declared_resource or+ raise MissingDeclaration,+ "#{self.class}: declare the resource it serves with `resource :things`"+ end+ end+ end+enddiff --git a/app/controllers/json_api_kit/base_controller/versioning.rb b/app/controllers/json_api_kit/base_controller/versioning.rbnew file mode 100644index 00000000000..174e175f8f1--- /dev/null+++ b/app/controllers/json_api_kit/base_controller/versioning.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++module JsonApiKit+ class BaseController+ module Versioning+ extend ActiveSupport::Concern++ included { before_action :resolve_version }++ private++ def resolve_version+ response.headers[ApiVersion::HEADER] = Timeline.resolve(requested_version).to_s+ rescue Error => error+ render_document(Document::Errors.new(error))+ end++ def requested_version = request.headers[ApiVersion::HEADER]+ end+ end+enddiff --git a/lib/json_api_kit/api_version.rb b/lib/json_api_kit/api_version.rbnew file mode 100644index 00000000000..cecb51f62fd--- /dev/null+++ b/lib/json_api_kit/api_version.rb@@ -0,0 +1,66 @@+# frozen_string_literal: true++module JsonApiKit+ class ApiVersion+ include Comparable++ HEADER = "Api-Version"+ WIRE_FORMAT = /\A\d{4}-\d{2}-\d{2}\z/++ class Refusal < BadRequest+ def initialize(version = nil)+ @version = version+ super()+ end++ def source = { header: HEADER }++ private++ attr_reader :version+ end++ class Required < Refusal+ def title = "#{HEADER} is required"++ def detail = "Send #{HEADER}: #{version}."+ end++ class NotADate < Refusal+ def title = "#{HEADER} is not a date"++ def detail = "#{HEADER} must be written as YYYY-MM-DD."+ end++ class Unknown < Refusal+ def title = "No such version"++ def detail = "The first version is #{version}."+ end++ class InTheFuture < Refusal+ def title = "#{HEADER} is in the future"++ def detail = "The current version is #{version}."+ end++ def self.parse(raw)+ raise NotADate unless WIRE_FORMAT.match?(raw)+ new(Date.iso8601(raw))+ rescue Date::Error+ raise NotADate+ end++ attr_reader :date++ def initialize(date)+ @date = date+ end++ def <=>(other) = date <=> other.date++ def future? = date.future?++ def to_s = date.iso8601+ end+enddiff --git a/lib/json_api_kit/timeline.rb b/lib/json_api_kit/timeline.rbnew file mode 100644index 00000000000..e235fb3ae40--- /dev/null+++ b/lib/json_api_kit/timeline.rb@@ -0,0 +1,35 @@+# frozen_string_literal: true++module JsonApiKit+ class Timeline+ # The day this API was first released.+ FIRST_RELEASE = "2026-08-31"++ class << self+ delegate :first, :current, :resolve, to: :core++ private++ def core = @core ||= new([FIRST_RELEASE])+ end++ def initialize(dates)+ @versions = dates.map { ApiVersion.parse(it) }.sort+ end++ def first = versions.first++ def current = versions.last++ def resolve(raw)+ raise ApiVersion::Required.new(current) if raw.blank?+ pin = ApiVersion.parse(raw)+ raise ApiVersion::InTheFuture.new(current) if pin.future?+ versions.reverse_each.detect { it <= pin } or raise ApiVersion::Unknown.new(first)+ end++ private++ attr_reader :versions+ end+enddiff --git a/plugins/discourse-data-explorer/spec/requests/api/queries_spec.rb b/plugins/discourse-data-explorer/spec/requests/api/queries_spec.rbindex 484980bc4a4..318216baffc 100644--- a/plugins/discourse-data-explorer/spec/requests/api/queries_spec.rb+++ b/plugins/discourse-data-explorer/spec/requests/api/queries_spec.rb@@ -43,11 +43,12 @@ RSpec.describe "JSON:API queries", type: :request dolet(:query_parameters) { {} }let(:user) { admin }let(:parsed_body) { JSON.parse(response.body) }+ let(:headers) { { "HTTP_API_VERSION" => JsonApiKit::Timeline.current.to_s } }before doSiteSetting.data_explorer_enabled = truesign_in(user)- get path, params: query_parameters+ get path, headers:, params: query_parametersendshared_examples "a request only for admins" dodiff --git a/spec/integration/json_api_kit/endpoint_spec.rb b/spec/integration/json_api_kit/endpoint_spec.rbindex 1fa1031a3d1..8b76b5b6964 100644--- a/spec/integration/json_api_kit/endpoint_spec.rb+++ b/spec/integration/json_api_kit/endpoint_spec.rb@@ -32,6 +32,7 @@ RSpec.describe "a JSON:API endpoint", type: :request dolet(:profile_media_type) { JsonApiKit::Pagination::Profile::MEDIA_TYPE }let(:profile) { "https://jsonapi.org/profiles/ethanresnick/cursor-pagination" }let(:path) { "/api/topics" }+ let(:version) { JsonApiKit::Timeline.current.to_s }let(:headers) { {} }let(:parsed_body) { JSON.parse(response.body) }let(:error) { parsed_body["errors"].sole }@@ -48,7 +49,7 @@ RSpec.describe "a JSON:API endpoint", type: :request doget "/api/forbidden" => "json_api_kit_spec/failing#forbidden"endRails.application.routes.disable_clear_and_finalize = false- get path, headers:, params: query+ get path, headers: { "HTTP_API_VERSION" => version, **headers }, params: queryendafter { Rails.application.reload_routes! }@@ -77,7 +78,7 @@ RSpec.describe "a JSON:API endpoint", type: :request doit "reports a missing declaration" doexpect(Discourse).to have_received(:warn_exception) do |error, _|- expect(error).to be_a(JsonApiKit::BaseController::MissingDeclaration)+ expect(error).to be_a(JsonApiKit::BaseController::Serving::MissingDeclaration)expect(error.message).to match(/declare the resource it serves/)endend@@ -144,7 +145,7 @@ RSpec.describe "a JSON:API endpoint", type: :request dolet(:next_link) { URI.parse(parsed_body.dig("links", "next")) }it "sends the rows after the window when a client follows the next link" do- get "#{next_link.path}?#{next_link.query}"+ get "#{next_link.path}?#{next_link.query}", headers: { "HTTP_API_VERSION" => version }expect(JSON.parse(response.body)["data"].map { it["id"] }).to eq([newest.id.to_s])enddiff --git a/spec/integration/json_api_kit/support.rb b/spec/integration/json_api_kit/support.rbindex 6b8944126a8..927740848e1 100644--- a/spec/integration/json_api_kit/support.rb+++ b/spec/integration/json_api_kit/support.rb@@ -176,8 +176,9 @@ RSpec.shared_context "with a listing of topics" dorelationship_object(type, row, name, data:).deep_merge(links: { prev: nil, next: next_page })end- def refusal(title:, detail:, parameter: nil, status: "400", **members)- { status:, title:, detail:, source: parameter && { parameter: }, **members }.compact+ def refusal(title:, detail:, parameter: nil, header: nil, status: "400", **members)+ source = { parameter:, header: }.compact.presence+ { status:, title:, detail:, source:, **members }.compactenddef not_found = refusal(status: "404", title: "No such record", detail: "No record has this ID.")diff --git a/spec/integration/json_api_kit/versions_spec.rb b/spec/integration/json_api_kit/versions_spec.rbnew file mode 100644index 00000000000..2cefcf8235d--- /dev/null+++ b/spec/integration/json_api_kit/versions_spec.rb@@ -0,0 +1,116 @@+# frozen_string_literal: true++require_relative "support"++module JsonApiKitSpec+ class VersionedTopicsController < JsonApiKit::BaseController+ resource :topics+ end+end++RSpec.describe "JSON:API versioning", type: :request do+ include_context "with a listing of topics"++ let(:first_version) { JsonApiKit::Timeline.first.to_s }+ let(:first_date) { Date.parse(first_version) }+ let(:version) { first_version }+ let(:headers) { { "HTTP_API_VERSION" => version } }+ let(:parsed_body) { JSON.parse(response.body) }+ let(:error) { parsed_body["errors"].sole }++ before do+ freeze_time(first_date + 1.year)+ Rails.application.routes.disable_clear_and_finalize = true+ Rails.application.routes.draw do+ get "/api/versioned-topics" => "json_api_kit_spec/versioned_topics#index"+ end+ Rails.application.routes.disable_clear_and_finalize = false+ get "/api/versioned-topics", headers:+ end++ after { Rails.application.reload_routes! }++ it { expect(response).to have_http_status(:ok) }++ it "sends the version it resolved" do+ expect(response.headers["Api-Version"]).to eq(first_version)+ end++ context "when the version is later than the first one" do+ let(:version) { (first_date + 1.day).to_s }++ it { expect(response).to have_http_status(:ok) }++ it "sends the newest version at or before it" do+ expect(response.headers["Api-Version"]).to eq(first_version)+ end+ end++ context "when the version is earlier than the first one" do+ let(:version) { (first_date - 1.day).to_s }++ it { expect(response).to have_http_status(:bad_request) }++ it "sends the reason" do+ expect(error).to eq(+ refusal(+ title: "No such version",+ detail: "The first version is #{first_version}.",+ header: "Api-Version",+ ).deep_stringify_keys,+ )+ end+ end++ context "when the version is in the future" do+ let(:version) { (Time.zone.today + 1.day).to_s }++ it { expect(response).to have_http_status(:bad_request) }++ it "sends the reason" do+ expect(error).to eq(+ refusal(+ title: "Api-Version is in the future",+ detail: "The current version is #{first_version}.",+ header: "Api-Version",+ ).deep_stringify_keys,+ )+ end+ end++ context "when the version is not a date" do+ let(:version) { "yesterday" }++ it { expect(response).to have_http_status(:bad_request) }++ it "sends the reason" do+ expect(error).to eq(+ refusal(+ title: "Api-Version is not a date",+ detail: "Api-Version must be written as YYYY-MM-DD.",+ header: "Api-Version",+ ).deep_stringify_keys,+ )+ end+ end++ context "when the version header is missing" do+ let(:headers) { {} }++ it { expect(response).to have_http_status(:bad_request) }++ it "sends the reason" do+ expect(error).to eq(+ refusal(+ title: "Api-Version is required",+ detail: "Send Api-Version: #{first_version}.",+ header: "Api-Version",+ ).deep_stringify_keys,+ )+ end++ it "sends no version" do+ expect(response.headers).not_to have_key("Api-Version")+ end+ end+enddiff --git a/spec/lib/json_api_kit/api_version_spec.rb b/spec/lib/json_api_kit/api_version_spec.rbnew file mode 100644index 00000000000..fddd4a09243--- /dev/null+++ b/spec/lib/json_api_kit/api_version_spec.rb@@ -0,0 +1,87 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::ApiVersion do+ subject(:version) { described_class.parse(raw) }++ let(:raw) { "2026-09-01" }++ before { freeze_time(Date.new(2027, 1, 20)) }++ describe ".parse" do+ it "returns the version with that date" do+ expect(version.date).to eq(Date.new(2026, 9, 1))+ end++ context "when the date has no day" do+ let(:raw) { "2026-09" }++ it { expect { version }.to raise_error(described_class::NotADate) }+ end++ context "when the date has no separators" do+ let(:raw) { "20260901" }++ it { expect { version }.to raise_error(described_class::NotADate) }+ end++ context "when the date has a time" do+ let(:raw) { "2026-09-01T00:00:00Z" }++ it { expect { version }.to raise_error(described_class::NotADate) }+ end++ context "when the date is not a real date" do+ let(:raw) { "2026-02-30" }++ it { expect { version }.to raise_error(described_class::NotADate) }+ end++ context "when there is no date" do+ let(:raw) { nil }++ it { expect { version }.to raise_error(described_class::NotADate) }+ end+ end++ describe "#<=>" do+ context "when the other version is later" do+ let(:other) { described_class.parse("2026-11-15") }++ it "sorts before it" do+ expect(version).to be < other+ end+ end++ context "when the other version has the same date" do+ let(:other) { described_class.parse(raw) }++ it "equals it" do+ expect(version).to eq(other)+ end+ end+ end++ describe "#future?" do+ context "when the date is earlier than today" do+ it { is_expected.not_to be_future }+ end++ context "when the date is today" do+ let(:raw) { Time.zone.today.to_s }++ it { is_expected.not_to be_future }+ end++ context "when the date is later than today" do+ let(:raw) { (Time.zone.today + 1.day).to_s }++ it { is_expected.to be_future }+ end+ end++ describe "#to_s" do+ it "returns the date as YYYY-MM-DD" do+ expect(version.to_s).to eq(raw)+ end+ end+enddiff --git a/spec/lib/json_api_kit/timeline_spec.rb b/spec/lib/json_api_kit/timeline_spec.rbnew file mode 100644index 00000000000..d2dcdf59f33--- /dev/null+++ b/spec/lib/json_api_kit/timeline_spec.rb@@ -0,0 +1,77 @@+# frozen_string_literal: true++RSpec.describe JsonApiKit::Timeline do+ let(:earliest) { JsonApiKit::ApiVersion.parse("2026-09-01") }+ let(:middle) { JsonApiKit::ApiVersion.parse("2026-11-15") }+ let(:latest) { JsonApiKit::ApiVersion.parse("2027-01-05") }+ let(:timeline) { described_class.new([earliest, middle, latest].map(&:to_s)) }++ before do+ freeze_time(Date.new(2027, 1, 20))+ allow(described_class).to receive(:core).and_return(timeline)+ end++ describe ".first" do+ it "returns the earliest version" do+ expect(described_class.first).to eq(earliest)+ end+ end++ describe ".current" do+ it "returns the latest version" do+ expect(described_class.current).to eq(latest)+ end+ end++ describe ".resolve" do+ subject(:version) { described_class.resolve(raw) }++ let(:raw) { middle.to_s }++ context "when the date is a published version" do+ it "returns that version" do+ expect(version).to eq(middle)+ end+ end++ context "when the date falls between two versions" do+ let(:raw) { "2026-12-01" }++ it "returns the newest version before it" do+ expect(version).to eq(middle)+ end+ end++ context "when the date is later than every version but not in the future" do+ let(:raw) { "2027-01-10" }++ it "returns the latest version" do+ expect(version).to eq(latest)+ end+ end++ context "when there is no date" do+ let(:raw) { nil }++ it { expect { version }.to raise_error(JsonApiKit::ApiVersion::Required) }+ end++ context "when the date is earlier than the first version" do+ let(:raw) { (earliest.date - 1.day).to_s }++ it { expect { version }.to raise_error(JsonApiKit::ApiVersion::Unknown) }+ end++ context "when the date is in the future" do+ let(:raw) { (Time.zone.today + 1.day).to_s }++ it { expect { version }.to raise_error(JsonApiKit::ApiVersion::InTheFuture) }+ end++ context "when the date is invalid" do+ let(:raw) { "yesterday" }++ it { expect { version }.to raise_error(JsonApiKit::ApiVersion::NotADate) }+ end+ end+end