Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand Down
14 changes: 14 additions & 0 deletions lib/hyperclient/entry_point.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
76 changes: 75 additions & 1 deletion lib/hyperclient/link.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions lib/hyperclient/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions test/hyperclient/entry_point_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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|
Expand Down
Loading
Loading