rack-jwt-verifier 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e35869423f2fe2b5072d382a8c3404d899f4d1eb67ca2ac8026b341d6f055b52
4
+ data.tar.gz: 2367980ac3f213c2340ffd7af9158a16262c69d73e09a75762c593017ac3df2e
5
+ SHA512:
6
+ metadata.gz: b2c4f85b03428e8ff39073083dda5090101dfbbd2e1c8dec51a0c89e08ca6efffea64802042ddbee7f29f6ff5372f12b6c1ec1417498fd08890aedb7e876fbc7
7
+ data.tar.gz: 4a5d3e3e6f4e4039ed0622644dda9e2db72f83d57a645f38e9eee2893fa68cfbac6f6656a82390399ee7c68570e790e5757b4c56a1bef85643230303a5b39c8e
data/.rspec_status ADDED
@@ -0,0 +1,26 @@
1
+ example_id | status | run_time |
2
+ ---------------------------------------------------- | ------ | --------------- |
3
+ ./spec/rack_jwt_verifier/jwt_helper_spec.rb[1:1:1] | passed | 0.06296 seconds |
4
+ ./spec/rack_jwt_verifier/jwt_helper_spec.rb[1:2:1] | passed | 0.05566 seconds |
5
+ ./spec/rack_jwt_verifier/jwt_helper_spec.rb[1:2:2] | passed | 0.03186 seconds |
6
+ ./spec/rack_jwt_verifier/jwt_helper_spec.rb[1:3:1:1] | passed | 0.04063 seconds |
7
+ ./spec/rack_jwt_verifier/jwt_helper_spec.rb[1:3:2:1] | passed | 0.06923 seconds |
8
+ ./spec/rack_jwt_verifier/jwt_helper_spec.rb[1:3:3:1] | passed | 0.03564 seconds |
9
+ ./spec/rack_jwt_verifier/middleware_spec.rb[1:1:1] | passed | 0.02249 seconds |
10
+ ./spec/rack_jwt_verifier/middleware_spec.rb[1:2:1:1] | passed | 0.05022 seconds |
11
+ ./spec/rack_jwt_verifier/middleware_spec.rb[1:2:1:2] | passed | 0.02597 seconds |
12
+ ./spec/rack_jwt_verifier/middleware_spec.rb[1:2:2:1] | passed | 0.02197 seconds |
13
+ ./spec/rack_jwt_verifier/middleware_spec.rb[1:2:3:1] | passed | 0.03074 seconds |
14
+ ./spec/rack_jwt_verifier/middleware_spec.rb[1:2:4:1] | passed | 0.02496 seconds |
15
+ ./spec/rack_jwt_verifier/verifier_spec.rb[1:1:1] | passed | 0.01668 seconds |
16
+ ./spec/rack_jwt_verifier/verifier_spec.rb[1:1:2] | passed | 0.00633 seconds |
17
+ ./spec/rack_jwt_verifier/verifier_spec.rb[1:1:3] | passed | 0.05474 seconds |
18
+ ./spec/rack_jwt_verifier/verifier_spec.rb[1:1:4] | passed | 0.04057 seconds |
19
+ ./spec/rack_jwt_verifier/verifier_spec.rb[1:2:1] | passed | 0.03279 seconds |
20
+ ./spec/rack_jwt_verifier/verifier_spec.rb[1:2:2] | passed | 0.04898 seconds |
21
+ ./spec/rack_jwt_verifier/verifier_spec.rb[1:2:3:1] | passed | 0.03709 seconds |
22
+ ./spec/rack_jwt_verifier/verifier_spec.rb[1:2:3:2] | passed | 0.01822 seconds |
23
+ ./spec/rack_jwt_verifier/verifier_spec.rb[1:3:1] | passed | 0.01993 seconds |
24
+ ./spec/rack_jwt_verifier/verifier_spec.rb[1:3:2] | passed | 0.01473 seconds |
25
+ ./spec/rack_jwt_verifier/verifier_spec.rb[1:3:3] | passed | 0.03322 seconds |
26
+ ./spec/rack_jwt_verifier/verifier_spec.rb[1:3:4] | passed | 0.01368 seconds |
data/CHANGELOG.md ADDED
File without changes
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in rack_jwt_verifier.gemspec
6
+ gemspec
7
+
8
+ # Dependencies for development and testing
9
+ group :development, :test do
10
+ gem "rack"
11
+ gem "rspec", "~> 3.12"
12
+ gem "rack-test"
13
+ gem "webmock", "~> 3.14" # Added for mocking network requests in Verifier
14
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,63 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ rack-jwt-verifier (0.1.0)
5
+ jwt (~> 2.8)
6
+ rack (>= 2.0)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ addressable (2.8.7)
12
+ public_suffix (>= 2.0.2, < 7.0)
13
+ base64 (0.2.0)
14
+ bigdecimal (3.1.8)
15
+ crack (1.0.0)
16
+ bigdecimal
17
+ rexml
18
+ diff-lcs (1.6.2)
19
+ hashdiff (1.1.0)
20
+ jwt (2.8.2)
21
+ base64
22
+ public_suffix (5.1.1)
23
+ rack (3.2.3)
24
+ rack-test (2.2.0)
25
+ rack (>= 1.3)
26
+ rake (13.2.1)
27
+ rexml (3.3.2)
28
+ strscan
29
+ rspec (3.13.1)
30
+ rspec-core (~> 3.13.0)
31
+ rspec-expectations (~> 3.13.0)
32
+ rspec-mocks (~> 3.13.0)
33
+ rspec-core (3.13.5)
34
+ rspec-support (~> 3.13.0)
35
+ rspec-expectations (3.13.5)
36
+ diff-lcs (>= 1.2.0, < 2.0)
37
+ rspec-support (~> 3.13.0)
38
+ rspec-mocks (3.13.6)
39
+ diff-lcs (>= 1.2.0, < 2.0)
40
+ rspec-support (~> 3.13.0)
41
+ rspec-support (3.13.6)
42
+ strscan (3.1.0)
43
+ timecop (0.9.10)
44
+ webmock (3.23.1)
45
+ addressable (>= 2.8.0)
46
+ crack (>= 0.3.2)
47
+ hashdiff (>= 0.4.0, < 2.0.0)
48
+
49
+ PLATFORMS
50
+ x86_64-linux
51
+
52
+ DEPENDENCIES
53
+ bundler (~> 2.0)
54
+ rack
55
+ rack-jwt-verifier!
56
+ rack-test
57
+ rake (~> 13.0)
58
+ rspec (~> 3.12)
59
+ timecop (~> 0.9)
60
+ webmock (~> 3.14)
61
+
62
+ BUNDLED WITH
63
+ 2.4.22
data/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Daniele Frisanco
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,136 @@
1
+ RackJwtVerifier
2
+ ===============
3
+
4
+ A robust and production-ready Rack middleware for authenticating requests using JSON Web Tokens (JWT) signed by an external Single Sign-On (SSO) provider.
5
+
6
+ This gem handles the cryptographic verification, caching of public keys, and integration into any Rack application (including Ruby on Rails).
7
+
8
+ Features
9
+ --------
10
+
11
+ * **Cryptographic Verification:** Verifies the JWT signature using the `RS256` algorithm and public keys fetched from a remote URL.
12
+
13
+ * **Flexible Caching:** Uses a configurable cache store for public keys, defaulting to in-memory caching but easily upgradable to **Redis** or **Memcached** for multi-process environments.
14
+
15
+ * **Claim Validation:** Enforces standard JWT claims, including expiration (`exp`) and not-before (`nbf`).
16
+
17
+ * **Rack Middleware:** Protects application routes by halting unauthorized requests with a `401 Unauthorized` response.
18
+
19
+
20
+ Installation
21
+ ------------
22
+
23
+ Add this line to your application's `Gemfile`:
24
+
25
+ ```ruby
26
+ gem 'rack_jwt_verifier'
27
+ ```
28
+
29
+ And then execute:
30
+
31
+ ```bash
32
+ $ bundle install
33
+ ```
34
+
35
+ Usage and Integration
36
+ ---------------------
37
+
38
+ ### 1\. Basic Setup (In-Memory Caching)
39
+
40
+ The simplest way to integrate is by providing the URL where your SSO provider exposes its public key (usually a PEM-encoded RSA key). The public key will be cached in memory for **5 minutes** per worker process.
41
+
42
+ **In `config/application.rb` (for Rails) or `config.ru` (for generic Rack):**
43
+
44
+ ```ruby
45
+ # Requires `rack_jwt_verifier` implicitly in Rails, or explicitly in config.ru
46
+ # Replace the URL with your actual SSO Public Key endpoint
47
+ PUBLIC_KEY_URL = "https://sso.example.com/api/v1/public_key"
48
+ Rails.application.config.middleware.use RackJwtVerifier::Middleware,
49
+ public_key_url: PUBLIC_KEY_URL
50
+ ```
51
+ ### 2\. Production Setup with Redis Caching
52
+
53
+ For horizontally scaled applications (e.g., using Puma or multiple Docker containers), the default in-memory cache is inefficient. To prevent a "cache stampede" where all workers simultaneously fetch the key, you must use a distributed cache like Redis.
54
+
55
+ **Prerequisites:** You need a Redis client library installed (e.g., `redis-rails` or `connection\_pool`).
56
+
57
+ #### Example: Using Redis as the Cache Store
58
+
59
+ The `RackJwtVerifier` expects a cache object that responds to the standard Ruby cache interface: `#read(key)` and `#write(key, value, expires\_in: ttl)`.
60
+
61
+ **Example using `ActiveSupport::Cache::RedisCacheStore` (Common in Rails apps):**
62
+
63
+ ```ruby
64
+ # In config/initializers/rack_jwt_verifier.rb
65
+
66
+ # 1. Configure your Redis cache client
67
+ # This example assumes you have Redis configured via Rails:
68
+ REDIS_CACHE_CLIENT = ActiveSupport::Cache.lookup_store(:redis_cache_store, {
69
+ url: ENV.fetch("REDIS_URL", "redis://localhost:6379/1"),
70
+ reconnect_attempts: 1 })
71
+ # 2. Configure the Verifier with the Redis client
72
+ Rails.application.config.middleware.use RackJwtVerifier::Middleware,
73
+ public_key_url: ENV.fetch("SSO_PUBLIC_KEY_URL"),
74
+ cache_store: REDIS_CACHE_CLIENT
75
+ ```
76
+
77
+ By passing the Redis cache client via the `cache\_store` option, all your application workers will share a single cache, ensuring the public key is fetched from the network only once every 5 minutes (or whatever TTL is configured internally).
78
+
79
+ ### 3\. Customizing JWT Decoding
80
+
81
+ You can pass a `:decode\_options` hash to the middleware to override the default settings for the JWT gem.
82
+
83
+ | Option | Default Value | Purpose |
84
+ | -- | -- | -- |
85
+ | `:leeway` | `60` seconds | Sets clock skew tolerance for `exp` and `nbf` checks. Set to `0` for strict timing. |
86
+ | `:algorithm` | `"RS256"` | The expected signing algorithm. |
87
+ | `:iss` | (None) | **RECOMMENDED**: Set this to enforce a specific issuer claim. |
88
+ | `:aud` | (None) | **RECOMMENDED**: Set this to enforce an audience claim. |
89
+
90
+ **Example: Strict Expiration and Issuer Check:**
91
+
92
+ ```ruby
93
+ Rails.application.config.middleware.use RackJwtVerifier::Middleware,
94
+ public_key_url: ENV.fetch("SSO_PUBLIC_KEY_URL"),
95
+ decode_options: {
96
+ # No clock skew tolerance
97
+ leeway: 0,
98
+ # Ensure the token was issued by our expected SSO provider
99
+ iss: "[https://my-sso.com/token-service](https://my-sso.com/token-service)"
100
+ }
101
+ ```
102
+
103
+ How it Works
104
+ ------------
105
+
106
+ 1. **Request Flow:** On every incoming HTTP request, the middleware intercepts the call.
107
+
108
+ 2. **Token Extraction:** It looks for a token in the `Authorization: Bearer <token>` header.
109
+
110
+ 3. **Key Retrieval:** The Verifier attempts to read the public key PEM string from the configured `cache\_store` (Redis or In-Memory).
111
+ * If the key is present, it's used immediately.
112
+ * If the key is missing or expired, a network request is made to the `public\_key\_url`, and the key is written back to the cache for 5 minutes.
113
+
114
+ 4. **Verification:** The public key is used to cryptographically verify the JWT's signature and validate its claims (`exp`, `nbf`, `iss`, etc.).
115
+
116
+ 5. **Authorization:**
117
+ * If verification succeeds, the request passes to your application.
118
+ * If verification fails (e.g., token expired, bad signature, or missing token), the request is halted, and a `401 Unauthorized` response is immediately returned.
119
+
120
+
121
+ Development
122
+ -----------
123
+
124
+ The testing setup uses RSpec, WebMock for network request mocking, and Timecop for robust time-dependent testing (like expiration checks).
125
+
126
+ To run the full suite:
127
+
128
+ ```bash
129
+ $ bundle install
130
+ $ bundle exec rspec
131
+ ```
132
+
133
+ License
134
+ -------
135
+
136
+ The gem is available as open source under the terms of the [MIT License](https://www.google.com/search?q=LICENSE.txt).
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RackJwtVerifier
4
+ # A simple, thread-safe, in-memory cache implementation designed to mimic
5
+ # a real cache store (like Rails.cache or Redis) but without external dependencies.
6
+ # This is the default cache store used if the user doesn't configure one.
7
+ class InProcessCache
8
+ # The cache lifespan in seconds (5 minutes)
9
+ DEFAULT_EXPIRY = 300
10
+
11
+ def initialize
12
+ @store = {}
13
+ @lock = Mutex.new # Ensure thread safety for multi-threaded environments
14
+ end
15
+
16
+ # Reads the value for a given key. Automatically checks for expiry.
17
+ # @param key [String] The cache key.
18
+ # @return [Object, nil] The cached value or nil if expired or not found.
19
+ def read(key)
20
+ @lock.synchronize do
21
+ entry = @store[key]
22
+ return nil unless entry
23
+
24
+ value, expires_at = entry
25
+
26
+ # Check if the entry is expired
27
+ return nil if Time.now.to_i >= expires_at
28
+
29
+ value
30
+ end
31
+ end
32
+
33
+ # Writes a value to the cache with an optional expiration time.
34
+ # @param key [String] The cache key.
35
+ # @param value [Object] The value to store.
36
+ # @param options [Hash] Options, expecting :expires_in (seconds).
37
+ # @return [Object] The stored value.
38
+ def write(key, value, options = {})
39
+ @lock.synchronize do
40
+ expiry = options[:expires_in] || DEFAULT_EXPIRY
41
+ expires_at = Time.now.to_i + expiry
42
+ @store[key] = [value, expires_at]
43
+ value
44
+ end
45
+ end
46
+
47
+ # Deletes an entry from the cache.
48
+ # @param key [String] The cache key.
49
+ # @return [Object, nil] The deleted entry value or nil.
50
+ def delete(key)
51
+ @lock.synchronize do
52
+ @store.delete(key)
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'jwt'
4
+ require 'openssl'
5
+
6
+ # A helper class for handling JWT creation and verification using RSA keys (RS256).
7
+ # This is typically used by the application or a separate service to *create* tokens.
8
+ module RackJwtVerifier
9
+ class JwtHelper
10
+ # The private_key must be an OpenSSL::PKey::RSA object (or similar).
11
+ attr_reader :private_key, :public_key
12
+
13
+ # Initializes the helper with the RSA Private Key used for signing.
14
+ #
15
+ # @param private_key_pem [String] The PEM string of the RSA Private Key.
16
+ def initialize(private_key_pem)
17
+ # !! IMPORTANT !!
18
+ # This key signs the tokens.
19
+ @private_key = OpenSSL::PKey::RSA.new(private_key_pem)
20
+ @public_key = @private_key.public_key
21
+ end
22
+
23
+ # Encodes a payload into a JWT.
24
+ #
25
+ # @param payload [Hash] The data to be encoded in the JWT (e.g., user ID, roles).
26
+ # @param expires_in [Integer] Time in seconds until the token expires (default: 1 hour).
27
+ # @return [String] The signed JWT string.
28
+ def encode(payload, expires_in = 3600)
29
+ # Set standard expiration time (exp) and issued-at time (iat) claims
30
+ time = Time.now.to_i
31
+ payload_with_claims = payload.merge({
32
+ iat: time,
33
+ exp: time + expires_in
34
+ })
35
+
36
+ JWT.encode(payload_with_claims, @private_key, 'RS256')
37
+ end
38
+
39
+ # Decodes and verifies a JWT using the public key.
40
+ #
41
+ # NOTE: This method is used primarily for self-testing in the application
42
+ # but the primary verification logic for the middleware is in the Verifier class.
43
+ #
44
+ # @param token [String] The JWT string to decode.
45
+ # @return [Hash] The decoded payload if verification is successful.
46
+ # @raise [JWT::VerificationError, JWT::DecodeError] If the token is invalid or expired.
47
+ def decode(token)
48
+ # Decodes using the public key, performs signature verification (true),
49
+ # and restricts the algorithm to 'RS256'.
50
+ decoded = JWT.decode(token, @public_key, true, { algorithm: 'RS256' })
51
+ # Returns only the payload (the first element of the array).
52
+ decoded.first
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rack_jwt_verifier/verifier"
4
+
5
+ module RackJwtVerifier
6
+ # The primary middleware class responsible for intercepting requests,
7
+ # extracting the JWT, verifying it, and injecting the user's details
8
+ # into the Rack environment.
9
+ class Middleware
10
+ # The default key in the Rack environment used to store the verified JWT payload.
11
+ # This can be accessed by downstream applications (e.g., Rails controllers)
12
+ # to retrieve the authenticated user's details.
13
+ RACK_ENV_PAYLOAD_KEY = "rack_jwt_verifier.payload".freeze
14
+
15
+ def initialize(app, options = {})
16
+ @app = app
17
+ @options = options
18
+
19
+ # The Verifier instance is initialized with options (like public_key_url)
20
+ # and is responsible for all crypto and key management.
21
+ @verifier = Verifier.new(options)
22
+ end
23
+
24
+ def call(env)
25
+ token = extract_token(env)
26
+
27
+ # If no token is found, we immediately pass the request down the stack
28
+ # and the application is responsible for handling the unauthenticated state.
29
+ return @app.call(env) unless token
30
+
31
+ begin
32
+ # Use the Verifier to handle the complex crypto and validation logic
33
+ payload = @verifier.verify(token)
34
+
35
+ # On successful verification, store the payload in the Rack environment
36
+ env[RACK_ENV_PAYLOAD_KEY] = payload
37
+
38
+ @app.call(env)
39
+ rescue JWT::DecodeError => e
40
+ # If verification fails (invalid signature, expired, invalid claim),
41
+ # log the error and return an unauthenticated response.
42
+ warn "JWT Verification Failed: #{e.message}"
43
+
44
+ # Return a 401 Unauthorized response
45
+ unauthorized_response
46
+ end
47
+ end
48
+
49
+ private
50
+
51
+ # Extracts the JWT from the standard Authorization header format: "Bearer <token>"
52
+ def extract_token(env)
53
+ # Rack converts HTTP_AUTHORIZATION header to ENV['HTTP_AUTHORIZATION']
54
+ auth_header = env["HTTP_AUTHORIZATION"]
55
+
56
+ return nil unless auth_header
57
+
58
+ scheme, token = auth_header.split(" ", 2)
59
+
60
+ # Only process if the scheme is "Bearer" and a token is present
61
+ (scheme == "Bearer") ? token : nil
62
+ end
63
+
64
+ # Standard 401 Unauthorized Rack response
65
+ def unauthorized_response
66
+ # Status, Headers, Body (Array of strings)
67
+ [401, { "Content-Type" => "text/plain", "WWW-Authenticate" => "Bearer error=\"invalid_token\"" }, ["Unauthorized: Invalid or expired JWT."]]
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "jwt"
4
+ require "net/http"
5
+ require "json"
6
+
7
+ module RackJwtVerifier
8
+ # This class handles the cryptographic heavy lifting: fetching and caching
9
+ # public keys from the SSO provider, and performing the actual JWT decoding
10
+ # and signature verification.
11
+ class Verifier
12
+ # Error raised if we fail to fetch keys from the remote URL
13
+ class KeyFetchError < StandardError; end
14
+
15
+ # The cache key used to store the public key PEM string
16
+ PUBLIC_KEY_CACHE_KEY = 'rack_jwt_verifier:public_key'.freeze
17
+ # The TTL for the cache (5 minutes, must match the default in InProcessCache)
18
+ CACHE_TTL_SECONDS = 300
19
+
20
+ # Default options for JWT decoding to ensure strict security compliance
21
+ DEFAULT_DECODE_OPTIONS = {
22
+ algorithm: "RS256", # Must match your SSO provider's algorithm
23
+ # THIS MUST BE TRUE: Ensures the 'exp' claim is checked during decoding
24
+ verify_expiration: true,
25
+ verify_not_before: true,
26
+ leeway: 60, # Allow a 60-second clock skew for "exp" and "nbf" claims
27
+ # 'iss' validation will be added later when we configure the Verifier.
28
+ # verify_iss: true
29
+ }.freeze
30
+
31
+ # @param options [Hash] Configuration options.
32
+ # @option options [String] :public_key_url The URL to fetch the public key.
33
+ # @option options [Object] :cache_store Optional custom cache object (must respond to #read and #write).
34
+ # @option options [Hash] :decode_options Custom options for JWT.decode.
35
+ def initialize(options = {})
36
+ @public_key_url = options.fetch(:public_key_url)
37
+
38
+ # Inject cache store, defaulting to the simple InProcessCache.
39
+ # This allows users to pass in a Redis/Memcached client that responds to #read and #write.
40
+ @cache = options.fetch(:cache_store, InProcessCache.new)
41
+
42
+ # Merge default options over any user-provided options
43
+ @decode_options = DEFAULT_DECODE_OPTIONS.merge(options.fetch(:decode_options, {}))
44
+ end
45
+
46
+ # Decodes and verifies the JWT.
47
+ # @param token [String] The JWT string from the Authorization header.
48
+ # @return [Hash] The decoded payload (the user claims).
49
+ # @raise [JWT::DecodeError] If the token is invalid, expired, or signature fails.
50
+ def verify(token)
51
+ # 1. Fetch the key from cache or network
52
+ key = fetch_public_key
53
+
54
+ # 2. Perform the cryptographic verification and claim validation
55
+ # The `true` is required to enable verification checks.
56
+ payload, _header = JWT.decode(token, key, true, @decode_options)
57
+
58
+ # For standard usage, we only need the payload hash
59
+ payload
60
+ end
61
+
62
+ private
63
+
64
+ # Handles fetching the public key from the remote URL, using the injected cache.
65
+ def fetch_public_key
66
+ # 1. Try to read the PEM string from the cache
67
+ cached_pem = @cache.read(PUBLIC_KEY_CACHE_KEY)
68
+
69
+ if cached_pem
70
+ # Found in cache, convert PEM to OpenSSL object and return
71
+ return OpenSSL::PKey::RSA.new(cached_pem)
72
+ end
73
+
74
+ # 2. Key is missing or expired, fetch it from the network
75
+ uri = URI(@public_key_url)
76
+ response = Net::HTTP.get_response(uri)
77
+
78
+ unless response.is_a?(Net::HTTPSuccess)
79
+ raise KeyFetchError, "Failed to fetch public key from #{@public_key_url}: #{response.code}"
80
+ end
81
+
82
+ # 3. Process response
83
+ public_key_pem = response.body
84
+
85
+ # 4. Cache the new key PEM string
86
+ @cache.write(PUBLIC_KEY_CACHE_KEY, public_key_pem, expires_in: CACHE_TTL_SECONDS)
87
+
88
+ # 5. Return the OpenSSL object for verification
89
+ OpenSSL::PKey::RSA.new(public_key_pem)
90
+
91
+ rescue KeyFetchError
92
+ # Re-raise explicit KeyFetchError for easier debugging/rescue in middleware
93
+ raise
94
+ rescue StandardError => e
95
+ # Catch all other network/parsing/OpenSSL errors
96
+ raise KeyFetchError, "Error processing public key: #{e.message}"
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RackJwtVerifier
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This file serves as the main entry point for the rack_jwt_verifier gem.
4
+ # When a user calls `require 'rack_jwt_verifier'`, this file is loaded.
5
+
6
+ require_relative "rack_jwt_verifier/version"
7
+
8
+ # Require core component files so they are available under the RackJwtVerifier module.
9
+ # IMPORTANT: These paths rely on you moving `jwt_helper.rb` into the
10
+ # `lib/rack_jwt_verifier/` directory.
11
+ require_relative "rack_jwt_verifier/jwt_helper"
12
+ require_relative "rack_jwt_verifier/verifier"
13
+ require_relative "rack_jwt_verifier/middleware"
14
+ require_relative "rack_jwt_verifier/in_process_cache"
15
+
16
+
17
+ # The main namespace module for the gem. All classes (JwtHelper, Verifier,
18
+ # Middleware) are now accessible via RackJwtVerifier::ClassName.
19
+ module RackJwtVerifier
20
+ end
metadata ADDED
@@ -0,0 +1,174 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rack-jwt-verifier
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Daniele Frisanco
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-10-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: jwt
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.8'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.8'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rack
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '2.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '2.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '13.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '13.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: webmock
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '3.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '3.0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: timecop
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '0.9'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '0.9'
111
+ - !ruby/object:Gem::Dependency
112
+ name: rack-test
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ description: Verifies JWT signature, validates claims (expiration, issuer), and handles
126
+ public key retrieval to ensure requests are securely authenticated by an external
127
+ SSO provider.
128
+ email:
129
+ - daniele.frisanco@gmail.com
130
+ executables: []
131
+ extensions: []
132
+ extra_rdoc_files: []
133
+ files:
134
+ - ".rspec_status"
135
+ - CHANGELOG.md
136
+ - Gemfile
137
+ - Gemfile.lock
138
+ - LICENSE.md
139
+ - README.md
140
+ - lib/rack_jwt_verifier.rb
141
+ - lib/rack_jwt_verifier/in_process_cache.rb
142
+ - lib/rack_jwt_verifier/jwt_helper.rb
143
+ - lib/rack_jwt_verifier/middleware.rb
144
+ - lib/rack_jwt_verifier/verifier.rb
145
+ - lib/rack_jwt_verifier/version.rb
146
+ homepage: https://github.com/danielefrisanco/rack_jwt_verifier
147
+ licenses:
148
+ - MIT
149
+ metadata:
150
+ allowed_push_host: https://rubygems.org
151
+ homepage_uri: https://github.com/danielefrisanco/rack_jwt_verifier
152
+ source_code_uri: https://github.com/danielefrisanco/rack_jwt_verifier
153
+ changelog_uri: https://github.com/danielefrisanco/rack_jwt_verifier/CHANGELOG.md
154
+ post_install_message:
155
+ rdoc_options: []
156
+ require_paths:
157
+ - lib
158
+ required_ruby_version: !ruby/object:Gem::Requirement
159
+ requirements:
160
+ - - ">="
161
+ - !ruby/object:Gem::Version
162
+ version: 2.6.6
163
+ required_rubygems_version: !ruby/object:Gem::Requirement
164
+ requirements:
165
+ - - ">="
166
+ - !ruby/object:Gem::Version
167
+ version: '0'
168
+ requirements: []
169
+ rubygems_version: 3.2.3
170
+ signing_key:
171
+ specification_version: 4
172
+ summary: A Rack middleware for authenticating requests using JWTs (JSON Web Tokens)
173
+ and injecting user data into the Rack environment.
174
+ test_files: []