diff --git a/CHANGELOG.md b/CHANGELOG.md index b84f1c46..fc29a1d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ **Fixes and enhancements:** - Fix signature has expired error if payload is a string [#555](https://github.com/jwt/ruby-jwt/pull/555) - [@GobinathAL](https://github.com/GobinathAL). +- Fix key base equality and spaceship operators [#569](https://github.com/jwt/ruby-jwt/pull/569) - [@magneland](https://github.com/magneland). - Your contribution here ## [v2.7.1](https://github.com/jwt/ruby-jwt/tree/v2.8.0) (2023-06-09) diff --git a/lib/jwt/jwk/key_base.rb b/lib/jwt/jwk/key_base.rb index 6f0df55a..2c80d760 100644 --- a/lib/jwt/jwk/key_base.rb +++ b/lib/jwt/jwk/key_base.rb @@ -38,12 +38,14 @@ def []=(key, value) end def ==(other) - self[:kid] == other[:kid] + other.is_a?(::JWT::JWK::KeyBase) && self[:kid] == other[:kid] end alias eql? == def <=>(other) + return nil unless other.is_a?(::JWT::JWK::KeyBase) + self[:kid] <=> other[:kid] end diff --git a/spec/jwk/hmac_spec.rb b/spec/jwk/hmac_spec.rb index dcc7d4ce..a31b5498 100644 --- a/spec/jwk/hmac_spec.rb +++ b/spec/jwk/hmac_spec.rb @@ -82,4 +82,68 @@ end end end + + describe '#==' do + it 'is equal to itself' do + other = jwk + expect(jwk == other).to eq true + end + + it 'is equal to a clone of itself' do + other = jwk.clone + expect(jwk == other).to eq true + end + + it 'is not equal to nil' do + other = nil + expect(jwk == other).to eq false + end + + it 'is not equal to boolean true' do + other = true + expect(jwk == other).to eq false + end + + it 'is not equal to a non-key' do + other = Object.new + expect(jwk == other).to eq false + end + + it 'is not equal to a different key' do + other = described_class.new('other-key') + expect(jwk == other).to eq false + end + end + + describe '#<=>' do + it 'is equal to itself' do + other = jwk + expect(jwk <=> other).to eq 0 + end + + it 'is equal to a clone of itself' do + other = jwk.clone + expect(jwk <=> other).to eq 0 + end + + it 'is not comparable to nil' do + other = nil + expect(jwk <=> other).to eq nil + end + + it 'is not comparable to boolean true' do + other = true + expect(jwk <=> other).to eq nil + end + + it 'is not comparable to a non-key' do + other = Object.new + expect(jwk <=> other).to eq nil + end + + it 'is not equal to a different key' do + other = described_class.new('other-key') + expect(jwk <=> other).not_to eq 0 + end + end end