api_keys 0.10.0 → 0.11.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3a0f38e1872bcafaaab8195c090e3f0f6fe2de26c99ded081fa6efebf9ce350b
4
- data.tar.gz: 8c66c076ecd44f4daf4419a4fb3f8504e49a7da31990276e88ee4b860d7e7a22
3
+ metadata.gz: a071706f4940979df9bbacf70e59f90a901608fba593a34cbd37b8e517490270
4
+ data.tar.gz: a0c36e4184ae8e28af66cc2370b9cb7704b62b10b1b308b153e6ab17817032f0
5
5
  SHA512:
6
- metadata.gz: 9e92633218bdd91c2beed9e4db6e76ef5963530533f97bbcf10e3308da598426d4000c4f4a0c9bc934ec481d01d60e0ab0ba27998301ff79c50aaec6e6b5cc67
7
- data.tar.gz: 394dca13057ef620fe3479af766c7ba69e3fa16bfa2529d202ccbd05dc1992acd9399d90d100e25d412fd9d5cc49027b6af88e561870dbc7c303fcf847f652fb
6
+ metadata.gz: 6e853d95adfcd70d79eab85873fdbcf99fdace6a8e5ee6fed9b905a6da44d0aca04ec2b0dc4b512bf416437428a87384a8c356c877924865d646c673463bd9f0
7
+ data.tar.gz: 3d6b2c95c8b09c2fccae7948399fc7d1b69595b339cf47d97e1648b2fee7117450d24804df1e95e845cf011e50a939b43b7ae63e62b3964ffb9ca188264fa426
data/CHANGELOG.md CHANGED
@@ -1,3 +1,13 @@
1
+ ## [0.11.0] - 2026-11-23
2
+
3
+ ### Added
4
+
5
+ - `config.on_key_refused`, a supported way to react to a refusal of an identified key. `authenticate_api_key!` calls it with `api_key:`, `error_code:` (a Symbol) and `request:` after the refusal is rendered and recorded, for every refusal whose key was identified (origin or IP lock, environment, key type, revoked, expired, missing scope, untrusted). It is never called for a missing, malformed or unknown token. It cannot change the response: it is not given the controller, and a raise is rescued and logged with its class only. It runs in the request, so it should enqueue a job and return. Before, the only way to get the refused key and the request together was to override the private `record_key_refusal`: `render_unauthorized` gets no key, and the `after_authentication` job gets no request. The README has an example (email the owner when their public key is refused on a site that is not on its list) and the security notes for it: the origin host is chosen by whoever sends the request.
6
+
7
+ ### Upgrading
8
+
9
+ - Nothing to do. An app that overrides `record_key_refusal` keeps working: the gem still calls it (and `super` still records the refusal), then calls `on_key_refused`. Moving that code to `on_key_refused` is recommended.
10
+
1
11
  ## [0.10.0] - 2026-11-13
2
12
 
3
13
  ### Added
data/README.md CHANGED
@@ -1540,6 +1540,68 @@ The dashboard's key page then says *"Requests are arriving but refused: last at
1540
1540
  - `enable_async_operations = false` turns them off with every other job.
1541
1541
  - New installs get the columns from the start. Existing installs run `rails generate api_keys:add_key_activity`; until then, authentication is unchanged and refusals are not recorded.
1542
1542
 
