From 0f6678ec5e36d87930dae1ecf3dce28e3e336d11 Mon Sep 17 00:00:00 2001 From: "Daniel (dB.) Doubrovkine" Date: Sun, 22 Nov 2026 09:01:44 -0500 Subject: [PATCH] Honor the Allow header Remember the Allow header of a link's most recent response, including 405 responses, and expose it with Link#_allow, Link#_allow?, Resource#_allow and Resource#_allow?. Add an opt-in EntryPoint#enforce_allowed_methods setting that raises Hyperclient::MethodNotAllowedError before sending a method the link's most recent Allow header doesn't list. It defaults to off, so existing clients keep sending every request and receiving the server's 405. Closes #4. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011Gr21htyJfr8XZGHBcPwkW --- CHANGELOG.md | 1 + README.md | 34 +++++ lib/hyperclient/entry_point.rb | 14 ++ lib/hyperclient/link.rb | 76 +++++++++- lib/hyperclient/resource.rb | 15 ++ test/hyperclient/entry_point_test.rb | 14 ++ test/hyperclient/link_test.rb | 203 +++++++++++++++++++++++++++ test/hyperclient/resource_test.rb | 31 ++++ 8 files changed, 387 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ea0959..d9e4427 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ * [#337](https://github.com/codegram/hyperclient/pull/337): Updated danger-pr-comment to 0.3.0 and stopped posting empty Danger reports - [@dblock](https://github.com/dblock). * [#338](https://github.com/codegram/hyperclient/pull/338): Documented link properties, including HAL `profile` via `Link#_profile` - [@dblock](https://github.com/dblock). * [#339](https://github.com/codegram/hyperclient/pull/339): Sped up CI by running JRuby with `--dev`, separating JSON 2 and JSON 3 bundler caches, skipping duplicate branch builds, and updating `actions/checkout` to v7 - [@dblock](https://github.com/dblock). +* [#340](https://github.com/codegram/hyperclient/pull/340): Added `Link#_allow`, `Link#_allow?`, `Resource#_allow` and `Resource#_allow?` to read the `Allow` header, and an opt-in `enforce_allowed_methods` setting that raises `Hyperclient::MethodNotAllowedError` instead of sending a method the link's most recent response disallowed - [@dblock](https://github.com/dblock). * Your contribution here. ### 2.1.0 (2026/10/14) diff --git a/README.md b/README.md index f360510..d7e745d 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ Hyperclient is a Hypermedia API client written in Ruby. It fully supports [JSON - [Curies](#curies) - [Attributes](#attributes) - [HTTP](#http) + - [Allowed Methods](#allowed-methods) - [Testing Using Hyperclient](#testing-using-hyperclient) - [Reference](#reference) - [Hyperclient Users](#hyperclient-users) @@ -244,6 +245,39 @@ place._delete HTTP methods always return a new instance of Resource. +## Allowed Methods + +Hyperclient remembers the `Allow` header of the most recent response on the link that made the request, including a `405 Method Not Allowed` response, whose `Allow` header lists the methods the server supports. Each response replaces what the link knows. Use `_allow` and `_allow?` to check before sending a request. + +```ruby +order = api.order(id: 1) # a server responding with "Allow: GET, HEAD, OPTIONS" +order._get +order._allow # => ["GET", "HEAD", "OPTIONS"], or nil without an Allow header +order._allow?(:delete) # => false +``` + +By default, Hyperclient still sends any method and leaves it to the server to refuse it. Set `enforce_allowed_methods` to have links refuse to send a method that their most recent `Allow` header doesn't list, raising `Hyperclient::MethodNotAllowedError` without contacting the server. A response without an `Allow` header lifts the restriction, and `_options` is always sent so you can rediscover the allowed methods. + +```ruby +api = Hyperclient.new('http://127.0.0.1:9292/') do |client| + client.enforce_allowed_methods = true +end + +order = api.order(id: 1) # a server responding with "Allow: GET, HEAD, OPTIONS" +order._get + +begin + order._delete +rescue Hyperclient::MethodNotAllowedError => e + e.message # => "DELETE is not allowed on /orders/1, the server allows only GET, HEAD, OPTIONS." + e.allowed # => ["GET", "HEAD", "OPTIONS"] +end +``` + +Methods are compared case-insensitively, an empty `Allow` header means no methods are allowed, and `HEAD` is only allowed when listed. A resource also exposes the `Allow` header of the response that created it with `_allow` and `_allow?`. Hyperclient never sends extra `OPTIONS` requests. + +There is no method to clear or override what a link remembers. With `enforce_allowed_methods` on, the remembered `Allow` header is replaced by the link's next response, so call `_options` to ask the server again. Alternatively, use a new link object, which starts without restrictions, such as `link._expand` or a link from a freshly fetched resource. + # Testing Using Hyperclient You can combine RSpec, Faraday::Adapter::Rack and Hyperclient to test your HAL API without having to ever examine the raw JSON response. diff --git a/lib/hyperclient/entry_point.rb b/lib/hyperclient/entry_point.rb index f9ce119..8bd18b8 100644 --- a/lib/hyperclient/entry_point.rb +++ b/lib/hyperclient/entry_point.rb @@ -42,6 +42,7 @@ def initialize(url, &_block) @resource = nil @key = nil @uri_variables = nil + @enforce_allowed_methods = false yield self if block_given? end @@ -124,6 +125,19 @@ def faraday_block=(value) # value - A Hash containing the client options. attr_accessor :options + # Public: Set whether links refuse to send a method that the Allow header + # of their most recent response doesn't list, raising + # MethodNotAllowedError instead. Defaults to false. + attr_writer :enforce_allowed_methods + + # Public: Indicates if links enforce the methods allowed by the Allow + # header. + # + # Returns true if enabled, false otherwise. + def enforce_allowed_methods? + @enforce_allowed_methods == true + end + private # Internal: Returns a block to initialize the Faraday connection. The diff --git a/lib/hyperclient/link.rb b/lib/hyperclient/link.rb index 1952b02..0f3afdd 100644 --- a/lib/hyperclient/link.rb +++ b/lib/hyperclient/link.rb @@ -10,6 +10,29 @@ def initialize(key, url) end end + # Public: Exception that is raised before sending a request with a method + # that the most recent response for the same Link excluded from its Allow + # header. + class MethodNotAllowedError < StandardError + # Public: Returns the upper-case String HTTP method that was refused. + attr_reader :http_method + + # Public: Returns the String url of the Link. + attr_reader :url + + # Public: Returns the Array of upper-case String methods that the server + # allows. + attr_reader :allowed + + def initialize(http_method, url, allowed) + @http_method = http_method + @url = url + @allowed = allowed + allows = allowed.empty? ? 'no methods' : "only #{allowed.join(', ')}" + super("#{http_method} is not allowed on #{url}, the server allows #{allows}.") + end + end + # Internal: The Link is used to let a Resource interact with the API. # class Link @@ -31,6 +54,20 @@ def initialize(key, link, entry_point, uri_variables = nil, query_params = nil) @uri_variables = uri_variables @query_params = query_params @resource = nil + @allow = nil + end + + # Internal: Parses the Allow header from response headers. + # + # headers - The Hash-like response headers, or nil. + # + # Returns nil when there is no Allow header, otherwise an Array of + # upper-case String methods, which is empty when the header is empty. + def self.parse_allow(headers) + value = headers && (headers['Allow'] || headers['allow']) + return if value.nil? + + Array(value).join(',').split(',').map { |m| m.strip.upcase }.reject(&:empty?).uniq end # Public: Each implementation to allow the class to use the Enumerable @@ -123,6 +160,25 @@ def _hreflang @link['hreflang'] end + # Public: Returns the methods listed in the Allow header of the most + # recent response for this Link, as upper-case Strings. + # + # Returns nil if no response has been received yet or the most recent + # response did not carry an Allow header. + def _allow + @allow&.dup + end + + # Public: Indicates if the server allows the given method on this Link, + # according to the Allow header of the most recent response. + # + # method - A Symbol or String HTTP method, case-insensitive. + # + # Returns true if the method is allowed or no Allow header was received. + def _allow?(method) + @allow.nil? || @allow.include?(method.to_s.upcase) + end + def _resource @resource || _get end @@ -231,8 +287,26 @@ def _add_query_params(url) uri.to_s end + # Internal: Raises MethodNotAllowedError if the most recent response for + # this Link excluded the method from its Allow header. OPTIONS is always + # sent, so that callers can rediscover the allowed methods. + def ensure_allowed!(method) + return if method == :options || _allow?(method) || !@entry_point.enforce_allowed_methods? + + raise MethodNotAllowedError.new(method.to_s.upcase, _url, @allow.dup) + end + def http_method(method, body = nil) - response = @entry_point.connection.run_request(method, _url, body, nil) + ensure_allowed!(method) + + begin + response = @entry_point.connection.run_request(method, _url, body, nil) + rescue Faraday::Error => e + @allow = Link.parse_allow(e.response_headers) if e.response + raise + end + + @allow = Link.parse_allow(response.headers) resource = Resource.new(response.body, @entry_point, response) # Only cache GET responses. Caching the response of a mutating diff --git a/lib/hyperclient/resource.rb b/lib/hyperclient/resource.rb index c11cee9..f6de2f3 100644 --- a/lib/hyperclient/resource.rb +++ b/lib/hyperclient/resource.rb @@ -62,6 +62,21 @@ def _status _response&.status end + # Public: Returns the methods listed in the Allow header of the response + # that created this resource, as upper-case Strings, or nil if there is no + # response or it did not carry an Allow header. + def _allow + Link.parse_allow(_response&.headers) + end + + # Public: Indicates if the response that created this resource allows the + # given Symbol or String HTTP method, case-insensitive. Returns true if + # there is no Allow header. + def _allow?(method) + allow = _allow + allow.nil? || allow.include?(method.to_s.upcase) + end + def [](name) send(name) if respond_to?(name) end diff --git a/test/hyperclient/entry_point_test.rb b/test/hyperclient/entry_point_test.rb index e36a788..bbd4fe4 100644 --- a/test/hyperclient/entry_point_test.rb +++ b/test/hyperclient/entry_point_test.rb @@ -123,6 +123,20 @@ module Hyperclient end end + describe 'enforce_allowed_methods' do + it 'is disabled by default' do + _(EntryPoint.new('http://my.api.org').enforce_allowed_methods?).must_equal false + end + + it 'can be enabled in the block' do + entry_point = EntryPoint.new('http://my.api.org') do |client| + client.enforce_allowed_methods = true + end + + _(entry_point.enforce_allowed_methods?).must_equal true + end + end + describe 'custom' do let(:entry_point) do EntryPoint.new 'http://my.api.org' do |entry_point| diff --git a/test/hyperclient/link_test.rb b/test/hyperclient/link_test.rb index 97f2871..afecbeb 100644 --- a/test/hyperclient/link_test.rb +++ b/test/hyperclient/link_test.rb @@ -377,6 +377,209 @@ module Hyperclient end end + describe 'Allow header' do + let(:link) { Link.new('key', { 'href' => '/productions/1' }, entry_point) } + let(:url) { 'http://api.example.org/productions/1' } + + it 'does not know the allowed methods before a request' do + _(link._allow).must_be_nil + _(link._allow?(:delete)).must_equal true + end + + it 'sends any method when the response has no Allow header' do + stub_request(entry_point.connection) do |stub| + stub.get(url) { [200, {}, nil] } + stub.delete(url) { [204, {}, nil] } + end + + link._get + + _(link._allow).must_be_nil + _(link._delete).must_be_kind_of Resource + end + + it 'parses methods case-insensitively, ignoring whitespace and empty entries' do + stub_request(entry_point.connection) do |stub| + stub.get(url) { [200, { 'allow' => ' get,head ,, Post,get ' }, nil] } + end + + link._get + + _(link._allow).must_equal %w[GET HEAD POST] + _(link._allow?(:post)).must_equal true + _(link._allow?('Head')).must_equal true + _(link._allow?(:delete)).must_equal false + end + + it 'sends a method that the Allow header does not list by default' do + stub_request(entry_point.connection) do |stub| + stub.get(url) { [200, { 'Allow' => 'GET, HEAD' }, nil] } + stub.delete(url) { [204, {}, nil] } + end + + link._get + + _(entry_point.enforce_allowed_methods?).must_equal false + _(link._allow?(:delete)).must_equal false + _(link._delete).must_be_kind_of Resource + end + + it 'repeats a request that returned 405 by default' do + requests = 0 + stub_request(entry_point.connection) do |stub| + stub.delete(url) do + requests += 1 + [405, { 'Allow' => 'GET' }, nil] + end + end + + _(-> { link._delete }).must_raise Faraday::ClientError + _(link._allow).must_equal %w[GET] + _(-> { link._delete }).must_raise Faraday::ClientError + _(requests).must_equal 2 + end + + it 'returns a copy of the allowed methods' do + stub_request(entry_point.connection) do |stub| + stub.get(url) { [200, { 'Allow' => 'GET' }, nil] } + end + + link._get + link._allow << 'DELETE' + + _(link._allow?(:delete)).must_equal false + end + + describe 'with enforce_allowed_methods' do + before do + entry_point.enforce_allowed_methods = true + end + + it 'sends an allowed method' do + stub_request(entry_point.connection) do |stub| + stub.get(url) { [200, { 'Allow' => 'GET, POST' }, nil] } + stub.post(url) { [201, {}, nil] } + end + + link._get + + _(link._post('foo' => 'bar')).must_be_kind_of Resource + end + + it 'raises MethodNotAllowedError without sending a disallowed method' do + stub_request(entry_point.connection) do |stub| + stub.get(url) { [200, { 'Allow' => 'GET, HEAD' }, nil] } + end + + link._get + error = _(-> { link._delete }).must_raise MethodNotAllowedError + + _(error.http_method).must_equal 'DELETE' + _(error.url).must_equal '/productions/1' + _(error.allowed).must_equal %w[GET HEAD] + _(error.message).must_equal 'DELETE is not allowed on /productions/1, the server allows only GET, HEAD.' + end + + it 'raises for every method when the Allow header is empty, except OPTIONS' do + stub_request(entry_point.connection) do |stub| + stub.head(url) { [200, { 'Allow' => '' }, nil] } + stub.options(url) { [200, { 'Allow' => 'GET' }, nil] } + stub.get(url) { [200, {}, nil] } + end + + link._head + + _(link._allow).must_equal [] + error = _(-> { link._get }).must_raise MethodNotAllowedError + _(error.message).must_equal 'GET is not allowed on /productions/1, the server allows no methods.' + _(-> { link._head }).must_raise MethodNotAllowedError + + link._options + + _(link._allow).must_equal %w[GET] + _(link._get).must_be_kind_of Resource + end + + it 'does not imply HEAD from GET' do + stub_request(entry_point.connection) do |stub| + stub.get(url) { [200, { 'Allow' => 'GET' }, nil] } + end + + link._get + + _(-> { link._head }).must_raise MethodNotAllowedError + end + + it 'records the Allow header of a 405 response and refuses to repeat the request' do + requests = 0 + stub_request(entry_point.connection) do |stub| + stub.delete(url) do + requests += 1 + [405, { 'Allow' => 'GET, PUT' }, nil] + end + stub.put(url) { [200, {}, nil] } + end + + _(-> { link._delete }).must_raise Faraday::ClientError + _(link._allow).must_equal %w[GET PUT] + _(-> { link._delete }).must_raise MethodNotAllowedError + _(requests).must_equal 1 + _(link._put('foo' => 'bar')).must_be_kind_of Resource + end + + it 'records the Allow header of a 405 response when errors are not raised' do + entry_point.connection(default: false) do |conn| + conn.adapter :test do |stub| + stub.post(url) { [405, { 'Allow' => 'GET' }, nil] } + end + end + + _(link._post._status).must_equal 405 + _(-> { link._post }).must_raise MethodNotAllowedError + end + + it 'uses the most recent response' do + stub_request(entry_point.connection) do |stub| + stub.get(url) { [200, { 'Allow' => 'GET, PATCH' }, nil] } + stub.patch(url) { [200, {}, nil] } + stub.delete(url) { [204, {}, nil] } + end + + link._get + + _(-> { link._delete }).must_raise MethodNotAllowedError + link._patch('foo' => 'bar') + + _(link._allow).must_be_nil + _(link._delete).must_be_kind_of Resource + end + + it 'keeps the allowed methods per link' do + stub_request(entry_point.connection) do |stub| + stub.get(url) { [200, { 'Allow' => 'GET' }, nil] } + stub.delete(url) { [204, {}, nil] } + end + + link._get + + _(Link.new('key', { 'href' => '/productions/1' }, entry_point)._delete).must_be_kind_of Resource + end + + it 'starts an expanded link without restrictions' do + stub_request(entry_point.connection) do |stub| + stub.get(url) { [200, { 'Allow' => 'GET' }, nil] } + stub.delete(url) { [204, {}, nil] } + end + + link._get + + _(-> { link._delete }).must_raise MethodNotAllowedError + _(link._expand._allow).must_be_nil + _(link._expand._delete).must_be_kind_of Resource + end + end + end + describe 'inspect' do it 'outputs a custom-friendly output' do link = Link.new('key', { 'href' => '/productions/1' }, 'foo') diff --git a/test/hyperclient/resource_test.rb b/test/hyperclient/resource_test.rb index e39706b..058bb3d 100644 --- a/test/hyperclient/resource_test.rb +++ b/test/hyperclient/resource_test.rb @@ -229,6 +229,37 @@ module Hyperclient end end + describe '._allow' do + it 'returns nil without a response object' do + resource = Resource.new({}, entry_point) + + _(resource._allow).must_be_nil + _(resource._allow?(:delete)).must_equal true + end + + it 'returns nil without an Allow header' do + resource = Resource.new({}, entry_point, stub(headers: {})) + + _(resource._allow).must_be_nil + _(resource._allow?(:delete)).must_equal true + end + + it 'returns the allowed methods' do + resource = Resource.new({}, entry_point, stub(headers: Faraday::Utils::Headers.new('allow' => 'get, Head'))) + + _(resource._allow).must_equal %w[GET HEAD] + _(resource._allow?(:head)).must_equal true + _(resource._allow?('DELETE')).must_equal false + end + + it 'returns an empty list for an empty Allow header' do + resource = Resource.new({}, entry_point, stub(headers: { 'Allow' => ' ' })) + + _(resource._allow).must_equal [] + _(resource._allow?(:get)).must_equal false + end + end + describe 'inspect' do it 'outputs a custom-friendly output' do resource = Resource.new({ '_links' => { 'self' => { 'href' => '/orders/523' } }, 'title' => 'Order' },