pax_global_header00006660000000000000000000000064144406762210014520gustar00rootroot0000000000000052 comment=781fbd19b92b84a1f55c7ec7c0e069f870a5fb36 ruby-jwt-2.7.1/000077500000000000000000000000001444067622100133125ustar00rootroot00000000000000ruby-jwt-2.7.1/.codeclimate.yml000066400000000000000000000001751444067622100163670ustar00rootroot00000000000000plugins: fixme: enabled: true shellcheck: enabled: true rubocop: enabled: true channel: rubocop-1-31-0 ruby-jwt-2.7.1/.github/000077500000000000000000000000001444067622100146525ustar00rootroot00000000000000ruby-jwt-2.7.1/.github/workflows/000077500000000000000000000000001444067622100167075ustar00rootroot00000000000000ruby-jwt-2.7.1/.github/workflows/test.yml000066400000000000000000000057531444067622100204230ustar00rootroot00000000000000--- name: test on: push: branches: - "*" pull_request: branches: - "*" jobs: lint: name: RuboCop timeout-minutes: 30 runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: "3.1" bundler-cache: true - name: Run RuboCop run: bundle exec rubocop test: name: ${{ matrix.os }} - Ruby ${{ matrix.ruby }} - ${{ matrix.gemfile }} runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: - ubuntu-20.04 ruby: - "2.5" - "2.6" - "2.7" - "3.0" - "3.1" - "3.2" gemfile: - gemfiles/standalone.gemfile - gemfiles/openssl.gemfile - gemfiles/rbnacl.gemfile - gemfiles/rbnacl-pre-6.gemfile experimental: [false] include: - os: ubuntu-22.04 ruby: "3.1" gemfile: 'gemfiles/standalone.gemfile' experimental: false - os: ubuntu-20.04 ruby: "truffleruby-head" gemfile: 'gemfiles/standalone.gemfile' experimental: true - os: ubuntu-22.04 ruby: "head" gemfile: 'gemfiles/standalone.gemfile' experimental: true continue-on-error: ${{ matrix.experimental }} env: BUNDLE_GEMFILE: ${{ matrix.gemfile }} steps: - uses: actions/checkout@v3 - name: Install libsodium run: | sudo apt-get update -q sudo apt-get install libsodium-dev -y - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby }} bundler-cache: true - name: Run tests run: bundle exec rspec - name: Upload test coverage folder for later reporting uses: actions/upload-artifact@v3 with: name: coverage-reports path: ${{github.workspace}}/coverage-*/coverage.json retention-days: 1 coverage: name: Report coverage to Code Climate runs-on: ubuntu-20.04 needs: test if: success() && github.ref == 'refs/heads/main' env: CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }} steps: - uses: actions/checkout@v3 - name: Download coverage reports from the test job uses: actions/download-artifact@v3 with: name: coverage-reports - uses: paambaati/codeclimate-action@v3.2.0 with: coverageLocations: "coverage-*/coverage.json:simplecov" smoke: name: Built GEM smoke test timeout-minutes: 30 runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: "3.1" - name: Build GEM run: gem build - name: Install built GEM run: gem install jwt-*.gem - name: Run test run: bin/smoke.rb ruby-jwt-2.7.1/.gitignore000066400000000000000000000002121444067622100152750ustar00rootroot00000000000000.idea/ jwt.gemspec pkg Gemfile.lock coverage/ .DS_Store .rbenv-gemsets .ruby-version .vscode/ .bundle *gemfile.lock .byebug_history *.gem ruby-jwt-2.7.1/.rspec000066400000000000000000000000361444067622100144260ustar00rootroot00000000000000--require spec_helper --color ruby-jwt-2.7.1/.rubocop.yml000066400000000000000000000017011444067622100155630ustar00rootroot00000000000000AllCops: TargetRubyVersion: 2.5 NewCops: enable SuggestExtensions: false Exclude: - 'gemfiles/*.gemfile' - 'vendor/**/*' Style/Documentation: Enabled: false Style/BlockDelimiters: Exclude: - spec/**/*_spec.rb Style/GuardClause: Enabled: false Style/IfUnlessModifier: Enabled: false Style/Lambda: Enabled: false Style/RaiseArgs: Enabled: false Metrics/AbcSize: Max: 25 Metrics/ClassLength: Max: 121 Metrics/ModuleLength: Max: 100 Metrics/MethodLength: Max: 20 Metrics/BlockLength: Exclude: - spec/**/*_spec.rb - '*.gemspec' Layout/LineLength: Enabled: false Layout/EndAlignment: EnforcedStyleAlignWith: variable Layout/EmptyLineBetweenDefs: Enabled: true AllowAdjacentOneLineDefs: true Style/FormatString: Enabled: false Layout/MultilineMethodCallIndentation: EnforcedStyle: indented Layout/MultilineOperationIndentation: EnforcedStyle: indented Style/WordArray: Enabled: false ruby-jwt-2.7.1/.simplecov000066400000000000000000000007371444067622100153230ustar00rootroot00000000000000# frozen_string_literal: true require 'openssl' require 'simplecov_json_formatter' SimpleCov.start do command_name "Job #{File.basename(ENV['BUNDLE_GEMFILE'])}" if ENV['BUNDLE_GEMFILE'] project_name 'Ruby JWT - Ruby JSON Web Token implementation' coverage_dir "coverage-#{::OpenSSL::Digest::SHA256.hexdigest(ENV['GITHUB_STEP_SUMMARY'])}" if ENV['GITHUB_STEP_SUMMARY'] add_filter 'spec' end if ENV['CI'] SimpleCov.formatters = SimpleCov::Formatter::JSONFormatter end ruby-jwt-2.7.1/AUTHORS000066400000000000000000000030721444067622100143640ustar00rootroot00000000000000Tim Rudat Joakim Antman Jeff Lindsay A.B shields Bob Aman Emilio Cristalli Egon Zemmer Zane Shannon Nikita Shatov Paul Battley Oliver blackanger Ville Lautanala Tyler Pickett James Stonehill Adam Michael Martin Emde Saverio Trioni Peter M. Goldstein Korstiaan de Ridder Richard Larocque Andrew Davis Yason Khaburzaniya Klaas Jan Wierenga Nick Hammond Bart de Water Steve Sloan Antonis Berkakis Bill Mill Kevin Olbrich Simon Fish jb08 lukas Rodrigo López Dato ojab Ritikesh sawyerzhang Larry Lv smudge wohlgejm Tom Wey yann ARMAND Brian Flethcer Jurriaan Pruis Erik Michaels-Ober Matthew Simpson Steven Davidovitz Nicolas Leger Pierre Michard RahulBajaj Rob Wygand Ryan Brushett Ryan McIlmoyl Ryan Metzler Severin Schoepke Shaun Guth Steve Teti T.J. Schuck Taiki Sugawara Takehiro Adachi Tobias Haar Toby Pinder Tomé Duarte Travis Hunter Yuji Yaginuma Zuzanna Stolińska aarongray danielgrippi fusagiko/takayamaki mai fujii nycvotes-dev revodoge rono23 antonmorant Adam Greene Alexander Boyd Alexandr Kostrikov Aman Gupta Ariel Salomon Arnaud Mesureur Artsiom Kuts Austin Kabiru B Bouke van der Bijl Brandon Keepers Dan Leyden Dave Grijalva Dmitry Pashkevich Dorian Marié Ernie Miller Evgeni Golov Ewoud Kohl van Wijngaarden HoneyryderChuck Igor Victor Ilyaaaaaaaaaaaaa Zhitomirskiy Jens Hausherr Jeremiah Wuenschel John Downey Jordan Brough Josh Bodah JotaSe Juanito Fatas Julio Lopez Katelyn Kasperowicz Leonardo Saraiva Lowell Kirsh Loïc Lengrand Lucas Mazza Makoto Chiba Manuel Bustillo Marco Adkins Meredith Leu Micah Gates Michał Begejowicz Mike Eirih Mike Pastore Mingan Mitch Birti ruby-jwt-2.7.1/Appraisals000066400000000000000000000003511444067622100153330ustar00rootroot00000000000000# frozen_string_literal: true appraise 'standalone' do # No additions end appraise 'openssl' do gem 'openssl', '~> 2.1' end appraise 'rbnacl' do gem 'rbnacl', '>= 6' end appraise 'rbnacl-pre-6' do gem 'rbnacl', '< 6' end ruby-jwt-2.7.1/CHANGELOG.md000066400000000000000000001556761444067622100151470ustar00rootroot00000000000000# Changelog ## [v2.7.1](https://github.com/jwt/ruby-jwt/tree/v2.8.0) (2023-06-09) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.7.0...v2.8.0) **Fixes and enhancements:** - Handle invalid algorithm when decoding JWT [#559](https://github.com/jwt/ruby-jwt/pull/559) - [@nataliastanko](https://github.com/nataliastanko) - Do not raise error when verifying bad HMAC signature [#563](https://github.com/jwt/ruby-jwt/pull/563) - [@hieuk09](https://github.com/hieuk09) ## [v2.7.0](https://github.com/jwt/ruby-jwt/tree/v2.7.0) (2023-02-01) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.6.0...v2.7.0) **Features:** - Support OKP (Ed25519) keys for JWKs [#540](https://github.com/jwt/ruby-jwt/pull/540) ([@anakinj](https://github.com/anakinj)) - JWK Sets can now be used for tokens with nil kid [#543](https://github.com/jwt/ruby-jwt/pull/543) ([@bellebaum](https://github.com/bellebaum)) **Fixes and enhancements:** - Fix issue with multiple keys returned by keyfinder and multiple allowed algorithms [#545](https://github.com/jwt/ruby-jwt/pull/545) ([@mpospelov](https://github.com/mpospelov)) - Non-string `kid` header values are now rejected [#543](https://github.com/jwt/ruby-jwt/pull/543) ([@bellebaum](https://github.com/bellebaum)) ## [v2.6.0](https://github.com/jwt/ruby-jwt/tree/v2.6.0) (2022-12-22) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.5.0...v2.6.0) **Features:** - Support custom algorithms by passing algorithm objects[#512](https://github.com/jwt/ruby-jwt/pull/512) ([@anakinj](https://github.com/anakinj)). - Support descriptive (not key related) JWK parameters[#520](https://github.com/jwt/ruby-jwt/pull/520) ([@bellebaum](https://github.com/bellebaum)). - Support for JSON Web Key Sets[#525](https://github.com/jwt/ruby-jwt/pull/525) ([@bellebaum](https://github.com/bellebaum)). - Support HMAC keys over 32 chars when using RbNaCl[#521](https://github.com/jwt/ruby-jwt/pull/521) ([@anakinj](https://github.com/anakinj)). **Fixes and enhancements:** - Raise descriptive error on empty hmac_secret and OpenSSL 3.0/openssl gem <3.0.1 [#530](https://github.com/jwt/ruby-jwt/pull/530) ([@jonmchan](https://github.com/jonmchan)). ## [v2.5.0](https://github.com/jwt/ruby-jwt/tree/v2.5.0) (2022-08-25) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.4.1...v2.5.0) **Features:** - Support JWK thumbprints as key ids [#481](https://github.com/jwt/ruby-jwt/pull/481) ([@anakinj](https://github.com/anakinj)). - Support OpenSSL >= 3.0 [#496](https://github.com/jwt/ruby-jwt/pull/496) ([@anakinj](https://github.com/anakinj)). **Fixes and enhancements:** - Bring back the old Base64 (RFC2045) deocode mechanisms [#488](https://github.com/jwt/ruby-jwt/pull/488) ([@anakinj](https://github.com/anakinj)). - Rescue RbNaCl exception for EdDSA wrong key [#491](https://github.com/jwt/ruby-jwt/pull/491) ([@n-studio](https://github.com/n-studio)). - New parameter name for cases when kid is not found using JWK key loader proc [#501](https://github.com/jwt/ruby-jwt/pull/501) ([@anakinj](https://github.com/anakinj)). - Fix NoMethodError when a 2 segment token is missing 'alg' header [#502](https://github.com/jwt/ruby-jwt/pull/502) ([@cmrd-senya](https://github.com/cmrd-senya)). ## [v2.4.1](https://github.com/jwt/ruby-jwt/tree/v2.4.1) (2022-06-07) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.4.0...v2.4.1) **Fixes and enhancements:** - Raise JWT::DecodeError on invalid signature [\#484](https://github.com/jwt/ruby-jwt/pull/484) ([@freakyfelt!](https://github.com/freakyfelt!)). ## [v2.4.0](https://github.com/jwt/ruby-jwt/tree/v2.4.0) (2022-06-06) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.3.0...v2.4.0) **Features:** - Dropped support for Ruby 2.5 and older [#453](https://github.com/jwt/ruby-jwt/pull/453) - [@anakinj](https://github.com/anakinj). - Use Ruby built-in url-safe base64 methods [#454](https://github.com/jwt/ruby-jwt/pull/454) - [@bdewater](https://github.com/bdewater). - Updated rubocop to 1.23.0 [#457](https://github.com/jwt/ruby-jwt/pull/457) - [@anakinj](https://github.com/anakinj). - Add x5c header key finder [#338](https://github.com/jwt/ruby-jwt/pull/338) - [@bdewater](https://github.com/bdewater). - Author driven changelog process [#463](https://github.com/jwt/ruby-jwt/pull/463) - [@anakinj](https://github.com/anakinj). - Allow regular expressions and procs to verify issuer [\#437](https://github.com/jwt/ruby-jwt/pull/437) ([rewritten](https://github.com/rewritten)). - Add Support to be able to verify from multiple keys [\#425](https://github.com/jwt/ruby-jwt/pull/425) ([ritikesh](https://github.com/ritikesh)). **Fixes and enhancements:** - Readme: Typo fix re MissingRequiredClaim [\#451](https://github.com/jwt/ruby-jwt/pull/451) ([antonmorant](https://github.com/antonmorant)). - Fix RuboCop TODOs [\#476](https://github.com/jwt/ruby-jwt/pull/476) ([typhoon2099](https://github.com/typhoon2099)). - Make specific algorithms in README linkable [\#472](https://github.com/jwt/ruby-jwt/pull/472) ([milieu](https://github.com/milieu)). - Update note about supported JWK types [\#475](https://github.com/jwt/ruby-jwt/pull/475) ([dpashkevich](https://github.com/dpashkevich)). - Create CODE\_OF\_CONDUCT.md [\#449](https://github.com/jwt/ruby-jwt/pull/449) ([loic5](https://github.com/loic5)). ## [v2.3.0](https://github.com/jwt/ruby-jwt/tree/v2.3.0) (2021-10-03) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.2.3...v2.3.0) **Closed issues:** - \[SECURITY\] Algorithm Confusion Through kid Header [\#440](https://github.com/jwt/ruby-jwt/issues/440) - JWT to memory [\#436](https://github.com/jwt/ruby-jwt/issues/436) - ArgumentError: wrong number of arguments \(given 2, expected 1\) [\#429](https://github.com/jwt/ruby-jwt/issues/429) - HMAC section of README outdated [\#421](https://github.com/jwt/ruby-jwt/issues/421) - NoMethodError: undefined method `zero?' for nil:NilClass if JWT has no 'alg' field [\#410](https://github.com/jwt/ruby-jwt/issues/410) - Release new version [\#409](https://github.com/jwt/ruby-jwt/issues/409) - NameError: uninitialized constant JWT::JWK [\#403](https://github.com/jwt/ruby-jwt/issues/403) **Merged pull requests:** - Release 2.3.0 [\#448](https://github.com/jwt/ruby-jwt/pull/448) ([excpt](https://github.com/excpt)) - Fix Style/MultilineIfModifier issues [\#447](https://github.com/jwt/ruby-jwt/pull/447) ([anakinj](https://github.com/anakinj)) - feat\(EdDSA\): Accept EdDSA as algorithm header [\#446](https://github.com/jwt/ruby-jwt/pull/446) ([Pierre-Michard](https://github.com/Pierre-Michard)) - Pass kid param through JWT::JWK.create\_from [\#445](https://github.com/jwt/ruby-jwt/pull/445) ([shaun-guth-allscripts](https://github.com/shaun-guth-allscripts)) - fix document about passing JWKs as a simple Hash [\#443](https://github.com/jwt/ruby-jwt/pull/443) ([takayamaki](https://github.com/takayamaki)) - Tests for mixing JWK keys with mismatching algorithms [\#441](https://github.com/jwt/ruby-jwt/pull/441) ([anakinj](https://github.com/anakinj)) - verify\_claims test shouldnt be within the verify\_sub test [\#431](https://github.com/jwt/ruby-jwt/pull/431) ([andyjdavis](https://github.com/andyjdavis)) - Allow decode options to specify required claims [\#430](https://github.com/jwt/ruby-jwt/pull/430) ([andyjdavis](https://github.com/andyjdavis)) - Fix OpenSSL::PKey::EC public\_key handing in tests [\#427](https://github.com/jwt/ruby-jwt/pull/427) ([anakinj](https://github.com/anakinj)) - Add documentation for find\_key [\#426](https://github.com/jwt/ruby-jwt/pull/426) ([ritikesh](https://github.com/ritikesh)) - Give ruby 3.0 as a string to avoid number formatting issues [\#424](https://github.com/jwt/ruby-jwt/pull/424) ([anakinj](https://github.com/anakinj)) - Tests for iat verification behaviour [\#423](https://github.com/jwt/ruby-jwt/pull/423) ([anakinj](https://github.com/anakinj)) - Remove HMAC with nil secret from documentation [\#422](https://github.com/jwt/ruby-jwt/pull/422) ([boardfish](https://github.com/boardfish)) - Update broken link in README [\#420](https://github.com/jwt/ruby-jwt/pull/420) ([severin](https://github.com/severin)) - Add metadata for RubyGems [\#418](https://github.com/jwt/ruby-jwt/pull/418) ([nickhammond](https://github.com/nickhammond)) - Fixed a typo about class name [\#417](https://github.com/jwt/ruby-jwt/pull/417) ([mai-f](https://github.com/mai-f)) - Fix references for v2.2.3 on CHANGELOG [\#416](https://github.com/jwt/ruby-jwt/pull/416) ([vyper](https://github.com/vyper)) - Raise IncorrectAlgorithm if token has no alg header [\#411](https://github.com/jwt/ruby-jwt/pull/411) ([bouk](https://github.com/bouk)) ## [v2.2.3](https://github.com/jwt/ruby-jwt/tree/v2.2.3) (2021-04-19) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.2.2...v2.2.3) **Implemented enhancements:** - Verify algorithm before evaluating keyfinder [\#343](https://github.com/jwt/ruby-jwt/issues/343) - Why jwt depends on json \< 2.0 ? [\#179](https://github.com/jwt/ruby-jwt/issues/179) - Support for JWK in-lieu of rsa\_public [\#158](https://github.com/jwt/ruby-jwt/issues/158) - Fix rspec `raise_error` warning [\#413](https://github.com/jwt/ruby-jwt/pull/413) ([excpt](https://github.com/excpt)) - Add support for JWKs with HMAC key type. [\#372](https://github.com/jwt/ruby-jwt/pull/372) ([phlegx](https://github.com/phlegx)) - Improve 'none' algorithm handling [\#365](https://github.com/jwt/ruby-jwt/pull/365) ([danleyden](https://github.com/danleyden)) - Handle parsed JSON JWKS input with string keys [\#348](https://github.com/jwt/ruby-jwt/pull/348) ([martinemde](https://github.com/martinemde)) - Allow Numeric values during encoding [\#327](https://github.com/jwt/ruby-jwt/pull/327) ([fanfilmu](https://github.com/fanfilmu)) **Closed issues:** - "Signature verification raised", yet jwt.io says "Signature Verified" [\#401](https://github.com/jwt/ruby-jwt/issues/401) - truffleruby-head build is failing [\#396](https://github.com/jwt/ruby-jwt/issues/396) - JWT::JWK::EC needs `require 'forwardable'` [\#392](https://github.com/jwt/ruby-jwt/issues/392) - How to use a 'signing key' as used by next-auth [\#389](https://github.com/jwt/ruby-jwt/issues/389) - undefined method `verify' for nil:NilClass when validate a JWT with JWK [\#383](https://github.com/jwt/ruby-jwt/issues/383) - Make specifying "algorithm" optional on decode [\#380](https://github.com/jwt/ruby-jwt/issues/380) - ADFS created access tokens can't be validated due to missing 'kid' header [\#370](https://github.com/jwt/ruby-jwt/issues/370) - new version? [\#355](https://github.com/jwt/ruby-jwt/issues/355) - JWT gitlab OmniAuth provider setup support [\#354](https://github.com/jwt/ruby-jwt/issues/354) - Release with support for RSA.import for ruby \< 2.4 hasn't been released [\#347](https://github.com/jwt/ruby-jwt/issues/347) - cannot load such file -- jwt [\#339](https://github.com/jwt/ruby-jwt/issues/339) **Merged pull requests:** - Prepare 2.2.3 release [\#415](https://github.com/jwt/ruby-jwt/pull/415) ([excpt](https://github.com/excpt)) - Remove codeclimate code coverage dev dependency [\#414](https://github.com/jwt/ruby-jwt/pull/414) ([excpt](https://github.com/excpt)) - Add forwardable dependency [\#408](https://github.com/jwt/ruby-jwt/pull/408) ([anakinj](https://github.com/anakinj)) - Ignore casing of algorithm [\#405](https://github.com/jwt/ruby-jwt/pull/405) ([johnnyshields](https://github.com/johnnyshields)) - Document function and add tests for verify claims method [\#404](https://github.com/jwt/ruby-jwt/pull/404) ([yasonk](https://github.com/yasonk)) - documenting calling verify\_jti callback with 2 arguments in the readme [\#402](https://github.com/jwt/ruby-jwt/pull/402) ([HoneyryderChuck](https://github.com/HoneyryderChuck)) - Target the master branch on the build status badge [\#399](https://github.com/jwt/ruby-jwt/pull/399) ([anakinj](https://github.com/anakinj)) - Improving the local development experience [\#397](https://github.com/jwt/ruby-jwt/pull/397) ([anakinj](https://github.com/anakinj)) - Fix sourcelevel broken links [\#395](https://github.com/jwt/ruby-jwt/pull/395) ([anakinj](https://github.com/anakinj)) - Don't recommend installing gem with sudo [\#391](https://github.com/jwt/ruby-jwt/pull/391) ([tjschuck](https://github.com/tjschuck)) - Enable rubocop locally and on ci [\#390](https://github.com/jwt/ruby-jwt/pull/390) ([anakinj](https://github.com/anakinj)) - Ci and test cleanup [\#387](https://github.com/jwt/ruby-jwt/pull/387) ([anakinj](https://github.com/anakinj)) - Make JWT::JWK::EC compatible with Ruby 2.3 [\#386](https://github.com/jwt/ruby-jwt/pull/386) ([anakinj](https://github.com/anakinj)) - Support JWKs for pre 2.3 rubies [\#382](https://github.com/jwt/ruby-jwt/pull/382) ([anakinj](https://github.com/anakinj)) - Replace Travis CI with GitHub Actions \(also favor openssl/rbnacl combinations over rails compatibility tests\) [\#381](https://github.com/jwt/ruby-jwt/pull/381) ([anakinj](https://github.com/anakinj)) - Add auth0 sponsor message [\#379](https://github.com/jwt/ruby-jwt/pull/379) ([excpt](https://github.com/excpt)) - Adapt HMAC to JWK RSA code style. [\#378](https://github.com/jwt/ruby-jwt/pull/378) ([phlegx](https://github.com/phlegx)) - Disable Rails cops [\#376](https://github.com/jwt/ruby-jwt/pull/376) ([anakinj](https://github.com/anakinj)) - Support exporting RSA JWK private keys [\#375](https://github.com/jwt/ruby-jwt/pull/375) ([anakinj](https://github.com/anakinj)) - Ebert is SourceLevel nowadays [\#374](https://github.com/jwt/ruby-jwt/pull/374) ([anakinj](https://github.com/anakinj)) - Add support for JWKs with EC key type [\#371](https://github.com/jwt/ruby-jwt/pull/371) ([richardlarocque](https://github.com/richardlarocque)) - Add Truffleruby head to CI [\#368](https://github.com/jwt/ruby-jwt/pull/368) ([gogainda](https://github.com/gogainda)) - Add more docs about JWK support [\#341](https://github.com/jwt/ruby-jwt/pull/341) ([take](https://github.com/take)) ## [v2.2.2](https://github.com/jwt/ruby-jwt/tree/v2.2.2) (2020-08-18) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.2.1...v2.2.2) **Implemented enhancements:** - JWK does not decode. [\#332](https://github.com/jwt/ruby-jwt/issues/332) - Inconsistent use of symbol and string keys in args \(exp and alrogithm\). [\#331](https://github.com/jwt/ruby-jwt/issues/331) - Pin simplecov to \< 0.18 [\#356](https://github.com/jwt/ruby-jwt/pull/356) ([anakinj](https://github.com/anakinj)) - verifies algorithm before evaluating keyfinder [\#346](https://github.com/jwt/ruby-jwt/pull/346) ([jb08](https://github.com/jb08)) - Update Rails 6 appraisal to use actual release version [\#336](https://github.com/jwt/ruby-jwt/pull/336) ([smudge](https://github.com/smudge)) - Update Travis [\#326](https://github.com/jwt/ruby-jwt/pull/326) ([berkos](https://github.com/berkos)) - Improvement/encode hmac without key [\#312](https://github.com/jwt/ruby-jwt/pull/312) ([JotaSe](https://github.com/JotaSe)) **Fixed bugs:** - v2.2.1 warning: already initialized constant JWT Error [\#335](https://github.com/jwt/ruby-jwt/issues/335) - 2.2.1 is no longer raising `JWT::DecodeError` on `nil` verification key [\#328](https://github.com/jwt/ruby-jwt/issues/328) - Fix algorithm picking from decode options [\#359](https://github.com/jwt/ruby-jwt/pull/359) ([excpt](https://github.com/excpt)) - Raise error when verification key is empty [\#358](https://github.com/jwt/ruby-jwt/pull/358) ([anakinj](https://github.com/anakinj)) **Closed issues:** - JWT RSA: is it possible to encrypt using the public key? [\#366](https://github.com/jwt/ruby-jwt/issues/366) - Example unsigned token that bypasses verification [\#364](https://github.com/jwt/ruby-jwt/issues/364) - Verify exp claim/field even if it's not present [\#363](https://github.com/jwt/ruby-jwt/issues/363) - Decode any token [\#360](https://github.com/jwt/ruby-jwt/issues/360) - \[question\] example of using a pub/priv keys for signing? [\#351](https://github.com/jwt/ruby-jwt/issues/351) - JWT::ExpiredSignature raised for non-JSON payloads [\#350](https://github.com/jwt/ruby-jwt/issues/350) - verify\_aud only verifies that at least one aud is expected [\#345](https://github.com/jwt/ruby-jwt/issues/345) - Sinatra 4.90s TTFB [\#344](https://github.com/jwt/ruby-jwt/issues/344) - How to Logout [\#342](https://github.com/jwt/ruby-jwt/issues/342) - jwt token decoding even when wrong token is provided for some letters [\#337](https://github.com/jwt/ruby-jwt/issues/337) - Need to use `symbolize_keys` everywhere! [\#330](https://github.com/jwt/ruby-jwt/issues/330) - eval\(\) used in Forwardable limits usage in iOS App Store [\#324](https://github.com/jwt/ruby-jwt/issues/324) - HS512256 OpenSSL Exception: First num too large [\#322](https://github.com/jwt/ruby-jwt/issues/322) - Can we change the separator character? [\#321](https://github.com/jwt/ruby-jwt/issues/321) - Verifying iat without leeway may break with poorly synced clocks [\#319](https://github.com/jwt/ruby-jwt/issues/319) - Adding support for 'hd' hosted domain string [\#314](https://github.com/jwt/ruby-jwt/issues/314) - There is no "typ" header in version 2.0.0 [\#233](https://github.com/jwt/ruby-jwt/issues/233) **Merged pull requests:** - Release v2.2.2 [\#367](https://github.com/jwt/ruby-jwt/pull/367) ([excpt](https://github.com/excpt)) - Fix 'already initialized constant JWT Error' [\#357](https://github.com/jwt/ruby-jwt/pull/357) ([excpt](https://github.com/excpt)) - Support RSA.import for all Ruby versions. [\#333](https://github.com/jwt/ruby-jwt/pull/333) ([rabajaj0509](https://github.com/rabajaj0509)) - Removed forwardable dependency [\#325](https://github.com/jwt/ruby-jwt/pull/325) ([anakinj](https://github.com/anakinj)) ## [v2.2.1](https://github.com/jwt/ruby-jwt/tree/v2.2.1) (2019-05-24) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.2.0...v2.2.1) **Fixed bugs:** - need to `require 'forwardable'` to use `Forwardable` [\#316](https://github.com/jwt/ruby-jwt/issues/316) - Add forwardable dependency for JWK RSA KeyFinder [\#317](https://github.com/jwt/ruby-jwt/pull/317) ([excpt](https://github.com/excpt)) **Merged pull requests:** - Release 2.2.1 [\#318](https://github.com/jwt/ruby-jwt/pull/318) ([excpt](https://github.com/excpt)) ## [v2.2.0](https://github.com/jwt/ruby-jwt/tree/v2.2.0) (2019-05-23) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.2.0.pre.beta.0...v2.2.0) **Closed issues:** - misspelled es512 curve name [\#310](https://github.com/jwt/ruby-jwt/issues/310) - With Base64 decode i can read the hashed content [\#306](https://github.com/jwt/ruby-jwt/issues/306) - hide post-it's for graphviz views [\#303](https://github.com/jwt/ruby-jwt/issues/303) **Merged pull requests:** - Release 2.2.0 [\#315](https://github.com/jwt/ruby-jwt/pull/315) ([excpt](https://github.com/excpt)) ## [v2.2.0.pre.beta.0](https://github.com/jwt/ruby-jwt/tree/v2.2.0.pre.beta.0) (2019-03-20) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.1.0...v2.2.0.pre.beta.0) **Implemented enhancements:** - Use iat\_leeway option [\#273](https://github.com/jwt/ruby-jwt/issues/273) - Use of global state in latest version breaks thread safety of JWT.decode [\#268](https://github.com/jwt/ruby-jwt/issues/268) - JSON support [\#246](https://github.com/jwt/ruby-jwt/issues/246) - Change the Github homepage URL to https [\#301](https://github.com/jwt/ruby-jwt/pull/301) ([ekohl](https://github.com/ekohl)) - Fix Salt length for conformance with PS family specification. [\#300](https://github.com/jwt/ruby-jwt/pull/300) ([tobypinder](https://github.com/tobypinder)) - Add support for Ruby 2.6 [\#299](https://github.com/jwt/ruby-jwt/pull/299) ([bustikiller](https://github.com/bustikiller)) - update homepage in gemspec to use HTTPS [\#298](https://github.com/jwt/ruby-jwt/pull/298) ([evgeni](https://github.com/evgeni)) - Make sure alg parameter value isn't added twice [\#297](https://github.com/jwt/ruby-jwt/pull/297) ([korstiaan](https://github.com/korstiaan)) - Claims Validation [\#295](https://github.com/jwt/ruby-jwt/pull/295) ([jamesstonehill](https://github.com/jamesstonehill)) - JWT::Encode refactorings, alg and exp related bugfixes [\#293](https://github.com/jwt/ruby-jwt/pull/293) ([anakinj](https://github.com/anakinj)) - Proposal of simple JWK support [\#289](https://github.com/jwt/ruby-jwt/pull/289) ([anakinj](https://github.com/anakinj)) - Add RSASSA-PSS signature signing support [\#285](https://github.com/jwt/ruby-jwt/pull/285) ([oliver-hohn](https://github.com/oliver-hohn)) - Add note about using a hard coded algorithm in README [\#280](https://github.com/jwt/ruby-jwt/pull/280) ([revodoge](https://github.com/revodoge)) - Add Appraisal support [\#278](https://github.com/jwt/ruby-jwt/pull/278) ([olbrich](https://github.com/olbrich)) - Fix decode threading issue [\#269](https://github.com/jwt/ruby-jwt/pull/269) ([ab320012](https://github.com/ab320012)) - Removed leeway from verify\_iat [\#257](https://github.com/jwt/ruby-jwt/pull/257) ([ab320012](https://github.com/ab320012)) **Fixed bugs:** - Inconsistent handling of payload claim data types [\#282](https://github.com/jwt/ruby-jwt/issues/282) - Issued at validation [\#247](https://github.com/jwt/ruby-jwt/issues/247) - Fix bug and simplify segment validation [\#292](https://github.com/jwt/ruby-jwt/pull/292) ([anakinj](https://github.com/anakinj)) **Security fixes:** - Decoding JWT with ES256 and secp256k1 curve [\#277](https://github.com/jwt/ruby-jwt/issues/277) **Closed issues:** - RS256, public and private keys [\#291](https://github.com/jwt/ruby-jwt/issues/291) - Allow passing current time to `decode` [\#288](https://github.com/jwt/ruby-jwt/issues/288) - Verify exp claim without verifying jwt [\#281](https://github.com/jwt/ruby-jwt/issues/281) - Audience as an array - how to specify? [\#276](https://github.com/jwt/ruby-jwt/issues/276) - signature validation using decode method for JWT [\#271](https://github.com/jwt/ruby-jwt/issues/271) - JWT is easily breakable [\#267](https://github.com/jwt/ruby-jwt/issues/267) - Ruby JWT Token [\#265](https://github.com/jwt/ruby-jwt/issues/265) - ECDSA supported algorithms constant is defined as a string, not an array [\#264](https://github.com/jwt/ruby-jwt/issues/264) - NoMethodError: undefined method `group' for \ [\#261](https://github.com/jwt/ruby-jwt/issues/261) - 'DecodeError'will replace 'ExpiredSignature' [\#260](https://github.com/jwt/ruby-jwt/issues/260) - TypeError: no implicit conversion of OpenSSL::PKey::RSA into String [\#259](https://github.com/jwt/ruby-jwt/issues/259) - NameError: uninitialized constant JWT::Algos::Eddsa::RbNaCl [\#258](https://github.com/jwt/ruby-jwt/issues/258) - Get new token if curren token expired [\#256](https://github.com/jwt/ruby-jwt/issues/256) - Infer algorithm from header [\#254](https://github.com/jwt/ruby-jwt/issues/254) - Why is the result of decode is an array? [\#252](https://github.com/jwt/ruby-jwt/issues/252) - Add support for headless token [\#251](https://github.com/jwt/ruby-jwt/issues/251) - Leeway or exp\_leeway [\#215](https://github.com/jwt/ruby-jwt/issues/215) - Could you describe purpose of cert fixtures and their cryptokey lengths. [\#185](https://github.com/jwt/ruby-jwt/issues/185) **Merged pull requests:** - Release v2.2.0-beta.0 [\#302](https://github.com/jwt/ruby-jwt/pull/302) ([excpt](https://github.com/excpt)) - Misc config improvements [\#296](https://github.com/jwt/ruby-jwt/pull/296) ([jamesstonehill](https://github.com/jamesstonehill)) - Fix JSON conflict between \#293 and \#292 [\#294](https://github.com/jwt/ruby-jwt/pull/294) ([anakinj](https://github.com/anakinj)) - Drop Ruby 2.2 from test matrix [\#290](https://github.com/jwt/ruby-jwt/pull/290) ([anakinj](https://github.com/anakinj)) - Remove broken reek config [\#283](https://github.com/jwt/ruby-jwt/pull/283) ([excpt](https://github.com/excpt)) - Add missing test, Update common files [\#275](https://github.com/jwt/ruby-jwt/pull/275) ([excpt](https://github.com/excpt)) - Remove iat\_leeway option [\#274](https://github.com/jwt/ruby-jwt/pull/274) ([wohlgejm](https://github.com/wohlgejm)) - improving code quality of jwt module [\#266](https://github.com/jwt/ruby-jwt/pull/266) ([ab320012](https://github.com/ab320012)) - fixed ECDSA supported versions const [\#263](https://github.com/jwt/ruby-jwt/pull/263) ([starbeast](https://github.com/starbeast)) - Added my name to contributor list [\#262](https://github.com/jwt/ruby-jwt/pull/262) ([ab320012](https://github.com/ab320012)) - Use `Class#new` Shorthand For Error Subclasses [\#255](https://github.com/jwt/ruby-jwt/pull/255) ([akabiru](https://github.com/akabiru)) - \[CI\] Test against Ruby 2.5 [\#253](https://github.com/jwt/ruby-jwt/pull/253) ([nicolasleger](https://github.com/nicolasleger)) - Fix README [\#250](https://github.com/jwt/ruby-jwt/pull/250) ([rono23](https://github.com/rono23)) - Fix link format [\#248](https://github.com/jwt/ruby-jwt/pull/248) ([y-yagi](https://github.com/y-yagi)) ## [v2.1.0](https://github.com/jwt/ruby-jwt/tree/v2.1.0) (2017-10-06) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.0.0...v2.1.0) **Implemented enhancements:** - Ed25519 support planned? [\#217](https://github.com/jwt/ruby-jwt/issues/217) - Verify JTI Proc [\#207](https://github.com/jwt/ruby-jwt/issues/207) - Allow a list of algorithms for decode [\#241](https://github.com/jwt/ruby-jwt/pull/241) ([lautis](https://github.com/lautis)) - verify takes 2 params, second being payload closes: \#207 [\#238](https://github.com/jwt/ruby-jwt/pull/238) ([ab320012](https://github.com/ab320012)) - simplified logic for keyfinder [\#237](https://github.com/jwt/ruby-jwt/pull/237) ([ab320012](https://github.com/ab320012)) - Show backtrace if rbnacl-libsodium not loaded [\#231](https://github.com/jwt/ruby-jwt/pull/231) ([buzztaiki](https://github.com/buzztaiki)) - Support for ED25519 [\#229](https://github.com/jwt/ruby-jwt/pull/229) ([ab320012](https://github.com/ab320012)) **Fixed bugs:** - JWT.encode failing on encode for string [\#235](https://github.com/jwt/ruby-jwt/issues/235) - The README says it uses an algorithm by default [\#226](https://github.com/jwt/ruby-jwt/issues/226) - Fix string payload issue [\#236](https://github.com/jwt/ruby-jwt/pull/236) ([excpt](https://github.com/excpt)) **Security fixes:** - Add HS256 algorithm to decode default options [\#228](https://github.com/jwt/ruby-jwt/pull/228) ([marcoadkins](https://github.com/marcoadkins)) **Closed issues:** - Change from 1.5.6 to 2.0.0 and appears a "Completed 401 Unauthorized" [\#240](https://github.com/jwt/ruby-jwt/issues/240) - Why doesn't the decode function use a default algorithm? [\#227](https://github.com/jwt/ruby-jwt/issues/227) **Merged pull requests:** - Release 2.1.0 preparations [\#243](https://github.com/jwt/ruby-jwt/pull/243) ([excpt](https://github.com/excpt)) - Update README.md [\#242](https://github.com/jwt/ruby-jwt/pull/242) ([excpt](https://github.com/excpt)) - Update ebert configuration [\#232](https://github.com/jwt/ruby-jwt/pull/232) ([excpt](https://github.com/excpt)) - added algos/strategy classes + structs for inputs [\#230](https://github.com/jwt/ruby-jwt/pull/230) ([ab320012](https://github.com/ab320012)) ## [v2.0.0](https://github.com/jwt/ruby-jwt/tree/v2.0.0) (2017-09-03) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.0.0.beta1...v2.0.0) **Fixed bugs:** - Support versions outside 2.1 [\#209](https://github.com/jwt/ruby-jwt/issues/209) - Verifying expiration without leeway throws exception [\#206](https://github.com/jwt/ruby-jwt/issues/206) - Ruby interpreter warning [\#200](https://github.com/jwt/ruby-jwt/issues/200) - TypeError: no implicit conversion of String into Integer [\#188](https://github.com/jwt/ruby-jwt/issues/188) - Fix JWT.encode\(nil\) [\#203](https://github.com/jwt/ruby-jwt/pull/203) ([tmm1](https://github.com/tmm1)) **Closed issues:** - Possibility to disable claim verifications [\#222](https://github.com/jwt/ruby-jwt/issues/222) - Proper way to verify Firebase id tokens [\#216](https://github.com/jwt/ruby-jwt/issues/216) **Merged pull requests:** - Release 2.0.0 preparations :\) [\#225](https://github.com/jwt/ruby-jwt/pull/225) ([excpt](https://github.com/excpt)) - Skip 'exp' claim validation for array payloads [\#224](https://github.com/jwt/ruby-jwt/pull/224) ([excpt](https://github.com/excpt)) - Use a default leeway of 0 [\#223](https://github.com/jwt/ruby-jwt/pull/223) ([travisofthenorth](https://github.com/travisofthenorth)) - Fix reported codesmells [\#221](https://github.com/jwt/ruby-jwt/pull/221) ([excpt](https://github.com/excpt)) - Add fancy gem version badge [\#220](https://github.com/jwt/ruby-jwt/pull/220) ([excpt](https://github.com/excpt)) - Add missing dist option to .travis.yml [\#219](https://github.com/jwt/ruby-jwt/pull/219) ([excpt](https://github.com/excpt)) - Fix ruby version requirements in gemspec file [\#218](https://github.com/jwt/ruby-jwt/pull/218) ([excpt](https://github.com/excpt)) - Fix a little typo in the readme [\#214](https://github.com/jwt/ruby-jwt/pull/214) ([RyanBrushett](https://github.com/RyanBrushett)) - Update README.md [\#212](https://github.com/jwt/ruby-jwt/pull/212) ([zuzannast](https://github.com/zuzannast)) - Fix typo in HS512256 algorithm description [\#211](https://github.com/jwt/ruby-jwt/pull/211) ([ojab](https://github.com/ojab)) - Allow configuration of multiple acceptable issuers [\#210](https://github.com/jwt/ruby-jwt/pull/210) ([ojab](https://github.com/ojab)) - Enforce `exp` to be an `Integer` [\#205](https://github.com/jwt/ruby-jwt/pull/205) ([lucasmazza](https://github.com/lucasmazza)) - ruby 1.9.3 support message upd [\#204](https://github.com/jwt/ruby-jwt/pull/204) ([maokomioko](https://github.com/maokomioko)) ## [v2.0.0.beta1](https://github.com/jwt/ruby-jwt/tree/v2.0.0.beta1) (2017-02-27) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v1.5.6...v2.0.0.beta1) **Implemented enhancements:** - Error with method sign for String [\#171](https://github.com/jwt/ruby-jwt/issues/171) - Refactor the encondig code [\#121](https://github.com/jwt/ruby-jwt/issues/121) - Refactor [\#196](https://github.com/jwt/ruby-jwt/pull/196) ([EmilioCristalli](https://github.com/EmilioCristalli)) - Move signature logic to its own module [\#195](https://github.com/jwt/ruby-jwt/pull/195) ([EmilioCristalli](https://github.com/EmilioCristalli)) - Add options for claim-specific leeway [\#187](https://github.com/jwt/ruby-jwt/pull/187) ([EmilioCristalli](https://github.com/EmilioCristalli)) - Add user friendly encode error if private key is a String, \#171 [\#176](https://github.com/jwt/ruby-jwt/pull/176) ([ogonki-vetochki](https://github.com/ogonki-vetochki)) - Return empty string if signature less than byte\_size \#155 [\#175](https://github.com/jwt/ruby-jwt/pull/175) ([ogonki-vetochki](https://github.com/ogonki-vetochki)) - Remove 'typ' optional parameter [\#174](https://github.com/jwt/ruby-jwt/pull/174) ([ogonki-vetochki](https://github.com/ogonki-vetochki)) - Pass payload to keyfinder [\#172](https://github.com/jwt/ruby-jwt/pull/172) ([CodeMonkeySteve](https://github.com/CodeMonkeySteve)) - Use RbNaCl for HMAC if available with fallback to OpenSSL [\#149](https://github.com/jwt/ruby-jwt/pull/149) ([mwpastore](https://github.com/mwpastore)) **Fixed bugs:** - ruby-jwt::raw\_to\_asn1: Fails for signatures less than byte\_size [\#155](https://github.com/jwt/ruby-jwt/issues/155) - The leeway parameter is applies to all time based verifications [\#129](https://github.com/jwt/ruby-jwt/issues/129) - Make algorithm option required to verify signature [\#184](https://github.com/jwt/ruby-jwt/pull/184) ([EmilioCristalli](https://github.com/EmilioCristalli)) - Validate audience when payload is a scalar and options is an array [\#183](https://github.com/jwt/ruby-jwt/pull/183) ([steti](https://github.com/steti)) **Closed issues:** - Different encoded value between servers with same password [\#197](https://github.com/jwt/ruby-jwt/issues/197) - Signature is different at each run [\#190](https://github.com/jwt/ruby-jwt/issues/190) - Include custom headers with password [\#189](https://github.com/jwt/ruby-jwt/issues/189) - can't create token - 'NotImplementedError: Unsupported signing method' [\#186](https://github.com/jwt/ruby-jwt/issues/186) - Cannot verify JWT at all?? [\#177](https://github.com/jwt/ruby-jwt/issues/177) - verify\_iss: true is raising JWT::DecodeError instead of JWT::InvalidIssuerError [\#170](https://github.com/jwt/ruby-jwt/issues/170) **Merged pull requests:** - Version bump 2.0.0.beta1 [\#199](https://github.com/jwt/ruby-jwt/pull/199) ([excpt](https://github.com/excpt)) - Update CHANGELOG.md and minor fixes [\#198](https://github.com/jwt/ruby-jwt/pull/198) ([excpt](https://github.com/excpt)) - Add Codacy coverage reporter [\#194](https://github.com/jwt/ruby-jwt/pull/194) ([excpt](https://github.com/excpt)) - Add minimum required ruby version to gemspec [\#193](https://github.com/jwt/ruby-jwt/pull/193) ([excpt](https://github.com/excpt)) - Code smell fixes [\#192](https://github.com/jwt/ruby-jwt/pull/192) ([excpt](https://github.com/excpt)) - Version bump to 2.0.0.dev [\#191](https://github.com/jwt/ruby-jwt/pull/191) ([excpt](https://github.com/excpt)) - Basic encode module refactoring \#121 [\#182](https://github.com/jwt/ruby-jwt/pull/182) ([ogonki-vetochki](https://github.com/ogonki-vetochki)) - Fix travis ci build configuration [\#181](https://github.com/jwt/ruby-jwt/pull/181) ([excpt](https://github.com/excpt)) - Fix travis ci build configuration [\#180](https://github.com/jwt/ruby-jwt/pull/180) ([excpt](https://github.com/excpt)) - Fix typo in README [\#178](https://github.com/jwt/ruby-jwt/pull/178) ([tomeduarte](https://github.com/tomeduarte)) - Fix code style [\#173](https://github.com/jwt/ruby-jwt/pull/173) ([excpt](https://github.com/excpt)) - Fixed a typo in a spec name [\#169](https://github.com/jwt/ruby-jwt/pull/169) ([mingan](https://github.com/mingan)) ## [v1.5.6](https://github.com/jwt/ruby-jwt/tree/v1.5.6) (2016-09-19) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v1.5.5...v1.5.6) **Fixed bugs:** - Fix missing symbol handling in aud verify code [\#166](https://github.com/jwt/ruby-jwt/pull/166) ([excpt](https://github.com/excpt)) **Merged pull requests:** - Update changelog [\#168](https://github.com/jwt/ruby-jwt/pull/168) ([excpt](https://github.com/excpt)) - Fix rubocop code smells [\#167](https://github.com/jwt/ruby-jwt/pull/167) ([excpt](https://github.com/excpt)) ## [v1.5.5](https://github.com/jwt/ruby-jwt/tree/v1.5.5) (2016-09-16) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v1.5.4...v1.5.5) **Implemented enhancements:** - JWT.decode always raises JWT::ExpiredSignature for tokens created with Time objects passed as the `exp` parameter [\#148](https://github.com/jwt/ruby-jwt/issues/148) **Fixed bugs:** - expiration check does not give "Signature has expired" error for the exact time of expiration [\#157](https://github.com/jwt/ruby-jwt/issues/157) - JTI claim broken? [\#152](https://github.com/jwt/ruby-jwt/issues/152) - Audience Claim broken? [\#151](https://github.com/jwt/ruby-jwt/issues/151) - 1.5.3 breaks compatibility with 1.5.2 [\#133](https://github.com/jwt/ruby-jwt/issues/133) - Version 1.5.3 breaks 1.9.3 compatibility, but not documented as such [\#132](https://github.com/jwt/ruby-jwt/issues/132) - Fix: exp claim check [\#161](https://github.com/jwt/ruby-jwt/pull/161) ([excpt](https://github.com/excpt)) **Security fixes:** - \[security\] Signature verified after expiration/sub/iss checks [\#153](https://github.com/jwt/ruby-jwt/issues/153) - Signature validation before claim verification [\#160](https://github.com/jwt/ruby-jwt/pull/160) ([excpt](https://github.com/excpt)) **Closed issues:** - Rendering Json Results in JWT::DecodeError [\#162](https://github.com/jwt/ruby-jwt/issues/162) - PHP Libraries [\#154](https://github.com/jwt/ruby-jwt/issues/154) - Is ruby-jwt thread-safe? [\#150](https://github.com/jwt/ruby-jwt/issues/150) - JWT 1.5.3 [\#143](https://github.com/jwt/ruby-jwt/issues/143) - gem install v 1.5.3 returns error [\#141](https://github.com/jwt/ruby-jwt/issues/141) - Adding a CHANGELOG [\#140](https://github.com/jwt/ruby-jwt/issues/140) **Merged pull requests:** - Bump version [\#165](https://github.com/jwt/ruby-jwt/pull/165) ([excpt](https://github.com/excpt)) - Improve error message for exp claim in payload [\#164](https://github.com/jwt/ruby-jwt/pull/164) ([excpt](https://github.com/excpt)) - Fix \#151 and code refactoring [\#163](https://github.com/jwt/ruby-jwt/pull/163) ([excpt](https://github.com/excpt)) - Create specs for README.md examples [\#159](https://github.com/jwt/ruby-jwt/pull/159) ([excpt](https://github.com/excpt)) - Tiny Readme Improvement [\#156](https://github.com/jwt/ruby-jwt/pull/156) ([b264](https://github.com/b264)) - Added test execution to Rakefile [\#147](https://github.com/jwt/ruby-jwt/pull/147) ([jabbrwcky](https://github.com/jabbrwcky)) - Bump version [\#145](https://github.com/jwt/ruby-jwt/pull/145) ([excpt](https://github.com/excpt)) - Add a changelog file [\#142](https://github.com/jwt/ruby-jwt/pull/142) ([excpt](https://github.com/excpt)) - Return decoded\_segments [\#139](https://github.com/jwt/ruby-jwt/pull/139) ([akostrikov](https://github.com/akostrikov)) ## [v1.5.4](https://github.com/jwt/ruby-jwt/tree/v1.5.4) (2016-03-24) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v1.5.3...v1.5.4) **Closed issues:** - 404 at https://rubygems.global.ssl.fastly.net/gems/jwt-1.5.3.gem [\#137](https://github.com/jwt/ruby-jwt/issues/137) **Merged pull requests:** - Update README.md [\#138](https://github.com/jwt/ruby-jwt/pull/138) ([excpt](https://github.com/excpt)) - Fix base64url\_decode [\#136](https://github.com/jwt/ruby-jwt/pull/136) ([excpt](https://github.com/excpt)) - Fix ruby 1.9.3 compatibility [\#135](https://github.com/jwt/ruby-jwt/pull/135) ([excpt](https://github.com/excpt)) - iat can be a float value [\#134](https://github.com/jwt/ruby-jwt/pull/134) ([llimllib](https://github.com/llimllib)) ## [v1.5.3](https://github.com/jwt/ruby-jwt/tree/v1.5.3) (2016-02-24) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.5.2...v1.5.3) **Implemented enhancements:** - Refactor obsolete code for ruby 1.8 support [\#120](https://github.com/jwt/ruby-jwt/issues/120) - Fix "Rubocop/Metrics/CyclomaticComplexity" issue in lib/jwt.rb [\#106](https://github.com/jwt/ruby-jwt/issues/106) - Fix "Rubocop/Metrics/CyclomaticComplexity" issue in lib/jwt.rb [\#105](https://github.com/jwt/ruby-jwt/issues/105) - Allow a proc to be passed for JTI verification [\#126](https://github.com/jwt/ruby-jwt/pull/126) ([yahooguntu](https://github.com/yahooguntu)) - Relax restrictions on "jti" claim verification [\#113](https://github.com/jwt/ruby-jwt/pull/113) ([lwe](https://github.com/lwe)) **Closed issues:** - Verifications not functioning in latest release [\#128](https://github.com/jwt/ruby-jwt/issues/128) - Base64 is generating invalid length base64 strings - cross language interop [\#127](https://github.com/jwt/ruby-jwt/issues/127) - Digest::Digest is deprecated; use Digest [\#119](https://github.com/jwt/ruby-jwt/issues/119) - verify\_rsa no method 'verify' for class String [\#115](https://github.com/jwt/ruby-jwt/issues/115) - Add a changelog [\#111](https://github.com/jwt/ruby-jwt/issues/111) **Merged pull requests:** - Drop ruby 1.9.3 support [\#131](https://github.com/jwt/ruby-jwt/pull/131) ([excpt](https://github.com/excpt)) - Allow string hash keys in validation configurations [\#130](https://github.com/jwt/ruby-jwt/pull/130) ([tpickett66](https://github.com/tpickett66)) - Add ruby 2.3.0 for travis ci testing [\#123](https://github.com/jwt/ruby-jwt/pull/123) ([excpt](https://github.com/excpt)) - Remove obsolete json code [\#122](https://github.com/jwt/ruby-jwt/pull/122) ([excpt](https://github.com/excpt)) - Add fancy badges to README.md [\#118](https://github.com/jwt/ruby-jwt/pull/118) ([excpt](https://github.com/excpt)) - Refactor decode and verify functionality [\#117](https://github.com/jwt/ruby-jwt/pull/117) ([excpt](https://github.com/excpt)) - Drop echoe dependency for gem releases [\#116](https://github.com/jwt/ruby-jwt/pull/116) ([excpt](https://github.com/excpt)) - Updated readme for iss/aud options [\#114](https://github.com/jwt/ruby-jwt/pull/114) ([ryanmcilmoyl](https://github.com/ryanmcilmoyl)) - Fix error misspelling [\#112](https://github.com/jwt/ruby-jwt/pull/112) ([kat3kasper](https://github.com/kat3kasper)) ## [jwt-1.5.2](https://github.com/jwt/ruby-jwt/tree/jwt-1.5.2) (2015-10-27) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.5.1...jwt-1.5.2) **Implemented enhancements:** - Must we specify algorithm when calling decode to avoid vulnerabilities? [\#107](https://github.com/jwt/ruby-jwt/issues/107) - Code review: Rspec test refactoring [\#85](https://github.com/jwt/ruby-jwt/pull/85) ([excpt](https://github.com/excpt)) **Fixed bugs:** - aud verifies if aud is passed in, :sub does not [\#102](https://github.com/jwt/ruby-jwt/issues/102) - iat check does not use leeway so nbf could pass, but iat fail [\#83](https://github.com/jwt/ruby-jwt/issues/83) **Closed issues:** - Test ticket from Code Climate [\#104](https://github.com/jwt/ruby-jwt/issues/104) - Test ticket from Code Climate [\#100](https://github.com/jwt/ruby-jwt/issues/100) - Is it possible to decode the payload without validating the signature? [\#97](https://github.com/jwt/ruby-jwt/issues/97) - What is audience? [\#96](https://github.com/jwt/ruby-jwt/issues/96) - Options hash uses both symbols and strings as keys. [\#95](https://github.com/jwt/ruby-jwt/issues/95) **Merged pull requests:** - Fix incorrect `iat` examples [\#109](https://github.com/jwt/ruby-jwt/pull/109) ([kjwierenga](https://github.com/kjwierenga)) - Update docs to include instructions for the algorithm parameter. [\#108](https://github.com/jwt/ruby-jwt/pull/108) ([aarongray](https://github.com/aarongray)) - make sure :sub check behaves like :aud check [\#103](https://github.com/jwt/ruby-jwt/pull/103) ([skippy](https://github.com/skippy)) - Change hash syntax [\#101](https://github.com/jwt/ruby-jwt/pull/101) ([excpt](https://github.com/excpt)) - Include LICENSE and README.md in gem [\#99](https://github.com/jwt/ruby-jwt/pull/99) ([bkeepers](https://github.com/bkeepers)) - Remove unused variable in the sample code. [\#98](https://github.com/jwt/ruby-jwt/pull/98) ([hypermkt](https://github.com/hypermkt)) - Fix iat claim example [\#94](https://github.com/jwt/ruby-jwt/pull/94) ([larrylv](https://github.com/larrylv)) - Fix wrong description in README.md [\#93](https://github.com/jwt/ruby-jwt/pull/93) ([larrylv](https://github.com/larrylv)) - JWT and JWA are now RFC. [\#92](https://github.com/jwt/ruby-jwt/pull/92) ([aj-michael](https://github.com/aj-michael)) - Update README.md [\#91](https://github.com/jwt/ruby-jwt/pull/91) ([nsarno](https://github.com/nsarno)) - Fix missing verify parameter in docs [\#90](https://github.com/jwt/ruby-jwt/pull/90) ([ernie](https://github.com/ernie)) - Iat check uses leeway. [\#89](https://github.com/jwt/ruby-jwt/pull/89) ([aj-michael](https://github.com/aj-michael)) - nbf check allows exact time matches. [\#88](https://github.com/jwt/ruby-jwt/pull/88) ([aj-michael](https://github.com/aj-michael)) ## [jwt-1.5.1](https://github.com/jwt/ruby-jwt/tree/jwt-1.5.1) (2015-06-22) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.5.0...jwt-1.5.1) **Implemented enhancements:** - Fix either README or source code [\#78](https://github.com/jwt/ruby-jwt/issues/78) - Validate against draft 20 [\#38](https://github.com/jwt/ruby-jwt/issues/38) **Fixed bugs:** - ECDSA signature verification fails for valid tokens [\#84](https://github.com/jwt/ruby-jwt/issues/84) - Shouldn't verification of additional claims, like iss, aud etc. be enforced when in options? [\#81](https://github.com/jwt/ruby-jwt/issues/81) - decode fails with 'none' algorithm and verify [\#75](https://github.com/jwt/ruby-jwt/issues/75) **Closed issues:** - Doc mismatch: uninitialized constant JWT::ExpiredSignature [\#79](https://github.com/jwt/ruby-jwt/issues/79) - TypeError when specifying a wrong algorithm [\#77](https://github.com/jwt/ruby-jwt/issues/77) - jti verification doesn't prevent replays [\#73](https://github.com/jwt/ruby-jwt/issues/73) **Merged pull requests:** - Correctly sign ECDSA JWTs [\#87](https://github.com/jwt/ruby-jwt/pull/87) ([jurriaan](https://github.com/jurriaan)) - fixed results of decoded tokens in readme [\#86](https://github.com/jwt/ruby-jwt/pull/86) ([piscolomo](https://github.com/piscolomo)) - Force verification of "iss" and "aud" claims [\#82](https://github.com/jwt/ruby-jwt/pull/82) ([lwe](https://github.com/lwe)) ## [jwt-1.5.0](https://github.com/jwt/ruby-jwt/tree/jwt-1.5.0) (2015-05-09) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.4.1...jwt-1.5.0) **Implemented enhancements:** - Needs to support asymmetric key signatures over shared secrets [\#46](https://github.com/jwt/ruby-jwt/issues/46) - Implement Elliptic Curve Crypto Signatures [\#74](https://github.com/jwt/ruby-jwt/pull/74) ([jtdowney](https://github.com/jtdowney)) - Add an option to verify the signature on decode [\#71](https://github.com/jwt/ruby-jwt/pull/71) ([javawizard](https://github.com/javawizard)) **Closed issues:** - Check JWT vulnerability [\#76](https://github.com/jwt/ruby-jwt/issues/76) **Merged pull requests:** - Fixed some examples to make them copy-pastable [\#72](https://github.com/jwt/ruby-jwt/pull/72) ([jer](https://github.com/jer)) ## [jwt-1.4.1](https://github.com/jwt/ruby-jwt/tree/jwt-1.4.1) (2015-03-12) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.4.0...jwt-1.4.1) **Fixed bugs:** - jti verification not working per the spec [\#68](https://github.com/jwt/ruby-jwt/issues/68) - Verify ISS should be off by default [\#66](https://github.com/jwt/ruby-jwt/issues/66) **Merged pull requests:** - Fix \#66 \#68 [\#69](https://github.com/jwt/ruby-jwt/pull/69) ([excpt](https://github.com/excpt)) - When throwing errors, mention expected/received values [\#65](https://github.com/jwt/ruby-jwt/pull/65) ([rolodato](https://github.com/rolodato)) ## [jwt-1.4.0](https://github.com/jwt/ruby-jwt/tree/jwt-1.4.0) (2015-03-10) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.3.0...jwt-1.4.0) **Closed issues:** - The behavior using 'json' differs from 'multi\_json' [\#41](https://github.com/jwt/ruby-jwt/issues/41) **Merged pull requests:** - Release 1.4.0 [\#64](https://github.com/jwt/ruby-jwt/pull/64) ([excpt](https://github.com/excpt)) - Update README.md and remove dead code [\#63](https://github.com/jwt/ruby-jwt/pull/63) ([excpt](https://github.com/excpt)) - Add 'iat/ aud/ sub/ jti' support for ruby-jwt [\#62](https://github.com/jwt/ruby-jwt/pull/62) ([ZhangHanDong](https://github.com/ZhangHanDong)) - Add 'iss' support for ruby-jwt [\#61](https://github.com/jwt/ruby-jwt/pull/61) ([ZhangHanDong](https://github.com/ZhangHanDong)) - Clarify .encode API in README [\#60](https://github.com/jwt/ruby-jwt/pull/60) ([jbodah](https://github.com/jbodah)) ## [jwt-1.3.0](https://github.com/jwt/ruby-jwt/tree/jwt-1.3.0) (2015-02-24) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.2.1...jwt-1.3.0) **Closed issues:** - Signature Verification to Return Verification Error rather than decode error [\#57](https://github.com/jwt/ruby-jwt/issues/57) - Incorrect readme for leeway [\#55](https://github.com/jwt/ruby-jwt/issues/55) - What is the reason behind stripping the = in base64 encoding? [\#54](https://github.com/jwt/ruby-jwt/issues/54) - Preperations for version 2.x [\#50](https://github.com/jwt/ruby-jwt/issues/50) - Release a new version [\#47](https://github.com/jwt/ruby-jwt/issues/47) - Catch up for ActiveWhatever 4.1.1 series [\#40](https://github.com/jwt/ruby-jwt/issues/40) **Merged pull requests:** - raise verification error for signiture verification [\#58](https://github.com/jwt/ruby-jwt/pull/58) ([punkle](https://github.com/punkle)) - Added support for not before claim verification [\#56](https://github.com/jwt/ruby-jwt/pull/56) ([punkle](https://github.com/punkle)) ## [jwt-1.2.1](https://github.com/jwt/ruby-jwt/tree/jwt-1.2.1) (2015-01-22) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.2.0...jwt-1.2.1) **Closed issues:** - JWT.encode\({"exp": 10}, "secret"\) [\#52](https://github.com/jwt/ruby-jwt/issues/52) - JWT.encode\({"exp": 10}, "secret"\) [\#51](https://github.com/jwt/ruby-jwt/issues/51) **Merged pull requests:** - Accept expiration claims as string [\#53](https://github.com/jwt/ruby-jwt/pull/53) ([yarmand](https://github.com/yarmand)) ## [jwt-1.2.0](https://github.com/jwt/ruby-jwt/tree/jwt-1.2.0) (2014-11-24) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.13...jwt-1.2.0) **Closed issues:** - set token to expire [\#42](https://github.com/jwt/ruby-jwt/issues/42) **Merged pull requests:** - Added support for `exp` claim [\#45](https://github.com/jwt/ruby-jwt/pull/45) ([zshannon](https://github.com/zshannon)) - rspec 3 breaks passing tests [\#44](https://github.com/jwt/ruby-jwt/pull/44) ([zshannon](https://github.com/zshannon)) ## [jwt-0.1.13](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.13) (2014-05-08) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.0.0...jwt-0.1.13) **Closed issues:** - yanking of version 0.1.12 causes issues [\#39](https://github.com/jwt/ruby-jwt/issues/39) - Semantic versioning [\#37](https://github.com/jwt/ruby-jwt/issues/37) - Update gem to get latest changes [\#36](https://github.com/jwt/ruby-jwt/issues/36) ## [jwt-1.0.0](https://github.com/jwt/ruby-jwt/tree/jwt-1.0.0) (2014-05-07) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.11...jwt-1.0.0) **Closed issues:** - API request - JWT::decoded\_header\(\) [\#26](https://github.com/jwt/ruby-jwt/issues/26) **Merged pull requests:** - return header along with playload after decoding [\#35](https://github.com/jwt/ruby-jwt/pull/35) ([sawyerzhang](https://github.com/sawyerzhang)) - Raise JWT::DecodeError on nil token [\#34](https://github.com/jwt/ruby-jwt/pull/34) ([tjmw](https://github.com/tjmw)) - Make MultiJson optional for Ruby 1.9+ [\#33](https://github.com/jwt/ruby-jwt/pull/33) ([petergoldstein](https://github.com/petergoldstein)) - Allow access to header and payload without signature verification [\#32](https://github.com/jwt/ruby-jwt/pull/32) ([petergoldstein](https://github.com/petergoldstein)) - Update specs to use RSpec 3.0.x syntax [\#31](https://github.com/jwt/ruby-jwt/pull/31) ([petergoldstein](https://github.com/petergoldstein)) - Travis - Add Ruby 2.0.0, 2.1.0, Rubinius [\#30](https://github.com/jwt/ruby-jwt/pull/30) ([petergoldstein](https://github.com/petergoldstein)) ## [jwt-0.1.11](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.11) (2014-01-17) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.10...jwt-0.1.11) **Closed issues:** - url safe encode and decode [\#28](https://github.com/jwt/ruby-jwt/issues/28) - Release [\#27](https://github.com/jwt/ruby-jwt/issues/27) **Merged pull requests:** - fixed urlsafe base64 encoding [\#29](https://github.com/jwt/ruby-jwt/pull/29) ([tobscher](https://github.com/tobscher)) ## [jwt-0.1.10](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.10) (2014-01-10) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.8...jwt-0.1.10) **Closed issues:** - change to signature of JWT.decode method [\#14](https://github.com/jwt/ruby-jwt/issues/14) **Merged pull requests:** - Fix warning: assigned but unused variable - e [\#25](https://github.com/jwt/ruby-jwt/pull/25) ([sferik](https://github.com/sferik)) - Echoe doesn't define a license= method [\#24](https://github.com/jwt/ruby-jwt/pull/24) ([sferik](https://github.com/sferik)) - Use OpenSSL::Digest instead of deprecated OpenSSL::Digest::Digest [\#23](https://github.com/jwt/ruby-jwt/pull/23) ([JuanitoFatas](https://github.com/JuanitoFatas)) - Handle some invalid JWTs [\#22](https://github.com/jwt/ruby-jwt/pull/22) ([steved](https://github.com/steved)) - Add MIT license to gemspec [\#21](https://github.com/jwt/ruby-jwt/pull/21) ([nycvotes-dev](https://github.com/nycvotes-dev)) - Tweaks and improvements [\#20](https://github.com/jwt/ruby-jwt/pull/20) ([threedaymonk](https://github.com/threedaymonk)) - Don't leave errors in OpenSSL.errors when there is a decoding error. [\#19](https://github.com/jwt/ruby-jwt/pull/19) ([lowellk](https://github.com/lowellk)) ## [jwt-0.1.8](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.8) (2013-03-14) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.7...jwt-0.1.8) **Merged pull requests:** - Contrib and update [\#18](https://github.com/jwt/ruby-jwt/pull/18) ([threedaymonk](https://github.com/threedaymonk)) - Verify if verify is truthy \(not just true\) [\#17](https://github.com/jwt/ruby-jwt/pull/17) ([threedaymonk](https://github.com/threedaymonk)) ## [jwt-0.1.7](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.7) (2013-03-07) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.6...jwt-0.1.7) **Merged pull requests:** - Catch MultiJson::LoadError and reraise as JWT::DecodeError [\#16](https://github.com/jwt/ruby-jwt/pull/16) ([rwygand](https://github.com/rwygand)) ## [jwt-0.1.6](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.6) (2013-03-05) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.5...jwt-0.1.6) **Merged pull requests:** - Fixes a theoretical timing attack [\#15](https://github.com/jwt/ruby-jwt/pull/15) ([mgates](https://github.com/mgates)) - Use StandardError as parent for DecodeError [\#13](https://github.com/jwt/ruby-jwt/pull/13) ([Oscil8](https://github.com/Oscil8)) ## [jwt-0.1.5](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.5) (2012-07-20) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.4...jwt-0.1.5) **Closed issues:** - Unable to specify signature header fields [\#7](https://github.com/jwt/ruby-jwt/issues/7) **Merged pull requests:** - MultiJson dependency uses ~\> but should be \>= [\#12](https://github.com/jwt/ruby-jwt/pull/12) ([sporkmonger](https://github.com/sporkmonger)) - Oops. :-\) [\#11](https://github.com/jwt/ruby-jwt/pull/11) ([sporkmonger](https://github.com/sporkmonger)) - Fix issue with signature verification in JRuby [\#10](https://github.com/jwt/ruby-jwt/pull/10) ([sporkmonger](https://github.com/sporkmonger)) - Depend on MultiJson [\#9](https://github.com/jwt/ruby-jwt/pull/9) ([lautis](https://github.com/lautis)) - Allow for custom headers on encode and decode [\#8](https://github.com/jwt/ruby-jwt/pull/8) ([dgrijalva](https://github.com/dgrijalva)) - Missing development dependency for echoe gem. [\#6](https://github.com/jwt/ruby-jwt/pull/6) ([sporkmonger](https://github.com/sporkmonger)) ## [jwt-0.1.4](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.4) (2011-11-11) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.3...jwt-0.1.4) **Merged pull requests:** - Fix for RSA verification [\#5](https://github.com/jwt/ruby-jwt/pull/5) ([jordan-brough](https://github.com/jordan-brough)) ## [jwt-0.1.3](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.3) (2011-06-30) [Full Changelog](https://github.com/jwt/ruby-jwt/compare/10d7492ea325c65fce41191c73cd90d4de494772...jwt-0.1.3) **Closed issues:** - signatures calculated incorrectly \(hexdigest instead of digest\) [\#1](https://github.com/jwt/ruby-jwt/issues/1) **Merged pull requests:** - Bumped a version and added a .gemspec using rake build\_gemspec [\#3](https://github.com/jwt/ruby-jwt/pull/3) ([zhitomirskiyi](https://github.com/zhitomirskiyi)) - Added RSA support [\#2](https://github.com/jwt/ruby-jwt/pull/2) ([zhitomirskiyi](https://github.com/zhitomirskiyi)) \* *This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)* ruby-jwt-2.7.1/CODE_OF_CONDUCT.md000066400000000000000000000121371444067622100161150ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at antmanj@gmail.com. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. ruby-jwt-2.7.1/CONTRIBUTING.md000066400000000000000000000060001444067622100155370ustar00rootroot00000000000000# Contributing to [ruby-jwt](https://github.com/jwt/ruby-jwt) ## Forking the project Fork the project on GitHub and clone your own fork. Instuctions on forking can be found from the [GitHub Docs](https://docs.github.com/en/get-started/quickstart/fork-a-repo) ``` git clone git@github.com:you/ruby-jwt.git cd ruby-jwt git remote add upstream https://github.com/jwt/ruby-jwt ``` ## Create a branch for your implementation Make sure you have the latest upstream main branch of the project. ``` git fetch --all git checkout main git rebase upstream/main git push origin main git checkout -b fix-a-little-problem ``` ## Running the tests and linter Before you start with your implementation make sure you are able to get a successful test run with the current revision. The tests are written with rspec and [Appraisal](https://github.com/thoughtbot/appraisal) is used to ensure compatibility with 3rd party dependencies providing cryptographic features. [Rubocop](https://github.com/rubocop/rubocop) is used to enforce the Ruby style. To run the complete set of tests and linter run the following ```bash bundle install bundle exec appraisal rake test bundle exec rubocop ``` ## Implement your feature Implement tests and your change. Don't be shy adding a little something in the [README](README.md). Add a short description of the change in either the `Features` or `Fixes` section in the [CHANGELOG](CHANGELOG.md) file. The form of the row (You need to return to the row when you know the pull request id) ``` - Fix a little problem [#123](https://github.com/jwt/ruby-jwt/pull/123) - [@you](https://github.com/you). ``` ## Push your branch and create a pull request Before pushing make sure the tests pass and RuboCop is happy. ``` bundle exec appraisal rake test bundle exec rubocop git push origin fix-a-little-problem ``` Make a new pull request on the [ruby-jwt project](https://github.com/jwt/ruby-jwt/pulls) with a description what the change is about. ## Update the CHANGELOG, again Update the [CHANGELOG](CHANGELOG.md) with the pull request id from the previous step. You can ammend the previous commit with the updated changelog change and force push your branch. The PR will get automatically updated. ``` git add CHANGELOG.md git commit --amend --no-edit git push origin fix-a-little-problem -f ``` ## Keep an eye on your pull request A maintainer will review and probably merge you changes when time allows, be patient. ## Keeping your branch up-to-date It's recommended that you keep your branch up-to-date by rebasing to the upstream main. ``` git fetch upstream git checkout fix-a-little-problem git rebase upstream/main git push origin fix-a-little-problem -f ``` # Releasing a new version The version is using the [Semantic Versioning](http://semver.org/) and the version is located in the [version.rb](lib/jwt/version.rb) file. Also update the [CHANGELOG](CHANGELOG.md) to reflect the upcoming version release. ```bash rake release ``` **If you want a release cut with your PR, please include a version bump according to ** ruby-jwt-2.7.1/Gemfile000066400000000000000000000002251444067622100146040ustar00rootroot00000000000000# frozen_string_literal: true source 'https://rubygems.org' gemspec gem 'rubocop', '< 1.32' # Keep .codeclimate.yml channel in sync with this one ruby-jwt-2.7.1/LICENSE000066400000000000000000000020401444067622100143130ustar00rootroot00000000000000Copyright (c) 2011 Jeff Lindsay Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ruby-jwt-2.7.1/README.md000066400000000000000000000630371444067622100146020ustar00rootroot00000000000000# JWT [![Gem Version](https://badge.fury.io/rb/jwt.svg)](https://badge.fury.io/rb/jwt) [![Build Status](https://github.com/jwt/ruby-jwt/workflows/test/badge.svg?branch=main)](https://github.com/jwt/ruby-jwt/actions) [![Code Climate](https://codeclimate.com/github/jwt/ruby-jwt/badges/gpa.svg)](https://codeclimate.com/github/jwt/ruby-jwt) [![Test Coverage](https://codeclimate.com/github/jwt/ruby-jwt/badges/coverage.svg)](https://codeclimate.com/github/jwt/ruby-jwt/coverage) [![Issue Count](https://codeclimate.com/github/jwt/ruby-jwt/badges/issue_count.svg)](https://codeclimate.com/github/jwt/ruby-jwt) A ruby implementation of the [RFC 7519 OAuth JSON Web Token (JWT)](https://tools.ietf.org/html/rfc7519) standard. If you have further questions related to development or usage, join us: [ruby-jwt google group](https://groups.google.com/forum/#!forum/ruby-jwt). ## Announcements * Ruby 2.4 support was dropped in version 2.4.0 * Ruby 1.9.3 support was dropped at December 31st, 2016. * Version 1.5.3 yanked. See: [#132](https://github.com/jwt/ruby-jwt/issues/132) and [#133](https://github.com/jwt/ruby-jwt/issues/133) See [CHANGELOG.md](CHANGELOG.md) for a complete set of changes. ## Sponsors |Logo|Message| |-|-| |![auth0 logo](https://user-images.githubusercontent.com/83319/31722733-de95bbde-b3ea-11e7-96bf-4f4e8f915588.png)|If you want to quickly add secure token-based authentication to Ruby projects, feel free to check Auth0's Ruby SDK and free plan at [auth0.com/developers](https://auth0.com/developers?utm_source=GHsponsor&utm_medium=GHsponsor&utm_campaign=rubyjwt&utm_content=auth)| ## Installing ### Using Rubygems: ```bash gem install jwt ``` ### Using Bundler: Add the following to your Gemfile ``` gem 'jwt' ``` And run `bundle install` ## Algorithms and Usage The JWT spec supports NONE, HMAC, RSASSA, ECDSA and RSASSA-PSS algorithms for cryptographic signing. Currently the jwt gem supports NONE, HMAC, RSASSA and ECDSA. If you are using cryptographic signing, you need to specify the algorithm in the options hash whenever you call JWT.decode to ensure that an attacker [cannot bypass the algorithm verification step](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). **It is strongly recommended that you hard code the algorithm, as you may leave yourself vulnerable by dynamically picking the algorithm** See: [ JSON Web Algorithms (JWA) 3.1. "alg" (Algorithm) Header Parameter Values for JWS](https://tools.ietf.org/html/rfc7518#section-3.1) ### **NONE** * none - unsigned token ```ruby require 'jwt' payload = { data: 'test' } # IMPORTANT: set nil as password parameter token = JWT.encode payload, nil, 'none' # eyJhbGciOiJub25lIn0.eyJkYXRhIjoidGVzdCJ9. puts token # Set password to nil and validation to false otherwise this won't work decoded_token = JWT.decode token, nil, false # Array # [ # {"data"=>"test"}, # payload # {"alg"=>"none"} # header # ] puts decoded_token ``` ### **HMAC** * HS256 - HMAC using SHA-256 hash algorithm * HS512256 - HMAC using SHA-512-256 hash algorithm (only available with RbNaCl; see note below) * HS384 - HMAC using SHA-384 hash algorithm * HS512 - HMAC using SHA-512 hash algorithm ```ruby # The secret must be a string. With OpenSSL 3.0/openssl gem `<3.0.1`, JWT::DecodeError will be raised if it isn't provided. hmac_secret = 'my$ecretK3y' token = JWT.encode payload, hmac_secret, 'HS256' # eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.pNIWIL34Jo13LViZAJACzK6Yf0qnvT_BuwOxiMCPE-Y puts token decoded_token = JWT.decode token, hmac_secret, true, { algorithm: 'HS256' } # Array # [ # {"data"=>"test"}, # payload # {"alg"=>"HS256"} # header # ] puts decoded_token ``` Note: If [RbNaCl](https://github.com/RubyCrypto/rbnacl) is loadable, ruby-jwt will use it for HMAC-SHA256, HMAC-SHA512-256, and HMAC-SHA512. RbNaCl prior to 6.0.0 only support a maximum key size of 32 bytes for these algorithms. [RbNaCl](https://github.com/RubyCrypto/rbnacl) requires [libsodium](https://github.com/jedisct1/libsodium), it can be installed on MacOS with `brew install libsodium`. ### **RSA** * RS256 - RSA using SHA-256 hash algorithm * RS384 - RSA using SHA-384 hash algorithm * RS512 - RSA using SHA-512 hash algorithm ```ruby rsa_private = OpenSSL::PKey::RSA.generate 2048 rsa_public = rsa_private.public_key token = JWT.encode payload, rsa_private, 'RS256' # eyJhbGciOiJSUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.GplO4w1spRgvEJQ3-FOtZr-uC8L45Jt7SN0J4woBnEXG_OZBSNcZjAJWpjadVYEe2ev3oUBFDYM1N_-0BTVeFGGYvMewu8E6aMjSZvOpf1cZBew-Vt4poSq7goG2YRI_zNPt3af2lkPqXD796IKC5URrEvcgF5xFQ-6h07XRDpSRx1ECrNsUOt7UM3l1IB4doY11GzwQA5sHDTmUZ0-kBT76ZMf12Srg_N3hZwphxBtudYtN5VGZn420sVrQMdPE_7Ni3EiWT88j7WCr1xrF60l8sZT3yKCVleG7D2BEXacTntB7GktBv4Xo8OKnpwpqTpIlC05dMowMkz3rEAAYbQ puts token decoded_token = JWT.decode token, rsa_public, true, { algorithm: 'RS256' } # Array # [ # {"data"=>"test"}, # payload # {"alg"=>"RS256"} # header # ] puts decoded_token ``` ### **ECDSA** * ES256 - ECDSA using P-256 and SHA-256 * ES384 - ECDSA using P-384 and SHA-384 * ES512 - ECDSA using P-521 and SHA-512 * ES256K - ECDSA using P-256K and SHA-256 ```ruby ecdsa_key = OpenSSL::PKey::EC.generate('prime256v1') token = JWT.encode payload, ecdsa_key, 'ES256' # eyJhbGciOiJFUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.AlLW--kaF7EX1NMX9WJRuIW8NeRJbn2BLXHns7Q5TZr7Hy3lF6MOpMlp7GoxBFRLISQ6KrD0CJOrR8aogEsPeg puts token decoded_token = JWT.decode token, ecdsa_key, true, { algorithm: 'ES256' } # Array # [ # {"test"=>"data"}, # payload # {"alg"=>"ES256"} # header # ] puts decoded_token ``` ### **EDDSA** In order to use this algorithm you need to add the `RbNaCl` gem to you `Gemfile`. ```ruby gem 'rbnacl' ``` For more detailed installation instruction check the official [repository](https://github.com/RubyCrypto/rbnacl) on GitHub. * ED25519 ```ruby private_key = RbNaCl::Signatures::Ed25519::SigningKey.new('abcdefghijklmnopqrstuvwxyzABCDEF') public_key = private_key.verify_key token = JWT.encode payload, private_key, 'ED25519' # eyJhbGciOiJFRDI1NTE5In0.eyJkYXRhIjoidGVzdCJ9.6xIztXyOupskddGA_RvKU76V9b2dCQUYhoZEVFnRimJoPYIzZ2Fm47CWw8k2NTCNpgfAuxg9OXjaiVK7MvrbCQ puts token decoded_token = JWT.decode token, public_key, true, { algorithm: 'ED25519' } # Array # [ # {"test"=>"data"}, # payload # {"alg"=>"ED25519"} # header # ] ``` ### **RSASSA-PSS** In order to use this algorithm you need to add the `openssl` gem to your `Gemfile` with a version greater or equal to `2.1`. ```ruby gem 'openssl', '~> 2.1' ``` * PS256 - RSASSA-PSS using SHA-256 hash algorithm * PS384 - RSASSA-PSS using SHA-384 hash algorithm * PS512 - RSASSA-PSS using SHA-512 hash algorithm ```ruby rsa_private = OpenSSL::PKey::RSA.generate 2048 rsa_public = rsa_private.public_key token = JWT.encode payload, rsa_private, 'PS256' # eyJhbGciOiJQUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.KEmqagMUHM-NcmXo6818ZazVTIAkn9qU9KQFT1c5Iq91n0KRpAI84jj4ZCdkysDlWokFs3Dmn4MhcXP03oJKLFgnoPL40_Wgg9iFr0jnIVvnMUp1kp2RFUbL0jqExGTRA3LdAhuvw6ZByGD1bkcWjDXygjQw-hxILrT1bENjdr0JhFd-cB0-ps5SB0mwhFNcUw-OM3Uu30B1-mlFaelUY8jHJYKwLTZPNxHzndt8RGXF8iZLp7dGb06HSCKMcVzhASGMH4ZdFystRe2hh31cwcvnl-Eo_D4cdwmpN3Abhk_8rkxawQJR3duh8HNKc4AyFPo7SabEaSu2gLnLfN3yfg puts token decoded_token = JWT.decode token, rsa_public, true, { algorithm: 'PS256' } # Array # [ # {"data"=>"test"}, # payload # {"alg"=>"PS256"} # header # ] puts decoded_token ``` ### **Custom algorithms** An object implementing custom signing or verification behaviour can be passed in the `algorithm` option when encoding and decoding. The given object needs to implement the method `valid_alg?` and `verify` and/or `alg` and `sign`, depending if object is used for encoding or decoding. ```ruby module CustomHS512Algorithm def self.alg 'HS512' end def self.valid_alg?(alg_to_validate) alg_to_validate == alg end def self.sign(data:, signing_key:) OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha512'), data, signing_key) end def self.verify(data:, signature:, verification_key:) ::OpenSSL.secure_compare(sign(data: data, signing_key: verification_key), signature) end end token = ::JWT.encode({'pay' => 'load'}, 'secret', CustomHS512Algorithm) payload, header = ::JWT.decode(token, 'secret', true, algorithm: CustomHS512Algorithm) ``` ## Support for reserved claim names JSON Web Token defines some reserved claim names and defines how they should be used. JWT supports these reserved claim names: - 'exp' (Expiration Time) Claim - 'nbf' (Not Before Time) Claim - 'iss' (Issuer) Claim - 'aud' (Audience) Claim - 'jti' (JWT ID) Claim - 'iat' (Issued At) Claim - 'sub' (Subject) Claim ## Add custom header fields Ruby-jwt gem supports custom [header fields](https://tools.ietf.org/html/rfc7519#section-5) To add custom header fields you need to pass `header_fields` parameter ```ruby token = JWT.encode payload, key, algorithm='HS256', header_fields={} ``` **Example:** ```ruby require 'jwt' payload = { data: 'test' } # IMPORTANT: set nil as password parameter token = JWT.encode payload, nil, 'none', { typ: 'JWT' } # eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJkYXRhIjoidGVzdCJ9. puts token # Set password to nil and validation to false otherwise this won't work decoded_token = JWT.decode token, nil, false # Array # [ # {"data"=>"test"}, # payload # {"typ"=>"JWT", "alg"=>"none"} # header # ] puts decoded_token ``` ### Expiration Time Claim From [Oauth JSON Web Token 4.1.4. "exp" (Expiration Time) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.4): > The `exp` (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the `exp` claim requires that the current date/time MUST be before the expiration date/time listed in the `exp` claim. Implementers MAY provide for some small `leeway`, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a ***NumericDate*** value. Use of this claim is OPTIONAL. **Handle Expiration Claim** ```ruby exp = Time.now.to_i + 4 * 3600 exp_payload = { data: 'data', exp: exp } token = JWT.encode exp_payload, hmac_secret, 'HS256' begin decoded_token = JWT.decode token, hmac_secret, true, { algorithm: 'HS256' } rescue JWT::ExpiredSignature # Handle expired token, e.g. logout user or deny access end ``` The Expiration Claim verification can be disabled. ```ruby # Decode token without raising JWT::ExpiredSignature error JWT.decode token, hmac_secret, true, { verify_expiration: false, algorithm: 'HS256' } ``` **Adding Leeway** ```ruby exp = Time.now.to_i - 10 leeway = 30 # seconds exp_payload = { data: 'data', exp: exp } # build expired token token = JWT.encode exp_payload, hmac_secret, 'HS256' begin # add leeway to ensure the token is still accepted decoded_token = JWT.decode token, hmac_secret, true, { exp_leeway: leeway, algorithm: 'HS256' } rescue JWT::ExpiredSignature # Handle expired token, e.g. logout user or deny access end ``` ### Not Before Time Claim From [Oauth JSON Web Token 4.1.5. "nbf" (Not Before) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.5): > The `nbf` (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the `nbf` claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the `nbf` claim. Implementers MAY provide for some small `leeway`, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a ***NumericDate*** value. Use of this claim is OPTIONAL. **Handle Not Before Claim** ```ruby nbf = Time.now.to_i - 3600 nbf_payload = { data: 'data', nbf: nbf } token = JWT.encode nbf_payload, hmac_secret, 'HS256' begin decoded_token = JWT.decode token, hmac_secret, true, { algorithm: 'HS256' } rescue JWT::ImmatureSignature # Handle invalid token, e.g. logout user or deny access end ``` The Not Before Claim verification can be disabled. ```ruby # Decode token without raising JWT::ImmatureSignature error JWT.decode token, hmac_secret, true, { verify_not_before: false, algorithm: 'HS256' } ``` **Adding Leeway** ```ruby nbf = Time.now.to_i + 10 leeway = 30 nbf_payload = { data: 'data', nbf: nbf } # build expired token token = JWT.encode nbf_payload, hmac_secret, 'HS256' begin # add leeway to ensure the token is valid decoded_token = JWT.decode token, hmac_secret, true, { nbf_leeway: leeway, algorithm: 'HS256' } rescue JWT::ImmatureSignature # Handle invalid token, e.g. logout user or deny access end ``` ### Issuer Claim From [Oauth JSON Web Token 4.1.1. "iss" (Issuer) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.1): > The `iss` (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The `iss` value is a case-sensitive string containing a ***StringOrURI*** value. Use of this claim is OPTIONAL. You can pass multiple allowed issuers as an Array, verification will pass if one of them matches the `iss` value in the payload. ```ruby iss = 'My Awesome Company Inc. or https://my.awesome.website/' iss_payload = { data: 'data', iss: iss } token = JWT.encode iss_payload, hmac_secret, 'HS256' begin # Add iss to the validation to check if the token has been manipulated decoded_token = JWT.decode token, hmac_secret, true, { iss: iss, verify_iss: true, algorithm: 'HS256' } rescue JWT::InvalidIssuerError # Handle invalid token, e.g. logout user or deny access end ``` You can also pass a Regexp or Proc (with arity 1), verification will pass if the regexp matches or the proc returns truthy. On supported ruby versions (>= 2.5) you can also delegate to methods, on older versions you will have to convert them to proc (using `to_proc`) ```ruby JWT.decode token, hmac_secret, true, iss: %r'https://my.awesome.website/', verify_iss: true, algorithm: 'HS256' ``` ```ruby JWT.decode token, hmac_secret, true, iss: ->(issuer) { issuer.start_with?('My Awesome Company Inc') }, verify_iss: true, algorithm: 'HS256' ``` ```ruby JWT.decode token, hmac_secret, true, iss: method(:valid_issuer?), verify_iss: true, algorithm: 'HS256' # somewhere in the same class: def valid_issuer?(issuer) # custom validation end ``` ### Audience Claim From [Oauth JSON Web Token 4.1.3. "aud" (Audience) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.3): > The `aud` (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the `aud` claim when this claim is present, then the JWT MUST be rejected. In the general case, the `aud` value is an array of case-sensitive strings, each containing a ***StringOrURI*** value. In the special case when the JWT has one audience, the `aud` value MAY be a single case-sensitive string containing a ***StringOrURI*** value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL. ```ruby aud = ['Young', 'Old'] aud_payload = { data: 'data', aud: aud } token = JWT.encode aud_payload, hmac_secret, 'HS256' begin # Add aud to the validation to check if the token has been manipulated decoded_token = JWT.decode token, hmac_secret, true, { aud: aud, verify_aud: true, algorithm: 'HS256' } rescue JWT::InvalidAudError # Handle invalid token, e.g. logout user or deny access puts 'Audience Error' end ``` ### JWT ID Claim From [Oauth JSON Web Token 4.1.7. "jti" (JWT ID) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.7): > The `jti` (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The `jti` claim can be used to prevent the JWT from being replayed. The `jti` value is a case-sensitive string. Use of this claim is OPTIONAL. ```ruby # Use the secret and iat to create a unique key per request to prevent replay attacks jti_raw = [hmac_secret, iat].join(':').to_s jti = Digest::MD5.hexdigest(jti_raw) jti_payload = { data: 'data', iat: iat, jti: jti } token = JWT.encode jti_payload, hmac_secret, 'HS256' begin # If :verify_jti is true, validation will pass if a JTI is present #decoded_token = JWT.decode token, hmac_secret, true, { verify_jti: true, algorithm: 'HS256' } # Alternatively, pass a proc with your own code to check if the JTI has already been used decoded_token = JWT.decode token, hmac_secret, true, { verify_jti: proc { |jti| my_validation_method(jti) }, algorithm: 'HS256' } # or decoded_token = JWT.decode token, hmac_secret, true, { verify_jti: proc { |jti, payload| my_validation_method(jti, payload) }, algorithm: 'HS256' } rescue JWT::InvalidJtiError # Handle invalid token, e.g. logout user or deny access puts 'Error' end ``` ### Issued At Claim From [Oauth JSON Web Token 4.1.6. "iat" (Issued At) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.6): > The `iat` (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. The `leeway` option is not taken into account when verifying this claim. The `iat_leeway` option was removed in version 2.2.0. Its value MUST be a number containing a ***NumericDate*** value. Use of this claim is OPTIONAL. **Handle Issued At Claim** ```ruby iat = Time.now.to_i iat_payload = { data: 'data', iat: iat } token = JWT.encode iat_payload, hmac_secret, 'HS256' begin # Add iat to the validation to check if the token has been manipulated decoded_token = JWT.decode token, hmac_secret, true, { verify_iat: true, algorithm: 'HS256' } rescue JWT::InvalidIatError # Handle invalid token, e.g. logout user or deny access end ``` ### Subject Claim From [Oauth JSON Web Token 4.1.2. "sub" (Subject) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.2): > The `sub` (subject) claim identifies the principal that is the subject of the JWT. The Claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The sub value is a case-sensitive string containing a ***StringOrURI*** value. Use of this claim is OPTIONAL. ```ruby sub = 'Subject' sub_payload = { data: 'data', sub: sub } token = JWT.encode sub_payload, hmac_secret, 'HS256' begin # Add sub to the validation to check if the token has been manipulated decoded_token = JWT.decode token, hmac_secret, true, { sub: sub, verify_sub: true, algorithm: 'HS256' } rescue JWT::InvalidSubError # Handle invalid token, e.g. logout user or deny access end ``` ### Finding a Key To dynamically find the key for verifying the JWT signature, pass a block to the decode block. The block receives headers and the original payload as parameters. It should return with the key to verify the signature that was used to sign the JWT. ```ruby issuers = %w[My_Awesome_Company1 My_Awesome_Company2] iss_payload = { data: 'data', iss: issuers.first } secrets = { issuers.first => hmac_secret, issuers.last => 'hmac_secret2' } token = JWT.encode iss_payload, hmac_secret, 'HS256' begin # Add iss to the validation to check if the token has been manipulated decoded_token = JWT.decode(token, nil, true, { iss: issuers, verify_iss: true, algorithm: 'HS256' }) do |_headers, payload| secrets[payload['iss']] end rescue JWT::InvalidIssuerError # Handle invalid token, e.g. logout user or deny access end ``` ### Required Claims You can specify claims that must be present for decoding to be successful. JWT::MissingRequiredClaim will be raised if any are missing ```ruby # Will raise a JWT::MissingRequiredClaim error if the 'exp' claim is absent JWT.decode token, hmac_secret, true, { required_claims: ['exp'], algorithm: 'HS256' } ``` ### X.509 certificates in x5c header A JWT signature can be verified using certificate(s) given in the `x5c` header. Before doing that, the trustworthiness of these certificate(s) must be established. This is done in accordance with RFC 5280 which (among other things) verifies the certificate(s) are issued by a trusted root certificate, the timestamps are valid, and none of the certificate(s) are revoked (i.e. being present in the root certificate's Certificate Revocation List). ```ruby root_certificates = [] # trusted `OpenSSL::X509::Certificate` objects crl_uris = root_certificates.map(&:crl_uris) crls = crl_uris.map do |uri| # look up cached CRL by `uri` and return it if found, otherwise continue crl = Net::HTTP.get(uri) crl = OpenSSL::X509::CRL.new(crl) # cache `crl` using `uri` as the key, expiry set to `crl.next_update` timestamp end begin JWT.decode(token, nil, true, { x5c: { root_certificates: root_certificates, crls: crls }) rescue JWT::DecodeError # Handle error, e.g. x5c header certificate revoked or expired end ``` ### JSON Web Key (JWK) JWK is a JSON structure representing a cryptographic key. This gem currently supports RSA, EC, OKP and HMAC keys. OKP support requires [RbNaCl](https://github.com/RubyCrypto/rbnacl) and currently only supports the Ed25519 curve. To encode a JWT using your JWK: ```ruby optional_parameters = { kid: 'my-kid', use: 'sig', alg: 'RS512' } jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), optional_parameters) # Encoding payload = { data: 'data' } token = JWT.encode(payload, jwk.signing_key, jwk[:alg], kid: jwk[:kid]) # JSON Web Key Set for advertising your signing keys jwks_hash = JWT::JWK::Set.new(jwk).export ``` To decode a JWT using a trusted entity's JSON Web Key Set (JWKS): ```ruby jwks = JWT::JWK::Set.new(jwks_hash) jwks.filter! {|key| key[:use] == 'sig' } # Signing keys only! algorithms = jwks.map { |key| key[:alg] }.compact.uniq JWT.decode(token, nil, true, algorithms: algorithms, jwks: jwks) ``` The `jwks` option can also be given as a lambda that evaluates every time a kid is resolved. This can be used to implement caching of remotely fetched JWK Sets. If the requested `kid` is not found from the given set the loader will be called a second time with the `kid_not_found` option set to `true`. The application can choose to implement some kind of JWK cache invalidation or other mechanism to handle such cases. Tokens without a specified `kid` are rejected by default. This behaviour may be overwritten by setting the `allow_nil_kid` option for `decode` to `true`. ```ruby jwks_loader = ->(options) do # The jwk loader would fetch the set of JWKs from a trusted source. # To avoid malicious requests triggering cache invalidations there needs to be # some kind of grace time or other logic for determining the validity of the invalidation. # This example only allows cache invalidations every 5 minutes. if options[:kid_not_found] && @cache_last_update < Time.now.to_i - 300 logger.info("Invalidating JWK cache. #{options[:kid]} not found from previous cache") @cached_keys = nil end @cached_keys ||= begin @cache_last_update = Time.now.to_i # Replace with your own JWKS fetching routine jwks = JWT::JWK::Set.new(jwks_hash) jwks.select! { |key| key[:use] == 'sig' } # Signing Keys only jwks end end begin JWT.decode(token, nil, true, { algorithms: ['RS512'], jwks: jwks_loader }) rescue JWT::JWKError # Handle problems with the provided JWKs rescue JWT::DecodeError # Handle other decode related issues e.g. no kid in header, no matching public key found etc. end ``` ### Importing and exporting JSON Web Keys The ::JWT::JWK class can be used to import both JSON Web Keys and OpenSSL keys and export to either format with and without the private key included. To include the private key in the export pass the `include_private` parameter to the export method. ```ruby # Import a JWK Hash (showing an HMAC example) jwk = JWT::JWK.new({ kty: 'oct', k: 'my-secret', kid: 'my-kid' }) # Import an OpenSSL key # You can optionally add descriptive parameters to the JWK desc_params = { kid: 'my-kid', use: 'sig' } jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), desc_params) # Export as JWK Hash (public key only by default) jwk_hash = jwk.export jwk_hash_with_private_key = jwk.export(include_private: true) # Export as OpenSSL key public_key = jwk.verify_key private_key = jwk.signing_key if jwk.private? # You can also import and export entire JSON Web Key Sets jwks_hash = { keys: [{ kty: 'oct', k: 'my-secret', kid: 'my-kid' }] } jwks = JWT::JWK::Set.new(jwks_hash) jwks_hash = jwks.export ``` ### Key ID (kid) and JWKs The key id (kid) generation in the gem is a custom algorithm and not based on any standards. To use a standardized JWK thumbprint (RFC 7638) as the kid for JWKs a generator type can be specified in the global configuration or can be given to the JWK instance on initialization. ```ruby JWT.configuration.jwk.kid_generator_type = :rfc7638_thumbprint # OR JWT.configuration.jwk.kid_generator = ::JWT::JWK::Thumbprint # OR jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), nil, kid_generator: ::JWT::JWK::Thumbprint) jwk_hash = jwk.export thumbprint_as_the_kid = jwk_hash[:kid] ``` # Development and Tests We depend on [Bundler](http://rubygems.org/gems/bundler) for defining gemspec and performing releases to rubygems.org, which can be done with ```bash rake release ``` The tests are written with rspec. [Appraisal](https://github.com/thoughtbot/appraisal) is used to ensure compatibility with 3rd party dependencies providing cryptographic features. ```bash bundle install bundle exec appraisal rake test ``` ## How to contribute See [CONTRIBUTING](CONTRIBUTING.md). ## Contributors See [AUTHORS](AUTHORS). ## License See [LICENSE](LICENSE). ruby-jwt-2.7.1/Rakefile000066400000000000000000000003611444067622100147570ustar00rootroot00000000000000# frozen_string_literal: true require 'bundler/setup' require 'bundler/gem_tasks' require 'rspec/core/rake_task' require 'rubocop/rake_task' RSpec::Core::RakeTask.new(:test) RuboCop::RakeTask.new(:rubocop) task default: %i[rubocop test] ruby-jwt-2.7.1/bin/000077500000000000000000000000001444067622100140625ustar00rootroot00000000000000ruby-jwt-2.7.1/bin/console.rb000077500000000000000000000005601444067622100160550ustar00rootroot00000000000000#!/usr/bin/env ruby # frozen_string_literal: true require 'bundler/setup' require 'jwt' # You can add fixtures and/or initialization code here to make experimenting # with your gem easier. You can also use a different console, if you like. # (If you use this, don't forget to add pry to your Gemfile!) # require "pry" # Pry.start require 'irb' IRB.start(__FILE__) ruby-jwt-2.7.1/bin/smoke.rb000077500000000000000000000004211444067622100155250ustar00rootroot00000000000000#!/usr/bin/env ruby # frozen_string_literal: true require 'jwt' puts "Running simple encode/decode test for #{::JWT.gem_version}" secret = 'secretkeyforsigning' token = ::JWT.encode({ con: 'tent' }, secret, 'HS256') ::JWT.decode(token, secret, true, algorithm: 'HS256') ruby-jwt-2.7.1/gemfiles/000077500000000000000000000000001444067622100151055ustar00rootroot00000000000000ruby-jwt-2.7.1/gemfiles/openssl.gemfile000066400000000000000000000002141444067622100201170ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "rubocop", "< 1.32" gem "openssl", "~> 2.1" gemspec path: "../" ruby-jwt-2.7.1/gemfiles/rbnacl-pre-6.gemfile000066400000000000000000000002101444067622100206200ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "rubocop", "< 1.32" gem "rbnacl", "< 6" gemspec path: "../" ruby-jwt-2.7.1/gemfiles/rbnacl.gemfile000066400000000000000000000002111444067622100176720ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "rubocop", "< 1.32" gem "rbnacl", ">= 6" gemspec path: "../" ruby-jwt-2.7.1/gemfiles/rbnacl_pre_6.gemfile000066400000000000000000000002101444067622100207640ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "rubocop", "< 1.32" gem "rbnacl", "< 6" gemspec path: "../" ruby-jwt-2.7.1/gemfiles/standalone.gemfile000066400000000000000000000001641444067622100205700ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "rubocop", "< 1.32" gemspec path: "../" ruby-jwt-2.7.1/lib/000077500000000000000000000000001444067622100140605ustar00rootroot00000000000000ruby-jwt-2.7.1/lib/jwt.rb000066400000000000000000000014761444067622100152210ustar00rootroot00000000000000# frozen_string_literal: true require 'jwt/version' require 'jwt/base64' require 'jwt/json' require 'jwt/decode' require 'jwt/configuration' require 'jwt/encode' require 'jwt/error' require 'jwt/jwk' # JSON Web Token implementation # # Should be up to date with the latest spec: # https://tools.ietf.org/html/rfc7519 module JWT extend ::JWT::Configuration module_function def encode(payload, key, algorithm = 'HS256', header_fields = {}) Encode.new(payload: payload, key: key, algorithm: algorithm, headers: header_fields).segments end def decode(jwt, key = nil, verify = true, options = {}, &keyfinder) # rubocop:disable Style/OptionalBooleanParameter Decode.new(jwt, key, verify, configuration.decode.to_h.merge(options), &keyfinder).decode_segments end end ruby-jwt-2.7.1/lib/jwt/000077500000000000000000000000001444067622100146645ustar00rootroot00000000000000ruby-jwt-2.7.1/lib/jwt/algos.rb000066400000000000000000000027711444067622100163250ustar00rootroot00000000000000# frozen_string_literal: true begin require 'rbnacl' rescue LoadError raise if defined?(RbNaCl) end require 'openssl' require 'jwt/algos/hmac' require 'jwt/algos/eddsa' require 'jwt/algos/ecdsa' require 'jwt/algos/rsa' require 'jwt/algos/ps' require 'jwt/algos/none' require 'jwt/algos/unsupported' require 'jwt/algos/algo_wrapper' module JWT module Algos extend self ALGOS = [Algos::Ecdsa, Algos::Rsa, Algos::Eddsa, Algos::Ps, Algos::None, Algos::Unsupported].tap do |l| if ::JWT.rbnacl_6_or_greater? require_relative 'algos/hmac_rbnacl' l.unshift(Algos::HmacRbNaCl) elsif ::JWT.rbnacl? require_relative 'algos/hmac_rbnacl_fixed' l.unshift(Algos::HmacRbNaClFixed) else l.unshift(Algos::Hmac) end end.freeze def find(algorithm) indexed[algorithm && algorithm.downcase] end def create(algorithm) Algos::AlgoWrapper.new(*find(algorithm)) end def implementation?(algorithm) (algorithm.respond_to?(:valid_alg?) && algorithm.respond_to?(:verify)) || (algorithm.respond_to?(:alg) && algorithm.respond_to?(:sign)) end private def indexed @indexed ||= begin fallback = [nil, Algos::Unsupported] ALGOS.each_with_object(Hash.new(fallback)) do |cls, hash| cls.const_get(:SUPPORTED).each do |alg| hash[alg.downcase] = [alg, cls] end end end end end end ruby-jwt-2.7.1/lib/jwt/algos/000077500000000000000000000000001444067622100157715ustar00rootroot00000000000000ruby-jwt-2.7.1/lib/jwt/algos/algo_wrapper.rb000066400000000000000000000010031444067622100207720ustar00rootroot00000000000000# frozen_string_literal: true module JWT module Algos class AlgoWrapper attr_reader :alg, :cls def initialize(alg, cls) @alg = alg @cls = cls end def valid_alg?(alg_to_check) alg&.casecmp(alg_to_check)&.zero? == true end def sign(data:, signing_key:) cls.sign(alg, data, signing_key) end def verify(data:, signature:, verification_key:) cls.verify(alg, verification_key, data, signature) end end end end ruby-jwt-2.7.1/lib/jwt/algos/ecdsa.rb000066400000000000000000000050011444067622100173710ustar00rootroot00000000000000# frozen_string_literal: true module JWT module Algos module Ecdsa module_function NAMED_CURVES = { 'prime256v1' => { algorithm: 'ES256', digest: 'sha256' }, 'secp256r1' => { # alias for prime256v1 algorithm: 'ES256', digest: 'sha256' }, 'secp384r1' => { algorithm: 'ES384', digest: 'sha384' }, 'secp521r1' => { algorithm: 'ES512', digest: 'sha512' }, 'secp256k1' => { algorithm: 'ES256K', digest: 'sha256' } }.freeze SUPPORTED = NAMED_CURVES.map { |_, c| c[:algorithm] }.uniq.freeze def sign(algorithm, msg, key) curve_definition = curve_by_name(key.group.curve_name) key_algorithm = curve_definition[:algorithm] if algorithm != key_algorithm raise IncorrectAlgorithm, "payload algorithm is #{algorithm} but #{key_algorithm} signing key was provided" end digest = OpenSSL::Digest.new(curve_definition[:digest]) asn1_to_raw(key.dsa_sign_asn1(digest.digest(msg)), key) end def verify(algorithm, public_key, signing_input, signature) curve_definition = curve_by_name(public_key.group.curve_name) key_algorithm = curve_definition[:algorithm] if algorithm != key_algorithm raise IncorrectAlgorithm, "payload algorithm is #{algorithm} but #{key_algorithm} verification key was provided" end digest = OpenSSL::Digest.new(curve_definition[:digest]) public_key.dsa_verify_asn1(digest.digest(signing_input), raw_to_asn1(signature, public_key)) rescue OpenSSL::PKey::PKeyError raise JWT::VerificationError, 'Signature verification raised' end def curve_by_name(name) NAMED_CURVES.fetch(name) do raise UnsupportedEcdsaCurve, "The ECDSA curve '#{name}' is not supported" end end def raw_to_asn1(signature, private_key) byte_size = (private_key.group.degree + 7) / 8 sig_bytes = signature[0..(byte_size - 1)] sig_char = signature[byte_size..-1] || '' OpenSSL::ASN1::Sequence.new([sig_bytes, sig_char].map { |int| OpenSSL::ASN1::Integer.new(OpenSSL::BN.new(int, 2)) }).to_der end def asn1_to_raw(signature, public_key) byte_size = (public_key.group.degree + 7) / 8 OpenSSL::ASN1.decode(signature).value.map { |value| value.value.to_s(2).rjust(byte_size, "\x00") }.join end end end end ruby-jwt-2.7.1/lib/jwt/algos/eddsa.rb000066400000000000000000000023041444067622100173750ustar00rootroot00000000000000# frozen_string_literal: true module JWT module Algos module Eddsa module_function SUPPORTED = %w[ED25519 EdDSA].freeze def sign(algorithm, msg, key) if key.class != RbNaCl::Signatures::Ed25519::SigningKey raise EncodeError, "Key given is a #{key.class} but has to be an RbNaCl::Signatures::Ed25519::SigningKey" end unless SUPPORTED.map(&:downcase).map(&:to_sym).include?(algorithm.downcase.to_sym) raise IncorrectAlgorithm, "payload algorithm is #{algorithm} but #{key.primitive} signing key was provided" end key.sign(msg) end def verify(algorithm, public_key, signing_input, signature) unless SUPPORTED.map(&:downcase).map(&:to_sym).include?(algorithm.downcase.to_sym) raise IncorrectAlgorithm, "payload algorithm is #{algorithm} but #{key.primitive} signing key was provided" end raise DecodeError, "key given is a #{public_key.class} but has to be a RbNaCl::Signatures::Ed25519::VerifyKey" if public_key.class != RbNaCl::Signatures::Ed25519::VerifyKey public_key.verify(signature, signing_input) rescue RbNaCl::CryptoError false end end end end ruby-jwt-2.7.1/lib/jwt/algos/hmac.rb000066400000000000000000000050151444067622100172270ustar00rootroot00000000000000# frozen_string_literal: true module JWT module Algos module Hmac module_function MAPPING = { 'HS256' => OpenSSL::Digest::SHA256, 'HS384' => OpenSSL::Digest::SHA384, 'HS512' => OpenSSL::Digest::SHA512 }.freeze SUPPORTED = MAPPING.keys def sign(algorithm, msg, key) key ||= '' raise JWT::DecodeError, 'HMAC key expected to be a String' unless key.is_a?(String) OpenSSL::HMAC.digest(MAPPING[algorithm].new, key, msg) rescue OpenSSL::HMACError => e if key == '' && e.message == 'EVP_PKEY_new_mac_key: malloc failure' raise JWT::DecodeError, 'OpenSSL 3.0 does not support nil or empty hmac_secret' end raise e end def verify(algorithm, key, signing_input, signature) SecurityUtils.secure_compare(signature, sign(algorithm, signing_input, key)) end # Copy of https://github.com/rails/rails/blob/v7.0.3.1/activesupport/lib/active_support/security_utils.rb # rubocop:disable Naming/MethodParameterName, Style/StringLiterals, Style/NumericPredicate module SecurityUtils # Constant time string comparison, for fixed length strings. # # The values compared should be of fixed length, such as strings # that have already been processed by HMAC. Raises in case of length mismatch. if defined?(OpenSSL.fixed_length_secure_compare) def fixed_length_secure_compare(a, b) OpenSSL.fixed_length_secure_compare(a, b) end else def fixed_length_secure_compare(a, b) raise ArgumentError, "string length mismatch." unless a.bytesize == b.bytesize l = a.unpack "C#{a.bytesize}" res = 0 b.each_byte { |byte| res |= byte ^ l.shift } res == 0 end end module_function :fixed_length_secure_compare # Secure string comparison for strings of variable length. # # While a timing attack would not be able to discern the content of # a secret compared via secure_compare, it is possible to determine # the secret length. This should be considered when using secure_compare # to compare weak, short secrets to user input. def secure_compare(a, b) a.bytesize == b.bytesize && fixed_length_secure_compare(a, b) end module_function :secure_compare end # rubocop:enable Naming/MethodParameterName, Style/StringLiterals, Style/NumericPredicate end end end ruby-jwt-2.7.1/lib/jwt/algos/hmac_rbnacl.rb000066400000000000000000000026241444067622100205530ustar00rootroot00000000000000# frozen_string_literal: true module JWT module Algos module HmacRbNaCl module_function MAPPING = { 'HS256' => ::RbNaCl::HMAC::SHA256, 'HS512256' => ::RbNaCl::HMAC::SHA512256, 'HS384' => nil, 'HS512' => ::RbNaCl::HMAC::SHA512 }.freeze SUPPORTED = MAPPING.keys def sign(algorithm, msg, key) if (hmac = resolve_algorithm(algorithm)) hmac.auth(key_for_rbnacl(hmac, key).encode('binary'), msg.encode('binary')) else Hmac.sign(algorithm, msg, key) end end def verify(algorithm, key, signing_input, signature) if (hmac = resolve_algorithm(algorithm)) hmac.verify(key_for_rbnacl(hmac, key).encode('binary'), signature.encode('binary'), signing_input.encode('binary')) else Hmac.verify(algorithm, key, signing_input, signature) end rescue ::RbNaCl::BadAuthenticatorError, ::RbNaCl::LengthError false end def key_for_rbnacl(hmac, key) key ||= '' raise JWT::DecodeError, 'HMAC key expected to be a String' unless key.is_a?(String) return padded_empty_key(hmac.key_bytes) if key == '' key end def resolve_algorithm(algorithm) MAPPING.fetch(algorithm) end def padded_empty_key(length) Array.new(length, 0x0).pack('C*').encode('binary') end end end end ruby-jwt-2.7.1/lib/jwt/algos/hmac_rbnacl_fixed.rb000066400000000000000000000027261444067622100217350ustar00rootroot00000000000000# frozen_string_literal: true module JWT module Algos module HmacRbNaClFixed module_function MAPPING = { 'HS256' => ::RbNaCl::HMAC::SHA256, 'HS512256' => ::RbNaCl::HMAC::SHA512256, 'HS384' => nil, 'HS512' => ::RbNaCl::HMAC::SHA512 }.freeze SUPPORTED = MAPPING.keys def sign(algorithm, msg, key) key ||= '' raise JWT::DecodeError, 'HMAC key expected to be a String' unless key.is_a?(String) if (hmac = resolve_algorithm(algorithm)) && key.bytesize <= hmac.key_bytes hmac.auth(padded_key_bytes(key, hmac.key_bytes), msg.encode('binary')) else Hmac.sign(algorithm, msg, key) end end def verify(algorithm, key, signing_input, signature) key ||= '' raise JWT::DecodeError, 'HMAC key expected to be a String' unless key.is_a?(String) if (hmac = resolve_algorithm(algorithm)) && key.bytesize <= hmac.key_bytes hmac.verify(padded_key_bytes(key, hmac.key_bytes), signature.encode('binary'), signing_input.encode('binary')) else Hmac.verify(algorithm, key, signing_input, signature) end rescue ::RbNaCl::BadAuthenticatorError, ::RbNaCl::LengthError false end def resolve_algorithm(algorithm) MAPPING.fetch(algorithm) end def padded_key_bytes(key, bytesize) key.bytes.fill(0, key.bytesize...bytesize).pack('C*') end end end end ruby-jwt-2.7.1/lib/jwt/algos/none.rb000066400000000000000000000003501444067622100172530ustar00rootroot00000000000000# frozen_string_literal: true module JWT module Algos module None module_function SUPPORTED = %w[none].freeze def sign(*) '' end def verify(*) true end end end end ruby-jwt-2.7.1/lib/jwt/algos/ps.rb000066400000000000000000000025261444067622100167450ustar00rootroot00000000000000# frozen_string_literal: true module JWT module Algos module Ps # RSASSA-PSS signing algorithms module_function SUPPORTED = %w[PS256 PS384 PS512].freeze def sign(algorithm, msg, key) require_openssl! raise EncodeError, "The given key is a #{key_class}. It has to be an OpenSSL::PKey::RSA instance." if key.is_a?(String) translated_algorithm = algorithm.sub('PS', 'sha') key.sign_pss(translated_algorithm, msg, salt_length: :digest, mgf1_hash: translated_algorithm) end def verify(algorithm, public_key, signing_input, signature) require_openssl! translated_algorithm = algorithm.sub('PS', 'sha') public_key.verify_pss(translated_algorithm, signature, signing_input, salt_length: :auto, mgf1_hash: translated_algorithm) rescue OpenSSL::PKey::PKeyError raise JWT::VerificationError, 'Signature verification raised' end def require_openssl! if Object.const_defined?('OpenSSL') if ::Gem::Version.new(OpenSSL::VERSION) < ::Gem::Version.new('2.1') raise JWT::RequiredDependencyError, "You currently have OpenSSL #{OpenSSL::VERSION}. PS support requires >= 2.1" end else raise JWT::RequiredDependencyError, 'PS signing requires OpenSSL +2.1' end end end end end ruby-jwt-2.7.1/lib/jwt/algos/rsa.rb000066400000000000000000000012741444067622100171070ustar00rootroot00000000000000# frozen_string_literal: true module JWT module Algos module Rsa module_function SUPPORTED = %w[RS256 RS384 RS512].freeze def sign(algorithm, msg, key) raise EncodeError, "The given key is a #{key.class}. It has to be an OpenSSL::PKey::RSA instance." if key.instance_of?(String) key.sign(OpenSSL::Digest.new(algorithm.sub('RS', 'sha')), msg) end def verify(algorithm, public_key, signing_input, signature) public_key.verify(OpenSSL::Digest.new(algorithm.sub('RS', 'sha')), signature, signing_input) rescue OpenSSL::PKey::PKeyError raise JWT::VerificationError, 'Signature verification raised' end end end end ruby-jwt-2.7.1/lib/jwt/algos/unsupported.rb000066400000000000000000000005211444067622100207040ustar00rootroot00000000000000# frozen_string_literal: true module JWT module Algos module Unsupported module_function SUPPORTED = [].freeze def sign(*) raise NotImplementedError, 'Unsupported signing method' end def verify(*) raise JWT::VerificationError, 'Algorithm not supported' end end end end ruby-jwt-2.7.1/lib/jwt/base64.rb000066400000000000000000000005511444067622100162760ustar00rootroot00000000000000# frozen_string_literal: true require 'base64' module JWT # Base64 helpers class Base64 class << self def url_encode(str) ::Base64.encode64(str).tr('+/', '-_').gsub(/[\n=]/, '') end def url_decode(str) str += '=' * (4 - str.length.modulo(4)) ::Base64.decode64(str.tr('-_', '+/')) end end end end ruby-jwt-2.7.1/lib/jwt/claims_validator.rb000066400000000000000000000012561444067622100205320ustar00rootroot00000000000000# frozen_string_literal: true require_relative './error' module JWT class ClaimsValidator NUMERIC_CLAIMS = %i[ exp iat nbf ].freeze def initialize(payload) @payload = payload.transform_keys(&:to_sym) end def validate! validate_numeric_claims true end private def validate_numeric_claims NUMERIC_CLAIMS.each do |claim| validate_is_numeric(claim) if @payload.key?(claim) end end def validate_is_numeric(claim) return if @payload[claim].is_a?(Numeric) raise InvalidPayload, "#{claim} claim must be a Numeric value but it is a #{@payload[claim].class}" end end end ruby-jwt-2.7.1/lib/jwt/configuration.rb000066400000000000000000000004101444067622100200530ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'configuration/container' module JWT module Configuration def configure yield(configuration) end def configuration @configuration ||= ::JWT::Configuration::Container.new end end end ruby-jwt-2.7.1/lib/jwt/configuration/000077500000000000000000000000001444067622100175335ustar00rootroot00000000000000ruby-jwt-2.7.1/lib/jwt/configuration/container.rb000066400000000000000000000005631444067622100220460ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'decode_configuration' require_relative 'jwk_configuration' module JWT module Configuration class Container attr_accessor :decode, :jwk def initialize reset! end def reset! @decode = DecodeConfiguration.new @jwk = JwkConfiguration.new end end end end ruby-jwt-2.7.1/lib/jwt/configuration/decode_configuration.rb000066400000000000000000000022521444067622100242330ustar00rootroot00000000000000# frozen_string_literal: true module JWT module Configuration class DecodeConfiguration attr_accessor :verify_expiration, :verify_not_before, :verify_iss, :verify_iat, :verify_jti, :verify_aud, :verify_sub, :leeway, :algorithms, :required_claims def initialize @verify_expiration = true @verify_not_before = true @verify_iss = false @verify_iat = false @verify_jti = false @verify_aud = false @verify_sub = false @leeway = 0 @algorithms = ['HS256'] @required_claims = [] end def to_h { verify_expiration: verify_expiration, verify_not_before: verify_not_before, verify_iss: verify_iss, verify_iat: verify_iat, verify_jti: verify_jti, verify_aud: verify_aud, verify_sub: verify_sub, leeway: leeway, algorithms: algorithms, required_claims: required_claims } end end end end ruby-jwt-2.7.1/lib/jwt/configuration/jwk_configuration.rb000066400000000000000000000013511444067622100236020ustar00rootroot00000000000000# frozen_string_literal: true require_relative '../jwk/kid_as_key_digest' require_relative '../jwk/thumbprint' module JWT module Configuration class JwkConfiguration def initialize self.kid_generator_type = :key_digest end def kid_generator_type=(value) self.kid_generator = case value when :key_digest JWT::JWK::KidAsKeyDigest when :rfc7638_thumbprint JWT::JWK::Thumbprint else raise ArgumentError, "#{value} is not a valid kid generator type." end end attr_accessor :kid_generator end end end ruby-jwt-2.7.1/lib/jwt/decode.rb000066400000000000000000000106111444067622100164330ustar00rootroot00000000000000# frozen_string_literal: true require 'json' require 'jwt/verify' require 'jwt/x5c_key_finder' # JWT::Decode module module JWT # Decoding logic for JWT class Decode def initialize(jwt, key, verify, options, &keyfinder) raise(JWT::DecodeError, 'Nil JSON web token') unless jwt @jwt = jwt @key = key @options = options @segments = jwt.split('.') @verify = verify @signature = '' @keyfinder = keyfinder end def decode_segments validate_segment_count! if @verify decode_signature verify_algo set_key verify_signature verify_claims end raise(JWT::DecodeError, 'Not enough or too many segments') unless header && payload [payload, header] end private def verify_signature return unless @key || @verify return if none_algorithm? raise JWT::DecodeError, 'No verification key available' unless @key return if Array(@key).any? { |key| verify_signature_for?(key) } raise(JWT::VerificationError, 'Signature verification failed') end def verify_algo raise(JWT::IncorrectAlgorithm, 'An algorithm must be specified') if allowed_algorithms.empty? raise(JWT::IncorrectAlgorithm, 'Token is missing alg header') unless alg_in_header raise(JWT::IncorrectAlgorithm, 'Expected a different algorithm') if allowed_and_valid_algorithms.empty? end def set_key @key = find_key(&@keyfinder) if @keyfinder @key = ::JWT::JWK::KeyFinder.new(jwks: @options[:jwks], allow_nil_kid: @options[:allow_nil_kid]).key_for(header['kid']) if @options[:jwks] if (x5c_options = @options[:x5c]) @key = X5cKeyFinder.new(x5c_options[:root_certificates], x5c_options[:crls]).from(header['x5c']) end end def verify_signature_for?(key) allowed_and_valid_algorithms.any? do |alg| alg.verify(data: signing_input, signature: @signature, verification_key: key) end end def allowed_and_valid_algorithms @allowed_and_valid_algorithms ||= allowed_algorithms.select { |alg| alg.valid_alg?(alg_in_header) } end # Order is very important - first check for string keys, next for symbols ALGORITHM_KEYS = ['algorithm', :algorithm, 'algorithms', :algorithms].freeze def given_algorithms ALGORITHM_KEYS.each do |alg_key| alg = @options[alg_key] return Array(alg) if alg end [] end def allowed_algorithms @allowed_algorithms ||= resolve_allowed_algorithms end def resolve_allowed_algorithms algs = given_algorithms.map do |alg| if Algos.implementation?(alg) alg else Algos.create(alg) end end sort_by_alg_header(algs) end # Move algorithms matching the JWT alg header to the beginning of the list def sort_by_alg_header(algs) return algs if algs.size <= 1 algs.partition { |alg| alg.valid_alg?(alg_in_header) }.flatten end def find_key(&keyfinder) key = (keyfinder.arity == 2 ? yield(header, payload) : yield(header)) # key can be of type [string, nil, OpenSSL::PKey, Array] return key if key && !Array(key).empty? raise JWT::DecodeError, 'No verification key available' end def verify_claims Verify.verify_claims(payload, @options) Verify.verify_required_claims(payload, @options) end def validate_segment_count! return if segment_length == 3 return if !@verify && segment_length == 2 # If no verifying required, the signature is not needed return if segment_length == 2 && none_algorithm? raise(JWT::DecodeError, 'Not enough or too many segments') end def segment_length @segments.count end def none_algorithm? alg_in_header == 'none' end def decode_signature @signature = ::JWT::Base64.url_decode(@segments[2] || '') end def alg_in_header header['alg'] end def header @header ||= parse_and_decode @segments[0] end def payload @payload ||= parse_and_decode @segments[1] end def signing_input @segments.first(2).join('.') end def parse_and_decode(segment) JWT::JSON.parse(::JWT::Base64.url_decode(segment)) rescue ::JSON::ParserError raise JWT::DecodeError, 'Invalid segment encoding' end end end ruby-jwt-2.7.1/lib/jwt/encode.rb000066400000000000000000000032031444067622100164440ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'algos' require_relative 'claims_validator' # JWT::Encode module module JWT # Encoding logic for JWT class Encode ALG_KEY = 'alg' def initialize(options) @payload = options[:payload] @key = options[:key] @algorithm = resolve_algorithm(options[:algorithm]) @headers = options[:headers].transform_keys(&:to_s) @headers[ALG_KEY] = @algorithm.alg end def segments validate_claims! combine(encoded_header_and_payload, encoded_signature) end private def resolve_algorithm(algorithm) return algorithm if Algos.implementation?(algorithm) Algos.create(algorithm) end def encoded_header @encoded_header ||= encode_header end def encoded_payload @encoded_payload ||= encode_payload end def encoded_signature @encoded_signature ||= encode_signature end def encoded_header_and_payload @encoded_header_and_payload ||= combine(encoded_header, encoded_payload) end def encode_header encode_data(@headers) end def encode_payload encode_data(@payload) end def signature @algorithm.sign(data: encoded_header_and_payload, signing_key: @key) end def validate_claims! return unless @payload.is_a?(Hash) ClaimsValidator.new(@payload).validate! end def encode_signature ::JWT::Base64.url_encode(signature) end def encode_data(data) ::JWT::Base64.url_encode(JWT::JSON.generate(data)) end def combine(*parts) parts.join('.') end end end ruby-jwt-2.7.1/lib/jwt/error.rb000066400000000000000000000013731444067622100163460ustar00rootroot00000000000000# frozen_string_literal: true module JWT class EncodeError < StandardError; end class DecodeError < StandardError; end class RequiredDependencyError < StandardError; end class VerificationError < DecodeError; end class ExpiredSignature < DecodeError; end class IncorrectAlgorithm < DecodeError; end class ImmatureSignature < DecodeError; end class InvalidIssuerError < DecodeError; end class UnsupportedEcdsaCurve < IncorrectAlgorithm; end class InvalidIatError < DecodeError; end class InvalidAudError < DecodeError; end class InvalidSubError < DecodeError; end class InvalidJtiError < DecodeError; end class InvalidPayload < DecodeError; end class MissingRequiredClaim < DecodeError; end class JWKError < DecodeError; end end ruby-jwt-2.7.1/lib/jwt/json.rb000066400000000000000000000003711444067622100161630ustar00rootroot00000000000000# frozen_string_literal: true require 'json' module JWT # JSON wrapper class JSON class << self def generate(data) ::JSON.generate(data) end def parse(data) ::JSON.parse(data) end end end end ruby-jwt-2.7.1/lib/jwt/jwk.rb000066400000000000000000000025111444067622100160030ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'jwk/key_finder' require_relative 'jwk/set' module JWT module JWK class << self def create_from(key, params = nil, options = {}) if key.is_a?(Hash) jwk_kty = key[:kty] || key['kty'] raise JWT::JWKError, 'Key type (kty) not provided' unless jwk_kty return mappings.fetch(jwk_kty.to_s) do |kty| raise JWT::JWKError, "Key type #{kty} not supported" end.new(key, params, options) end mappings.fetch(key.class) do |klass| raise JWT::JWKError, "Cannot create JWK from a #{klass.name}" end.new(key, params, options) end def classes @mappings = nil # reset the cached mappings @classes ||= [] end alias new create_from alias import create_from private def mappings @mappings ||= generate_mappings end def generate_mappings classes.each_with_object({}) do |klass, hash| next unless klass.const_defined?('KTYS') Array(klass::KTYS).each do |kty| hash[kty] = klass end end end end end end require_relative 'jwk/key_base' require_relative 'jwk/ec' require_relative 'jwk/rsa' require_relative 'jwk/hmac' require_relative 'jwk/okp_rbnacl' if ::JWT.rbnacl? ruby-jwt-2.7.1/lib/jwt/jwk/000077500000000000000000000000001444067622100154575ustar00rootroot00000000000000ruby-jwt-2.7.1/lib/jwt/jwk/ec.rb000066400000000000000000000173601444067622100164020ustar00rootroot00000000000000# frozen_string_literal: true require 'forwardable' module JWT module JWK class EC < KeyBase # rubocop:disable Metrics/ClassLength KTY = 'EC' KTYS = [KTY, OpenSSL::PKey::EC, JWT::JWK::EC].freeze BINARY = 2 EC_PUBLIC_KEY_ELEMENTS = %i[kty crv x y].freeze EC_PRIVATE_KEY_ELEMENTS = %i[d].freeze EC_KEY_ELEMENTS = (EC_PRIVATE_KEY_ELEMENTS + EC_PUBLIC_KEY_ELEMENTS).freeze def initialize(key, params = nil, options = {}) params ||= {} # For backwards compatibility when kid was a String params = { kid: params } if params.is_a?(String) key_params = extract_key_params(key) params = params.transform_keys(&:to_sym) check_jwk_params!(key_params, params) super(options, key_params.merge(params)) end def keypair ec_key end def private? ec_key.private_key? end def signing_key ec_key end def verify_key ec_key end def public_key ec_key end def members EC_PUBLIC_KEY_ELEMENTS.each_with_object({}) { |i, h| h[i] = self[i] } end def export(options = {}) exported = parameters.clone exported.reject! { |k, _| EC_PRIVATE_KEY_ELEMENTS.include? k } unless private? && options[:include_private] == true exported end def key_digest _crv, x_octets, y_octets = keypair_components(ec_key) sequence = OpenSSL::ASN1::Sequence([OpenSSL::ASN1::Integer.new(OpenSSL::BN.new(x_octets, BINARY)), OpenSSL::ASN1::Integer.new(OpenSSL::BN.new(y_octets, BINARY))]) OpenSSL::Digest::SHA256.hexdigest(sequence.to_der) end def []=(key, value) if EC_KEY_ELEMENTS.include?(key.to_sym) raise ArgumentError, 'cannot overwrite cryptographic key attributes' end super(key, value) end private def ec_key @ec_key ||= create_ec_key(self[:crv], self[:x], self[:y], self[:d]) end def extract_key_params(key) case key when JWT::JWK::EC key.export(include_private: true) when OpenSSL::PKey::EC # Accept OpenSSL key as input @ec_key = key # Preserve the object to avoid recreation parse_ec_key(key) when Hash key.transform_keys(&:to_sym) else raise ArgumentError, 'key must be of type OpenSSL::PKey::EC or Hash with key parameters' end end def check_jwk_params!(key_params, params) raise ArgumentError, 'cannot overwrite cryptographic key attributes' unless (EC_KEY_ELEMENTS & params.keys).empty? raise JWT::JWKError, "Incorrect 'kty' value: #{key_params[:kty]}, expected #{KTY}" unless key_params[:kty] == KTY raise JWT::JWKError, 'Key format is invalid for EC' unless key_params[:crv] && key_params[:x] && key_params[:y] end def keypair_components(ec_keypair) encoded_point = ec_keypair.public_key.to_bn.to_s(BINARY) case ec_keypair.group.curve_name when 'prime256v1' crv = 'P-256' x_octets, y_octets = encoded_point.unpack('xa32a32') when 'secp256k1' crv = 'P-256K' x_octets, y_octets = encoded_point.unpack('xa32a32') when 'secp384r1' crv = 'P-384' x_octets, y_octets = encoded_point.unpack('xa48a48') when 'secp521r1' crv = 'P-521' x_octets, y_octets = encoded_point.unpack('xa66a66') else raise JWT::JWKError, "Unsupported curve '#{ec_keypair.group.curve_name}'" end [crv, x_octets, y_octets] end def encode_octets(octets) return unless octets ::JWT::Base64.url_encode(octets) end def encode_open_ssl_bn(key_part) ::JWT::Base64.url_encode(key_part.to_s(BINARY)) end def parse_ec_key(key) crv, x_octets, y_octets = keypair_components(key) octets = key.private_key&.to_bn&.to_s(BINARY) { kty: KTY, crv: crv, x: encode_octets(x_octets), y: encode_octets(y_octets), d: encode_octets(octets) }.compact end if ::JWT.openssl_3? def create_ec_key(jwk_crv, jwk_x, jwk_y, jwk_d) # rubocop:disable Metrics/MethodLength curve = EC.to_openssl_curve(jwk_crv) x_octets = decode_octets(jwk_x) y_octets = decode_octets(jwk_y) point = OpenSSL::PKey::EC::Point.new( OpenSSL::PKey::EC::Group.new(curve), OpenSSL::BN.new([0x04, x_octets, y_octets].pack('Ca*a*'), 2) ) sequence = if jwk_d # https://datatracker.ietf.org/doc/html/rfc5915.html # ECPrivateKey ::= SEQUENCE { # version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), # privateKey OCTET STRING, # parameters [0] ECParameters {{ NamedCurve }} OPTIONAL, # publicKey [1] BIT STRING OPTIONAL # } OpenSSL::ASN1::Sequence([ OpenSSL::ASN1::Integer(1), OpenSSL::ASN1::OctetString(OpenSSL::BN.new(decode_octets(jwk_d), 2).to_s(2)), OpenSSL::ASN1::ObjectId(curve, 0, :EXPLICIT), OpenSSL::ASN1::BitString(point.to_octet_string(:uncompressed), 1, :EXPLICIT) ]) else OpenSSL::ASN1::Sequence([ OpenSSL::ASN1::Sequence([OpenSSL::ASN1::ObjectId('id-ecPublicKey'), OpenSSL::ASN1::ObjectId(curve)]), OpenSSL::ASN1::BitString(point.to_octet_string(:uncompressed)) ]) end OpenSSL::PKey::EC.new(sequence.to_der) end else def create_ec_key(jwk_crv, jwk_x, jwk_y, jwk_d) curve = EC.to_openssl_curve(jwk_crv) x_octets = decode_octets(jwk_x) y_octets = decode_octets(jwk_y) key = OpenSSL::PKey::EC.new(curve) # The details of the `Point` instantiation are covered in: # - https://docs.ruby-lang.org/en/2.4.0/OpenSSL/PKey/EC.html # - https://www.openssl.org/docs/manmaster/man3/EC_POINT_new.html # - https://tools.ietf.org/html/rfc5480#section-2.2 # - https://www.secg.org/SEC1-Ver-1.0.pdf # Section 2.3.3 of the last of these references specifies that the # encoding of an uncompressed point consists of the byte `0x04` followed # by the x value then the y value. point = OpenSSL::PKey::EC::Point.new( OpenSSL::PKey::EC::Group.new(curve), OpenSSL::BN.new([0x04, x_octets, y_octets].pack('Ca*a*'), 2) ) key.public_key = point key.private_key = OpenSSL::BN.new(decode_octets(jwk_d), 2) if jwk_d key end end def decode_octets(jwk_data) ::JWT::Base64.url_decode(jwk_data) end def decode_open_ssl_bn(jwk_data) OpenSSL::BN.new(::JWT::Base64.url_decode(jwk_data), BINARY) end class << self def import(jwk_data) new(jwk_data) end def to_openssl_curve(crv) # The JWK specs and OpenSSL use different names for the same curves. # See https://tools.ietf.org/html/rfc5480#section-2.1.1.1 for some # pointers on different names for common curves. case crv when 'P-256' then 'prime256v1' when 'P-384' then 'secp384r1' when 'P-521' then 'secp521r1' when 'P-256K' then 'secp256k1' else raise JWT::JWKError, 'Invalid curve provided' end end end end end end ruby-jwt-2.7.1/lib/jwt/jwk/hmac.rb000066400000000000000000000052441444067622100167210ustar00rootroot00000000000000# frozen_string_literal: true module JWT module JWK class HMAC < KeyBase KTY = 'oct' KTYS = [KTY, String, JWT::JWK::HMAC].freeze HMAC_PUBLIC_KEY_ELEMENTS = %i[kty].freeze HMAC_PRIVATE_KEY_ELEMENTS = %i[k].freeze HMAC_KEY_ELEMENTS = (HMAC_PRIVATE_KEY_ELEMENTS + HMAC_PUBLIC_KEY_ELEMENTS).freeze def initialize(key, params = nil, options = {}) params ||= {} # For backwards compatibility when kid was a String params = { kid: params } if params.is_a?(String) key_params = extract_key_params(key) params = params.transform_keys(&:to_sym) check_jwk(key_params, params) super(options, key_params.merge(params)) end def keypair secret end def private? true end def public_key nil end def verify_key secret end def signing_key secret end # See https://tools.ietf.org/html/rfc7517#appendix-A.3 def export(options = {}) exported = parameters.clone exported.reject! { |k, _| HMAC_PRIVATE_KEY_ELEMENTS.include? k } unless private? && options[:include_private] == true exported end def members HMAC_KEY_ELEMENTS.each_with_object({}) { |i, h| h[i] = self[i] } end def key_digest sequence = OpenSSL::ASN1::Sequence([OpenSSL::ASN1::UTF8String.new(signing_key), OpenSSL::ASN1::UTF8String.new(KTY)]) OpenSSL::Digest::SHA256.hexdigest(sequence.to_der) end def []=(key, value) if HMAC_KEY_ELEMENTS.include?(key.to_sym) raise ArgumentError, 'cannot overwrite cryptographic key attributes' end super(key, value) end private def secret self[:k] end def extract_key_params(key) case key when JWT::JWK::HMAC key.export(include_private: true) when String # Accept String key as input { kty: KTY, k: key } when Hash key.transform_keys(&:to_sym) else raise ArgumentError, 'key must be of type String or Hash with key parameters' end end def check_jwk(keypair, params) raise ArgumentError, 'cannot overwrite cryptographic key attributes' unless (HMAC_KEY_ELEMENTS & params.keys).empty? raise JWT::JWKError, "Incorrect 'kty' value: #{keypair[:kty]}, expected #{KTY}" unless keypair[:kty] == KTY raise JWT::JWKError, 'Key format is invalid for HMAC' unless keypair[:k] end class << self def import(jwk_data) new(jwk_data) end end end end end ruby-jwt-2.7.1/lib/jwt/jwk/key_base.rb000066400000000000000000000021261444067622100175670ustar00rootroot00000000000000# frozen_string_literal: true module JWT module JWK class KeyBase def self.inherited(klass) super ::JWT::JWK.classes << klass end def initialize(options, params = {}) options ||= {} @parameters = params.transform_keys(&:to_sym) # Uniform interface # For backwards compatibility, kid_generator may be specified in the parameters options[:kid_generator] ||= @parameters.delete(:kid_generator) # Make sure the key has a kid kid_generator = options[:kid_generator] || ::JWT.configuration.jwk.kid_generator self[:kid] ||= kid_generator.new(self).generate end def kid self[:kid] end def hash self[:kid].hash end def [](key) @parameters[key.to_sym] end def []=(key, value) @parameters[key.to_sym] = value end def ==(other) self[:kid] == other[:kid] end alias eql? == def <=>(other) self[:kid] <=> other[:kid] end private attr_reader :parameters end end end ruby-jwt-2.7.1/lib/jwt/jwk/key_finder.rb000066400000000000000000000026171444067622100201310ustar00rootroot00000000000000# frozen_string_literal: true module JWT module JWK class KeyFinder def initialize(options) @allow_nil_kid = options[:allow_nil_kid] jwks_or_loader = options[:jwks] @jwks_loader = if jwks_or_loader.respond_to?(:call) jwks_or_loader else ->(_options) { jwks_or_loader } end end def key_for(kid) raise ::JWT::DecodeError, 'No key id (kid) found from token headers' unless kid || @allow_nil_kid raise ::JWT::DecodeError, 'Invalid type for kid header parameter' unless kid.nil? || kid.is_a?(String) jwk = resolve_key(kid) raise ::JWT::DecodeError, 'No keys found in jwks' unless @jwks.any? raise ::JWT::DecodeError, "Could not find public key for kid #{kid}" unless jwk jwk.verify_key end private def resolve_key(kid) key_matcher = ->(key) { (kid.nil? && @allow_nil_kid) || key[:kid] == kid } # First try without invalidation to facilitate application caching @jwks ||= JWT::JWK::Set.new(@jwks_loader.call(kid: kid)) jwk = @jwks.find { |key| key_matcher.call(key) } return jwk if jwk # Second try, invalidate for backwards compatibility @jwks = JWT::JWK::Set.new(@jwks_loader.call(invalidate: true, kid_not_found: true, kid: kid)) @jwks.find { |key| key_matcher.call(key) } end end end end ruby-jwt-2.7.1/lib/jwt/jwk/kid_as_key_digest.rb000066400000000000000000000003171444067622100214460ustar00rootroot00000000000000# frozen_string_literal: true module JWT module JWK class KidAsKeyDigest def initialize(jwk) @jwk = jwk end def generate @jwk.key_digest end end end end ruby-jwt-2.7.1/lib/jwt/jwk/okp_rbnacl.rb000066400000000000000000000060531444067622100201220ustar00rootroot00000000000000# frozen_string_literal: true module JWT module JWK class OKPRbNaCl < KeyBase KTY = 'OKP' KTYS = [KTY, JWT::JWK::OKPRbNaCl, RbNaCl::Signatures::Ed25519::SigningKey, RbNaCl::Signatures::Ed25519::VerifyKey].freeze OKP_PUBLIC_KEY_ELEMENTS = %i[kty n x].freeze OKP_PRIVATE_KEY_ELEMENTS = %i[d].freeze def initialize(key, params = nil, options = {}) params ||= {} # For backwards compatibility when kid was a String params = { kid: params } if params.is_a?(String) key_params = extract_key_params(key) params = params.transform_keys(&:to_sym) check_jwk_params!(key_params, params) super(options, key_params.merge(params)) end def verify_key return @verify_key if defined?(@verify_key) @verify_key = verify_key_from_parameters end def signing_key return @signing_key if defined?(@signing_key) @signing_key = signing_key_from_parameters end def key_digest Thumbprint.new(self).to_s end def private? !signing_key.nil? end def members OKP_PUBLIC_KEY_ELEMENTS.each_with_object({}) { |i, h| h[i] = self[i] } end def export(options = {}) exported = parameters.clone exported.reject! { |k, _| OKP_PRIVATE_KEY_ELEMENTS.include?(k) } unless private? && options[:include_private] == true exported end private def extract_key_params(key) case key when JWT::JWK::KeyBase key.export(include_private: true) when RbNaCl::Signatures::Ed25519::SigningKey @signing_key = key @verify_key = key.verify_key parse_okp_key_params(@verify_key, @signing_key) when RbNaCl::Signatures::Ed25519::VerifyKey @signing_key = nil @verify_key = key parse_okp_key_params(@verify_key) when Hash key.transform_keys(&:to_sym) else raise ArgumentError, 'key must be of type RbNaCl::Signatures::Ed25519::SigningKey, RbNaCl::Signatures::Ed25519::VerifyKey or Hash with key parameters' end end def check_jwk_params!(key_params, _given_params) raise JWT::JWKError, "Incorrect 'kty' value: #{key_params[:kty]}, expected #{KTY}" unless key_params[:kty] == KTY end def parse_okp_key_params(verify_key, signing_key = nil) params = { kty: KTY, crv: 'Ed25519', x: ::JWT::Base64.url_encode(verify_key.to_bytes) } if signing_key params[:d] = ::JWT::Base64.url_encode(signing_key.to_bytes) end params end def verify_key_from_parameters RbNaCl::Signatures::Ed25519::VerifyKey.new(::JWT::Base64.url_decode(self[:x])) end def signing_key_from_parameters return nil unless self[:d] RbNaCl::Signatures::Ed25519::SigningKey.new(::JWT::Base64.url_decode(self[:d])) end class << self def import(jwk_data) new(jwk_data) end end end end end ruby-jwt-2.7.1/lib/jwt/jwk/rsa.rb000066400000000000000000000153631444067622100166010ustar00rootroot00000000000000# frozen_string_literal: true module JWT module JWK class RSA < KeyBase # rubocop:disable Metrics/ClassLength BINARY = 2 KTY = 'RSA' KTYS = [KTY, OpenSSL::PKey::RSA, JWT::JWK::RSA].freeze RSA_PUBLIC_KEY_ELEMENTS = %i[kty n e].freeze RSA_PRIVATE_KEY_ELEMENTS = %i[d p q dp dq qi].freeze RSA_KEY_ELEMENTS = (RSA_PRIVATE_KEY_ELEMENTS + RSA_PUBLIC_KEY_ELEMENTS).freeze RSA_OPT_PARAMS = %i[p q dp dq qi].freeze RSA_ASN1_SEQUENCE = (%i[n e d] + RSA_OPT_PARAMS).freeze # https://www.rfc-editor.org/rfc/rfc3447#appendix-A.1.2 def initialize(key, params = nil, options = {}) params ||= {} # For backwards compatibility when kid was a String params = { kid: params } if params.is_a?(String) key_params = extract_key_params(key) params = params.transform_keys(&:to_sym) check_jwk_params!(key_params, params) super(options, key_params.merge(params)) end def keypair rsa_key end def private? rsa_key.private? end def public_key rsa_key.public_key end def signing_key rsa_key if private? end def verify_key rsa_key.public_key end def export(options = {}) exported = parameters.clone exported.reject! { |k, _| RSA_PRIVATE_KEY_ELEMENTS.include? k } unless private? && options[:include_private] == true exported end def members RSA_PUBLIC_KEY_ELEMENTS.each_with_object({}) { |i, h| h[i] = self[i] } end def key_digest sequence = OpenSSL::ASN1::Sequence([OpenSSL::ASN1::Integer.new(public_key.n), OpenSSL::ASN1::Integer.new(public_key.e)]) OpenSSL::Digest::SHA256.hexdigest(sequence.to_der) end def []=(key, value) if RSA_KEY_ELEMENTS.include?(key.to_sym) raise ArgumentError, 'cannot overwrite cryptographic key attributes' end super(key, value) end private def rsa_key @rsa_key ||= self.class.create_rsa_key(jwk_attributes(*(RSA_KEY_ELEMENTS - [:kty]))) end def extract_key_params(key) case key when JWT::JWK::RSA key.export(include_private: true) when OpenSSL::PKey::RSA # Accept OpenSSL key as input @rsa_key = key # Preserve the object to avoid recreation parse_rsa_key(key) when Hash key.transform_keys(&:to_sym) else raise ArgumentError, 'key must be of type OpenSSL::PKey::RSA or Hash with key parameters' end end def check_jwk_params!(key_params, params) raise ArgumentError, 'cannot overwrite cryptographic key attributes' unless (RSA_KEY_ELEMENTS & params.keys).empty? raise JWT::JWKError, "Incorrect 'kty' value: #{key_params[:kty]}, expected #{KTY}" unless key_params[:kty] == KTY raise JWT::JWKError, 'Key format is invalid for RSA' unless key_params[:n] && key_params[:e] end def parse_rsa_key(key) { kty: KTY, n: encode_open_ssl_bn(key.n), e: encode_open_ssl_bn(key.e), d: encode_open_ssl_bn(key.d), p: encode_open_ssl_bn(key.p), q: encode_open_ssl_bn(key.q), dp: encode_open_ssl_bn(key.dmp1), dq: encode_open_ssl_bn(key.dmq1), qi: encode_open_ssl_bn(key.iqmp) }.compact end def jwk_attributes(*attributes) attributes.each_with_object({}) do |attribute, hash| hash[attribute] = decode_open_ssl_bn(self[attribute]) end end def encode_open_ssl_bn(key_part) return unless key_part ::JWT::Base64.url_encode(key_part.to_s(BINARY)) end def decode_open_ssl_bn(jwk_data) self.class.decode_open_ssl_bn(jwk_data) end class << self def import(jwk_data) new(jwk_data) end def decode_open_ssl_bn(jwk_data) return nil unless jwk_data OpenSSL::BN.new(::JWT::Base64.url_decode(jwk_data), BINARY) end def create_rsa_key_using_der(rsa_parameters) validate_rsa_parameters!(rsa_parameters) sequence = RSA_ASN1_SEQUENCE.each_with_object([]) do |key, arr| next if rsa_parameters[key].nil? arr << OpenSSL::ASN1::Integer.new(rsa_parameters[key]) end if sequence.size > 2 # Append "two-prime" version for private key sequence.unshift(OpenSSL::ASN1::Integer.new(0)) raise JWT::JWKError, 'Creating a RSA key with a private key requires the CRT parameters to be defined' if sequence.size < RSA_ASN1_SEQUENCE.size end OpenSSL::PKey::RSA.new(OpenSSL::ASN1::Sequence(sequence).to_der) end def create_rsa_key_using_sets(rsa_parameters) validate_rsa_parameters!(rsa_parameters) OpenSSL::PKey::RSA.new.tap do |rsa_key| rsa_key.set_key(rsa_parameters[:n], rsa_parameters[:e], rsa_parameters[:d]) rsa_key.set_factors(rsa_parameters[:p], rsa_parameters[:q]) if rsa_parameters[:p] && rsa_parameters[:q] rsa_key.set_crt_params(rsa_parameters[:dp], rsa_parameters[:dq], rsa_parameters[:qi]) if rsa_parameters[:dp] && rsa_parameters[:dq] && rsa_parameters[:qi] end end def create_rsa_key_using_accessors(rsa_parameters) # rubocop:disable Metrics/AbcSize validate_rsa_parameters!(rsa_parameters) OpenSSL::PKey::RSA.new.tap do |rsa_key| rsa_key.n = rsa_parameters[:n] rsa_key.e = rsa_parameters[:e] rsa_key.d = rsa_parameters[:d] if rsa_parameters[:d] rsa_key.p = rsa_parameters[:p] if rsa_parameters[:p] rsa_key.q = rsa_parameters[:q] if rsa_parameters[:q] rsa_key.dmp1 = rsa_parameters[:dp] if rsa_parameters[:dp] rsa_key.dmq1 = rsa_parameters[:dq] if rsa_parameters[:dq] rsa_key.iqmp = rsa_parameters[:qi] if rsa_parameters[:qi] end end def validate_rsa_parameters!(rsa_parameters) return unless rsa_parameters.key?(:d) parameters = RSA_OPT_PARAMS - rsa_parameters.keys return if parameters.empty? || parameters.size == RSA_OPT_PARAMS.size raise JWT::JWKError, 'When one of p, q, dp, dq or qi is given all the other optimization parameters also needs to be defined' # https://www.rfc-editor.org/rfc/rfc7518.html#section-6.3.2 end if ::JWT.openssl_3? alias create_rsa_key create_rsa_key_using_der elsif OpenSSL::PKey::RSA.new.respond_to?(:set_key) alias create_rsa_key create_rsa_key_using_sets else alias create_rsa_key create_rsa_key_using_accessors end end end end end ruby-jwt-2.7.1/lib/jwt/jwk/set.rb000066400000000000000000000034421444067622100166020ustar00rootroot00000000000000# frozen_string_literal: true require 'forwardable' module JWT module JWK class Set include Enumerable extend Forwardable attr_reader :keys def initialize(jwks = nil, options = {}) # rubocop:disable Metrics/CyclomaticComplexity jwks ||= {} @keys = case jwks when JWT::JWK::Set # Simple duplication jwks.keys when JWT::JWK::KeyBase # Singleton [jwks] when Hash jwks = jwks.transform_keys(&:to_sym) [*jwks[:keys]].map { |k| JWT::JWK.new(k, nil, options) } when Array jwks.map { |k| JWT::JWK.new(k, nil, options) } else raise ArgumentError, 'Can only create new JWKS from Hash, Array and JWK' end end def export(options = {}) { keys: @keys.map { |k| k.export(options) } } end def_delegators :@keys, :each, :size, :delete, :dig def select!(&block) return @keys.select! unless block self if @keys.select!(&block) end def reject!(&block) return @keys.reject! unless block self if @keys.reject!(&block) end def uniq!(&block) self if @keys.uniq!(&block) end def merge(enum) @keys += JWT::JWK::Set.new(enum.to_a).keys self end def union(enum) dup.merge(enum) end def add(key) @keys << JWT::JWK.new(key) self end def ==(other) other.is_a?(JWT::JWK::Set) && keys.sort == other.keys.sort end alias eql? == alias filter! select! alias length size # For symbolic manipulation alias | union alias + union alias << add end end end ruby-jwt-2.7.1/lib/jwt/jwk/thumbprint.rb000066400000000000000000000007141444067622100202020ustar00rootroot00000000000000# frozen_string_literal: true module JWT module JWK # https://tools.ietf.org/html/rfc7638 class Thumbprint attr_reader :jwk def initialize(jwk) @jwk = jwk end def generate ::Base64.urlsafe_encode64( Digest::SHA256.digest( JWT::JSON.generate( jwk.members.sort.to_h ) ), padding: false ) end alias to_s generate end end end ruby-jwt-2.7.1/lib/jwt/verify.rb000066400000000000000000000062221444067622100165170ustar00rootroot00000000000000# frozen_string_literal: true require 'jwt/error' module JWT # JWT verify methods class Verify DEFAULTS = { leeway: 0 }.freeze class << self %w[verify_aud verify_expiration verify_iat verify_iss verify_jti verify_not_before verify_sub verify_required_claims].each do |method_name| define_method method_name do |payload, options| new(payload, options).send(method_name) end end def verify_claims(payload, options) options.each do |key, val| next unless key.to_s =~ /verify/ Verify.send(key, payload, options) if val end end end def initialize(payload, options) @payload = payload @options = DEFAULTS.merge(options) end def verify_aud return unless (options_aud = @options[:aud]) aud = @payload['aud'] raise(JWT::InvalidAudError, "Invalid audience. Expected #{options_aud}, received #{aud || ''}") if ([*aud] & [*options_aud]).empty? end def verify_expiration return unless @payload.include?('exp') raise(JWT::ExpiredSignature, 'Signature has expired') if @payload['exp'].to_i <= (Time.now.to_i - exp_leeway) end def verify_iat return unless @payload.include?('iat') iat = @payload['iat'] raise(JWT::InvalidIatError, 'Invalid iat') if !iat.is_a?(Numeric) || iat.to_f > Time.now.to_f end def verify_iss return unless (options_iss = @options[:iss]) iss = @payload['iss'] options_iss = Array(options_iss).map { |item| item.is_a?(Symbol) ? item.to_s : item } case iss when *options_iss nil else raise(JWT::InvalidIssuerError, "Invalid issuer. Expected #{options_iss}, received #{iss || ''}") end end def verify_jti options_verify_jti = @options[:verify_jti] jti = @payload['jti'] if options_verify_jti.respond_to?(:call) verified = options_verify_jti.arity == 2 ? options_verify_jti.call(jti, @payload) : options_verify_jti.call(jti) raise(JWT::InvalidJtiError, 'Invalid jti') unless verified elsif jti.to_s.strip.empty? raise(JWT::InvalidJtiError, 'Missing jti') end end def verify_not_before return unless @payload.include?('nbf') raise(JWT::ImmatureSignature, 'Signature nbf has not been reached') if @payload['nbf'].to_i > (Time.now.to_i + nbf_leeway) end def verify_sub return unless (options_sub = @options[:sub]) sub = @payload['sub'] raise(JWT::InvalidSubError, "Invalid subject. Expected #{options_sub}, received #{sub || ''}") unless sub.to_s == options_sub.to_s end def verify_required_claims return unless (options_required_claims = @options[:required_claims]) options_required_claims.each do |required_claim| raise(JWT::MissingRequiredClaim, "Missing required claim #{required_claim}") unless @payload.include?(required_claim) end end private def global_leeway @options[:leeway] end def exp_leeway @options[:exp_leeway] || global_leeway end def nbf_leeway @options[:nbf_leeway] || global_leeway end end end ruby-jwt-2.7.1/lib/jwt/version.rb000066400000000000000000000017321444067622100167010ustar00rootroot00000000000000# frozen_string_literal: true # Moments version builder module module JWT def self.gem_version Gem::Version.new VERSION::STRING end # Moments version builder module module VERSION # major version MAJOR = 2 # minor version MINOR = 7 # tiny version TINY = 1 # alpha, beta, etc. tag PRE = nil # Build version string STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.') end def self.openssl_3? return false if OpenSSL::OPENSSL_VERSION.include?('LibreSSL') return true if OpenSSL::OPENSSL_VERSION_NUMBER >= 3 * 0x10000000 end def self.rbnacl? defined?(::RbNaCl) end def self.rbnacl_6_or_greater? rbnacl? && ::Gem::Version.new(::RbNaCl::VERSION) >= ::Gem::Version.new('6.0.0') end def self.openssl_3_hmac_empty_key_regression? openssl_3? && openssl_version <= ::Gem::Version.new('3.0.0') end def self.openssl_version @openssl_version ||= ::Gem::Version.new(OpenSSL::VERSION) end end ruby-jwt-2.7.1/lib/jwt/x5c_key_finder.rb000066400000000000000000000035461444067622100201170ustar00rootroot00000000000000# frozen_string_literal: true require 'base64' require 'jwt/error' module JWT # If the x5c header certificate chain can be validated by trusted root # certificates, and none of the certificates are revoked, returns the public # key from the first certificate. # See https://tools.ietf.org/html/rfc7515#section-4.1.6 class X5cKeyFinder def initialize(root_certificates, crls = nil) raise(ArgumentError, 'Root certificates must be specified') unless root_certificates @store = build_store(root_certificates, crls) end def from(x5c_header_or_certificates) signing_certificate, *certificate_chain = parse_certificates(x5c_header_or_certificates) store_context = OpenSSL::X509::StoreContext.new(@store, signing_certificate, certificate_chain) if store_context.verify signing_certificate.public_key else error = "Certificate verification failed: #{store_context.error_string}." if (current_cert = store_context.current_cert) error = "#{error} Certificate subject: #{current_cert.subject}." end raise(JWT::VerificationError, error) end end private def build_store(root_certificates, crls) store = OpenSSL::X509::Store.new store.purpose = OpenSSL::X509::PURPOSE_ANY store.flags = OpenSSL::X509::V_FLAG_CRL_CHECK | OpenSSL::X509::V_FLAG_CRL_CHECK_ALL root_certificates.each { |certificate| store.add_cert(certificate) } crls&.each { |crl| store.add_crl(crl) } store end def parse_certificates(x5c_header_or_certificates) if x5c_header_or_certificates.all? { |obj| obj.is_a?(OpenSSL::X509::Certificate) } x5c_header_or_certificates else x5c_header_or_certificates.map do |encoded| OpenSSL::X509::Certificate.new(::JWT::Base64.url_decode(encoded)) end end end end end ruby-jwt-2.7.1/ruby-jwt.gemspec000066400000000000000000000025161444067622100164460ustar00rootroot00000000000000# frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'jwt/version' Gem::Specification.new do |spec| spec.name = 'jwt' spec.version = JWT.gem_version spec.authors = [ 'Tim Rudat' ] spec.email = 'timrudat@gmail.com' spec.summary = 'JSON Web Token implementation in Ruby' spec.description = 'A pure ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.' spec.homepage = 'https://github.com/jwt/ruby-jwt' spec.license = 'MIT' spec.required_ruby_version = '>= 2.5' spec.metadata = { 'bug_tracker_uri' => 'https://github.com/jwt/ruby-jwt/issues', 'changelog_uri' => "https://github.com/jwt/ruby-jwt/blob/v#{JWT.gem_version}/CHANGELOG.md", 'rubygems_mfa_required' => 'true' } spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(spec|gemfiles|coverage|bin)/}) || # Irrelevant folders f.match(/^\.+/) || # Files and folders starting with . f.match(/^(Appraisals|Gemfile|Rakefile)$/) # Irrelevant files end spec.executables = [] spec.require_paths = %w[lib] spec.add_development_dependency 'appraisal' spec.add_development_dependency 'bundler' spec.add_development_dependency 'rake' spec.add_development_dependency 'rspec' spec.add_development_dependency 'simplecov' end ruby-jwt-2.7.1/spec/000077500000000000000000000000001444067622100142445ustar00rootroot00000000000000ruby-jwt-2.7.1/spec/configuration/000077500000000000000000000000001444067622100171135ustar00rootroot00000000000000ruby-jwt-2.7.1/spec/configuration/jwk_configuration_spec.rb000066400000000000000000000011251444067622100241730ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe JWT::Configuration::JwkConfiguration do describe '.kid_generator_type=' do context 'when invalid value is passed' do it 'raises ArgumentError' do expect { subject.kid_generator_type = :foo }.to raise_error(ArgumentError, 'foo is not a valid kid generator type.') end end context 'when valid value is passed' do it 'sets the generator matching the value' do subject.kid_generator_type = :rfc7638_thumbprint expect(subject.kid_generator).to eq(::JWT::JWK::Thumbprint) end end end end ruby-jwt-2.7.1/spec/fixtures/000077500000000000000000000000001444067622100161155ustar00rootroot00000000000000ruby-jwt-2.7.1/spec/fixtures/certs/000077500000000000000000000000001444067622100172355ustar00rootroot00000000000000ruby-jwt-2.7.1/spec/fixtures/certs/ec256-private-v2.pem000066400000000000000000000003431444067622100225610ustar00rootroot00000000000000-----BEGIN EC PRIVATE KEY----- MHcCAQEEIFZpgytOAXPVreqGsHPdD9pojw30bnlqfUAqFZ3V3/qeoAoGCCqGSM49 AwEHoUQDQgAE7JbAf3pWEEPje6NG+4dGOwIZnNwRFIe7DnQ4xFWKPrL5tVWlBh7N DFhjGNhiyO+aQjbcx9uWV74ifq7i21Bemg== -----END EC PRIVATE KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec256-private.pem000066400000000000000000000003431444067622100222340ustar00rootroot00000000000000-----BEGIN EC PRIVATE KEY----- MHcCAQEEIJmVse5uPfj6B4TcXrUAvf9/8pJh+KrKKYLNcmOnp/vPoAoGCCqGSM49 AwEHoUQDQgAEAr+WbDE5VtIDGhtYMxvEc6cMsDBc/DX1wuhIMu8dQzOLSt0tpqK9 MVfXbVfrKdayVFgoWzs8MilcYq0QIhKx/w== -----END EC PRIVATE KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec256-public-v2.pem000066400000000000000000000002621444067622100223650ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7JbAf3pWEEPje6NG+4dGOwIZnNwR FIe7DnQ4xFWKPrL5tVWlBh7NDFhjGNhiyO+aQjbcx9uWV74ifq7i21Bemg== -----END PUBLIC KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec256-public.pem000066400000000000000000000002621444067622100220400ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEAr+WbDE5VtIDGhtYMxvEc6cMsDBc /DX1wuhIMu8dQzOLSt0tpqK9MVfXbVfrKdayVFgoWzs8MilcYq0QIhKx/w== -----END PUBLIC KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec256-wrong-private.pem000066400000000000000000000003371444067622100233710ustar00rootroot00000000000000-----BEGIN EC PRIVATE KEY----- MHQCAQEEICfA4AaomONdmPTzeyrx5U/jugYXTERyb5U3ETTv7Hx7oAcGBSuBBAAK oUQDQgAEPmuXZT3jpJnEMVPOW6RMsmxeGLOCE1PN6fwvUwOsxv7YnyoQ5/bpo64n +Jp4slSl1aUNoCBF2oz9bS0iyBo3jg== -----END EC PRIVATE KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec256-wrong-public.pem000066400000000000000000000002561444067622100231750ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEPmuXZT3jpJnEMVPOW6RMsmxeGLOCE1PN 6fwvUwOsxv7YnyoQ5/bpo64n+Jp4slSl1aUNoCBF2oz9bS0iyBo3jg== -----END PUBLIC KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec256k-private.pem000066400000000000000000000003371444067622100224120ustar00rootroot00000000000000-----BEGIN EC PRIVATE KEY----- MHQCAQEEIMTine3s8tT+8bswDM4/z8o+wIYGb9PQPrw8x6Nu6QDdoAcGBSuBBAAK oUQDQgAEy8wuv6+fXodLPLfhxm132y1R8m4dkng7tHe7N+sULV2Eth6AxEXQfd+E 4nuceR21UNCvQKqxiYwCzVwIKcHe/A== -----END EC PRIVATE KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec256k-public.pem000066400000000000000000000002561444067622100222160ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEy8wuv6+fXodLPLfhxm132y1R8m4dkng7 tHe7N+sULV2Eth6AxEXQfd+E4nuceR21UNCvQKqxiYwCzVwIKcHe/A== -----END PUBLIC KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec384-private.pem000066400000000000000000000004401444067622100222340ustar00rootroot00000000000000-----BEGIN EC PRIVATE KEY----- MIGkAgEBBDDxOljqUKw9YNhkluSJIBAYO1YXcNtS+vckd5hpTZ5toxsOlwbmyrnU Tn+D5Xma1m2gBwYFK4EEACKhZANiAASQwYTiRvXu1hMHceSosMs/8uf50sJI3jvK kdSkvuRAPxSzhtrUvCQDnVsThFq4aOdZZY1qh2ErJGtzmrx+pEsJvJnvfOTG3NGU KRalek+LQfVqAUSvDMKlxdkz2e67tso= -----END EC PRIVATE KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec384-public.pem000066400000000000000000000003271444067622100220440ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEkMGE4kb17tYTB3HkqLDLP/Ln+dLCSN47 ypHUpL7kQD8Us4ba1LwkA51bE4RauGjnWWWNaodhKyRrc5q8fqRLCbyZ73zkxtzR lCkWpXpPi0H1agFErwzCpcXZM9nuu7bK -----END PUBLIC KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec384-wrong-private.pem000066400000000000000000000004401444067622100233660ustar00rootroot00000000000000-----BEGIN EC PRIVATE KEY----- MIGkAgEBBDAfZW47dSKnC5JkSVOk1ERxCIi/IJ1p1WBnVGx4hnrNHy+dxtaZJaF+ YLInFQ/QbYegBwYFK4EEACKhZANiAAQwXkx4BFBGLXbzl5yVrfxK7er8hSi38iDE K2+7cdrR137Wn5JUnL4WTwXTzkyUgfBOL3sHNozwfgU03GD/EOUEKqzsIJiz2cbP bFALd4hS+8T4szDLVC9Jl1W6k0CAtmM= -----END EC PRIVATE KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec384-wrong-public.pem000066400000000000000000000003271444067622100231760ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEMF5MeARQRi1285ecla38Su3q/IUot/Ig xCtvu3Ha0dd+1p+SVJy+Fk8F085MlIHwTi97BzaM8H4FNNxg/xDlBCqs7CCYs9nG z2xQC3eIUvvE+LMwy1QvSZdVupNAgLZj -----END PUBLIC KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec512-private.pem000066400000000000000000000005551444067622100222340ustar00rootroot00000000000000-----BEGIN EC PRIVATE KEY----- MIHcAgEBBEIB0/+ffxEj7j62xvGaB5pvzk888e412ESO/EK/K0QlS9dSF8+Rj1rG zqpRB8fvDnoe8xdmkW/W5GKzojMyv7YQYumgBwYFK4EEACOhgYkDgYYABAEw74Yw aTbPY6TtWmxx6LJDzCX2nKWCPnKdZcEH9Ncu8g5RjRBRq2yacja3OoS6nA2YeDng reBJxZr376P6Ns6XcQFWDA6K/MCTrEBCsPxXZNxd8KR9vMGWhgNtWRrcKzwJfQkr suyehZkbbYyFnAWyARKHZuV7VUXmeEmRS/f93MPqVA== -----END EC PRIVATE KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec512-public.pem000066400000000000000000000004141444067622100220320ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBMO+GMGk2z2Ok7VpsceiyQ8wl9pyl gj5ynWXBB/TXLvIOUY0QUatsmnI2tzqEupwNmHg54K3gScWa9++j+jbOl3EBVgwO ivzAk6xAQrD8V2TcXfCkfbzBloYDbVka3Cs8CX0JK7LsnoWZG22MhZwFsgESh2bl e1VF5nhJkUv3/dzD6lQ= -----END PUBLIC KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec512-wrong-private.pem000066400000000000000000000005511444067622100233620ustar00rootroot00000000000000-----BEGIN EC PRIVATE KEY----- MIHbAgEBBEG/KbA2oCbiCT6L3V8XSz2WKBy0XhGvIFbl/ZkXIXnkYt+1B7wViSVo KCHuMFsi6xU/5nE1EuDG2UsQJmKeAMkIOKAHBgUrgQQAI6GBiQOBhgAEAG0TFWe5 cZ5DZIyfuysrCoQySTNxd+aT8sPIxsx7mW6YBTsuO6rEgxyegd2Auy4xtikxpzKv soMXR02999Aaus2jAAt/wxrhhr41BDP4MV0b6Zngb72hna0pcGqit5OyU8AbOJUZ +rdyowRGsOY+aPbOyVhdNcsEdxYC8GdIyCQLBC1H -----END EC PRIVATE KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/ec512-wrong-public.pem000066400000000000000000000004141444067622100231640ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAbRMVZ7lxnkNkjJ+7KysKhDJJM3F3 5pPyw8jGzHuZbpgFOy47qsSDHJ6B3YC7LjG2KTGnMq+ygxdHTb330Bq6zaMAC3/D GuGGvjUEM/gxXRvpmeBvvaGdrSlwaqK3k7JTwBs4lRn6t3KjBEaw5j5o9s7JWF01 ywR3FgLwZ0jIJAsELUc= -----END PUBLIC KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/rsa-1024-private.pem000066400000000000000000000015731444067622100225670ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQDO/ahgFDvniFoQ1dm+MdnkBi+Ts5W9AtQNgw4ZHIdPnqEzSgW7 0opKEu8hnlLqsIyU2BC2op/xOanipdbXObuFlA6bth1cYRI+YJlR3BbPGOIL6YbJ ud9m0gIsBlCDLm4e/E45ZS+emudISP7/SF7zxvxZlnr1z7HTm7nIIVBvuQIDAQAB AoGBAMzFQAccvU6GI6O4C5sOsiHUxMh3xtCftaxQVGgfQvVPVuXoeteep1Q0ewFl IV4vnkO5pH8pTtVTWG9x5KIy6QCql4qvr2jkOm4mo9uogrpNklvBl2lN4Lxubj0N mGRXaM3hckZl8+JT6uzfBfjy+pd8AOigJGPQCOZn4gmANW7pAkEA82Nh4wpj6ZRU NBiBq3ONZuH4xJm59MI2FWRJsGUFUYdSaFwyKKim52/13d8iUb7v9utWQFRatCXz Lqw9fQyVrwJBANm3dBOVxpUPrYEQsG0q2rdP+u6U3woylxwtQgJxImZKZmmJlPr8 9v23rhydvCe1ERPYe7EjF4RGWVPN3KLdExcCQDdzNfL3BApMS97OkoRQQC/nXbjU 2SPlN1MqVQuGCG8pqGG0V40h11y1CkvxMS10ldEojq77SOrwFnZUsXGS82sCQQC6 XdO7QCaxSq5XIRYlHN4EtS40NLOIYy3/LK6osHel4GIyTVd+UjSLk0QzssJxqwln V5TqWQO0cxPcLQiFUYEZAkEA2G84ilb9QXOgbNyoE1VifNk49hhodbSskLb86uwY Vgtzq1ZsqoPBCasr4WRiXt270n+mo5dNYRlZwiUn9lH78Q== -----END RSA PRIVATE KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/rsa-1024-public.pem000066400000000000000000000004201444067622100223610ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDO/ahgFDvniFoQ1dm+MdnkBi+T s5W9AtQNgw4ZHIdPnqEzSgW70opKEu8hnlLqsIyU2BC2op/xOanipdbXObuFlA6b th1cYRI+YJlR3BbPGOIL6YbJud9m0gIsBlCDLm4e/E45ZS+emudISP7/SF7zxvxZ lnr1z7HTm7nIIVBvuQIDAQAB -----END PUBLIC KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/rsa-2048-private.pem000066400000000000000000000032171444067622100225730ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEA4GzZTLU48c4WbyvHi+QKrB71x+T0eq5hqDbQqnlYjhD1Ika7 io1iplsdJWJuyxfYbUkb2Ol0fj4koZ/GS6lgCZr4+8UHbr1qf0Eu5HZSpszs2YxY 8U5RHnrpw67co7hlgAR9HbyNf5XIYgLV9ldHH/eazwnc3F/hgNsV0xjScVilejgo cJ4zcsyymvW8t42lteM7bI867ZuJhGop/V+Y0HFyrMsPoQyLuCUpr6ulOfrkr7ZO dhAIG8r1HcjOp/AUjM15vfXcbUZjkM/VloifX1YitU3upMGJ8/DpFGffMOImrn5r 6BT494V8rRyN2qvQoAkLJpqZ0avLxwiR2lgVQQIDAQABAoIBAEH0Ozgr2fxWEInD V/VooypKPvjr9F1JejGxSkmPN9MocKIOH3dsbZ1uEXa3ItBUxan4XlK06SNgp+tH xULfF/Y6sQlsse59hBq50Uoa69dRShn1AP6JgZVvkduMPBNxUYL5zrs6emsQXb9Q DglDRQfEAJ7vyxSIqQDxYcyT8uSUF70dqFe+E9B2VE3D6ccHc98k41pJrAFAUFH1 wwvDhfyYr7/Ultut9wzpZvU1meF3Vna3GOUHfxrG6wu1G+WIWHGjouzThsc1qiVI BtMCJxuCt5fOXRbU4STbMqhB6sZHiOh6J/dZU6JwRYt+IS8FB6kCNFSEWZWQledJ XqtYSQECgYEA9nmnFTRj3fTBq9zMXfCRujkSy6X2bOb39ftNXzHFuc+I6xmv/3Bs P9tDdjueP/SnCb7i/9hXkpEIcxjrjiqgcvD2ym1hE4q+odMzRAXYMdnmzI34SVZE U5hYJcYsXNKrTTleba7QgqdORmyJ9FwqLO40udvmrZMY223XDwgRkOkCgYEA6RkO 5wjjrWWp/G1YN3KXZTS1m2/eGrUThohXKAfAjbWWiouNLW2msXrxEWsPRL6xKiHu X9cwZwzi3MstAgk+bphUGUVUkGKNDjWHJA25tDYjbPtkd6xbL4eCHsKpNL3HNYr9 N0CIvgn7qjaHRBem0iK7T6keY4axaSVddEwYapkCgYEA13K5qaB1F4Smcpt8DTWH vPe8xUUaZlFzOJLmLCsuwmB2N8Ppg2j7RspcaxJsH021YaB5ftjWm+ipMSr8ZPY/ 8JlPsNzxuYpTXtNmAbT2KYVm6THEch61dTk6/DIBf1YrpUJbl5by7vJeStL/uBmE SGgksL5XIyzs0opuLdaIvFkCgYAyBLWE8AxjFfCvAQuwAj/ocLITo6KmWnrRIIqL RXaVMgUWv7FQsTnW1cnK8g05tC2yG8vZ9wQk6Mf5lwOWb0NdWgSZ0528ydj41pWk L+nMeN2LMjqxz2NVxJ8wWJcUgTCxFZ0WcRumo9/D+6V1ABpE9zz4cBLcSnfhVypB nV6T6QKBgQCSZNCQ9HPxjAgYcsqc5sjNwuN1GHQZSav3Tye3k6zHENe1lsteT9K8 xciGIuhybKZBvB4yImIIHCtnH+AS+mHAGqHarjNDMfvjOq0dMibPx4+bkIiHdBIH Xz+j5kmntvFiUnzr0Z/Tcqo+r8FvyCo1YWgwqGP8XoFrswD7gy7cZw== -----END RSA PRIVATE KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/rsa-2048-public.pem000066400000000000000000000007031444067622100223740ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4GzZTLU48c4WbyvHi+QK rB71x+T0eq5hqDbQqnlYjhD1Ika7io1iplsdJWJuyxfYbUkb2Ol0fj4koZ/GS6lg CZr4+8UHbr1qf0Eu5HZSpszs2YxY8U5RHnrpw67co7hlgAR9HbyNf5XIYgLV9ldH H/eazwnc3F/hgNsV0xjScVilejgocJ4zcsyymvW8t42lteM7bI867ZuJhGop/V+Y 0HFyrMsPoQyLuCUpr6ulOfrkr7ZOdhAIG8r1HcjOp/AUjM15vfXcbUZjkM/Vloif X1YitU3upMGJ8/DpFGffMOImrn5r6BT494V8rRyN2qvQoAkLJpqZ0avLxwiR2lgV QQIDAQAB -----END PUBLIC KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/rsa-2048-wrong-private.pem000066400000000000000000000032171444067622100237250ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAzHAVGaW9j4l3/b4ngcjjoIoIcnsQEWOMqErb5VhLZMGIq1gE O5qxPDAwooKsNotzcAOB3ZyLn7p5D+dmOrNUYkYWgYITNGeSifrnVqQugd5Fh1L8 K7zOGltUo2UtjbN4uJ56tzxBMZp2wejs2/Qu0eu0xZK3To+YkDcWOk92rmNgmUSQ C/kNyIOj+yBvOo3wTk6HvbhoIarCgJ6Lay1v/hMLyQLzwRY/Qfty1FTIDyTv2dch 47FsfkZ1KAL+MbUnHuCBPzGxRjXa8Iy9Z7YGxrYasUt1b0um64bscxoIiCu8yLL8 jlg01Rwrjr/MTwKRhwXlMp8B7HTonwtaG6arJwIDAQABAoIBAGFR4dmJusl/qW1T fj8cQLAFxaupxaZhe24J5NAyzgEy2Dqo9ariIwkB78UM66ozjEqAgOvcP+NTw5m8 kD/VapA1yTTxlO7XdzzUAhiOo80S4IphCMZRZNPLMmluGtdf3lIUr1pXBrn0TCBX H5o9jaREzpNXGof9d6T/dEdh2J9+uE/p1xE5GSxQfaPheZzCG7636La/DcArg/UR +TusPqp62BEmk96pE/KKJRmEeH+WnPfSh6sMpLxi3hkEU7AynpliGT6Z6xV4csBI S/rdpkcj5DWpbnQzkwdrnL2Q+POEq/vlx5/NlezvtQPNLvQWDyY4yBCoMKGb3EbX xrxP7MECgYEA/kwe4P0Mqk+087IyhjDBGPfcMt8gfYc9nzNfIYSWdSwuSag/hqHq I4GwHQzUV9ix3iM6w5hin10yAzWxCYZg9hquV+lSvNNpGB76FX6oOqwuAhyQMRwv eW+VUyfFXeJugwL5JuIaNTvwPpQVDHYtELLifie+uzJ5HC6dhg/XchcCgYEAzc5/ +IXjOlExd/mBgFk/5Y87ifA0ZOgbaJXifYgU0aNSgz1piHxU3n2p4jJ9lSdwwCl2 Fb5EN7666t20PL5QcXJ5ZdaTRLzRlYiqTWzfYHBgttbB1Jl3Ed9GsKuzRgaRqGFC ANJSqZlKG0NZ3keRtuKdFwq+IVOnsQr9g0TZiXECgYEAqUgtCiMKCloTIGMQpSnR cXiWWjsUmturls4Q1vQ3YHrvuVLKLyqb/dT4Uu5WcMAs765OESThCit0/pQAbVHK PCpYwubskAzAGjGM00BEZwJ1gixXhIm5xMIWCowgI7Z3ULlq+IptXeCvtkjHlksZ BtO+WLLGkkEwRCV38WWcSzMCgYA/Xxqgl/mD94RYAQgTUWgPc69Nph08BQyLg7ue E8z1UGkT6FEaqc4oRGGPOSTaTK63PQ0TXOb8k0pTD7l0CtYSWMFwzkXCoLGYbeCi vqd5tqDRLAe7QxYa9rl5pSUqptMrGeeNATZa6sya4H5Hp5oCyny8n54z/OJh7ZRq W0TwwQKBgQDDP7ksm2pcqadaVAmODdOlaDHbaEcxp8wN7YVz0lM3UpJth96ukbj7 S39eJhXYWOn6oJQb/lN9fGOYqjg3y6IchGZDp67ATvWYvn/NY0R7mt4K4oHx5TuN rSQlP3WmOGv8Kemw892uRfW/jZyBEHhsfS213WDttVPn9F635GdNWw== -----END RSA PRIVATE KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/rsa-2048-wrong-public.pem000066400000000000000000000007031444067622100235260ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzHAVGaW9j4l3/b4ngcjj oIoIcnsQEWOMqErb5VhLZMGIq1gEO5qxPDAwooKsNotzcAOB3ZyLn7p5D+dmOrNU YkYWgYITNGeSifrnVqQugd5Fh1L8K7zOGltUo2UtjbN4uJ56tzxBMZp2wejs2/Qu 0eu0xZK3To+YkDcWOk92rmNgmUSQC/kNyIOj+yBvOo3wTk6HvbhoIarCgJ6Lay1v /hMLyQLzwRY/Qfty1FTIDyTv2dch47FsfkZ1KAL+MbUnHuCBPzGxRjXa8Iy9Z7YG xrYasUt1b0um64bscxoIiCu8yLL8jlg01Rwrjr/MTwKRhwXlMp8B7HTonwtaG6ar JwIDAQAB -----END PUBLIC KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/rsa-4096-private.pem000066400000000000000000000062531444067622100226030ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIIJJwIBAAKCAgEAqETmgWBi5rCmb7euJplA/9xs65+bncc9Yvs5zjyycXSW82Jf RuyguGm0OvA2wog24dR4N2kT/87DcGtp5JqJWADVFNr+2V2r6i57/OMLruRpn3p2 r95dmo0COE+BxPFl7XEBT8JbH57ZtpgcB3/xkS14nLOWFf96hrXPlXJC+VMVKVZm A8k2LRh42vT5wUf4U0Doy/p7yFNSFFa6Q8wwe4TBy/z/f+rhFD1w8rxlYjallee/ ocm7bjZCwbJGMm7orLViqWfsFX3O35PeoJ5h/7uJ7iRwvTFERkTdwWP/0BeKBeIt BR3YFc2mut+V9W+WKRkMSL6Crc+oVSx3p8aB7j9SZFzQiRtes4BYETpX1xl2mgIq 5hvsFbLw7ESrlIodiwUMTrSIid2DQ6q80kv1zXPr4+Id6L0sJLxPCaXnTmNtasSw yedJJYxLjwhHJwtzFAeaq18H3O791YKhjAJ6YxK3zJ59jTE6Pkvqjq183f2PGHVR vgSN7aCmI6MBUUB5wDP2K8zX2sh40/uPDVSd6ei1vl3DpPk+h8iExx6AzbohfqZ+ 5RUUNx127L3MaQvOVC5TxV+R99gwKW++wzcVuO3m2KqVUj+K1uYBy3KBCUMBbckp EWGbN++jcdV5oJX6fsC66nOmKlntYwCL/pRww+oLsbzF8J3dxeDbKNF9JDsCAwEA AQKCAgBJF8TZJjlP5CQoGy227pNhkSpvH6HFY6qyuFZf09XfmrmHd4/Tiy41bRUx FO90iR7t8hFWYHqjf/k9eCtDdi164MGukYJqgVoQG6kYLLgCfI21DMlJk9otLFtu gnroRcP05EWhk9dpYONJgcGLMHSKj6n4x7nGTHe41HkbfcrB6ukiT7l4o4q5BAxb cFadMtoXr/ZvxJrIZgkddJ7snGHjBcP5DCkgM7MZy6aoilWv1/UNrOF9MdgNA9zz rrD3b136x7/XvqC6pS+bxuvJ8YK4R4qeu42NYT07GOcK/pk8lz0JWTodIt2eevqV 6lGFj7c2mv7PCpJRVgbVGL/RTVVap/+jbcRVLdnYKsII/dANG7iXnfwRgkLWet5D OOsPuvIuyiSaJIwcdRE3SSO+tZhKLt+gh/oLxBPw5Ex0FwsVTtYn3Q/X3EAx+Wph eFcRr3TVkDg0MfdWWkgk16DvYB5cWc29coTaH1g+2juadNHbtVAigwJorKc6sxH3 QGsW0WQJ8ZRZgJkSUuu3nr7QD3ZrgHptONQAh1RWGnIWi6OlMfaPdMo+SDnnL5SG mpOPjWadDc1XvMFnKQYMYB5GWU/ZNmnZmDLyg1Pc0Y+qRUc0s83nZFHN60KnUrSz 0MZDspSFtr0fMx0b2/EB4EbuXd3QjQURF6P6HtWBu6oFnzu1AQKCAQEA2R9BKJgJ vNP+DUu8NBzwmi0cKlAiaxt+w90i5DWq1XWPKgi+RVLkaQSJqHoYQVNgEwL/cWxp s2r3GCMNIdOrGdcm8dX/6UYFpRaFcViTycVEA7cwZOMppgqr2Q+ZYX42K7HObUVL JGvdEWWWfSsynUGsrG87DC1gl94ANxCdqkZdbW5d3X0w5v7M/1tlrmAeskZSZpeT 8BwwM6REb0U/B4/i8TLtLi/PGmMTOIxW41uKS/S6kq/gwyv+jNNO0ljhPt25iSbV K5ZHS4YuPKLl0tZMaOkPco9s6t4ES/Y317zQoTzUkAAkkFO4QPzRZL0ESqVBNR0h Ao7FLmFZzFHpoQKCAQEAxmZBn0UrJLXkD7bw66y4RwzjQYmxLlkEl3uvjrvVSuL1 mAHDW58aGIpFFZ8QSTtNewIBQYNifp/cdFHAagqtl/iMGEegaOpJAKu/ykrkfZUp 7mYDNng4ZWpypeKaGMAQoNzZiUpF+BDnqbeb/kgYu6sNlh9gRHR79rgAuZQxZ/1B tE8WcUFi4CnTq2QLqX4LwMuZHWXAJQoMoW3K5av+J544lIM6GdMJuIONtBBkKVQD ErrJ0bqYeykrFS6pKl/NBCZLGo5xFFRiYEdZ1GlA3uW3EGKppz6PS7194+x5UVts xZPUfkgdFjWCczkl4JDoWfaNn5sgXtiVbGh1n3gYWwKCAQB7vHEg1kyuXU4qe5/d PyTraIvlnVeQHNJIgy0QS3l5Pw8A0IzG6y+anehpqHNMP1zAWPQEytkOVAZPriIc xgl7p37dUa0PX0V2SPhxmR5YXeCeEXc197PTmb9H67jos8nhauqOoW/qaMJK2M9D tCubLUNf3eAT14R16CHNP93qnUE/TSeXQ3JsIofne0neb47u4F6zcuzvaNEbjSEn HJqID7sw5GoA6WQo0I+yqWAXICMXmHf/gtYfxGHEFeSUwexULH5BKG1R8sncw7J0 Ag3h8xkGrNON4SkcTLy8Iay/eS6YxRcKndo4mk2mU65tr77TX4xi3Z/jWkQLY5WO eJwhAoIBABO17wkSxyGDjJ/fDfpsE3bDmgRV2KuBHoqqOBvXH26sM7ghXLZKjT4o 5ooqXmTYJm91GIjYs71exnkr8hDW9L4nbEuxOgeSVyRg69H+NMshOaQ8sE8GDJxO wgsnAyY4Vq6UomwYW/E0RL/AxRezM/nZGaVzgo3qgLJXP4MwbOQm7hMq1FD2LQuW PDhH3Ty+kA5ca97W0Asd/3k+Pi0pNDvdZUOj8e7E369cKoTcKAdPGGsQ8aILhsCd q3EUTKwwDl8+KrH9utBJPejQzeTjfBVo/xH6q145QeVFcy9ku/zQN3M9p5vQMEuX j1lBMTkpTFw7uYBE2idyHw5BJoZsWQcCggEADfZTChqnOncItSflzGoaAACrr4/x KyT/4A+cPMCs11JN9J+EWsCezya2o1l/NF7YPcBR4qjCmFMEiq5GxH5fGLQp0aa7 V13mHA8XBQ25OW2K7BGJhMHdbuvTnl6jsOfC4+t7P2bUAYxoP6/ncxTzZ5OlBN5k aMv9firWl1kSKK75ww9DWn6j0rQ4dBetwX45EMcs+iKIdydg0fmJxR2EJ+uQsCFy xcWBEDqV7qLUi6UrAPL3v/DXUv9wKcKOTbKw/aNE8+YTWMUO330GCJ5cVU1eTL5t UrcNKOJkFIj7jJUCzv6vcy++hMJEbNXnnTVRnky6e9C2vwzMl33njntapg== -----END RSA PRIVATE KEY----- ruby-jwt-2.7.1/spec/fixtures/certs/rsa-4096-public.pem000066400000000000000000000014401444067622100224000ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAqETmgWBi5rCmb7euJplA /9xs65+bncc9Yvs5zjyycXSW82JfRuyguGm0OvA2wog24dR4N2kT/87DcGtp5JqJ WADVFNr+2V2r6i57/OMLruRpn3p2r95dmo0COE+BxPFl7XEBT8JbH57ZtpgcB3/x kS14nLOWFf96hrXPlXJC+VMVKVZmA8k2LRh42vT5wUf4U0Doy/p7yFNSFFa6Q8ww e4TBy/z/f+rhFD1w8rxlYjallee/ocm7bjZCwbJGMm7orLViqWfsFX3O35PeoJ5h /7uJ7iRwvTFERkTdwWP/0BeKBeItBR3YFc2mut+V9W+WKRkMSL6Crc+oVSx3p8aB 7j9SZFzQiRtes4BYETpX1xl2mgIq5hvsFbLw7ESrlIodiwUMTrSIid2DQ6q80kv1 zXPr4+Id6L0sJLxPCaXnTmNtasSwyedJJYxLjwhHJwtzFAeaq18H3O791YKhjAJ6 YxK3zJ59jTE6Pkvqjq183f2PGHVRvgSN7aCmI6MBUUB5wDP2K8zX2sh40/uPDVSd 6ei1vl3DpPk+h8iExx6AzbohfqZ+5RUUNx127L3MaQvOVC5TxV+R99gwKW++wzcV uO3m2KqVUj+K1uYBy3KBCUMBbckpEWGbN++jcdV5oJX6fsC66nOmKlntYwCL/pRw w+oLsbzF8J3dxeDbKNF9JDsCAwEAAQ== -----END PUBLIC KEY----- ruby-jwt-2.7.1/spec/integration/000077500000000000000000000000001444067622100165675ustar00rootroot00000000000000ruby-jwt-2.7.1/spec/integration/readme_examples_spec.rb000066400000000000000000000357121444067622100232710ustar00rootroot00000000000000# frozen_string_literal: true require 'logger' RSpec.describe 'README.md code test' do context 'algorithm usage' do let(:payload) { { data: 'test' } } it 'NONE' do token = JWT.encode payload, nil, 'none' decoded_token = JWT.decode token, nil, false expect(token).to eq 'eyJhbGciOiJub25lIn0.eyJkYXRhIjoidGVzdCJ9.' expect(decoded_token).to eq [ { 'data' => 'test' }, { 'alg' => 'none' } ] end it 'decodes with HMAC algorithm with secret key' do token = JWT.encode payload, 'my$ecretK3y', 'HS256' decoded_token = JWT.decode token, 'my$ecretK3y', false expect(token).to eq 'eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.pNIWIL34Jo13LViZAJACzK6Yf0qnvT_BuwOxiMCPE-Y' expect(decoded_token).to eq [ { 'data' => 'test' }, { 'alg' => 'HS256' } ] end it 'decodes with HMAC algorithm without secret key' do pending 'Different behaviour on OpenSSL 3.0 (https://github.com/openssl/openssl/issues/13089)' if ::JWT.openssl_3_hmac_empty_key_regression? token = JWT.encode payload, nil, 'HS256' decoded_token = JWT.decode token, nil, false expect(token).to eq 'eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.pVzcY2dX8JNM3LzIYeP2B1e1Wcpt1K3TWVvIYSF4x-o' expect(decoded_token).to eq [ { 'data' => 'test' }, { 'alg' => 'HS256' } ] end it 'RSA' do rsa_private = OpenSSL::PKey::RSA.generate 2048 rsa_public = rsa_private.public_key token = JWT.encode payload, rsa_private, 'RS256' decoded_token = JWT.decode token, rsa_public, true, algorithm: 'RS256' expect(decoded_token).to eq [ { 'data' => 'test' }, { 'alg' => 'RS256' } ] end it 'ECDSA' do ecdsa_key = OpenSSL::PKey::EC.generate('prime256v1') token = JWT.encode payload, ecdsa_key, 'ES256' decoded_token = JWT.decode token, ecdsa_key, true, algorithm: 'ES256' expect(decoded_token).to eq [ { 'data' => 'test' }, { 'alg' => 'ES256' } ] end if defined?(RbNaCl) it 'EDDSA' do eddsa_key = RbNaCl::Signatures::Ed25519::SigningKey.generate eddsa_public = eddsa_key.verify_key token = JWT.encode payload, eddsa_key, 'ED25519' decoded_token = JWT.decode token, eddsa_public, true, algorithm: 'ED25519' expect(decoded_token).to eq [ { 'data' => 'test' }, { 'alg' => 'ED25519' } ] end end if ::Gem::Version.new(OpenSSL::VERSION) >= ::Gem::Version.new('2.1') it 'RSASSA-PSS' do rsa_private = OpenSSL::PKey::RSA.generate 2048 rsa_public = rsa_private.public_key token = JWT.encode payload, rsa_private, 'PS256' decoded_token = JWT.decode token, rsa_public, true, algorithm: 'PS256' expect(decoded_token).to eq [ { 'data' => 'test' }, { 'alg' => 'PS256' } ] end end end context 'claims' do let(:hmac_secret) { 'MyP4ssW0rD' } context 'exp' do it 'without leeway' do exp = Time.now.to_i + (4 * 3600) exp_payload = { data: 'data', exp: exp } token = JWT.encode exp_payload, hmac_secret, 'HS256' expect do JWT.decode token, hmac_secret, true, algorithm: 'HS256' end.not_to raise_error end it 'with leeway' do exp = Time.now.to_i - 10 leeway = 30 # seconds exp_payload = { data: 'data', exp: exp } token = JWT.encode exp_payload, hmac_secret, 'HS256' expect do JWT.decode token, hmac_secret, true, leeway: leeway, algorithm: 'HS256' end.not_to raise_error end end context 'nbf' do it 'without leeway' do nbf = Time.now.to_i - 3600 nbf_payload = { data: 'data', nbf: nbf } token = JWT.encode nbf_payload, hmac_secret, 'HS256' expect do JWT.decode token, hmac_secret, true, algorithm: 'HS256' end.not_to raise_error end it 'with leeway' do nbf = Time.now.to_i + 10 leeway = 30 nbf_payload = { data: 'data', nbf: nbf } token = JWT.encode nbf_payload, hmac_secret, 'HS256' expect do JWT.decode token, hmac_secret, true, leeway: leeway, algorithm: 'HS256' end.not_to raise_error end end it 'iss' do iss = 'My Awesome Company Inc. or https://my.awesome.website/' iss_payload = { data: 'data', iss: iss } token = JWT.encode iss_payload, hmac_secret, 'HS256' expect do JWT.decode token, hmac_secret, true, iss: iss, algorithm: 'HS256' end.not_to raise_error end context 'aud' do it 'array' do aud = %w[Young Old] aud_payload = { data: 'data', aud: aud } token = JWT.encode aud_payload, hmac_secret, 'HS256' expect do JWT.decode token, hmac_secret, true, aud: %w[Old Young], verify_aud: true, algorithm: 'HS256' end.not_to raise_error end it 'string' do aud = 'Kids' aud_payload = { data: 'data', aud: aud } token = JWT.encode aud_payload, hmac_secret, 'HS256' expect do JWT.decode token, hmac_secret, true, aud: 'Kids', verify_aud: true, algorithm: 'HS256' end.not_to raise_error end end it 'jti' do iat = Time.now.to_i hmac_secret = 'test' jti_raw = [hmac_secret, iat].join(':').to_s jti = Digest::MD5.hexdigest(jti_raw) jti_payload = { data: 'data', iat: iat, jti: jti } token = JWT.encode jti_payload, hmac_secret, 'HS256' expect do JWT.decode token, hmac_secret, true, verify_jti: true, algorithm: 'HS256' end.not_to raise_error end context 'iat' do it 'without leeway' do iat = Time.now.to_i iat_payload = { data: 'data', iat: iat } token = JWT.encode iat_payload, hmac_secret, 'HS256' expect do JWT.decode token, hmac_secret, true, verify_iat: true, algorithm: 'HS256' end.not_to raise_error end it 'with leeway' do iat = Time.now.to_i - 7 iat_payload = { data: 'data', iat: iat, leeway: 10 } token = JWT.encode iat_payload, hmac_secret, 'HS256' expect do JWT.decode token, hmac_secret, true, verify_iat: true, algorithm: 'HS256' end.not_to raise_error end end context 'custom header fields' do it 'with custom field' do payload = { data: 'test' } token = JWT.encode payload, nil, 'none', typ: 'JWT' _, header = JWT.decode token, nil, false expect(header['typ']).to eq 'JWT' end end it 'sub' do sub = 'Subject' sub_payload = { data: 'data', sub: sub } token = JWT.encode sub_payload, hmac_secret, 'HS256' expect do JWT.decode token, hmac_secret, true, 'sub' => sub, :verify_sub => true, :algorithm => 'HS256' end.not_to raise_error end it 'required_claims' do payload = { data: 'test' } token = JWT.encode payload, hmac_secret, 'HS256' expect do JWT.decode token, hmac_secret, true, required_claims: ['exp'], algorithm: 'HS256' end.to raise_error(JWT::MissingRequiredClaim) expect do JWT.decode token, hmac_secret, true, required_claims: ['data'], algorithm: 'HS256' end.not_to raise_error end it 'find_key' do issuers = %w[My_Awesome_Company1 My_Awesome_Company2] iss_payload = { data: 'data', iss: issuers.first } secrets = { issuers.first => hmac_secret, issuers.last => 'hmac_secret2' } token = JWT.encode iss_payload, hmac_secret, 'HS256' expect do # Add iss to the validation to check if the token has been manipulated JWT.decode(token, nil, true, { iss: issuers, verify_iss: true, algorithm: 'HS256' }) do |_headers, payload| secrets[payload['iss']] end end.not_to raise_error end context 'The JWK based encode/decode routine' do it 'works as expected' do # ---------- ENCODE ---------- optional_parameters = { kid: 'my-kid', use: 'sig', alg: 'RS512' } jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), optional_parameters) # Encoding payload = { data: 'data' } token = JWT.encode(payload, jwk.signing_key, jwk[:alg], kid: jwk[:kid]) # JSON Web Key Set for advertising your signing keys jwks_hash = JWT::JWK::Set.new(jwk).export # ---------- DECODE ---------- jwks = JWT::JWK::Set.new(jwks_hash) jwks.filter! { |key| key[:use] == 'sig' } # Signing keys only! algorithms = jwks.map { |key| key[:alg] }.compact.uniq JWT.decode(token, nil, true, algorithms: algorithms, jwks: jwks) end end context 'The JWKS loader example' do let(:logger_output) { StringIO.new } let(:logger) { Logger.new(logger_output) } it 'works as expected (legacy)' do jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), 'optional-kid') payload = { data: 'data' } headers = { kid: jwk.kid } token = JWT.encode(payload, jwk.signing_key, 'RS512', headers) # The jwk loader would fetch the set of JWKs from a trusted source, # to avoid malicious invalidations some kind of protection needs to be implemented. # This example only allows cache invalidations every 5 minutes. jwk_loader = ->(options) do if options[:kid_not_found] && @cache_last_update < Time.now.to_i - 300 logger.info("Invalidating JWK cache. #{options[:kid]} not found from previous cache") @cached_keys = nil end @cached_keys ||= begin @cache_last_update = Time.now.to_i { keys: [jwk.export] } end end begin JWT.decode(token, nil, true, { algorithms: ['RS512'], jwks: jwk_loader }) rescue JWT::JWKError # Handle problems with the provided JWKs rescue JWT::DecodeError # Handle other decode related issues e.g. no kid in header, no matching public key found etc. end ## This is not in the example but verifies that the cache is invalidated after 5 minutes jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), 'new-kid') headers = { kid: jwk.kid } token = JWT.encode(payload, jwk.signing_key, 'RS512', headers) @cache_last_update = Time.now.to_i - 301 JWT.decode(token, nil, true, { algorithms: ['RS512'], jwks: jwk_loader }) expect(logger_output.string.chomp).to match(/^I, .* : Invalidating JWK cache. new-kid not found from previous cache/) jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), 'yet-another-new-kid') headers = { kid: jwk.kid } token = JWT.encode(payload, jwk.signing_key, 'RS512', headers) expect { JWT.decode(token, nil, true, { algorithms: ['RS512'], jwks: jwk_loader }) }.to raise_error(JWT::DecodeError, 'Could not find public key for kid yet-another-new-kid') end it 'works as expected' do jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), use: 'sig') jwks_hash = JWT::JWK::Set.new(jwk) payload = { data: 'data' } headers = { kid: jwk.kid } token = JWT.encode(payload, jwk.signing_key, 'RS512', headers) jwks_loader = ->(options) do # The jwk loader would fetch the set of JWKs from a trusted source. # To avoid malicious requests triggering cache invalidations there needs to be # some kind of grace time or other logic for determining the validity of the invalidation. # This example only allows cache invalidations every 5 minutes. if options[:kid_not_found] && @cache_last_update < Time.now.to_i - 300 logger.info("Invalidating JWK cache. #{options[:kid]} not found from previous cache") @cached_keys = nil end @cached_keys ||= begin @cache_last_update = Time.now.to_i # Replace with your own JWKS fetching routine jwks = JWT::JWK::Set.new(jwks_hash) jwks.select! { |key| key[:use] == 'sig' } # Signing Keys only jwks end end begin JWT.decode(token, nil, true, { algorithms: ['RS512'], jwks: jwks_loader }) rescue JWT::JWKError # Handle problems with the provided JWKs rescue JWT::DecodeError # Handle other decode related issues e.g. no kid in header, no matching public key found etc. end end end it 'JWK import and export' do # Import a JWK Hash (showing an HMAC example) _jwk = JWT::JWK.new({ kty: 'oct', k: 'my-secret', kid: 'my-kid' }) # Import an OpenSSL key # You can optionally add descriptive parameters to the JWK desc_params = { kid: 'my-kid', use: 'sig' } jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), desc_params) # Export as JWK Hash (public key only by default) _jwk_hash = jwk.export _jwk_hash_with_private_key = jwk.export(include_private: true) # Export as OpenSSL key _public_key = jwk.verify_key _private_key = jwk.signing_key if jwk.private? # You can also import and export entire JSON Web Key Sets jwks_hash = { keys: [{ kty: 'oct', k: 'my-secret', kid: 'my-kid' }] } jwks = JWT::JWK::Set.new(jwks_hash) _jwks_hash = jwks.export end it 'JWK with thumbprint as kid via symbol' do JWT.configuration.jwk.kid_generator_type = :rfc7638_thumbprint jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048)) jwk_hash = jwk.export expect(jwk_hash[:kid].size).to eq(43) end it 'JWK with thumbprint as kid via type' do JWT.configuration.jwk.kid_generator = ::JWT::JWK::Thumbprint jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048)) jwk_hash = jwk.export expect(jwk_hash[:kid].size).to eq(43) end it 'JWK with thumbprint given in the initializer (legacy)' do jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), kid_generator: ::JWT::JWK::Thumbprint) jwk_hash = jwk.export expect(jwk_hash[:kid].size).to eq(43) end it 'JWK with thumbprint given in the initializer' do jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), nil, kid_generator: ::JWT::JWK::Thumbprint) jwk_hash = jwk.export expect(jwk_hash[:kid].size).to eq(43) end end context 'custom algorithm example' do it 'allows a module to be used as algorithm on encode and decode' do custom_hs512_alg = Module.new do def self.alg 'HS512' end def self.valid_alg?(alg_to_validate) alg_to_validate == alg end def self.sign(data:, signing_key:) OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha512'), data, signing_key) end def self.verify(data:, signature:, verification_key:) sign(data: data, signing_key: verification_key) == signature end end token = ::JWT.encode({ 'pay' => 'load' }, 'secret', custom_hs512_alg) _payload, _header = ::JWT.decode(token, 'secret', true, algorithm: custom_hs512_alg) end end end ruby-jwt-2.7.1/spec/jwk/000077500000000000000000000000001444067622100150375ustar00rootroot00000000000000ruby-jwt-2.7.1/spec/jwk/decode_with_jwk_spec.rb000066400000000000000000000177251444067622100215430ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe JWT do describe '.decode for JWK usecase' do let(:keypair) { OpenSSL::PKey::RSA.new(2048) } let(:jwk) { JWT::JWK.new(keypair) } let(:public_jwks) { { keys: [jwk.export, { kid: 'not_the_correct_one', kty: 'oct', k: 'secret' }] } } let(:token_payload) { { 'data' => 'something' } } let(:token_headers) { { kid: jwk.kid } } let(:algorithm) { 'RS512' } let(:signed_token) { described_class.encode(token_payload, jwk.signing_key, algorithm, token_headers) } context 'when JWK features are used manually' do it 'is able to decode the token' do payload, _header = described_class.decode(signed_token, nil, true, { algorithms: [algorithm] }) do |header, _payload| JWT::JWK.import(public_jwks[:keys].find { |key| key[:kid] == header['kid'] }).verify_key end expect(payload).to eq(token_payload) end end context 'when jwk keys are given as an array' do context 'and kid is in the set' do it 'is able to decode the token' do payload, _header = described_class.decode(signed_token, nil, true, { algorithms: [algorithm], jwks: public_jwks }) expect(payload).to eq(token_payload) end end context 'and kid is not in the set' do before do public_jwks[:keys].first[:kid] = 'NOT_A_MATCH' end it 'raises an exception' do expect { described_class.decode(signed_token, nil, true, { algorithms: [algorithm], jwks: public_jwks }) }.to raise_error( JWT::DecodeError, /Could not find public key for kid .*/ ) end end context 'no keys are found in the set' do let(:public_jwks) { { keys: [] } } it 'raises an exception' do expect { described_class.decode(signed_token, nil, true, { algorithms: [algorithm], jwks: public_jwks }) }.to raise_error( JWT::DecodeError, /No keys found in jwks/ ) end end context 'token does not know the kid' do let(:token_headers) { {} } it 'raises an exception' do expect { described_class.decode(signed_token, nil, true, { algorithms: [algorithm], jwks: public_jwks }) }.to raise_error( JWT::DecodeError, 'No key id (kid) found from token headers' ) end end end context 'when jwk keys are loaded using a proc/lambda' do it 'decodes the token' do payload, _header = described_class.decode(signed_token, nil, true, { algorithms: [algorithm], jwks: lambda { |_opts| public_jwks } }) expect(payload).to eq(token_payload) end end context 'when jwk keys are rotated' do it 'decodes the token' do key_loader = ->(options) { options[:invalidate] ? public_jwks : { keys: [] } } payload, _header = described_class.decode(signed_token, nil, true, { algorithms: [algorithm], jwks: key_loader }) expect(payload).to eq(token_payload) end end context 'when jwk keys are loaded from JSON with string keys' do it 'decodes the token' do key_loader = ->(_options) { JSON.parse(JSON.generate(public_jwks)) } payload, _header = described_class.decode(signed_token, nil, true, { algorithms: [algorithm], jwks: key_loader }) expect(payload).to eq(token_payload) end end context 'when the token kid is nil' do let(:token_headers) { {} } context 'and allow_nil_kid is specified' do it 'decodes the token' do key_loader = ->(_options) { JSON.parse(JSON.generate(public_jwks)) } payload, _header = described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: key_loader, allow_nil_kid: true }) expect(payload).to eq(token_payload) end end end context 'when the token kid is not a string' do let(:token_headers) { { kid: 5 } } it 'raises an exception' do expect { described_class.decode(signed_token, nil, true, { algorithms: ['RS512'], jwks: public_jwks }) }.to raise_error( JWT::DecodeError, 'Invalid type for kid header parameter' ) end end context 'mixing algorithms using kid header' do let(:hmac_jwk) { JWT::JWK.new('secret') } let(:rsa_jwk) { JWT::JWK.new(OpenSSL::PKey::RSA.new(2048)) } let(:ec_jwk_secp384r1) { JWT::JWK.new(OpenSSL::PKey::EC.generate('secp384r1')) } let(:ec_jwk_secp521r1) { JWT::JWK.new(OpenSSL::PKey::EC.generate('secp521r1')) } let(:jwks) { { keys: [hmac_jwk.export(include_private: true), rsa_jwk.export, ec_jwk_secp384r1.export, ec_jwk_secp521r1.export] } } context 'when RSA key is pointed to as HMAC secret' do let(:signed_token) { described_class.encode({ 'foo' => 'bar' }, 'is not really relevant in the scenario', 'HS256', { kid: rsa_jwk.kid }) } it 'raises JWT::DecodeError' do expect { described_class.decode(signed_token, nil, true, algorithms: ['HS256'], jwks: jwks) }.to raise_error(JWT::DecodeError, 'HMAC key expected to be a String') end end context 'when EC key is pointed to as HMAC secret' do let(:signed_token) { described_class.encode({ 'foo' => 'bar' }, 'is not really relevant in the scenario', 'HS256', { kid: ec_jwk_secp384r1.kid }) } it 'raises JWT::DecodeError' do expect { described_class.decode(signed_token, nil, true, algorithms: ['HS256'], jwks: jwks) }.to raise_error(JWT::DecodeError, 'HMAC key expected to be a String') end end context 'when EC key is pointed to as RSA public key' do let(:signed_token) { described_class.encode({ 'foo' => 'bar' }, rsa_jwk.signing_key, algorithm, { kid: ec_jwk_secp384r1.kid }) } it 'fails in some way' do expect { described_class.decode(signed_token, nil, true, algorithms: [algorithm], jwks: jwks) }.to( raise_error(JWT::VerificationError, 'Signature verification raised') ) end end context 'when HMAC secret is pointed to as RSA public key' do let(:signed_token) { described_class.encode({ 'foo' => 'bar' }, rsa_jwk.signing_key, algorithm, { kid: hmac_jwk.kid }) } it 'fails in some way' do expect { described_class.decode(signed_token, nil, true, algorithms: [algorithm], jwks: jwks) }.to( raise_error(NoMethodError, /undefined method `verify' for/) ) end end context 'when HMAC secret is pointed to as EC public key' do let(:signed_token) { described_class.encode({ 'foo' => 'bar' }, ec_jwk_secp384r1.signing_key, 'ES384', { kid: hmac_jwk.kid }) } it 'fails in some way' do expect { described_class.decode(signed_token, nil, true, algorithms: ['ES384'], jwks: jwks) }.to( raise_error(NoMethodError, /undefined method `group' for/) ) end end context 'when ES384 key is pointed to as ES512 key' do let(:signed_token) { described_class.encode({ 'foo' => 'bar' }, ec_jwk_secp384r1.signing_key, 'ES512', { kid: ec_jwk_secp521r1.kid }) } it 'fails in some way' do expect { described_class.decode(signed_token, nil, true, algorithms: ['ES512'], jwks: jwks) }.to( raise_error(JWT::IncorrectAlgorithm, 'payload algorithm is ES512 but ES384 signing key was provided') ) end end if defined?(RbNaCl) context 'when OKP keys are used' do before do skip('Requires the rbnacl gem') unless ::JWT.rbnacl? end let(:keypair) { RbNaCl::Signatures::Ed25519::SigningKey.new(SecureRandom.hex) } let(:algorithm) { 'ED25519' } it 'decodes the token' do key_loader = ->(_options) { JSON.parse(JSON.generate(public_jwks)) } payload, _header = described_class.decode(signed_token, nil, true, { algorithms: [algorithm], jwks: key_loader }) expect(payload).to eq(token_payload) end end end end end end ruby-jwt-2.7.1/spec/jwk/ec_spec.rb000066400000000000000000000112651444067622100167720ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe JWT::JWK::EC do let(:ec_key) { OpenSSL::PKey::EC.generate('secp384r1') } describe '.new' do subject { described_class.new(keypair) } context 'when a keypair with both keys given' do let(:keypair) { ec_key } it 'creates an instance of the class' do expect(subject).to be_a described_class expect(subject.private?).to eq true end end context 'when a keypair with only public key is given' do let(:keypair) { OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256-public.pem'))) } it 'creates an instance of the class' do expect(subject).to be_a described_class expect(subject.private?).to eq false end end end describe '#keypair' do subject(:jwk) { described_class.new(ec_key) } it 'warns to stderr' do expect(jwk.keypair).to eq(ec_key) end end describe '#export' do let(:kid) { nil } subject { described_class.new(keypair, kid).export } context 'when keypair with private key is exported' do let(:keypair) { ec_key } it 'returns a hash with the both parts of the key' do expect(subject).to be_a Hash expect(subject).to include(:kty, :kid, :x, :y) # Exported keys do not currently include private key info, # event if the in-memory key had that information. This is # done to match the traditional behavior of RSA JWKs. ## expect(subject).to include(:d) end end context 'when keypair with public key is exported' do let(:keypair) { OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256-public.pem'))) } it 'returns a hash with the public parts of the key' do expect(subject).to be_a Hash expect(subject).to include(:kty, :kid, :x, :y) # Don't include private `d` if not explicitly requested. expect(subject).not_to include(:d) end context 'when a custom "kid" is provided' do let(:kid) { 'custom_key_identifier' } it 'exports it' do expect(subject[:kid]).to eq 'custom_key_identifier' end end end context 'when private key is requested' do subject { described_class.new(keypair).export(include_private: true) } let(:keypair) { ec_key } it 'returns a hash with the both parts of the key' do expect(subject).to be_a Hash expect(subject).to include(:kty, :kid, :x, :y) # `d` is the private part. expect(subject).to include(:d) end end context 'when a common parameter is given' do let(:parameters) { { use: 'sig' } } let(:keypair) { ec_key } subject { described_class.new(keypair, parameters).export } it 'returns a hash including the common parameter' do expect(subject).to include(:use) end end end describe '.import' do subject { described_class.import(params) } let(:include_private) { false } let(:exported_key) { described_class.new(keypair).export(include_private: include_private) } ['P-256', 'P-384', 'P-521', 'P-256K'].each do |crv| context "when crv=#{crv}" do let(:openssl_curve) { JWT::JWK::EC.to_openssl_curve(crv) } let(:ec_key) { OpenSSL::PKey::EC.generate(openssl_curve) } context 'when keypair is private' do let(:include_private) { true } let(:keypair) { ec_key } let(:params) { exported_key } it 'returns a private key' do expect(subject.private?).to eq true expect(subject).to be_a described_class # Regular export returns only the non-private parts. public_only = exported_key.reject { |k, _v| k == :d } expect(subject.export).to eq(public_only) # Private export returns the original input. expect(subject.export(include_private: true)).to eq(exported_key) end context 'with a custom "kid" value' do let(:exported_key) { super().merge(kid: 'custom_key_identifier') } it 'imports that "kid" value' do expect(subject.kid).to eq('custom_key_identifier') end end end context 'when keypair is public' do context 'returns a public key' do let(:keypair) { OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256-public.pem'))) } let(:params) { exported_key } it 'returns a hash with the public parts of the key' do expect(subject).to be_a described_class expect(subject.private?).to eq false expect(subject.export).to eq(exported_key) end end end end end end end ruby-jwt-2.7.1/spec/jwk/hmac_spec.rb000066400000000000000000000043611444067622100173120ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe JWT::JWK::HMAC do let(:hmac_key) { 'secret-key' } let(:key) { hmac_key } subject(:jwk) { described_class.new(key) } describe '.new' do context 'when a secret key given' do it 'creates an instance of the class' do expect(jwk).to be_a described_class expect(jwk.private?).to eq true end end end describe '#keypair' do it 'returns a string' do expect(jwk.keypair).to eq(key) end end describe '#export' do let(:kid) { nil } context 'when key is exported' do let(:key) { hmac_key } subject { described_class.new(key, kid).export } it 'returns a hash with the key' do expect(subject).to be_a Hash expect(subject).to include(:kty, :kid) end end context 'when key is exported with private key' do let(:key) { hmac_key } subject { described_class.new(key, kid).export(include_private: true) } it 'returns a hash with the key' do expect(subject).to be_a Hash expect(subject).to include(:kty, :kid, :k) end end end describe '.import' do subject { described_class.import(params) } let(:exported_key) { described_class.new(key).export(include_private: true) } context 'when secret key is given' do let(:key) { hmac_key } let(:params) { exported_key } it 'returns a key' do expect(subject).to be_a described_class expect(subject.export(include_private: true)).to eq(exported_key) end context 'with a custom "kid" value' do let(:exported_key) { super().merge(kid: 'custom_key_identifier') } it 'imports that "kid" value' do expect(subject.kid).to eq('custom_key_identifier') end end context 'with a common parameter' do let(:exported_key) { super().merge(use: 'sig') } it 'imports that common parameter' do expect(subject[:use]).to eq('sig') end end end end describe '#[]=' do context 'when k is given' do it 'raises an error' do expect { jwk[:k] = 'new_secret' }.to raise_error(ArgumentError, 'cannot overwrite cryptographic key attributes') end end end end ruby-jwt-2.7.1/spec/jwk/okp_rbnacl_spec.rb000066400000000000000000000102511444067622100205070ustar00rootroot00000000000000# frozen_string_literal: true require 'securerandom' describe 'JWT::JWK::OKPRbNaCl' do let(:described_class) { JWT::JWK::OKPRbNaCl } let(:private_key) { RbNaCl::Signatures::Ed25519::SigningKey.new(SecureRandom.hex) } let(:public_key) { private_key.verify_key } let(:key) { nil } subject(:instance) { described_class.new(key) } before do skip('Requires the rbnacl gem') unless ::JWT.rbnacl? end describe '.new' do context 'when private key is given' do let(:key) { private_key } it { is_expected.to be_a(described_class) } end context 'when public key is given' do let(:key) { public_key } it { is_expected.to be_a(described_class) } end context 'when something else than a public or private key is given' do let(:key) { OpenSSL::PKey::RSA.new(2048) } it 'raises an ArgumentError' do expect { instance }.to raise_error(ArgumentError) end end context 'when jwk parameters given' do let(:key) do { kty: 'OKP', use: 'sig', crv: 'Ed25519', kid: '27zV', x: '0I6olrZGYml7JGusuKJW9G7D0DZ9UormSady9kR7V4Q' } end it { is_expected.to be_a(described_class) } end end describe '#verify_key' do let(:key) { private_key } subject { instance.verify_key } it 'is the verify key' do expect(subject).to be_a(RbNaCl::Signatures::Ed25519::VerifyKey) end end describe '#private?' do subject { instance.private? } context 'when private key is given' do let(:key) { private_key } it { is_expected.to eq(true) } end context 'when public key is given' do let(:key) { public_key } it { is_expected.to eq(false) } end end describe '#export' do let(:options) { {} } subject { instance.export(options) } context 'when private key is given' do let(:key) { private_key } it 'exports the public key' do expect(subject).to include(crv: 'Ed25519', kty: 'OKP') expect(subject.keys).to eq(%i[kty crv x kid]) expect(subject[:x].size).to eq(43) expect(subject[:kid].size).to eq(43) end end context 'when private key is asked for' do let(:key) { private_key } let(:options) { { include_private: true } } it 'exports the private key' do expect(subject).to include(crv: 'Ed25519', kty: 'OKP') expect(subject.keys).to eq(%i[kty crv x d kid]) expect(subject[:x].size).to eq(43) expect(subject[:d].size).to eq(43) expect(subject[:kid].size).to eq(43) end end end describe '.import' do subject { described_class.import(import_data) } context 'when exported public key is given' do let(:import_data) { described_class.new(public_key).export } it 'creates a new instance of the class' do expect(subject.private?).to eq(false) expect(subject.verify_key).to be_a(RbNaCl::Signatures::Ed25519::VerifyKey) expect(subject.signing_key).to eq(nil) expect(subject.verify_key.to_bytes).to eq(public_key.to_bytes) expect(subject.kid).to eq(import_data[:kid]) end end context 'when exported private key is given' do let(:import_data) { described_class.new(private_key).export(include_private: true) } it 'creates a new instance of the class' do expect(subject.private?).to eq(true) expect(subject.verify_key).to be_a(RbNaCl::Signatures::Ed25519::VerifyKey) expect(subject.signing_key).to be_a(RbNaCl::Signatures::Ed25519::SigningKey) expect(subject.verify_key.to_bytes).to eq(public_key.to_bytes) expect(subject.kid).to eq(import_data[:kid]) end end context 'when JWK is given' do let(:import_data) { described_class.new(private_key) } it 'creates a new instance of the class' do expect(subject.private?).to eq(true) expect(subject.verify_key).to be_a(RbNaCl::Signatures::Ed25519::VerifyKey) expect(subject.signing_key).to be_a(RbNaCl::Signatures::Ed25519::SigningKey) expect(subject.verify_key.to_bytes).to eq(public_key.to_bytes) expect(subject.kid).to eq(import_data[:kid]) end end end end ruby-jwt-2.7.1/spec/jwk/rsa_spec.rb000066400000000000000000000205641444067622100171720ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe JWT::JWK::RSA do let(:rsa_key) { OpenSSL::PKey::RSA.new(2048) } describe '.new' do subject { described_class.new(keypair) } context 'when a keypair with both keys given' do let(:keypair) { rsa_key } it 'creates an instance of the class' do expect(subject).to be_a described_class expect(subject.private?).to eq true end end context 'when a keypair with only public key is given' do let(:keypair) { rsa_key.public_key } it 'creates an instance of the class' do expect(subject).to be_a described_class expect(subject.private?).to eq false end end end describe '#keypair' do subject(:jwk) { described_class.new(rsa_key) } it 'warns to stderr' do expect(jwk.keypair).to eq(rsa_key) end end describe '#export' do subject { described_class.new(keypair).export } context 'when keypair with private key is exported' do let(:keypair) { rsa_key } it 'returns a hash with the public parts of the key' do expect(subject).to be_a Hash expect(subject).to include(:kty, :n, :e, :kid) expect(subject).not_to include(:d, :p, :dp, :dq, :qi) end end context 'when keypair with public key is exported' do let(:keypair) { rsa_key.public_key } it 'returns a hash with the public parts of the key' do expect(subject).to be_a Hash expect(subject).to include(:kty, :n, :e, :kid) expect(subject).not_to include(:d, :p, :dp, :dq, :qi) end end context 'when unsupported keypair is given' do let(:keypair) { 'key' } it 'raises an error' do expect { subject }.to raise_error(ArgumentError) end end context 'when private key is requested' do subject { described_class.new(keypair).export(include_private: true) } let(:keypair) { rsa_key } it 'returns a hash with the public AND private parts of the key' do expect(subject).to be_a Hash expect(subject).to include(:kty, :n, :e, :kid, :d, :p, :q, :dp, :dq, :qi) end end end describe '.kid' do context 'when configuration says to use :rfc7638_thumbprint' do before do JWT.configuration.jwk.kid_generator_type = :rfc7638_thumbprint end it 'generates the kid based on the thumbprint' do expect(described_class.new(OpenSSL::PKey::RSA.new(2048)).kid.size).to eq(43) end end context 'when kid is given as a String parameter' do it 'uses the given kid' do expect(described_class.new(OpenSSL::PKey::RSA.new(2048), 'given').kid).to eq('given') end end context 'when kid is given in a hash parameter' do it 'uses the given kid' do expect(described_class.new(OpenSSL::PKey::RSA.new(2048), kid: 'given').kid).to eq('given') end end end describe '.common_parameters' do context 'when a common parameters hash is given' do it 'imports the common parameter' do expect(described_class.new(OpenSSL::PKey::RSA.new(2048), use: 'sig')[:use]).to eq('sig') end it 'converts string keys to symbol keys' do expect(described_class.new(OpenSSL::PKey::RSA.new(2048), { 'use' => 'sig' })[:use]).to eq('sig') end end end describe '.import' do subject { described_class.import(params) } let(:exported_key) { described_class.new(rsa_key).export } context 'when keypair is imported with symbol keys' do let(:params) { { kty: 'RSA', e: exported_key[:e], n: exported_key[:n] } } it 'returns a hash with the public parts of the key' do expect(subject).to be_a described_class expect(subject.private?).to eq false expect(subject.export).to eq(exported_key) end end context 'when keypair is imported with string keys from JSON' do let(:params) { { 'kty' => 'RSA', 'e' => exported_key[:e], 'n' => exported_key[:n] } } it 'returns a hash with the public parts of the key' do expect(subject).to be_a described_class expect(subject.private?).to eq false expect(subject.export).to eq(exported_key) end end context 'when private key is included in the data' do let(:exported_key) { described_class.new(rsa_key).export(include_private: true) } let(:params) { exported_key } it 'creates a complete keypair' do expect(subject).to be_a described_class expect(subject.private?).to eq true end end context 'when jwk_data is given without e and/or n' do let(:params) { { kty: 'RSA' } } it 'raises an error' do expect { subject }.to raise_error(JWT::JWKError, 'Key format is invalid for RSA') end end end shared_examples 'creating an RSA object from complete JWK parameters' do let(:rsa_parameters) { jwk_parameters.transform_values { |value| described_class.decode_open_ssl_bn(value) } } let(:all_jwk_parameters) { described_class.new(rsa_key).export(include_private: true) } context 'when public parameters (e, n) are given' do let(:jwk_parameters) { all_jwk_parameters.slice(:e, :n) } it 'creates a valid RSA object representing a public key' do expect(subject).to be_a(::OpenSSL::PKey::RSA) expect(subject.private?).to eq(false) end end context 'when only e, n, d, p and q are given' do let(:jwk_parameters) { all_jwk_parameters.slice(:e, :n, :d, :p, :q) } it 'raises an error telling all the exponents are required' do expect { subject }.to raise_error(JWT::JWKError, 'When one of p, q, dp, dq or qi is given all the other optimization parameters also needs to be defined') end end context 'when all key components n, e, d, p, q, dp, dq, qi are given' do let(:jwk_parameters) { all_jwk_parameters.slice(:n, :e, :d, :p, :q, :dp, :dq, :qi) } it 'creates a valid RSA object representing a public key' do expect(subject).to be_a(::OpenSSL::PKey::RSA) expect(subject.private?).to eq(true) end end end shared_examples 'creating an RSA object from partial JWK parameters' do context 'when e, n, d is given' do let(:jwk_parameters) { all_jwk_parameters.slice(:e, :n, :d) } before do skip 'OpenSSL prior to 2.2 does not seem to support partial parameters' if ::JWT.openssl_version < ::Gem::Version.new('2.2') end it 'creates a valid RSA object representing a private key' do expect(subject).to be_a(::OpenSSL::PKey::RSA) expect(subject.private?).to eq(true) end it 'can be used for encryption and decryption' do expect(subject.private_decrypt(subject.public_encrypt('secret'))).to eq('secret') end it 'can be used for signing and verification' do data = 'data_to_sign' signature = subject.sign(OpenSSL::Digest.new('SHA512'), data) expect(subject.verify(OpenSSL::Digest.new('SHA512'), signature, data)).to eq(true) end end end describe '.create_rsa_key_using_der' do subject(:rsa) { described_class.create_rsa_key_using_der(rsa_parameters) } include_examples 'creating an RSA object from complete JWK parameters' context 'when e, n, d is given' do let(:jwk_parameters) { all_jwk_parameters.slice(:e, :n, :d) } it 'expects all CRT parameters given and raises error' do expect { subject }.to raise_error(JWT::JWKError, 'Creating a RSA key with a private key requires the CRT parameters to be defined') end end end describe '.create_rsa_key_using_sets' do before do skip 'OpenSSL without the RSA#set_key method not supported' unless OpenSSL::PKey::RSA.new.respond_to?(:set_key) skip 'OpenSSL 3.0 does not allow mutating objects anymore' if ::JWT.openssl_3? end subject(:rsa) { described_class.create_rsa_key_using_sets(rsa_parameters) } include_examples 'creating an RSA object from complete JWK parameters' include_examples 'creating an RSA object from partial JWK parameters' end describe '.create_rsa_key_using_accessors' do before do skip 'OpenSSL if RSA#set_key is available there is no accessors anymore' if OpenSSL::PKey::RSA.new.respond_to?(:set_key) end subject(:rsa) { described_class.create_rsa_key_using_accessors(rsa_parameters) } include_examples 'creating an RSA object from complete JWK parameters' include_examples 'creating an RSA object from partial JWK parameters' end end ruby-jwt-2.7.1/spec/jwk/set_spec.rb000066400000000000000000000112241444067622100171710ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe JWT::JWK::Set do describe '.new' do it 'can create an empty set' do expect(described_class.new.keys).to eql([]) end context 'can create a set' do it 'from a JWK' do jwk = JWT::JWK.new 'testkey' expect(described_class.new(jwk).keys).to eql([jwk]) end it 'from a JWKS hash with symbol keys' do jwks = { keys: [{ kty: 'oct', k: 'testkey' }] } jwk = JWT::JWK.new({ kty: 'oct', k: 'testkey' }) expect(described_class.new(jwks).keys).to eql([jwk]) end it 'from a JWKS hash with string keys' do jwks = { 'keys' => [{ 'kty' => 'oct', 'k' => 'testkey' }] } jwk = JWT::JWK.new({ kty: 'oct', k: 'testkey' }) expect(described_class.new(jwks).keys).to eql([jwk]) end it 'from an array of keys' do jwk = JWT::JWK.new 'testkey' expect(described_class.new([jwk]).keys).to eql([jwk]) end it 'from an existing JWT::JWK::Set' do jwk = JWT::JWK.new({ kty: 'oct', k: 'testkey' }) jwks = described_class.new(jwk) expect(described_class.new(jwks)).to eql(jwks) end end it 'raises an error on invalid inputs' do expect { described_class.new(42) }.to raise_error(ArgumentError) end end describe '.export' do it 'exports the JWKS to Hash' do jwk = JWT::JWK.new({ kty: 'oct', k: 'testkey' }) jwks = described_class.new(jwk) exported = jwks.export expect(exported[:keys].size).to eql(1) expect(exported[:keys][0]).to eql(jwk.export) end end describe '.eql?' do it 'correctly classifies equal sets' do jwk = JWT::JWK.new({ kty: 'oct', k: 'testkey' }) jwks1 = described_class.new(jwk) jwks2 = described_class.new(jwk) expect(jwks1).to eql(jwks2) end it 'correctly classifies different sets' do jwk1 = JWT::JWK.new({ kty: 'oct', k: 'testkey' }) jwk2 = JWT::JWK.new({ kty: 'oct', k: 'testkex' }) jwks1 = described_class.new(jwk1) jwks2 = described_class.new(jwk2) expect(jwks1).not_to eql(jwks2) end end # TODO: No idea why this does not work. eql? returns true for the two elements, # but Array#uniq! doesn't recognize this, despite the documentation saying otherwise describe '.uniq!' do it 'filters out equal keys' do jwk = JWT::JWK.new({ kty: 'oct', k: 'testkey' }) jwk2 = JWT::JWK.new({ kty: 'oct', k: 'testkey' }) jwks = described_class.new([jwk, jwk2]) jwks.uniq! expect(jwks.keys.size).to eql(1) end end describe '.select!' do it 'filters the keyset' do jwks = described_class.new([]) jwks << JWT::JWK.new(OpenSSL::PKey::RSA.new(2048)) jwks << JWT::JWK.new(OpenSSL::PKey::EC.generate('secp384r1')) jwks.select! { |k| k[:kty] == 'RSA' } expect(jwks.size).to eql(1) expect(jwks.keys[0][:kty]).to eql('RSA') end end describe '.reject!' do it 'filters the keyset' do jwks = described_class.new([]) jwks << JWT::JWK.new(OpenSSL::PKey::RSA.new(2048)) jwks << JWT::JWK.new(OpenSSL::PKey::EC.generate('secp384r1')) jwks.reject! { |k| k[:kty] == 'RSA' } expect(jwks.size).to eql(1) expect(jwks.keys[0][:kty]).to eql('EC') end end describe '.merge' do context 'merges two JWKSs' do it 'when called via .union' do jwks1 = described_class.new(JWT::JWK.new(OpenSSL::PKey::RSA.new(2048))) jwks2 = described_class.new(JWT::JWK.new(OpenSSL::PKey::EC.generate('secp384r1'))) jwks3 = jwks1.union(jwks2) expect(jwks1.size).to eql(1) expect(jwks2.size).to eql(1) expect(jwks3.size).to eql(2) expect(jwks3.keys).to include(jwks1.keys[0]) expect(jwks3.keys).to include(jwks2.keys[0]) end it 'when called via "|" operator' do jwks1 = described_class.new(JWT::JWK.new(OpenSSL::PKey::RSA.new(2048))) jwks2 = described_class.new(JWT::JWK.new(OpenSSL::PKey::EC.generate('secp384r1'))) jwks3 = jwks1 | jwks2 expect(jwks1.size).to eql(1) expect(jwks2.size).to eql(1) expect(jwks3.size).to eql(2) expect(jwks3.keys).to include(jwks1.keys[0]) expect(jwks3.keys).to include(jwks2.keys[0]) end it 'when called directly' do jwks1 = described_class.new(JWT::JWK.new(OpenSSL::PKey::RSA.new(2048))) jwks2 = described_class.new(JWT::JWK.new(OpenSSL::PKey::EC.generate('secp384r1'))) jwks3 = jwks1.merge(jwks2) expect(jwks1.size).to eql(2) expect(jwks2.size).to eql(1) expect(jwks3).to eql(jwks1) expect(jwks3.keys).to include(jwks2.keys[0]) end end end end ruby-jwt-2.7.1/spec/jwk/thumbprint_spec.rb000066400000000000000000000032561444067622100206000ustar00rootroot00000000000000# frozen_string_literal: true describe JWT::JWK::Thumbprint do describe '#to_s' do let(:jwk_json) { nil } let(:jwk) { JWT::JWK.import(JSON.parse(jwk_json)) } subject(:thumbprint) { described_class.new(jwk).to_s } context 'when example from RFC is given' do let(:jwk_json) { ' { "kty": "RSA", "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAt' \ 'VT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn6' \ '4tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FD' \ 'W2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n9' \ '1CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINH' \ 'aQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw", "e": "AQAB", "alg": "RS256" } ' } it { is_expected.to eq('NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs') } end context 'when HMAC key is given' do let(:jwk_json) { ' { "kty":"oct", "alg":"HS512", "k":"B4uZ7IbZTnjdCQjUBXTpzMUznCYj3wdYDZcceeU0mLg" } ' } it { is_expected.to eq('wPf4ZF5qlzoFxsGkft4eu1iWcehgAcahZL4XPV4dT-s') } end context 'when EC key is given' do let(:jwk_json) do ' { "kty":"EC", "crv":"P-384", "x":"sbOnPOXPBULpeizfstr8b6b31QmvEnChXJNYBhXlmpGbs3vZtomBxNORYTT9Wylq", "y":"mfyY4VJDbdKGVjBSIhN9BJEq--6IPuKy3gbIr734n6Xd81lnvKslPwjB-sdGouD6" } ' end it { is_expected.to eq('dO52_we59sdR49HsGCpVzlDUQNvT3KxCTGakk4Un8qc') } end end end ruby-jwt-2.7.1/spec/jwk_spec.rb000066400000000000000000000056161444067622100164060ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe JWT::JWK do let(:rsa_key) { OpenSSL::PKey::RSA.new(2048) } let(:ec_key) { OpenSSL::PKey::EC.generate('secp384r1') } describe '.import' do let(:keypair) { rsa_key.public_key } let(:exported_key) { described_class.new(keypair).export } let(:params) { exported_key } subject { described_class.import(params) } it 'creates a ::JWT::JWK::RSA instance' do expect(subject).to be_a ::JWT::JWK::RSA expect(subject.export).to eq(exported_key) end context 'parsed from JSON' do let(:params) { exported_key } it 'creates a ::JWT::JWK::RSA instance from JSON parsed JWK' do expect(subject).to be_a ::JWT::JWK::RSA expect(subject.export).to eq(exported_key) end end context 'when keytype is not supported' do let(:params) { { kty: 'unsupported' } } it 'raises an error' do expect { subject }.to raise_error(JWT::JWKError) end end context 'when keypair with defined kid is imported' do it 'returns the predefined kid if jwt_data contains a kid' do params[:kid] = 'CUSTOM_KID' expect(subject.export).to eq(params) end end context 'when a common JWK parameter is specified' do it 'returns the defined common JWK parameter' do params[:use] = 'sig' expect(subject.export).to eq(params) end end end describe '.new' do let(:options) { nil } subject { described_class.new(keypair, options) } context 'when RSA key is given' do let(:keypair) { rsa_key } it { is_expected.to be_a ::JWT::JWK::RSA } end context 'when secret key is given' do let(:keypair) { 'secret-key' } it { is_expected.to be_a ::JWT::JWK::HMAC } end context 'when EC key is given' do let(:keypair) { ec_key } it { is_expected.to be_a ::JWT::JWK::EC } end context 'when kid is given' do let(:keypair) { rsa_key } let(:options) { 'CUSTOM_KID' } it 'sets the kid' do expect(subject.kid).to eq(options) end end context 'when a common parameter is given' do subject { described_class.new(keypair, params) } let(:keypair) { rsa_key } let(:params) { { 'use' => 'sig' } } it 'sets the common parameter' do expect(subject[:use]).to eq('sig') end end end describe '.[]' do let(:params) { { use: 'sig' } } let(:keypair) { rsa_key } subject { described_class.new(keypair, params) } it 'allows to read common parameters via the key-accessor' do expect(subject[:use]).to eq('sig') end it 'allows to set common parameters via the key-accessor' do subject[:use] = 'enc' expect(subject[:use]).to eq('enc') end it 'rejects key parameters as keys via the key-accessor' do expect { subject[:kty] = 'something' }.to raise_error(ArgumentError) end end end ruby-jwt-2.7.1/spec/jwt/000077500000000000000000000000001444067622100150505ustar00rootroot00000000000000ruby-jwt-2.7.1/spec/jwt/algos/000077500000000000000000000000001444067622100161555ustar00rootroot00000000000000ruby-jwt-2.7.1/spec/jwt/algos/ecdsa_spec.rb000066400000000000000000000017461444067622100206030ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe ::JWT::Algos::Ecdsa do describe '.curve_by_name' do subject { described_class.curve_by_name(curve_name) } context 'when secp256r1 is given' do let(:curve_name) { 'secp256r1' } it { is_expected.to eq(algorithm: 'ES256', digest: 'sha256') } end context 'when prime256v1 is given' do let(:curve_name) { 'prime256v1' } it { is_expected.to eq(algorithm: 'ES256', digest: 'sha256') } end context 'when secp521r1 is given' do let(:curve_name) { 'secp521r1' } it { is_expected.to eq(algorithm: 'ES512', digest: 'sha512') } end context 'when secp256k1 is given' do let(:curve_name) { 'secp256k1' } it { is_expected.to eq(algorithm: 'ES256K', digest: 'sha256') } end context 'when unknown is given' do let(:curve_name) { 'unknown' } it 'raises an error' do expect { subject }.to raise_error(JWT::UnsupportedEcdsaCurve) end end end end ruby-jwt-2.7.1/spec/jwt/algos/hmac_rbnacl_fixed_spec.rb000066400000000000000000000035741444067622100231350ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe '::JWT::Algos::HmacRbNaClFixed' do before do skip('Requires rbnacl gem < 6.0') ::JWT.rbnacl? end let(:described_class) { ::JWT::Algos::HmacRbNaClFixed } let(:data) { 'this_is_the_string_to_be_signed' } let(:key) { 'the secret key' } describe '.verify' do context 'when signature is generated with OpenSSL' do let!(:signature) { ::JWT::Algos::Hmac.sign('HS256', data, key) } it 'verifies the signature' do allow(OpenSSL::HMAC).to receive(:digest).and_call_original expect(described_class.verify('HS256', key, data, signature)).to eq(true) expect(OpenSSL::HMAC).not_to have_received(:digest) end end context 'when signature is generated with OpenSSL and key is very long' do let(:key) { 'a' * 100 } let!(:signature) { ::JWT::Algos::Hmac.sign('HS256', data, key) } it 'verifies the signature using OpenSSL features' do allow(OpenSSL::HMAC).to receive(:digest).and_call_original expect(described_class.verify('HS256', key, data, signature)).to eq(true) expect(OpenSSL::HMAC).to have_received(:digest).once end end context 'when signature is invalid' do let(:key) { 'a' * 100 } let(:signature) { JWT::Base64.url_decode('some_random_signature') } it 'can verify without error' do allow(OpenSSL::HMAC).to receive(:digest).and_call_original expect(described_class.verify('HS256', key, data, signature)).to eq(false) expect(OpenSSL::HMAC).not_to have_received(:digest) end end end describe '.sign' do context 'when signature is generated by RbNaCl' do let!(:signature) { described_class.sign('HS256', data, key) } it 'can verify the signature with OpenSSL' do expect(::JWT::Algos::Hmac.verify('HS256', key, data, signature)).to eq(true) end end end end ruby-jwt-2.7.1/spec/jwt/algos/hmac_rbnacl_spec.rb000066400000000000000000000036241444067622100217520ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe '::JWT::Algos::HmacRbNaCl' do before do skip('Requires the rbnacl gem greater than 6.0') unless ::JWT.rbnacl_6_or_greater? end let(:described_class) { ::JWT::Algos::HmacRbNaCl } let(:data) { 'this_is_the_string_to_be_signed' } let(:key) { 'the secret key' } describe '.verify' do context 'when signature is generated with OpenSSL' do let!(:signature) { ::JWT::Algos::Hmac.sign('HS256', data, key) } it 'verifies the signature' do allow(OpenSSL::HMAC).to receive(:digest).and_call_original expect(described_class.verify('HS256', key, data, signature)).to eq(true) expect(OpenSSL::HMAC).not_to have_received(:digest) end end context 'when signature is generated with OpenSSL and key is very long' do let(:key) { 'a' * 100 } let!(:signature) { ::JWT::Algos::Hmac.sign('HS256', data, key) } it 'verifies the signature using OpenSSL features' do allow(OpenSSL::HMAC).to receive(:digest).and_call_original expect(described_class.verify('HS256', key, data, signature)).to eq(true) expect(OpenSSL::HMAC).not_to have_received(:digest) end end context 'when signature is invalid' do let(:key) { 'a' * 100 } let(:signature) { JWT::Base64.url_decode('some_random_signature') } it 'can verify without error' do allow(OpenSSL::HMAC).to receive(:digest).and_call_original expect(described_class.verify('HS256', key, data, signature)).to eq(false) expect(OpenSSL::HMAC).not_to have_received(:digest) end end end describe '.sign' do context 'when signature is generated by RbNaCl' do let!(:signature) { described_class.sign('HS256', data, key) } it 'can verify the signature with OpenSSL' do expect(::JWT::Algos::Hmac.verify('HS256', key, data, signature)).to eq(true) end end end end ruby-jwt-2.7.1/spec/jwt/algos/hmac_spec.rb000066400000000000000000000072321444067622100204300ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe ::JWT::Algos::Hmac do describe '.sign' do subject { described_class.sign('HS256', 'test', hmac_secret) } # Address OpenSSL 3.0 errors with empty hmac_secret - https://github.com/jwt/ruby-jwt/issues/526 context 'when nil hmac_secret is passed' do let(:hmac_secret) { nil } context 'when OpenSSL 3.0 raises a malloc failure' do before do allow(OpenSSL::HMAC).to receive(:digest).and_raise(OpenSSL::HMACError.new('EVP_PKEY_new_mac_key: malloc failure')) end it 'raises JWT::DecodeError' do expect { subject }.to raise_error(JWT::DecodeError, 'OpenSSL 3.0 does not support nil or empty hmac_secret') end end context 'when OpenSSL raises any other error' do before do allow(OpenSSL::HMAC).to receive(:digest).and_raise(OpenSSL::HMACError.new('Another Random Error')) end it 'raises the original error' do expect { subject }.to raise_error(OpenSSL::HMACError, 'Another Random Error') end end context 'when other versions of openssl do not raise an exception' do let(:response) { Base64.decode64("Q7DO+ZJl+eNMEOqdNQGSbSezn1fG1nRWHYuiNueoGfs=\n") } before do allow(OpenSSL::HMAC).to receive(:digest).and_return(response) end it { is_expected.to eql(response) } end end context 'when blank hmac_secret is passed' do let(:hmac_secret) { '' } context 'when OpenSSL 3.0 raises a malloc failure' do before do allow(OpenSSL::HMAC).to receive(:digest).and_raise(OpenSSL::HMACError.new('EVP_PKEY_new_mac_key: malloc failure')) end it 'raises JWT::DecodeError' do expect { subject }.to raise_error(JWT::DecodeError, 'OpenSSL 3.0 does not support nil or empty hmac_secret') end end context 'when OpenSSL raises any other error' do before do allow(OpenSSL::HMAC).to receive(:digest).and_raise(OpenSSL::HMACError.new('Another Random Error')) end it 'raises the original error' do expect { subject }.to raise_error(OpenSSL::HMACError, 'Another Random Error') end end context 'when other versions of openssl do not raise an exception' do let(:response) { Base64.decode64("Q7DO+ZJl+eNMEOqdNQGSbSezn1fG1nRWHYuiNueoGfs=\n") } before do allow(OpenSSL::HMAC).to receive(:digest).and_return(response) end it { is_expected.to eql(response) } end end context 'when hmac_secret is passed' do let(:hmac_secret) { 'test' } context 'when OpenSSL 3.0 raises a malloc failure' do before do allow(OpenSSL::HMAC).to receive(:digest).and_raise(OpenSSL::HMACError.new('EVP_PKEY_new_mac_key: malloc failure')) end it 'raises the original error' do expect { subject }.to raise_error(OpenSSL::HMACError, 'EVP_PKEY_new_mac_key: malloc failure') end end context 'when OpenSSL raises any other error' do before do allow(OpenSSL::HMAC).to receive(:digest).and_raise(OpenSSL::HMACError.new('Another Random Error')) end it 'raises the original error' do expect { subject }.to raise_error(OpenSSL::HMACError, 'Another Random Error') end end context 'when other versions of openssl do not raise an exception' do let(:response) { Base64.decode64("iM0hCLU0fZc885zfkFPX3UJwSHbYyam9ji0WglnT3fc=\n") } before do allow(OpenSSL::HMAC).to receive(:digest).and_return(response) end it { is_expected.to eql(response) } end end end end ruby-jwt-2.7.1/spec/jwt/claims_validator_spec.rb000066400000000000000000000037431444067622100217330ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe JWT::ClaimsValidator do let(:validator) { described_class.new(claims) } describe '#validate!' do subject { validator.validate! } shared_examples_for 'a NumericDate claim' do |claim| context "when #{claim} payload is an integer" do let(:claims) { { claim => 12_345 } } it 'does not raise error' do expect { subject }.not_to raise_error end context 'and key is a string' do let(:claims) { { claim.to_s => 43.32 } } it 'does not raise error' do expect { subject }.not_to raise_error end end end context "when #{claim} payload is a float" do let(:claims) { { claim => 43.32 } } it 'does not raise error' do expect { subject }.not_to raise_error end end context "when #{claim} payload is a string" do let(:claims) { { claim => '1' } } it 'raises error' do expect { subject }.to raise_error JWT::InvalidPayload end context 'and key is a string' do let(:claims) { { claim.to_s => '1' } } it 'raises error' do expect { subject }.to raise_error JWT::InvalidPayload end end end context "when #{claim} payload is a Time object" do let(:claims) { { claim => Time.now } } it 'raises error' do expect { subject }.to raise_error JWT::InvalidPayload end end context "when #{claim} payload is a string" do let(:claims) { { claim => '1' } } it 'raises error' do expect { subject }.to raise_error JWT::InvalidPayload end end end context 'exp claim' do it_should_behave_like 'a NumericDate claim', :exp end context 'iat claim' do it_should_behave_like 'a NumericDate claim', :iat end context 'nbf claim' do it_should_behave_like 'a NumericDate claim', :nbf end end end ruby-jwt-2.7.1/spec/jwt/configuration_spec.rb000066400000000000000000000011021444067622100212500ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe ::JWT do describe 'JWT.configure' do it 'yields the configuration' do expect { |b| described_class.configure(&b) }.to yield_with_args(described_class.configuration) end it 'allows configuration to be changed via the block' do expect(described_class.configuration.decode.verify_expiration).to eq(true) described_class.configure do |config| config.decode.verify_expiration = false end expect(described_class.configuration.decode.verify_expiration).to eq(false) end end end ruby-jwt-2.7.1/spec/jwt/verify_spec.rb000066400000000000000000000302131444067622100177120ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe ::JWT::Verify do let(:base_payload) { { 'user_id' => 'some@user.tld' } } let(:options) { { leeway: 0 } } context '.verify_aud(payload, options)' do let(:scalar_aud) { 'ruby-jwt-aud' } let(:array_aud) { %w[ruby-jwt-aud test-aud ruby-ruby-ruby] } let(:scalar_payload) { base_payload.merge('aud' => scalar_aud) } let(:array_payload) { base_payload.merge('aud' => array_aud) } it 'must raise JWT::InvalidAudError when the singular audience does not match' do expect do described_class.verify_aud(scalar_payload, options.merge(aud: 'no-match')) end.to raise_error JWT::InvalidAudError end it 'must raise JWT::InvalidAudError when the payload has an array and none match the supplied value' do expect do described_class.verify_aud(array_payload, options.merge(aud: 'no-match')) end.to raise_error JWT::InvalidAudError end it 'must allow a matching singular audience to pass' do described_class.verify_aud(scalar_payload, options.merge(aud: scalar_aud)) end it 'must allow an array with any value matching the one in the options' do described_class.verify_aud(array_payload, options.merge(aud: array_aud.first)) end it 'must allow an array with any value matching any value in the options array' do described_class.verify_aud(array_payload, options.merge(aud: array_aud)) end it 'must allow a singular audience payload matching any value in the options array' do described_class.verify_aud(scalar_payload, options.merge(aud: array_aud)) end end context '.verify_expiration(payload, options)' do let(:payload) { base_payload.merge('exp' => (Time.now.to_i - 5)) } it 'must raise JWT::ExpiredSignature when the token has expired' do expect do described_class.verify_expiration(payload, options) end.to raise_error JWT::ExpiredSignature end it 'must allow some leeway in the expiration when global leeway is configured' do described_class.verify_expiration(payload, options.merge(leeway: 10)) end it 'must allow some leeway in the expiration when exp_leeway is configured' do described_class.verify_expiration(payload, options.merge(exp_leeway: 10)) end it 'must be expired if the exp claim equals the current time' do payload['exp'] = Time.now.to_i expect do described_class.verify_expiration(payload, options) end.to raise_error JWT::ExpiredSignature end context 'when leeway is not specified' do let(:options) { {} } it 'used a default leeway of 0' do expect do described_class.verify_expiration(payload, options) end.to raise_error JWT::ExpiredSignature end end end context '.verify_iat(payload, options)' do let(:iat) { Time.now.to_f } let(:payload) { base_payload.merge('iat' => iat) } it 'must allow a valid iat' do described_class.verify_iat(payload, options) end it 'must ignore configured leeway' do expect { described_class.verify_iat(payload.merge('iat' => (iat + 60)), options.merge(leeway: 70)) } .to raise_error(JWT::InvalidIatError) end it 'must properly handle integer times' do described_class.verify_iat(payload.merge('iat' => Time.now.to_i), options) end it 'must raise JWT::InvalidIatError when the iat value is not Numeric' do expect do described_class.verify_iat(payload.merge('iat' => 'not a number'), options) end.to raise_error JWT::InvalidIatError end it 'must raise JWT::InvalidIatError when the iat value is in the future' do expect do described_class.verify_iat(payload.merge('iat' => (iat + 120)), options) end.to raise_error JWT::InvalidIatError end end context '.verify_iss(payload, options)' do let(:iss) { 'ruby-jwt-gem' } let(:payload) { base_payload.merge('iss' => iss) } let(:invalid_token) { JWT.encode base_payload, payload[:secret] } context 'when iss is a String' do it 'must raise JWT::InvalidIssuerError when the configured issuer does not match the payload issuer' do expect do described_class.verify_iss(payload, options.merge(iss: 'mismatched-issuer')) end.to raise_error JWT::InvalidIssuerError end it 'must raise JWT::InvalidIssuerError when the payload does not include an issuer' do expect do described_class.verify_iss(base_payload, options.merge(iss: iss)) end.to raise_error(JWT::InvalidIssuerError, /received /) end it 'must allow a matching issuer to pass' do described_class.verify_iss(payload, options.merge(iss: iss)) end end context 'when iss is an Array' do it 'must raise JWT::InvalidIssuerError when no matching issuers in array' do expect do described_class.verify_iss(payload, options.merge(iss: %w[first second])) end.to raise_error JWT::InvalidIssuerError end it 'must raise JWT::InvalidIssuerError when the payload does not include an issuer' do expect do described_class.verify_iss(base_payload, options.merge(iss: %w[first second])) end.to raise_error(JWT::InvalidIssuerError, /received /) end it 'must allow an array with matching issuer to pass' do described_class.verify_iss(payload, options.merge(iss: ['first', iss, 'third'])) end end context 'when iss is a RegExp' do it 'must raise JWT::InvalidIssuerError when the regular expression does not match' do expect do described_class.verify_iss(payload, options.merge(iss: /\A(first|second)\z/)) end.to raise_error JWT::InvalidIssuerError end it 'must raise JWT::InvalidIssuerError when the payload does not include an issuer' do expect do described_class.verify_iss(base_payload, options.merge(iss: /\A(first|second)\z/)) end.to raise_error(JWT::InvalidIssuerError, /received /) end it 'must allow a regular expression matching the issuer to pass' do described_class.verify_iss(payload, options.merge(iss: /\A(first|#{iss}|third)\z/)) end end context 'when iss is a Proc' do it 'must raise JWT::InvalidIssuerError when the proc returns false' do expect do described_class.verify_iss(payload, options.merge(iss: ->(iss) { iss && iss.start_with?('first') })) end.to raise_error JWT::InvalidIssuerError end it 'must raise JWT::InvalidIssuerError when the payload does not include an issuer' do expect do described_class.verify_iss(base_payload, options.merge(iss: ->(iss) { iss && iss.start_with?('first') })) end.to raise_error(JWT::InvalidIssuerError, /received /) end it 'must allow a proc that returns true to pass' do described_class.verify_iss(payload, options.merge(iss: ->(iss) { iss && iss.start_with?('ruby') })) end end context 'when iss is a Method instance' do def issuer_start_with_first?(issuer) issuer&.start_with?('first') end def issuer_start_with_ruby?(issuer) issuer&.start_with?('ruby') end it 'must raise JWT::InvalidIssuerError when the method returns false' do expect do described_class.verify_iss(payload, options.merge(iss: method(:issuer_start_with_first?))) end.to raise_error JWT::InvalidIssuerError end it 'must raise JWT::InvalidIssuerError when the payload does not include an issuer' do expect do described_class.verify_iss(base_payload, options.merge(iss: method(:issuer_start_with_first?))) end.to raise_error(JWT::InvalidIssuerError, /received /) end it 'must allow a method that returns true to pass' do described_class.verify_iss(payload, options.merge(iss: method(:issuer_start_with_ruby?))) end end end context '.verify_jti(payload, options)' do let(:payload) { base_payload.merge('jti' => 'some-random-uuid-or-whatever') } it 'must allow any jti when the verfy_jti key in the options is truthy but not a proc' do described_class.verify_jti(payload, options.merge(verify_jti: true)) end it 'must raise JWT::InvalidJtiError when the jti is missing' do expect do described_class.verify_jti(base_payload, options) end.to raise_error JWT::InvalidJtiError, /missing/i end it 'must raise JWT::InvalidJtiError when the jti is an empty string' do expect do described_class.verify_jti(base_payload.merge('jti' => ' '), options) end.to raise_error JWT::InvalidJtiError, /missing/i end it 'must raise JWT::InvalidJtiError when verify_jti proc returns false' do expect do described_class.verify_jti(payload, options.merge(verify_jti: ->(_jti) { false })) end.to raise_error JWT::InvalidJtiError, /invalid/i end it 'true proc should not raise JWT::InvalidJtiError' do described_class.verify_jti(payload, options.merge(verify_jti: ->(_jti) { true })) end it 'it should not throw arguement error with 2 args' do expect do described_class.verify_jti(payload, options.merge(verify_jti: ->(_jti, _pl) { true })) end.to_not raise_error end it 'should have payload as second param in proc' do described_class.verify_jti(payload, options.merge(verify_jti: ->(_jti, pl) { expect(pl).to eq(payload) })) end end context '.verify_not_before(payload, options)' do let(:payload) { base_payload.merge('nbf' => (Time.now.to_i + 5)) } it 'must raise JWT::ImmatureSignature when the nbf in the payload is in the future' do expect do described_class.verify_not_before(payload, options) end.to raise_error JWT::ImmatureSignature end it 'must allow some leeway in the token age when global leeway is configured' do described_class.verify_not_before(payload, options.merge(leeway: 10)) end it 'must allow some leeway in the token age when nbf_leeway is configured' do described_class.verify_not_before(payload, options.merge(nbf_leeway: 10)) end end context '.verify_sub(payload, options)' do let(:sub) { 'ruby jwt subject' } it 'must raise JWT::InvalidSubError when the subjects do not match' do expect do described_class.verify_sub(base_payload.merge('sub' => 'not-a-match'), options.merge(sub: sub)) end.to raise_error JWT::InvalidSubError end it 'must allow a matching sub' do described_class.verify_sub(base_payload.merge('sub' => sub), options.merge(sub: sub)) end end context '.verify_claims' do let(:fail_verifications_options) { { iss: 'mismatched-issuer', aud: 'no-match', sub: 'some subject' } } let(:fail_verifications_payload) { { 'exp' => (Time.now.to_i - 50), 'jti' => ' ', 'iss' => 'some-issuer', 'nbf' => (Time.now.to_i + 50), 'iat' => 'not a number', 'sub' => 'not-a-match' } } %w[verify_aud verify_expiration verify_iat verify_iss verify_jti verify_not_before verify_sub].each do |method| let(:payload) { base_payload.merge(fail_verifications_payload) } it "must skip verification when #{method} option is set to false" do described_class.verify_claims(payload, options.merge(method => false)) end it "must raise error when #{method} option is set to true" do expect do described_class.verify_claims(payload, options.merge(method => true).merge(fail_verifications_options)) end.to raise_error JWT::DecodeError end end end context '.verify_required_claims(payload, options)' do it 'must raise JWT::MissingRequiredClaim if a required claim is absent' do expect do described_class.verify_required_claims(base_payload, options.merge(required_claims: ['exp'])) end.to raise_error JWT::MissingRequiredClaim end it 'must verify the claims if all required claims are present' do payload = base_payload.merge('exp' => (Time.now.to_i + 5), 'custom_claim' => true) described_class.verify_required_claims(payload, options.merge(required_claims: ['exp', 'custom_claim'])) end end end ruby-jwt-2.7.1/spec/jwt_spec.rb000066400000000000000000001035241444067622100164140ustar00rootroot00000000000000# frozen_string_literal: true RSpec.describe JWT do let(:payload) { { 'user_id' => 'some@user.tld' } } let :data do data = { :empty_token => 'e30K.e30K.e30K', :empty_token_2_segment => 'e30K.e30K.', :secret => 'My$ecretK3y', :rsa_private => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'rsa-2048-private.pem'))), :rsa_public => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'rsa-2048-public.pem'))), :wrong_rsa_private => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'rsa-2048-wrong-public.pem'))), :wrong_rsa_public => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'rsa-2048-wrong-public.pem'))), 'ES256_private' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256-private.pem'))), 'ES256_public' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256-public.pem'))), 'ES256_private_v2' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256-private-v2.pem'))), 'ES256_public_v2' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256-public-v2.pem'))), 'ES384_private' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec384-private.pem'))), 'ES384_public' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec384-public.pem'))), 'ES512_private' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec512-private.pem'))), 'ES512_public' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec512-public.pem'))), 'ES256K_private' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256k-private.pem'))), 'ES256K_public' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256k-public.pem'))), 'NONE' => 'eyJhbGciOiJub25lIn0.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.', 'HS256' => 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.kWOVtIOpWcG7JnyJG0qOkTDbOy636XrrQhMm_8JrRQ8', 'HS512256' => 'eyJhbGciOiJIUzUxMjI1NiJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.Ds_4ibvf7z4QOBoKntEjDfthy3WJ-3rKMspTEcHE2bA', 'HS384' => 'eyJhbGciOiJIUzM4NCJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.VuV4j4A1HKhWxCNzEcwc9qVF3frrEu-BRLzvYPkbWO0LENRGy5dOiBQ34remM3XH', 'HS512' => 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.8zNtCBTJIZTHpZ-BkhR-6sZY1K85Nm5YCKqV3AxRdsBJDt_RR-REH2db4T3Y0uQwNknhrCnZGvhNHrvhDwV1kA', 'RS256' => 'eyJhbGciOiJSUzI1NiJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.eSXvWP4GViiwUALj_-qTxU68I1oM0XjgDsCZBBUri2Ghh9d75QkVDoZ_v872GaqunN5A5xcnBK0-cOq-CR6OwibgJWfOt69GNzw5RrOfQ2mz3QI3NYEq080nF69h8BeqkiaXhI24Q51joEgfa9aj5Y-oitLAmtDPYTm7vTcdGufd6AwD3_3jajKBwkh0LPSeMtbe_5EyS94nFoEF9OQuhJYjUmp7agsBVa8FFEjVw5jEgVqkvERSj5hSY4nEiCAomdVxIKBfykyi0d12cgjhI7mBFwWkPku8XIPGZ7N8vpiSLdM68BnUqIK5qR7NAhtvT7iyLFgOqhZNUQ6Ret5VpQ', 'RS384' => 'eyJhbGciOiJSUzM4NCJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.Sfgk56moPghtsjaP4so6tOy3I553mgwX-5gByMC6dX8lpeWgsxSeAd_K8IyO7u4lwYOL0DSftnqO1HEOuN1AKyBbDvaTXz3u2xNA2x4NYLdW4AZA6ritbYcKLO5BHTXw5ueMbtA1jjGXP0zI_aK2iJTMBmB8SCF88RYBUH01Tyf4PlLj98pGL-v3prZd6kZkIeRJ3326h04hslcB5HQKmgeBk24QNLIoIC-CD329HPjJ7TtGx01lj-ehTBnwVbBGzYFAyoalV5KgvL_MDOfWPr1OYHnR5s_Fm6_3Vg4u6lBljvHOrmv4Nfx7d8HLgbo8CwH4qn1wm6VQCtuDd-uhRg', 'RS512' => 'eyJhbGciOiJSUzUxMiJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.LIIAUEuCkGNdpYguOO5LoW4rZ7ED2POJrB0pmEAAchyTdIK4HKh1jcLxc6KyGwZv40njCgub3y72q6vcQTn7oD0zWFCVQRIDW1911Ii2hRNHuigiPUnrnZh1OQ6z65VZRU6GKs8omoBGU9vrClBU0ODqYE16KxYmE_0n4Xw2h3D_L1LF0IAOtDWKBRDa3QHwZRM9sHsHNsBuD5ye9KzDYN1YALXj64LBfA-DoCKfpVAm9NkRPOyzjR2X2C3TomOSJgqWIVHJucudKDDAZyEbO4RA5pI-UFYy1370p9bRajvtDyoBuLDCzoSkMyQ4L2DnLhx5CbWcnD7Cd3GUmnjjTA', 'ES256' => '', 'ES384' => '', 'ES512' => '', 'PS256' => '', 'PS384' => '', 'PS512' => '' } if ::JWT.rbnacl? ed25519_private = RbNaCl::Signatures::Ed25519::SigningKey.new('abcdefghijklmnopqrstuvwxyzABCDEF') ed25519_public = ed25519_private.verify_key data.merge!( 'ED25519_private' => ed25519_private, 'ED25519_public' => ed25519_public, 'EdDSA_private' => ed25519_private, 'EdDSA_public' => ed25519_public ) end data end after(:each) do expect(OpenSSL.errors).to be_empty end context 'alg: NONE' do let(:alg) { 'none' } let(:encoded_token) { data['NONE'] } it 'should generate a valid token' do token = JWT.encode payload, nil, alg expect(token).to eq encoded_token end context 'decoding without verification' do it 'should decode a valid token' do jwt_payload, header = JWT.decode encoded_token, nil, false expect(header['alg']).to eq alg expect(jwt_payload).to eq payload end end context 'decoding with verification' do context 'without specifying the none algorithm' do it 'should fail to decode the token' do expect do JWT.decode encoded_token, nil, true end.to raise_error JWT::IncorrectAlgorithm end end context 'specifying the none algorithm' do context 'when the claims are valid' do it 'should decode the token' do jwt_payload, header = JWT.decode encoded_token, nil, true, { algorithms: 'none' } expect(header['alg']).to eq 'none' expect(jwt_payload).to eq payload end end context 'when the claims are invalid' do let(:encoded_token) { JWT.encode({ exp: 0 }, nil, 'none') } it 'should fail to decode the token' do expect do JWT.decode encoded_token, nil, true end.to raise_error JWT::DecodeError end end end end end context 'payload validation' do it 'validates the payload with the ClaimsValidator if the payload is a hash' do validator = double expect(JWT::ClaimsValidator).to receive(:new) { validator } expect(validator).to receive(:validate!) { true } payload = {} JWT.encode payload, 'secret', 'HS256' end it 'does not validate the payload if it is not present' do validator = double expect(JWT::ClaimsValidator).not_to receive(:new) { validator } payload = nil JWT.encode payload, 'secret', 'HS256' end end algorithms = %w[HS256 HS384 HS512] algorithms << 'HS512256' if ::JWT.rbnacl? algorithms.each do |alg| context "alg: #{alg}" do it 'should generate a valid token' do token = JWT.encode payload, data[:secret], alg expect(token).to eq data[alg] end it 'should decode a valid token' do jwt_payload, header = JWT.decode data[alg], data[:secret], true, algorithm: alg expect(header['alg']).to eq alg expect(jwt_payload).to eq payload end it 'wrong secret should raise JWT::DecodeError' do expect do JWT.decode data[alg], 'wrong_secret', true, algorithm: alg end.to raise_error JWT::VerificationError end it 'wrong secret and verify = false should not raise JWT::DecodeError' do expect do JWT.decode data[alg], 'wrong_secret', false end.not_to raise_error end end end %w[RS256 RS384 RS512].each do |alg| context "alg: #{alg}" do it 'should generate a valid token' do token = JWT.encode payload, data[:rsa_private], alg expect(token).to eq data[alg] end it 'should decode a valid token' do jwt_payload, header = JWT.decode data[alg], data[:rsa_public], true, algorithm: alg expect(header['alg']).to eq alg expect(jwt_payload).to eq payload end it 'should decode a valid token using algorithm hash string key' do jwt_payload, header = JWT.decode data[alg], data[:rsa_public], true, 'algorithm' => alg expect(header['alg']).to eq alg expect(jwt_payload).to eq payload end it 'wrong key should raise JWT::DecodeError' do key = OpenSSL::PKey.read File.read(File.join(CERT_PATH, 'rsa-2048-wrong-public.pem')) expect do JWT.decode data[alg], key, true, algorithm: alg end.to raise_error JWT::DecodeError end it 'wrong key and verify = false should not raise JWT::DecodeError' do key = OpenSSL::PKey.read File.read(File.join(CERT_PATH, 'rsa-2048-wrong-public.pem')) expect do JWT.decode data[alg], key, false end.not_to raise_error end end end if defined?(RbNaCl) %w[ED25519 EdDSA].each do |alg| context "alg: #{alg}" do before(:each) do data[alg] = JWT.encode payload, data["#{alg}_private"], alg end let(:wrong_key) { RbNaCl::Signatures::Ed25519::SigningKey.generate.verify_key } it 'should generate a valid token' do jwt_payload, header = JWT.decode data[alg], data["#{alg}_public"], true, algorithm: alg expect(header['alg']).to eq alg expect(jwt_payload).to eq payload end it 'should decode a valid token' do jwt_payload, header = JWT.decode data[alg], data["#{alg}_public"], true, algorithm: alg expect(header['alg']).to eq alg expect(jwt_payload).to eq payload end it 'wrong key should raise JWT::DecodeError' do expect do JWT.decode data[alg], wrong_key, true, algorithm: alg end.to raise_error JWT::DecodeError end it 'wrong key and verify = false should not raise JWT::DecodeError' do expect do JWT.decode data[alg], wrong_key, false end.not_to raise_error end end end end %w[ES256 ES384 ES512 ES256K].each do |alg| context "alg: #{alg}" do before(:each) do data[alg] = JWT.encode(payload, data["#{alg}_private"], alg) end let(:wrong_key) { OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256-wrong-public.pem'))) } it 'should generate a valid token' do jwt_payload, header = JWT.decode data[alg], data["#{alg}_public"], true, algorithm: alg expect(header['alg']).to eq alg expect(jwt_payload).to eq payload end it 'should decode a valid token' do jwt_payload, header = JWT.decode data[alg], data["#{alg}_public"], true, algorithm: alg expect(header['alg']).to eq alg expect(jwt_payload).to eq payload end it 'wrong key should raise JWT::DecodeError' do expect do JWT.decode data[alg], wrong_key end.to raise_error JWT::DecodeError end it 'wrong key and verify = false should not raise JWT::DecodeError' do expect do JWT.decode data[alg], wrong_key, false end.not_to raise_error end end end if ::Gem::Version.new(OpenSSL::VERSION) >= ::Gem::Version.new('2.1') %w[PS256 PS384 PS512].each do |alg| context "alg: #{alg}" do before(:each) do data[alg] = JWT.encode payload, data[:rsa_private], alg end let(:wrong_key) { data[:wrong_rsa_public] } it 'should generate a valid token' do token = data[alg] header, body, signature = token.split('.') expect(header).to eql(Base64.strict_encode64({ alg: alg }.to_json)) expect(body).to eql(Base64.strict_encode64(payload.to_json)) # Validate signature is made of up header and body of JWT translated_alg = alg.gsub('PS', 'sha') valid_signature = data[:rsa_public].verify_pss( translated_alg, ::JWT::Base64.url_decode(signature), [header, body].join('.'), salt_length: :auto, mgf1_hash: translated_alg ) expect(valid_signature).to be true end it 'should decode a valid token' do jwt_payload, header = JWT.decode data[alg], data[:rsa_public], true, algorithm: alg expect(header['alg']).to eq alg expect(jwt_payload).to eq payload end it 'wrong key should raise JWT::DecodeError' do expect do JWT.decode data[alg], wrong_key end.to raise_error JWT::DecodeError end it 'wrong key and verify = false should not raise JWT::DecodeError' do expect do JWT.decode data[alg], wrong_key, false end.not_to raise_error end end end else %w[PS256 PS384 PS512].each do |alg| context "alg: #{alg}" do it 'raises error about OpenSSL version' do expect { JWT.encode payload, data[:rsa_private], alg }.to raise_error( JWT::RequiredDependencyError, /You currently have OpenSSL .*. PS support requires >= 2.1/ ) end end end end context 'Invalid' do it 'algorithm should raise NotImplementedError' do expect do JWT.encode payload, 'secret', 'HS255' end.to raise_error NotImplementedError end it 'raises "No verification key available" error' do token = JWT.encode({}, 'foo') expect { JWT.decode(token, nil, true) }.to raise_error(JWT::DecodeError, 'No verification key available') end it 'ECDSA curve_name should raise JWT::IncorrectAlgorithm' do key = OpenSSL::PKey::EC.generate('secp256k1') expect do JWT.encode payload, key, 'ES256' end.to raise_error JWT::IncorrectAlgorithm token = JWT.encode payload, data['ES256_private'], 'ES256' expect do JWT.decode token, key end.to raise_error JWT::IncorrectAlgorithm end end context 'Verify' do context 'when key given as an array with multiple possible keys' do let(:payload) { { 'data' => 'data' } } let(:token) { JWT.encode(payload, secret, 'HS256') } let(:secret) { 'hmac_secret' } it 'should be able to verify signature when block returns multiple keys' do decoded_token = JWT.decode(token, nil, true, { algorithm: 'HS256' }) do ['not_the_secret', secret] end expect(decoded_token.first).to eq(payload) end it 'should be able to verify signature when multiple keys given as a parameter' do decoded_token = JWT.decode(token, ['not_the_secret', secret], true, { algorithm: 'HS256' }) expect(decoded_token.first).to eq(payload) end it 'should fail if only invalid keys are given' do expect do JWT.decode(token, ['not_the_secret', 'not_the_secret_2'], true, { algorithm: 'HS256' }) end.to raise_error(JWT::VerificationError, 'Signature verification failed') end end context 'when encoded payload is used to extract key through find_key' do it 'should be able to find a key using the block passed to decode' do payload_data = { key: 'secret' } token = JWT.encode payload_data, data[:secret], 'HS256' expect do JWT.decode(token, nil, true, { algorithm: 'HS256' }) do |_headers, payload| data[payload['key'].to_sym] end end.not_to raise_error end it 'should be able to verify signature when block returns multiple keys' do iss = 'My_Awesome_Company' iss_payload = { data: 'data', iss: iss } secrets = { iss => ['hmac_secret2', data[:secret]] } token = JWT.encode iss_payload, data[:secret], 'HS256' expect do JWT.decode(token, nil, true, { iss: iss, verify_iss: true, algorithm: 'HS256' }) do |_headers, payload| secrets[payload['iss']] end end.not_to raise_error end it 'should be able to find a key using the block passed to decode with iss verification' do iss = 'My_Awesome_Company' iss_payload = { data: 'data', iss: iss } secrets = { iss => data[:secret] } token = JWT.encode iss_payload, data[:secret], 'HS256' expect do JWT.decode(token, nil, true, { iss: iss, verify_iss: true, algorithm: 'HS256' }) do |_headers, payload| secrets[payload['iss']] end end.not_to raise_error end it 'should be able to verify signature when block returns multiple keys with iss verification' do iss = 'My_Awesome_Company' iss_payload = { data: 'data', iss: iss } secrets = { iss => ['hmac_secret2', data[:secret]] } token = JWT.encode iss_payload, data[:secret], 'HS256' expect do JWT.decode(token, nil, true, { iss: iss, verify_iss: true, algorithm: 'HS256' }) do |_headers, payload| secrets[payload['iss']] end end.not_to raise_error end it 'should be able to find a key using a block with multiple issuers' do issuers = %w[My_Awesome_Company1 My_Awesome_Company2] iss_payload = { data: 'data', iss: issuers.first } secrets = { issuers.first => data[:secret], issuers.last => 'hmac_secret2' } token = JWT.encode iss_payload, data[:secret], 'HS256' expect do JWT.decode(token, nil, true, { iss: issuers, verify_iss: true, algorithm: 'HS256' }) do |_headers, payload| secrets[payload['iss']] end end.not_to raise_error end it 'should be able to verify signature when block returns multiple keys with multiple issuers' do issuers = %w[My_Awesome_Company1 My_Awesome_Company2] iss_payload = { data: 'data', iss: issuers.first } secrets = { issuers.first => [data[:secret], 'hmac_secret1'], issuers.last => 'hmac_secret2' } token = JWT.encode iss_payload, data[:secret], 'HS256' expect do JWT.decode(token, nil, true, { iss: issuers, verify_iss: true, algorithm: 'HS256' }) do |_headers, payload| secrets[payload['iss']] end end.not_to raise_error end end context 'algorithm' do it 'should raise JWT::IncorrectAlgorithm on mismatch' do token = JWT.encode payload, data[:secret], 'HS256' expect do JWT.decode token, data[:secret], true, algorithm: 'HS384' end.to raise_error JWT::IncorrectAlgorithm expect do JWT.decode token, data[:secret], true, algorithm: 'HS256' end.not_to raise_error end it 'should raise JWT::IncorrectAlgorithm on mismatch prior to kid public key network call' do token = JWT.encode payload, data[:rsa_private], 'RS256' expect do JWT.decode(token, nil, true, { algorithms: ['RS384'] }) do |_, _| # unsuccessful keyfinder public key network call here end end.to raise_error JWT::IncorrectAlgorithm expect do JWT.decode(token, nil, true, { 'algorithms' => ['RS384'] }) do |_, _| # unsuccessful keyfinder public key network call here end end.to raise_error JWT::IncorrectAlgorithm end it 'should raise JWT::IncorrectAlgorithm when algorithms array does not contain algorithm' do token = JWT.encode payload, data[:secret], 'HS512' expect do JWT.decode token, data[:secret], true, algorithms: ['HS384'] end.to raise_error JWT::IncorrectAlgorithm expect do JWT.decode token, data[:secret], true, 'algorithms' => ['HS384'] end.to raise_error JWT::IncorrectAlgorithm expect do JWT.decode token, data[:secret], true, algorithms: ['HS512', 'HS384'] end.not_to raise_error expect do JWT.decode token, data[:secret], true, 'algorithms' => ['HS512', 'HS384'] end.not_to raise_error end context 'no algorithm provided' do it 'should use the default decode algorithm' do token = JWT.encode payload, data[:rsa_public].to_s jwt_payload, header = JWT.decode token, data[:rsa_public].to_s expect(header['alg']).to eq 'HS256' expect(jwt_payload).to eq payload end end context 'token is missing algorithm' do it 'should raise JWT::IncorrectAlgorithm' do expect do JWT.decode data[:empty_token] end.to raise_error JWT::IncorrectAlgorithm end context '2-segment token' do it 'should raise JWT::IncorrectAlgorithm' do expect do JWT.decode data[:empty_token_2_segment] end.to raise_error JWT::DecodeError end end end end context 'issuer claim' do let(:iss) { 'ruby-jwt-gem' } let(:invalid_token) { JWT.encode payload, data[:secret] } let :token do iss_payload = payload.merge(iss: iss) JWT.encode iss_payload, data[:secret] end it 'if verify_iss is set to false (default option) should not raise JWT::InvalidIssuerError' do expect do JWT.decode token, data[:secret], true, iss: iss, algorithm: 'HS256' end.not_to raise_error end end end context 'a token with no segments' do it 'raises JWT::DecodeError' do expect { JWT.decode('ThisIsNotAValidJWTToken', nil, true) }.to raise_error(JWT::DecodeError, 'Not enough or too many segments') end end context 'a token with not enough segments' do it 'raises JWT::DecodeError' do token = JWT.encode('ThisIsNotAValidJWTToken', 'secret').split('.').slice(1, 2).join expect { JWT.decode(token, nil, true) }.to raise_error(JWT::DecodeError, 'Not enough or too many segments') end end context 'a token with not too many segments' do it 'raises JWT::DecodeError' do expect { JWT.decode('ThisIsNotAValidJWTToken.second.third.signature', nil, true) }.to raise_error(JWT::DecodeError, 'Not enough or too many segments') end end context 'a token with invalid Base64 segments' do it 'raises JWT::DecodeError' do expect { JWT.decode('hello.there.world') }.to raise_error(JWT::DecodeError, 'Invalid segment encoding') end end context 'a token with two segments but does not require verifying' do it 'raises something else than "Not enough or too many segments"' do expect { JWT.decode('ThisIsNotAValidJWTToken.second', nil, false) }.to raise_error(JWT::DecodeError, 'Invalid segment encoding') end end it 'should not verify token even if the payload has claims' do head = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9' load = 'eyJ1c2VyX2lkIjo1NCwiZXhwIjoxNTA0MzkwODA0fQ' sign = 'Skpi6FfYMbZ-DwW9ocyRIosNMdPMAIWRLYxRO68GTQk' expect do JWT.decode([head, load, sign].join('.'), '', false) end.not_to raise_error end it 'should not raise InvalidPayload exception if payload is an array' do expect do JWT.encode(['my', 'payload'], 'secret') end.not_to raise_error end it 'should encode string payloads' do expect do JWT.encode 'Hello World', 'secret' end.not_to raise_error end context 'when the alg value is given as a header parameter' do it 'does not override the actual algorithm used' do headers = JSON.parse(::JWT::Base64.url_decode(JWT.encode('Hello World', 'secret', 'HS256', { alg: 'HS123' }).split('.').first)) expect(headers['alg']).to eq('HS256') end it 'should generate the same token' do expect(JWT.encode('Hello World', 'secret', 'HS256', { alg: 'HS256' })).to eq JWT.encode('Hello World', 'secret', 'HS256') end end context 'when hmac algorithm is used without secret key' do it 'encodes payload' do pending 'Different behaviour on OpenSSL 3.0 (https://github.com/openssl/openssl/issues/13089)' if ::JWT.openssl_3_hmac_empty_key_regression? payload = { a: 1, b: 'b' } token = JWT.encode(payload, '', 'HS256') expect do token_without_secret = JWT.encode(payload, nil, 'HS256') expect(token).to eq(token_without_secret) end.not_to raise_error end end context 'algorithm case insensitivity' do let(:payload) { { 'a' => 1, 'b' => 'b' } } it 'ignores algorithm casing during encode/decode' do enc = JWT.encode(payload, 'secret', 'hs256') expect(JWT.decode(enc, 'secret')).to eq([payload, { 'alg' => 'HS256' }]) enc = JWT.encode(payload, data[:rsa_private], 'rs512') expect(JWT.decode(enc, data[:rsa_public], true, algorithm: 'RS512')).to eq([payload, { 'alg' => 'RS512' }]) enc = JWT.encode(payload, data[:rsa_private], 'RS512') expect(JWT.decode(enc, data[:rsa_public], true, algorithm: 'rs512')).to eq([payload, { 'alg' => 'RS512' }]) end it 'raises error for invalid algorithm' do expect do JWT.encode(payload, '', 'xyz') end.to raise_error(NotImplementedError) end end describe '::JWT.decode with verify_iat parameter' do let!(:time_now) { Time.now } let(:token) { ::JWT.encode({ pay: 'load', iat: iat }, 'secret', 'HS256') } subject(:decoded_token) { ::JWT.decode(token, 'secret', true, verify_iat: true) } before { allow(Time).to receive(:now) { time_now } } context 'when iat is exactly the same as Time.now and iat is given as a float' do let(:iat) { time_now.to_f } it 'considers iat valid' do expect(decoded_token).to be_an(Array) end end context 'when iat is exactly the same as Time.now and iat is given as floored integer' do let(:iat) { time_now.to_f.floor } it 'considers iat valid' do expect(decoded_token).to be_an(Array) end end context 'when iat is 1 second before Time.now' do let(:iat) { time_now.to_i + 1 } it 'raises an error' do expect { decoded_token }.to raise_error(::JWT::InvalidIatError, 'Invalid iat') end end end describe '::JWT.decode with x5c parameter' do let(:alg) { 'RS256' } let(:root_certificates) { [instance_double('OpenSSL::X509::Certificate')] } let(:key_finder) { instance_double('::JWT::X5cKeyFinder') } before do expect(::JWT::X5cKeyFinder).to receive(:new).with(root_certificates, nil).and_return(key_finder) expect(key_finder).to receive(:from).and_return(data[:rsa_public]) end subject(:decoded_token) { ::JWT.decode(data[alg], nil, true, algorithm: alg, x5c: { root_certificates: root_certificates }) } it 'calls X5cKeyFinder#from to verify the signature and return the payload' do jwt_payload, header = decoded_token expect(header['alg']).to eq alg expect(jwt_payload).to eq payload end end describe 'when keyfinder given with 1 argument' do let(:token) { JWT.encode(payload, 'HS256', 'HS256') } it 'decodes the token' do expect(JWT.decode(token, nil, true, algorithm: 'HS256') { |header| header['alg'] }).to include(payload) end end describe 'when keyfinder given with 2 arguments' do let(:token) { JWT.encode(payload, payload['user_id'], 'HS256') } it 'decodes the token' do expect(JWT.decode(token, nil, true, algorithm: 'HS256') { |_header, payload| payload['user_id'] }).to include(payload) end end describe 'when keyfinder given with 3 arguments' do let(:token) { JWT.encode(payload, 'HS256', 'HS256') } it 'decodes the token but does not pass the payload' do expect(JWT.decode(token, nil, true, algorithm: 'HS256') do |header, token_payload, nothing| expect(token_payload).to eq(nil) # This behaviour is not correct, the payload should be available in the keyfinder expect(nothing).to eq(nil) header['alg'] end).to include(payload) end end describe 'when none token is and decoding without key and with verification' do let(:none_token) { ::JWT.encode(payload, nil, 'none') } it 'decodes the token' do expect(::JWT.decode(none_token, nil, true, algorithms: 'none')).to eq([payload, { 'alg' => 'none' }]) end end describe 'when none token is decoded with a key given' do let(:none_token) { ::JWT.encode(payload, nil, 'none') } it 'decodes the token' do expect(::JWT.decode(none_token, 'key', true, algorithms: 'none')).to eq([payload, { 'alg' => 'none' }]) end end describe 'when none token is decoded without verify' do let(:none_token) { ::JWT.encode(payload, nil, 'none') } it 'decodes the token' do expect(::JWT.decode(none_token, 'key', false)).to eq([payload, { 'alg' => 'none' }]) end end describe 'when token signed with nil and decoded with nil' do let(:no_key_token) { ::JWT.encode(payload, nil, 'HS512') } it 'raises JWT::DecodeError' do pending 'Different behaviour on OpenSSL 3.0 (https://github.com/openssl/openssl/issues/13089)' if ::JWT.openssl_3_hmac_empty_key_regression? expect { ::JWT.decode(no_key_token, nil, true, algorithms: 'HS512') }.to raise_error(JWT::DecodeError, 'No verification key available') end end context 'when token ends with a newline char' do let(:token) { "#{JWT.encode(payload, 'secret', 'HS256')}\n" } it 'ignores the newline and decodes the token' do expect(JWT.decode(token, 'secret', true, algorithm: 'HS256')).to include(payload) end end context 'when multiple algorithms given' do let(:token) { JWT.encode(payload, 'secret', 'HS256') } it 'starts trying with the algorithm referred in the header' do expect(::JWT::Algos::Rsa).not_to receive(:verify) JWT.decode(token, 'secret', true, algorithm: ['RS512', 'HS256']) end end context 'when keyfinder resolves to multiple keys and multiple algorithms given' do let(:iss_key_mappings) do { 'ES256' => [data['ES256_public_v2'], data['ES256_public']], 'HS256' => data['HS256'] } end context 'with issue with ES256 keys' do it 'tries until the first match' do token = JWT.encode(payload, data['ES256_private'], 'ES256', 'iss' => 'ES256') result = JWT.decode(token, nil, true, algorithm: ['ES256', 'HS256']) do |header, _| iss_key_mappings[header['iss']] end expect(result).to include(payload) end it 'tries until the first match' do token = JWT.encode(payload, data['ES256_private_v2'], 'ES256', 'iss' => 'ES256') result = JWT.decode(token, nil, true, algorithm: ['ES256', 'HS256']) do |header, _| iss_key_mappings[header['iss']] end expect(result).to include(payload) end end context 'with issue with HS256 keys' do it 'tries until the first match' do token = JWT.encode(payload, data['HS256'], 'HS256', 'iss' => 'HS256') result = JWT.decode(token, nil, true, algorithm: ['ES256', 'HS256']) do |header, _| iss_key_mappings[header['iss']] end expect(result).to include(payload) end end end context 'when token is missing the alg header' do let(:token) { 'e30.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.DIKUOt1lwwzWSPBf508IYqk0KzC2PL97OZc6pECzE1I' } it 'raises JWT::IncorrectAlgorithm error' do expect { JWT.decode(token, 'secret', true, algorithm: 'HS256') }.to raise_error(JWT::IncorrectAlgorithm, 'Token is missing alg header') end end context 'when token has null as the alg header' do let(:token) { 'eyJhbGciOm51bGx9.eyJwYXkiOiJsb2FkIn0.pizVPWJMK-GUuXXEcQD_faZGnZqz_6wKZpoGO4RdqbY' } it 'raises JWT::IncorrectAlgorithm error' do expect { JWT.decode(token, 'secret', true, algorithm: 'HS256') }.to raise_error(JWT::IncorrectAlgorithm, 'Token is missing alg header') end end context 'when the alg is invalid' do let(:token) { 'eyJhbGciOiJIUzI1NiJ9.eyJwYXkiOiJsb2FkIn0.ZpAhTTtuo-CmbgT6-95NaM_wFckKeyI157baZ29H41o' } it 'raises JWT::IncorrectAlgorithm error' do expect { JWT.decode(token, 'secret', true, algorithm: 'invalid-HS256') }.to raise_error(JWT::IncorrectAlgorithm, 'Expected a different algorithm') end end context 'when algorithm is a custom class' do let(:custom_algorithm) do Class.new do attr_reader :alg def initialize(signature: 'custom_signature', alg: 'custom') @signature = signature @alg = alg end def sign(*) @signature end def verify(data:, signature:, verification_key:) # rubocop:disable Lint/UnusedMethodArgument signature == @signature end def valid_alg?(alg) alg == self.alg end end end let(:token) { JWT.encode(payload, 'secret', custom_algorithm.new) } let(:expected_token) { 'eyJhbGciOiJjdXN0b20ifQ.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.Y3VzdG9tX3NpZ25hdHVyZQ' } it 'can be used for encoding' do expect(token).to eq(expected_token) end it 'can be used for decoding' do expect(JWT.decode(token, 'secret', true, algorithm: custom_algorithm.new)).to eq([payload, { 'alg' => 'custom' }]) end context 'when multiple custom algorithms are given for decoding' do it 'tries until the first match' do expect(JWT.decode(token, 'secret', true, algorithms: [custom_algorithm.new(signature: 'not_this'), custom_algorithm.new])).to eq([payload, { 'alg' => 'custom' }]) end end context 'when alg is not matching' do it 'fails the validation process' do expect { JWT.decode(token, 'secret', true, algorithms: custom_algorithm.new(alg: 'not_a_match')) }.to raise_error(JWT::IncorrectAlgorithm, 'Expected a different algorithm') end end context 'when signature is not matching' do it 'fails the validation process' do expect { JWT.decode(token, 'secret', true, algorithms: custom_algorithm.new(signature: 'not_a_match')) }.to raise_error(JWT::VerificationError, 'Signature verification failed') end end context 'when #sign method is missing' do before do custom_algorithm.instance_eval do remove_method :sign end end # This behaviour should be somehow nicer it 'raises an error on encoding' do expect { token }.to raise_error(NoMethodError) end it 'allows decoding' do expect(JWT.decode(expected_token, 'secret', true, algorithm: custom_algorithm.new)).to eq([payload, { 'alg' => 'custom' }]) end end context 'when #verify method is missing' do before do custom_algorithm.instance_eval do remove_method :verify end end it 'can be used for encoding' do expect(token).to eq(expected_token) end # This behaviour should be somehow nicer it 'raises error on decoding' do expect { JWT.decode(expected_token, 'secret', true, algorithm: custom_algorithm.new) }.to raise_error(NoMethodError) end end end end ruby-jwt-2.7.1/spec/spec_helper.rb000066400000000000000000000011021444067622100170540ustar00rootroot00000000000000# frozen_string_literal: true require 'rspec' require 'simplecov' require 'jwt' puts "OpenSSL::VERSION: #{OpenSSL::VERSION}" puts "OpenSSL::OPENSSL_VERSION: #{OpenSSL::OPENSSL_VERSION}" puts "OpenSSL::OPENSSL_LIBRARY_VERSION: #{OpenSSL::OPENSSL_LIBRARY_VERSION}\n\n" CERT_PATH = File.join(__dir__, 'fixtures', 'certs') RSpec.configure do |config| config.expect_with :rspec do |c| c.syntax = :expect end config.before(:example) { ::JWT.configuration.reset! } config.run_all_when_everything_filtered = true config.filter_run :focus config.order = 'random' end ruby-jwt-2.7.1/spec/x5c_key_finder_spec.rb000066400000000000000000000157621444067622100205140ustar00rootroot00000000000000# frozen_string_literal: true require 'spec_helper' require 'jwt/x5c_key_finder' describe JWT::X5cKeyFinder do let(:root_key) { OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'rsa-2048-private.pem'))) } let(:root_dn) { OpenSSL::X509::Name.parse('/DC=org/DC=fake-ca/CN=Fake CA') } let(:root_certificate) { generate_root_cert(root_dn, root_key) } let(:leaf_key) { generate_key } let(:leaf_dn) { OpenSSL::X509::Name.parse('/DC=org/DC=fake/CN=Fake') } let(:leaf_serial) { 2 } let(:leaf_not_after) { Time.now + 3600 } let(:leaf_signing_key) { root_key } let(:leaf_certificate) do cert = generate_cert( leaf_dn, leaf_key.public_key, leaf_serial, issuer: root_certificate, not_after: leaf_not_after ) ef = OpenSSL::X509::ExtensionFactory.new ef.config = OpenSSL::Config.parse(leaf_cdp) ef.subject_certificate = cert cert.add_extension(ef.create_extension('crlDistributionPoints', '@crlDistPts')) cert.sign(leaf_signing_key, 'sha256') cert end let(:leaf_cdp) { <<-_CNF_ } [crlDistPts] URI.1 = http://www.example.com/crl _CNF_ let(:crl) { issue_crl([], issuer: root_certificate, issuer_key: root_key) } let(:x5c_header) { [Base64.strict_encode64(leaf_certificate.to_der)] } subject(:keyfinder) { described_class.new([root_certificate], [crl]).from(x5c_header) } it 'returns the public key from a certificate that is signed by trusted roots and not revoked' do expect(keyfinder).to be_a(OpenSSL::PKey::RSA) expect(keyfinder.public_key.to_der).to eq(leaf_certificate.public_key.to_der) end context 'already parsed certificates' do let(:x5c_header) { [leaf_certificate] } it 'returns the public key from a certificate that is signed by trusted roots and not revoked' do expect(keyfinder).to be_a(OpenSSL::PKey::RSA) expect(keyfinder.public_key.to_der).to eq(leaf_certificate.public_key.to_der) end end context '::JWT.decode' do let(:token_payload) { { 'data' => 'something' } } let(:encoded_token) { JWT.encode(token_payload, leaf_key, 'RS256', { 'x5c' => x5c_header }) } let(:decoded_payload) do JWT.decode(encoded_token, nil, true, algorithms: ['RS256'], x5c: { root_certificates: [root_certificate], crls: [crl] }).first end it 'returns the encoded payload after successful certificate path verification' do expect(decoded_payload).to eq(token_payload) end end context 'certificate' do context 'expired' do let(:leaf_not_after) { Time.now - 3600 } it 'raises an error' do error = 'Certificate verification failed: certificate has expired. Certificate subject: /DC=org/DC=fake/CN=Fake.' expect { keyfinder }.to raise_error(JWT::VerificationError, error) end end context 'signature could not be verified with the given trusted roots' do let(:leaf_signing_key) { generate_key } it 'raises an error' do error = 'Certificate verification failed: certificate signature failure. Certificate subject: /DC=org/DC=fake/CN=Fake.' expect { keyfinder }.to raise_error(JWT::VerificationError, error) end end context 'could not be chained to a trusted root certificate' do context 'given an array' do subject(:keyfinder) { described_class.new([], [crl]).from(x5c_header) } it 'raises a verification error' do error = 'Certificate verification failed: unable to get local issuer certificate. Certificate subject: /DC=org/DC=fake/CN=Fake.' expect { keyfinder }.to raise_error(JWT::VerificationError, error) end end context 'given nil' do subject(:keyfinder) { described_class.new(nil, [crl]).from(x5c_header) } it 'raises a decode error' do error = 'Root certificates must be specified' expect { keyfinder }.to raise_error(ArgumentError, error) end end end context 'revoked' do let(:revocation) { [leaf_serial, Time.now - 60, 1] } let(:crl) { issue_crl([revocation], issuer: root_certificate, issuer_key: root_key) } it 'raises an error' do error = 'Certificate verification failed: certificate revoked. Certificate subject: /DC=org/DC=fake/CN=Fake.' expect { keyfinder }.to raise_error(JWT::VerificationError, error) end end end context 'CRL' do context 'expired' do let(:next_up) { Time.now - 60 } let(:crl) { issue_crl([], next_up: next_up, issuer: root_certificate, issuer_key: root_key) } it 'raises an error' do error = 'Certificate verification failed: CRL has expired. Certificate subject: /DC=org/DC=fake/CN=Fake.' expect { keyfinder }.to raise_error(JWT::VerificationError, error) end end context 'signature could not be verified with the given trusted roots' do let(:crl) { issue_crl([], issuer: root_certificate, issuer_key: generate_key) } it 'raises an error' do error = 'Certificate verification failed: CRL signature failure. Certificate subject: /DC=org/DC=fake/CN=Fake.' expect { keyfinder }.to raise_error(JWT::VerificationError, error) end end context 'not given' do subject(:keyfinder) { described_class.new([root_certificate], nil).from(x5c_header) } it 'raises an error' do error = 'Certificate verification failed: unable to get certificate CRL. Certificate subject: /DC=org/DC=fake/CN=Fake.' expect { keyfinder }.to raise_error(JWT::VerificationError, error) end end end private def generate_key OpenSSL::PKey::RSA.new(2048) end def generate_root_cert(root_dn, root_key) cert = generate_cert(root_dn, root_key, 1) ef = OpenSSL::X509::ExtensionFactory.new cert.add_extension(ef.create_extension('basicConstraints', 'CA:TRUE', true)) cert.sign(root_key, 'sha256') cert end def generate_cert(subject, key, serial, issuer: nil, not_after: nil) cert = OpenSSL::X509::Certificate.new issuer ||= cert cert.version = 2 cert.serial = serial cert.subject = subject cert.issuer = issuer.subject cert.public_key = key now = Time.now cert.not_before = now - 3600 cert.not_after = not_after || (now + 3600) cert end def issue_crl(revocations, issuer:, issuer_key:, next_up: nil) crl = OpenSSL::X509::CRL.new crl.issuer = issuer.subject crl.version = 1 now = Time.now crl.last_update = now - 3600 crl.next_update = next_up || (now + 3600) revocations.each do |rserial, time, reason_code| revoked = build_revoked(rserial, time, reason_code) crl.add_revoked(revoked) end crlnum = OpenSSL::ASN1::Integer(1) crl.add_extension(OpenSSL::X509::Extension.new('crlNumber', crlnum)) crl.sign(issuer_key, 'sha256') crl end def build_revoked(rserial, time, reason_code) revoked = OpenSSL::X509::Revoked.new revoked.serial = rserial revoked.time = time enum = OpenSSL::ASN1::Enumerated(reason_code) ext = OpenSSL::X509::Extension.new('CRLReason', enum) revoked.add_extension(ext) revoked end end