1543
+ ### Reacting to a refused key: `on_key_refused`
1544
+
1545
+ The columns above tell the owner when they come back to the dashboard. To act at the moment of a refusal (email the owner, post to your chat, count it in your own analytics), give the gem a callable:
1546
+
1547
+ ```ruby
1548
+ # config/initializers/api_keys.rb
1549
+ config.on_key_refused = ->(api_key:, error_code:, request:) do
1550
+ # ...
1551
+ end
1552
+ ```
1553
+
1554
+ `authenticate_api_key!` calls it for every refusal of an identified key, the same refusals that are recorded above: `origin_not_allowed`, `ip_not_allowed`, `restriction_misconfigured`, `environment_mismatch`, `unknown_environment`, `unknown_key_type`, `environment_misconfigured`, `revoked_key`, `expired_key`, `missing_scope` and `untrusted_key`. It receives the `ApiKeys::ApiKey`, the `error_code` the client got (a Symbol) and the `ActionDispatch::Request`.
1555
+
1556
+ - It is never called for a missing, malformed or unknown token. Those name no key, so nobody can make it run for a key without holding that key's token.
1557
+ - It runs after the refusal has been rendered and its statistics enqueued, and it is not given the controller. It cannot change the response.
1558
+ - An exception in it is rescued and logged (the class only, `[ApiKeys Auth] on_key_refused failed for key 42 (RuntimeError)`), and the client gets the same refusal as without it.
1559
+ - It runs inside the request, synchronously, and is not debounced: a client hammering a refused key calls it on every request. Keep it to an in-memory check and a job enqueue, and do the rest (database reads, mail) in the job. It does not depend on `enable_async_operations`.
1560
+ - Unlike `after_authentication`, which runs later in a job and therefore only gets serializable ids, this one gets the request. Read what you need from it here; do not pass the request to a job.
1561
+
1562
+ #### Example: email the owner when their public key is refused on a site that is not on its list
1563
+
1564
+ ```ruby
1565
+ # config/initializers/api_keys.rb
1566
+ config.on_key_refused = ->(api_key:, error_code:, request:) do
1567
+ next unless error_code == :origin_not_allowed
1568
+
1569
+ host = ApiKeys::Restrictions.extract_origin_host(request) # nil from curl or a server
1570
+ RefusedOriginMailJob.perform_later(api_key.id, host)
1571
+ end
1572
+ ```
1573
+
1574
+ ```ruby
1575
+ # app/jobs/refused_origin_mail_job.rb
1576
+ class RefusedOriginMailJob < ApplicationJob
1577
+ def perform(api_key_id, host)
1578
+ api_key = ApiKeys::ApiKey.find_by(id: api_key_id) or return
1579
+ return unless api_key.active? && api_key.allowed_origins.any?
1580
+
1581
+ # The host is attacker-controlled (see below). Mail about a plain DNS
1582
+ # name only, and nothing at all for anything else.
1583
+ if host
1584
+ return unless host.bytesize <= 253 && host.match?(/\A(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,63}\z/)
1585
+ return unless PublicSuffix.valid?(host, default_rule: nil) # not github.io or co.uk themselves (public_suffix gem)
1586
+ return if api_key.restrictions.origin_allowed?(host) # the owner added it since
1587
+ end
1588
+
1589
+ # Throttle: once per key and host, and a cap per key (store it on the key's metadata).
1590
+ RefusedOriginMailer.with(api_key: api_key, host: host).notice.deliver_later
1591
+ end
1592
+ end
1593
+ ```
1594
+
1595
+ **The origin host is chosen by the attacker.** A public key is in page source, so anyone can copy it and send it with any `Origin` or `Referer` header, from `curl` or their own site. A refused host proves nothing about who owns that site, and certainly not that it belongs to the key's owner. So:
1596
+
1597
+ - Validate it before you use it: a plain DNS name of a sane length, no wildcard, and not a public suffix like `github.io` or `co.uk` that nobody owns (the [`public_suffix`](https://github.com/weppos/publicsuffix-ruby) gem knows the list). Mail nothing when it fails.
1598
+ - Never let a mail or a page add it to the allowlist by itself. Say "if `example.com` is your site, you can add it", and make adding it an authenticated action by someone allowed to edit the key. If you link to that action, sign the host into the link, bound to the key, with an expiry, so nobody can craft a link that offers to allow their own site on another customer's key.
1599
+ - Do not make the host a link in the mail or put it in the subject line.
1600
+ - Throttle hard: per key and host, a maximum number of hosts per key, and per owner per day. Otherwise anyone holding the key can send a new made-up `Origin` every minute and turn your app into a mail cannon pointed at your customer.
1601
+ - Never put the key's allowlist in the mail. The refusal response does not echo it either.
1602
+
1603
+ Apps that overrode the private `record_key_refusal(api_key, error_code)` to get here can keep that override: it is still called, with `super` still recording the refusal, and `on_key_refused` runs after it. Moving to `on_key_refused` is recommended, since a private method can change without notice.
1604
+
1543
1605
  ## Key Types: Stripe-style Publishable & Secret Keys
1544
1606
 
1545
1607
  For applications that distribute software with embedded API keys (desktop apps, mobile apps, CLI tools), you may want to differentiate between key types with different permission levels. The `api_keys` gem supports Stripe-style publishable/secret key types with optional test/live environment isolation.
@@ -1919,6 +1981,7 @@ The mounted dashboard renders only the expiration and request-restriction fields
1919
1981
  - IP restrictions inherit the truthfulness of their resolver. Behind a proxy that is the only way in, keep `request.remote_ip` and list the proxy in `trusted_proxies`. If Rails is reachable directly, resolve `request.remote_addr`, or callers can choose the address being checked with `X-Forwarded-For` (see [Resolving the client IP](#resolving-the-client-ip)). Only trust a CDN-supplied header when direct access to the origin is blocked.
1920
1982
  - Everything fails closed: a locked list plus an unreadable request context, an unknown policy kind, or malformed stored policy data is a refusal, never a pass.
1921
1983
  - Refusals never echo the configured allowlist back to the caller. Reflecting your domains to an unauthenticated attacker would be a reconnaissance gift. If you want a more explicit message, override it through i18n (`api_keys.errors.origin_not_allowed`).
1984
+ - To tell the key's owner about a refusal, use [`config.on_key_refused`](#reacting-to-a-refused-key-on_key_refused). The refused origin it can read from the request is whatever the caller sent: validate it, and never treat it as proof that the site belongs to the owner.
1922
1985
  - Restriction checks read the current database row on every request, cache or no cache. Tightening the origins of a leaked publishable key takes effect on the very next call.
1923
1986
 
1924
1987
  ## Enterprise-ready by design
@@ -100,7 +100,7 @@ module ApiKeys
100
100
  status: :forbidden,
101
101
  required_scope: scope
102
102
  )
103
- record_key_refusal(refused_key, :missing_scope)
103
+ after_key_refusal(refused_key, :missing_scope)
104
104
  elsif !api_key_trusted?(@current_api_key)
105
105
  log_debug "[ApiKeys Auth] Trust check failed for key ID #{@current_api_key.id}."
106
106
  after_auth_context[:required_scope_check] = { required: scope, passed: true } if scope
@@ -113,7 +113,7 @@ module ApiKeys
113
113
  message: "API key is no longer trusted: the person behind it no longer stands behind it",
114
114
  status: :forbidden
115
115
  )
116
- record_key_refusal(refused_key, :untrusted_key)
116
+ after_key_refusal(refused_key, :untrusted_key)
117
117
  else
118
118
  after_auth_context[:required_scope_check] = { required: scope, passed: true } if scope
119
119
  # Authentication and scope check successful, enqueue stats update
@@ -125,7 +125,7 @@ module ApiKeys
125
125
  status = FORBIDDEN_ERROR_CODES.include?(result.error_code) ? :forbidden : :unauthorized
126
126
  render_unauthorized(error_code: result.error_code, message: result.message, status: status)
127
127
  # Only identified refusals carry a key; lookup failures have none to stamp.
128
- record_key_refusal(result.api_key, result.error_code) if result.api_key
128
+ after_key_refusal(result.api_key, result.error_code) if result.api_key
129
129
  end
130
130
 
131
131
  # Enqueue after_authentication callback asynchronously regardless of success/failure
@@ -220,6 +220,28 @@ module ApiKeys
220
220
  end
221
221
  end
222
222
 
223
+ # Everything that follows a refusal of an identified key, once the
224
+ # response is rendered: the gem's refusal stats, then the host's
225
+ # `config.on_key_refused`. Both are called separately, so a controller
226
+ # that overrides `record_key_refusal` (and calls super) keeps working and
227
+ # the configured callback still runs.
228
+ def after_key_refusal(api_key, error_code)
229
+ record_key_refusal(api_key, error_code)
230
+ run_on_key_refused(api_key, error_code)
231
+ end
232
+
233
+ # Calls `config.on_key_refused` with the refused key, the code the client
234
+ # received and the request. Never raises and never renders: the refusal
235
+ # has already been rendered, and the callback is not given the controller.
236
+ def run_on_key_refused(api_key, error_code)
237
+ callback = ApiKeys.configuration.on_key_refused
238
+ return unless callback && api_key
239
+
240
+ callback.call(api_key: api_key, error_code: error_code.to_sym, request: request)
241
+ rescue StandardError => error
242
+ log_error "[ApiKeys Auth] on_key_refused failed for key #{api_key&.id} (#{error.class})."
243
+ end
244
+
223
245
  # Enqueues the refusal half of UpdateStatsJob for a key that presented its
224
246
  # real token and was refused by a policy. It moves only last_refused_at,
225
247
  # last_refusal_code and (with track_requests_count) refusals_count; a
@@ -111,6 +111,24 @@ module ApiKeys
111
111
  # config.trusted_key_check = ->(api_key) { api_key.owner.managed_by?(api_key.created_by) }
112
112
  attr_reader :trusted_key_check
113
113
 
114
+ # Reacting to a refused key
115
+ #
116
+ # @!attribute [rw] on_key_refused
117
+ # @return [#call, nil] Callable run when `authenticate_api_key!` refuses
118
+ # a key it identified (the request presented the key's real token and a
119
+ # policy said no: origin or IP lock, environment, missing scope,
120
+ # revoked, expired, untrusted). It receives the keywords `api_key:`,
121
+ # `error_code:` (a Symbol) and `request:`, after the refusal has been
122
+ # rendered and recorded. It runs inside the request, so keep it to an
123
+ # in-memory check and a job enqueue. A raise is rescued and logged: the
124
+ # refusal the client gets never changes. Never called for a missing,
125
+ # malformed or unknown token. nil (the default) does nothing.
126
+ # @example Tell the owner when their public key is used on a site not on its list
127
+ # config.on_key_refused = ->(api_key:, error_code:, request:) do
128
+ # RefusedOriginJob.perform_later(api_key.id, ApiKeys::Restrictions.extract_origin_host(request)) if error_code == :origin_not_allowed
129
+ # end
130
+ attr_reader :on_key_refused
131
+
114
132
  # Idempotency-Key, for tests only
115
133
  #
116
134
  # @!attribute [rw] idempotency_in_test_transactions
@@ -370,6 +388,12 @@ module ApiKeys
370
388
  @trusted_key_check = value
371
389
  end
372
390
 
391
+ def on_key_refused=(value)
392
+ raise ArgumentError, "on_key_refused must be callable or nil" unless value.nil? || value.respond_to?(:call)
393
+
394
+ @on_key_refused = value
395
+ end
396
+
373
397
  def client_ip_resolver=(value)
374
398
  raise ArgumentError, "client_ip_resolver must be callable" unless value.respond_to?(:call)
375
399
 
@@ -763,6 +787,9 @@ module ApiKeys
763
787
  # The person behind a key: no check, every valid key is trusted
764
788
  @trusted_key_check = nil
765
789
 
790
+ # Reacting to a refused key: nothing by default
791
+ @on_key_refused = nil
792
+
766
793
  # Idempotency-Key: refuse every open transaction (tests may opt out)
767
794
  @idempotency_in_test_transactions = false
768
795
 
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ApiKeys
4
- VERSION = "0.10.0"
4
+ VERSION = "0.11.0"
5
5
  end
@@ -419,6 +419,22 @@ ApiKeys.configure do |config|
419
419
  # config.before_authentication = ->(context) { Rails.logger.info "Auth request: #{context[:request_uuid]}" }
420
420
  # config.after_authentication = ->(context) { Analytics.track_auth(context) }
421
421
 
422
+ # Called in the request, right after a refusal of an identified key (the
423
+ # request presented the key's real token and a policy said no: origin or IP
424
+ # lock, environment, missing scope, revoked, expired, untrusted). Gets the
425
+ # ApiKey, the error_code (a Symbol) and the request. Never called for a
426
+ # missing or unknown token. It cannot change the refusal, and a raise is
427
+ # rescued and logged. Keep it to a job enqueue: it runs on every refusal.
428
+ # The origin host in the request is attacker-controlled: validate it, and
429
+ # never treat it as proof that the site belongs to the key's owner.
430
+ #
431
+ # Default: nil (does nothing)
432
+ # config.on_key_refused = ->(api_key:, error_code:, request:) do
433
+ # next unless error_code == :origin_not_allowed
434
+ #
435
+ # RefusedOriginMailJob.perform_later(api_key.id, ApiKeys::Restrictions.extract_origin_host(request))
436
+ # end
437
+
422
438
  # ============================================================================
423
439
  # PERFORMANCE
424
440
  # ============================================================================
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: api_keys
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.10.0
4
+ version: 0.11.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - rameerez