Skip to content

Raise an error when JWK::Set::Fetcher fetches something that's not a JWKS #125

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion lib/json/jwk/set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,4 @@ def as_json(options = {})
end
end
end
end
end
18 changes: 11 additions & 7 deletions lib/json/jwk/set/fetcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ module JSON
class JWK
class Set
module Fetcher
class MalformedJWKSet < JWT::Exception; end

class Cache
def fetch(cache_key, options = {})
yield
Expand Down Expand Up @@ -65,13 +67,15 @@ def self.fetch(jwks_uri, kid:, auto_detect: true, **options)
kid
].collect(&:to_s).join(':')

jwks = Set.new(
JSON.parse(
cache.fetch(cache_key, options) do
http_client.get(jwks_uri).body
end
)
parsed_jwks = JSON.parse(
cache.fetch(cache_key, options) do
http_client.get(jwks_uri).body
end
)

raise MalformedJWKSet, "Malformed JWK Set: #{parsed_jwks.inspect}" unless parsed_jwks.is_a?(Hash) && parsed_jwks['keys'].is_a?(Array)

jwks = Set.new(parsed_jwks)
cache.delete(cache_key, options) if jwks[kid].blank?

if auto_detect
Expand All @@ -83,4 +87,4 @@ def self.fetch(jwks_uri, kid:, auto_detect: true, **options)
end
end
end
end
end
13 changes: 12 additions & 1 deletion spec/json/jwk/set/fetcher_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
describe JSON::JWK::Set::Fetcher::Cache do
let(:something) { SecureRandom.hex(32) }

it 'just execute givne block' do
it 'just execute given block' do
expect(
subject.fetch('cache_key') do
something
Expand Down Expand Up @@ -111,6 +111,17 @@ def delete(cache_key)
end.to request_to jwks_uri
end

context "when the JWKS uri returns a structure that's not a valid JWK Set" do
it "raises a JSON::JWK::Set::Fetcher::MalformedJWKSet error" do
stub_request(:get, jwks_uri).to_return(
status: 200,
body: '"hello there"' # Note that this is valid JSON, but not a valid JWK Set
)

expect { subject }.to raise_error(JSON::JWK::Set::Fetcher::MalformedJWKSet)
end
end

context 'when unknown' do
let(:kid) { 'unknown' }
let(:cache_key) do
Expand Down