api_keys 0.9.0 → 0.10.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: e5e832f996edf9ca24dad2920383f19b80aaebb5c56c9243154048fc5f5621b5
4
- data.tar.gz: d1c674160db7740b3791792e79e00c3d3f940c2c89aa9cc4eb8993977775d384
3
+ metadata.gz: 3a0f38e1872bcafaaab8195c090e3f0f6fe2de26c99ded081fa6efebf9ce350b
4
+ data.tar.gz: 8c66c076ecd44f4daf4419a4fb3f8504e49a7da31990276e88ee4b860d7e7a22
5
5
  SHA512:
6
- metadata.gz: 81a6c5e402cce5cc57d3bee554c057389081fbfb95e60aec758138f2288cbbc3c9c297631f9fb24ad7363857d27c42bd7ea36831752a5adc15c74ccb0574a9e1
7
- data.tar.gz: eebf27adfe99ab49b6c48ff9fe8f3685ea24d50d6b67b93074adf4ec6108d04b2cfc0dddbcf32377e0ed69f6a5276a4f6129cfe9fc163d7a5a7db2913943d852
6
+ metadata.gz: 9e92633218bdd91c2beed9e4db6e76ef5963530533f97bbcf10e3308da598426d4000c4f4a0c9bc934ec481d01d60e0ab0ba27998301ff79c50aaec6e6b5cc67
7
+ data.tar.gz: 394dca13057ef620fe3479af766c7ba69e3fa16bfa2529d202ccbd05dc1992acd9399d90d100e25d412fd9d5cc49027b6af88e561870dbc7c303fcf847f652fb
data/CHANGELOG.md CHANGED
@@ -1,3 +1,31 @@
1
+ ## [0.10.0] - 2026-11-13
2
+
3
+ ### Added
4
+
5
+ - An expiration picker modeled on OpenAI's API keys page. The dashboard's new key form asks "Expiration": **1 day, 7 days, 30 days, 1 year, Never, or Custom** (a date picker). It starts on "Select an expiration" and is required, so nobody makes a key that never expires by accident. A hint under it says the date the choice means ("This key will expire on December 13, 2026."). A custom date expires at 23:59:59 that day in the app's time zone (not `end_of_day`, whose fraction a MySQL `datetime` without sub-second precision rounds up to the next midnight). It must be within ten years.
6
+ - `config.expiration_options`, the picker's choices in order: durations (whole hours, days, weeks, months or years, up to ten years), `:never` and `:custom`. Default `[1.day, 7.days, 30.days, 1.year, :never, :custom]`. Without `:never`, the dashboard refuses a key that never expires, a crafted request included. Without `:custom`, it offers no date field and refuses a custom date. While `config.expire_after` is set, `:never` is shown under that lifetime's name ("90 days (default)"), since such a key expires anyway. The list governs the picker and the stock dashboard; `create_api_key!` takes any expiration your code asks for, so a controller of your own checks a submitted preset with `ExpirationOptions.offered?`.
7
+ - `create_api_key!(expires_in: 30.days)` and `create_api_key!(expires_on: "2027-01-31")`. `expires_in:` refuses to be combined with another expiration argument. `expires_on:` counts alone or with `expires_at_preset: "custom"`; beside another preset, or blank, it is ignored, since a form submits the date field whatever was chosen. `expires_at_preset:` takes every preset the picker sends: `"1_day"`, `"1_year"`, `"12_hours"`, `"2_weeks"`, `"never"`, `"custom"` (with `expires_on:`).
8
+ - `ApiKeys::ExpirationOptions.choices`, the picker in the configured order. `include_custom:` and `preview:` on it and on `for_select`, which is otherwise unchanged; `.parse(preset, on: date)`, `.offered?` and `.custom_offered?`; the presets now read every unit, singular or plural, up to ten years.
9
+ - `form.api_key_expiration_date_field`, the date field for "Custom".
10
+ - `api_key_expiration_label(api_key)`: "Expires on December 13, 2026", "Expired on November 1, 2026" or "Never expires".
11
+ - The token page says when the new key expires. The edit page shows the expiration, which cannot be changed. The keys list shows the date ("Dec 13, 2026", or "Never") instead of a rounded relative time ("Expires in 12 months" for a 1-year key), with the relative time as a tooltip.
12
+ - `ApiKeys::Errors::InvalidExpirationError`, an `ArgumentError` whose message the dashboard shows ("Pick the date the key expires.").
13
+
14
+ ### Fixed
15
+
16
+ - The dashboard's forms work in Chrome on apps with Rails' default origin check. Since 0.4.0 its pages sent `Referrer-Policy: no-referrer`; under it Chrome posts a same-origin form with `Origin: null`, and `forgery_protection_origin_check` (on by default since Rails 5) refused creating, updating and revoking keys with `ActionController::InvalidAuthenticityToken`. The pages now send `Referrer-Policy: same-origin`, which still sends no referrer to any other site.
17
+
18
+ ### Changed
19
+
20
+ - The dashboard offered No Expiration, 7, 30, 60, 90 and 365 days, with No Expiration preselected. It now offers the choices above and asks for one. Its controller reads presets through `ApiKeys::ExpirationOptions` instead of its own list, and refuses a preset the form did not offer ("Choose one of the offered expirations."). A request with no choice at all still gets what `create_api_key!` gives (never, or `config.expire_after`) while "Never" is offered.
21
+ - The dashboard uses the system sans-serif font (`--api-keys-font-family`) instead of the browser default serif, form labels are bold and sit above their fields, and the revoke icon lost its stray button border.
22
+ - `form.api_key_expiration_select` offers the picker (`ExpirationOptions.choices`) instead of the 0.9 list, starts on "Select an expiration" and renders `required`, instead of preselecting No Expiration. Pass `selected: "no_expiration"` for the old default, or `prompt: false` and `required: false` to turn either off. `custom: true` adds "Custom". A `selected:` the picker no longer offers ("60_days", "90_days", "365_days") selects nothing, so the browser asks for a choice rather than guessing one. A form that hides this select without disabling it (say, for a key type that cannot expire) must now disable it too, or the browser refuses to submit a required field it cannot show.
23
+
24
+ ### Upgrading
25
+
26
+ - Nothing to do for apps that use the stock dashboard, `ExpirationOptions.for_select`, `parse` or `create_api_key!`: `for_select` returns what it did in 0.9, and every preset 0.9 accepted still parses.
27
+ - Apps on `form.api_key_expiration_select` get the new picker: see Changed above.
28
+
1
29
  ## [0.9.0] - 2026-11-09
2
30
 
3
31
  ### Added
data/README.md CHANGED
@@ -212,7 +212,7 @@ config.authenticate_owner_method = :ensure_team_access!
212
212
 
213
213
  Once configured, your users can:
214
214
  - self-issue new API keys
215
- - set expiration dates
215
+ - choose when each key expires: 1 day, 7 days, 30 days, 1 year, never, or a custom date (the same choices OpenAI's API keys page offers)
216
216
  - attach scopes / permissions to individual keys (the edit form changes only the scopes it shows, the owner's default scopes, keeps any other scope a key holds, and drops a held scope its type no longer allows; keys of a `scopes: :ceiling` type show their live permissions instead, on the creation form as soon as such a type is selected, and the dashboard never takes scopes for them)
217
217
  - add and edit the key names
218
218
  - lock a key to specific web origins or IP addresses
@@ -336,7 +336,8 @@ module Settings
336
336
  name: api_key_params[:name],
337
337
  key_type: :secret,
338
338
  scopes: api_key_params[:scopes],
339
- expires_at_preset: params.dig(:api_key, :expires_at_preset)
339
+ expires_at_preset: params.dig(:api_key, :expires_at_preset),
340
+ expires_on: params.dig(:api_key, :expires_on) # the "Custom" date, if offered
340
341
  )
341
342
 
342
343
  ApiKeys::TokenSession.store(session, @api_key)
@@ -448,8 +449,10 @@ current_org.can_create_api_key?(key_type: :publishable)
448
449
  name: "My Key",
449
450
  key_type: :secret, # or :publishable
450
451
  scopes: ["read", "write"], # Blank values auto-removed; [] means none, omit for defaults
451
- expires_at: 30.days.from_now, # Explicit date
452
- expires_at_preset: "30_days", # OR use preset (takes precedence)
452
+ expires_in: 30.days, # How long it lives (or:)
453
+ # expires_at: 30.days.from_now, # an explicit time
454
+ # expires_on: "2027-01-31", # a custom date (expires at 23:59:59 that day)
455
+ # expires_at_preset: "30_days", # what the expiration picker submitted
453
456
  environment: :live, # Defaults to current_environment
454
457
  metadata: { team: "backend" }, # Optional JSON metadata
455
458
  allowed_origins: "example.com", # Optional: lock to web origins
@@ -577,28 +580,38 @@ None of this protects a session that has been stolen. Whoever holds a copy of th
577
580
 
578
581
  ### Expiration Options Helper
579
582
 
580
- For building expiration dropdowns:
583
+ The choices of the expiration picker (`config.expiration_options`), and how each one becomes an `expires_at`:
581
584
 
582
585
  ```ruby
583
- # Get options for select
586
+ # The picker, in the configured order (pair it with a prompt, as the dashboard does)
587
+ ApiKeys::ExpirationOptions.choices
588
+ # => [["1 day", "1_day"], ["7 days", "7_days"], ["30 days", "30_days"], ["1 year", "1_year"], ["Never", "no_expiration"]]
589
+
590
+ # The options forms used before 0.10, unchanged (it does not follow config.expiration_options)
584
591
  ApiKeys::ExpirationOptions.for_select
585
- # => [["No Expiration", "no_expiration"], ["7 days", "7_days"], ["30 days", "30_days"], ...]
592
+ # => [["No Expiration", "no_expiration"], ["7 days", "7_days"], ["30 days", "30_days"], ["60 days", "60_days"], ["90 days", "90_days"], ["1 year", "365_days"]]
586
593
 
587
- # Get default value
588
- ApiKeys::ExpirationOptions.default_value
589
- # => "no_expiration"
594
+ # With "Custom", for a form that also renders the date field
595
+ ApiKeys::ExpirationOptions.choices(include_custom: true)
590
596
 
591
- # Parse a preset to a date
592
- ApiKeys::ExpirationOptions.parse("30_days")
593
- # => 30.days.from_now
597
+ # With each choice's date, as data-api-keys-expires-on="December 13, 2026"
598
+ ApiKeys::ExpirationOptions.choices(preview: true)
594
599
 
595
- ApiKeys::ExpirationOptions.parse("no_expiration")
596
- # => nil
600
+ # Parse a preset to a time
601
+ ApiKeys::ExpirationOptions.parse("30_days") # => 30.days.from_now
602
+ ApiKeys::ExpirationOptions.parse("1_year") # => 1.year.from_now
603
+ ApiKeys::ExpirationOptions.parse("never") # => nil
604
+ ApiKeys::ExpirationOptions.parse("custom", on: "2027-01-31") # => 2027-01-31 23:59:59
597
605
 
598
- # Exclude "no expiration" option
606
+ # Exclude "Never"
599
607
  ApiKeys::ExpirationOptions.for_select(include_no_expiration: false)
608
+
609
+ # Did the form offer this preset?
610
+ ApiKeys::ExpirationOptions.offered?("60_days") # => false
600
611
  ```
601
612
 
613
+ A preset the parser does not understand raises `ArgumentError`, so a typo never makes a key permanent. "Custom" without a readable date, or one more than ten years out, raises `ApiKeys::Errors::InvalidExpirationError` (an `ArgumentError`) with a message you can show: "Pick the date the key expires."
614
+
602
615
  ---
603
616
 
604
617
  ### Form Builder Extensions (Opt-in)
@@ -613,19 +626,25 @@ end
613
626
 
614
627
  #### `api_key_expiration_select`
615
628
 
616
- Renders a select dropdown with all expiration presets:
629
+ Renders the expiration picker. Like OpenAI's, it starts on "Select an expiration" and is `required`, so nobody gets a key that never expires by accident. Each option carries the date it means in `data-api-keys-expires-on`, for a hint under the field:
617
630
 
618
631
  ```erb
619
632
  <%# Basic usage %>
620
633
  <%= form.api_key_expiration_select %>
621
634
 
622
635
  <%# With CSS classes (Tailwind example) %>
623
- <%= form.api_key_expiration_select(class: "w-full px-4 py-3 border rounded-lg") %>
636
+ <%= form.api_key_expiration_select({}, class: "w-full px-4 py-3 border rounded-lg") %>
624
637
 
625
- <%# With custom default selection %>
638
+ <%# Preselect a choice instead of asking %>
626
639
  <%= form.api_key_expiration_select(selected: "30_days") %>
640
+
641
+ <%# Offer "Custom", with the date field it needs (show it when Custom is chosen) %>
642
+ <%= form.api_key_expiration_select(custom: true) %>
643
+ <%= form.api_key_expiration_date_field(class: "form-input") %>
627
644
  ```
628
645
 
646
+ Pass both values to `create_api_key!`: `expires_at_preset: params.dig(:api_key, :expires_at_preset), expires_on: params.dig(:api_key, :expires_on)`. The date counts only when Custom is chosen, so an empty or stale date field beside another choice is ignored. The date field allows tomorrow up to ten years out.
647
+
629
648
  #### `api_key_scopes_checkboxes`
630
649
 
631
650
  Renders scope checkboxes with a block for custom markup. Before the boxes it can render one empty `api_key[scopes][]` field: browsers omit unchecked boxes, so without it a form with every box cleared would send no scopes at all, and a new key would silently get the default scopes while an edited key would keep its old ones. With it, clearing every box submits `[""]`, which `create_api_key!` and `ApiKey#scopes=` read as "no scopes". The submitted list replaces the key's scopes, so render a box for every scope the key may hold, or save it through `ApiKey#scopes_after_form_edit` (below).
@@ -779,7 +798,8 @@ end
779
798
  <%= form.text_field :name, placeholder: "e.g., Production Server" %>
780
799
 
781
800
  <%# Expiration (new keys only) %>
782
- <%= form.api_key_expiration_select(class: "form-select") %>
801
+ <%= form.api_key_expiration_select({ custom: true }, class: "form-select") %>
802
+ <%= form.api_key_expiration_date_field %>
783
803
 
784
804
  <%# Scopes %>
785
805
  <%= form.api_key_scopes_checkboxes(@available_scopes) do |scope, checked| %>
@@ -816,7 +836,7 @@ Based on real production integrations:
816
836
 
817
837
  1. **Use RESTful routes** - `resources :api_keys` with member/collection actions, not custom route definitions.
818
838
 
819
- 2. **Separate form-only params** - Access `expires_at_preset` via `params.dig(:api_key, :expires_at_preset)` rather than including it in strong params (it's not a model attribute).
839
+ 2. **Separate form-only params** - Access `expires_at_preset` and `expires_on` via `params.dig(:api_key, ...)` rather than including them in strong params (they're not model attributes).
820
840
 
821
841
  3. **Use `before_action` for shared setup** - Extract `@available_scopes` to a before_action rather than setting it in multiple actions.
822
842
 
@@ -841,7 +861,7 @@ If you want to write your own front-end instead of using the provided dashboard,
841
861
  @api_key = @user.create_api_key!(
842
862
  name: "my-key",
843
863
  scopes: %w[read write],
844
- expires_at: 42.days.from_now
864
+ expires_in: 30.days
845
865
  )
846
866
 
847
867
  # Get the plaintext token only available upon creation
@@ -905,6 +925,50 @@ And for any API key, you can always display a safe, user-friendly masked token t
905
925
  # => "ak_demo_••••yZn9"
906
926
  ```
907
927
 
928
+ ### Expiration: keys that expire on their own
929
+
930
+ Short-lived keys limit the damage of a leaked key. When someone creates a key, the dashboard asks when it should expire, the same way OpenAI's API keys page does: **1 day, 7 days, 30 days, 1 year, Never, or Custom** (pick a date). The form does not pick for them, and each choice says the date it means:
931
+
932
+ ![Choosing when an API key expires](api_keys_expiration.webp)
933
+
934
+ "Custom" opens a date picker. The key expires at 23:59:59 on that day:
935
+
936
+ ![Picking a custom expiration date](api_keys_expiration_custom.webp)
937
+
938
+ The keys list shows the date each key expires:
939
+
940
+ ![The keys list with expiration dates](api_keys_expiration_list.webp)
941
+
942
+ From code, say how long the key lives:
943
+
944
+ ```ruby
945
+ @user.create_api_key!(name: "CI", expires_in: 1.day)
946
+ @user.create_api_key!(name: "Partner", expires_in: 1.year)
947
+ @user.create_api_key!(name: "Launch", expires_on: "2027-01-31") # expires at 23:59:59 that day
948
+ @user.create_api_key!(name: "Server", expires_at: 90.days.from_now)
949
+ @user.create_api_key!(name: "Forever") # never expires (unless config.expire_after)
950
+ ```
951
+
952
+ Pick the choices the picker offers in the initializer. Durations can be whole hours, days, weeks, months or years, up to ten years:
953
+
954
+ ```ruby
955
+ # config/initializers/api_keys.rb
956
+ config.expiration_options = [1.day, 7.days, 30.days, 1.year, :never, :custom] # the default
957
+
958
+ # Every key created from the dashboard expires within 90 days: no "Never", no custom dates
959
+ config.expiration_options = [1.day, 7.days, 30.days, 90.days]
960
+ ```
961
+
962
+ Without `:never`, the dashboard refuses to create a key that never expires, even from a crafted request. The list governs the picker and the stock dashboard, not `create_api_key!`, which takes any expiration your code asks for. A controller of your own that passes a submitted preset through checks it first:
963
+
964
+ ```ruby
965
+ preset = params.dig(:api_key, :expires_at_preset)
966
+ unless ApiKeys::ExpirationOptions.offered?(preset, include_custom: ApiKeys::ExpirationOptions.custom_offered?)
967
+ # re-render the form: that choice is not offered
968
+ end
969
+ ```
970
+ With `config.expire_after` set, the never option names that lifetime instead ("90 days (default)"), because such a key expires anyway. A key's expiration is set when it is created: the edit page shows it, and to change it you create a new key and revoke the old one. The token page and the keys list show when each key expires, and `api_key_expiration_label(@api_key)` says it in words ("Expires on December 13, 2026").
971
+
908
972
  ### Scopes: define and verify API Key permissions
909
973
 
910
974
  Users can limit what each API key does by selecting scopes, and you can define those scopes.
Binary file
Binary file
Binary file
@@ -144,7 +144,11 @@ module ApiKeys
144
144
  def set_api_keys_security_headers
145
145
  response.headers["Cache-Control"] = "no-store, private"
146
146
  response.headers["Pragma"] = "no-cache"
147
- response.headers["Referrer-Policy"] = "no-referrer"
147
+ # Not "no-referrer": under it Chrome sends `Origin: null` with the
148
+ # dashboard's own form posts, and Rails' default origin check
149
+ # (forgery_protection_origin_check) refuses them. "same-origin" still
150
+ # sends nothing to any other site.
151
+ response.headers["Referrer-Policy"] = "same-origin"
148
152
  response.headers["X-Content-Type-Options"] = "nosniff"
149
153
  response.headers["X-Frame-Options"] = "DENY"
150
154
  response.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()"
@@ -89,7 +89,7 @@ module ApiKeys
89
89
  @api_key = current_api_keys_owner.create_api_key!(
90
90
  name: submitted_params[:name],
91
91
  scopes: scopes,
92
- expires_at: parse_expiration(submitted_params[:expires_at_preset]),
92
+ **chosen_expiration(submitted_params, type_config),
93
93
  key_type: submitted_params[:key_type].presence,
94
94
  # The model normalizes these raw strings; no parser needed here.
95
95
  allowed_origins: submitted_params[:allowed_origins],
@@ -105,8 +105,14 @@ module ApiKeys
105
105
  # If create! fails due to validation (e.g., quota exceeded)
106
106
  @api_key = e.record # Get the invalid ApiKey instance
107
107
  @api_key.expires_at_preset = submitted_params[:expires_at_preset]
108
+ @api_key.expires_on = submitted_params[:expires_on]
108
109
  flash.now[:alert] = "Failed to create API key: #{e.record.errors.full_messages.join(', ')}"
109
110
  render :new, status: :unprocessable_entity
111
+ rescue ApiKeys::Errors::InvalidExpirationError => e
112
+ # Written for the person filling in the form; never echoes their input.
113
+ flash.now[:alert] = "Failed to create API key: #{e.message}"
114
+ @api_key = rebuild_api_key_for_form(submitted_params)
115
+ render :new, status: :unprocessable_entity
110
116
  rescue ArgumentError
111
117
  flash.now[:alert] = "Failed to create API key: invalid options."
112
118
  @api_key = rebuild_api_key_for_form(submitted_params)
@@ -183,7 +189,7 @@ module ApiKeys
183
189
  submitted = params.require(:api_key)
184
190
  raise ActionController::ParameterMissing, :api_key unless submitted.respond_to?(:permit)
185
191
 
186
- permitted_params = submitted.permit(:name, :expires_at_preset, :key_type,
192
+ permitted_params = submitted.permit(:name, :expires_at_preset, :expires_on, :key_type,
187
193
  :allowed_origins, :allowed_ips, scopes: [])
188
194
  normalize_submitted_scopes!(permitted_params)
189
195
  end
@@ -255,18 +261,32 @@ module ApiKeys
255
261
  permitted_params
256
262
  end
257
263
 
258
- # Helper to parse the expiration preset string into a Time object
259
- def parse_expiration(preset)
260
- case preset
261
- when "7_days" then 7.days.from_now
262
- when "30_days" then 30.days.from_now
263
- when "60_days" then 60.days.from_now
264
- when "90_days" then 90.days.from_now
265
- when "365_days" then 365.days.from_now
266
- when "no_expiration" then nil
267
- when nil, "" then nil
268
- else raise ArgumentError, "Invalid expiration preset"
264
+ # The expiration the picker's choice asks for, as create_api_key!
265
+ # arguments. Only a choice the form offered is taken, so an app that took
266
+ # :never (or :custom) off config.expiration_options gets no such key from
267
+ # a crafted request either. A key type that cannot expire offers no
268
+ # picker, and the model refuses any expiration submitted for it.
269
+ #
270
+ # @return [Hash] { expires_at_preset:, expires_on: }, or {} for no choice
271
+ def chosen_expiration(submitted_params, type_config)
272
+ options = ApiKeys::ExpirationOptions
273
+ preset = submitted_params[:expires_at_preset].presence
274
+ expirable = type_config.nil? || ApiKeys::ApiKey.revocable_for(type_config)
275
+
276
+ if expirable && preset.nil?
277
+ # A request without a choice gets what create_api_key! gives: never,
278
+ # or config.expire_after. Never can only be had where it is offered.
279
+ return {} if options.never_offered? || !ApiKeys.configuration.expire_after.nil?
280
+
281
+ raise ApiKeys::Errors::InvalidExpirationError, "Choose when this key expires."
269
282
  end
283
+ if expirable && !options.offered?(preset, include_custom: options.custom_offered?)
284
+ raise ApiKeys::Errors::InvalidExpirationError, "Choose one of the offered expirations."
285
+ end
286
+ return {} if preset.nil?
287
+ return { expires_at_preset: preset } unless preset == options::CUSTOM
288
+
289
+ { expires_at_preset: preset, expires_on: submitted_params[:expires_on].to_s }
270
290
  end
271
291
 
272
292
  def rebuild_api_key_for_form(submitted_params)
@@ -276,6 +296,7 @@ module ApiKeys
276
296
  key_type: submitted_params[:key_type]
277
297
  )
278
298
  api_key.expires_at_preset = submitted_params[:expires_at_preset]
299
+ api_key.expires_on = submitted_params[:expires_on]
279
300
  if ApiKeys::ApiKey.restrictions_column?
280
301
  api_key.allowed_origins = submitted_params[:allowed_origins] unless submitted_params[:allowed_origins].nil?
281
302
  api_key.allowed_ips = submitted_params[:allowed_ips] unless submitted_params[:allowed_ips].nil?
@@ -52,20 +52,28 @@
52
52
  <%= form.text_field :name, placeholder: "e.g., myproject-production-key" %>
53
53
  </div>
54
54
 
55
+ <%# The expiration picker: 1 day, 7 days, 30 days, 1 year, Never, Custom %>
56
+ <%# (config.expiration_options). Like OpenAI's, it asks for a choice instead %>
57
+ <%# of defaulting to one; the hint below it says the date it means. %>
58
+ <% offers_custom = ApiKeys::ExpirationOptions.custom_offered? %>
59
+ <% custom_chosen = offers_custom && api_key.expires_at_preset == ApiKeys::ExpirationOptions::CUSTOM %>
55
60
  <div data-api-keys-expiration>
56
- <%= form.label :expires_at_preset, "Expiration" %>
61
+ <%# Explicit ids: form_with leaves them out where form_with_generates_ids is off. %>
62
+ <%= form.label :expires_at_preset, "Expiration", for: "api_key_expires_at_preset" %>
57
63
  <%= form.select :expires_at_preset,
58
- options_for_select([
59
- ["No Expiration", "no_expiration"],
60
- ["7 days", "7_days"],
61
- ["30 days", "30_days"],
62
- ["60 days", "60_days"],
63
- ["90 days", "90_days"],
64
- ["365 days", "365_days"] # Common presets
65
- ], api_key.expires_at_preset.presence || (api_key.expires_at.present? ? nil : "no_expiration")), # Default selection
66
- {}, # html options
67
- {} # data attributes
68
- %>
64
+ options_for_select(ApiKeys::ExpirationOptions.choices(include_custom: offers_custom, preview: true),
65
+ api_key.expires_at_preset),
66
+ { prompt: "Select an expiration" },
67
+ { required: true, id: "api_key_expires_at_preset" } %>
68
+ <% if offers_custom %>
69
+ <%= tag.div class: "api-keys-custom-expiration", data: { api_keys_custom_expiration: "" }, hidden: !custom_chosen do %>
70
+ <%= form.label :expires_on, "Expires on", for: "api_key_expires_on" %>
71
+ <%= form.date_field :expires_on, value: api_key.expires_on, required: custom_chosen, disabled: !custom_chosen,
72
+ id: "api_key_expires_on",
73
+ **ApiKeys::ExpirationOptions.custom_date_range %>
74
+ <% end %>
75
+ <% end %>
76
+ <small class="api-keys-form-help" data-api-keys-expiration-hint aria-live="polite" hidden></small>
69
77
  </div>
70
78
 
71
79
  <%# The offered scopes are the owner's default scopes. The controller reads %>
@@ -126,6 +134,13 @@
126
134
  <%= form.text_field :name %>
127
135
  </div>
128
136
 
137
+ <%# An expiration is set when the key is created and cannot change. %>
138
+ <div class="api-keys-expiration-summary">
139
+ <p><strong>Expiration</strong></p>
140
+ <span title="<%= api_key.expires_at&.strftime('%Y-%m-%d %H:%M:%S %Z') %>"><%= api_key_expiration_label(api_key) %></span>
141
+ <small class="api-keys-form-help">A key's expiration is set when it is created. To change it, create a new key and revoke this one.</small>
142
+ </div>
143
+
129
144
  <%# A `scopes: :ceiling` key is authorized by its type's live permissions and %>
130
145
  <%# its stored scopes are metadata, so the form shows the live ceiling and %>
131
146
  <%# offers nothing to edit; the controller ignores scopes submitted for it. %>
@@ -195,7 +210,7 @@
195
210
  </div>
196
211
  <% end %>
197
212
 
198
- <% if !api_key.persisted? && ApiKeys.configuration.key_types.present? %>
213
+ <% unless api_key.persisted? %>
199
214
  <% key_type_policies = ApiKeys.configuration.key_types.to_h do |type, config| %>
200
215
  <% [type.to_s, {
201
216
  restrictions: ApiKeys::ApiKey.restriction_kinds_for(config).map(&:to_s),
@@ -206,11 +221,49 @@
206
221
  <script nonce="<%= content_security_policy_nonce %>">
207
222
  (() => {
208
223
  const form = document.getElementById("api-keys-key-form");
209
- const keyType = form && form.querySelector("#api_key_key_type");
210
- if (!form || !keyType) return;
224
+ if (!form) return;
225
+
226
+ // The expiration picker: show the date field only for Custom, and say
227
+ // in words when the chosen key would expire.
228
+ const expiration = form.querySelector("#api_key_expires_at_preset");
229
+ const customExpiration = form.querySelector("[data-api-keys-custom-expiration]");
230
+ const customDate = customExpiration && customExpiration.querySelector("input");
231
+ const hint = form.querySelector("[data-api-keys-expiration-hint]");
232
+ const longDate = (isoDate) => new Date(isoDate + "T00:00:00").toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
233
+
234
+ const updateExpiration = () => {
235
+ if (!expiration) return;
236
+ const custom = !expiration.disabled && expiration.value === "custom";
237
+ if (customDate) {
238
+ customExpiration.hidden = !custom;
239
+ customDate.disabled = !custom;
240
+ customDate.required = custom;
241
+ }
242
+ if (!hint) return;
243
+
244
+ const option = expiration.selectedOptions[0];
245
+ let text = "";
246
+ if (expiration.disabled) {
247
+ text = "";
248
+ } else if (option && option.dataset.apiKeysExpiresOn) {
249
+ text = "This key will expire on " + option.dataset.apiKeysExpiresOn + ".";
250
+ } else if (expiration.value === "no_expiration") {
251
+ text = "This key will never expire.";
252
+ } else if (custom && customDate && customDate.value) {
253
+ text = "This key will expire at the end of " + longDate(customDate.value) + ".";
254
+ }
255
+ hint.textContent = text;
256
+ hint.hidden = !text;
257
+ };
258
+
259
+ if (expiration) expiration.addEventListener("change", updateExpiration);
260
+ if (customDate) customDate.addEventListener("input", updateExpiration);
211
261
 
262
+ // Key types: show the fields the chosen type allows.
263
+ const keyType = form.querySelector("#api_key_key_type");
212
264
  const policies = <%= raw json_escape(key_type_policies.to_json) %>;
213
265
  const updatePolicyFields = () => {
266
+ if (!keyType) return;
214
267
  const policy = policies[keyType.value];
215
268
 
216
269
  form.querySelectorAll("[data-api-keys-restriction-kind]").forEach((container) => {
@@ -237,8 +290,9 @@
237
290
  });
238
291
  };
239
292
 
240
- keyType.addEventListener("change", updatePolicyFields);
293
+ if (keyType) keyType.addEventListener("change", () => { updatePolicyFields(); updateExpiration(); });
241
294
  updatePolicyFields();
295
+ updateExpiration();
242
296
  })();
243
297
  </script>
244
298
  <% end %>
@@ -17,18 +17,20 @@
17
17
  </td>
18
18
 
19
19
  <td class="api-keys-cell-expires">
20
+ <%# The date, as OpenAI's key list shows it; the relative time is the tooltip. %>
20
21
  <% if key.expires_at? %>
22
+ <% expires_on = key.expires_at.strftime("%b %-d, %Y") %>
21
23
  <% if key.expired? %>
22
- <strong class="api-keys-expired-text" title="<%= key.expires_at.strftime('%Y-%m-%d %H:%M:%S %Z') %>">
23
- Expired <%= time_ago_in_words(key.expires_at) %> ago
24
+ <strong class="api-keys-expired-text" title="Expired <%= time_ago_in_words(key.expires_at) %> ago (<%= key.expires_at.strftime('%Y-%m-%d %H:%M:%S %Z') %>)">
25
+ Expired <%= expires_on %>
24
26
  </strong>
25
27
  <% else %>
26
- <span title="<%= key.expires_at.strftime('%Y-%m-%d %H:%M:%S %Z') %>">
27
- Expires in <%= time_ago_in_words(key.expires_at) %>
28
+ <span title="In <%= time_ago_in_words(key.expires_at) %> (<%= key.expires_at.strftime('%Y-%m-%d %H:%M:%S %Z') %>)">
29
+ <%= expires_on %>
28
30
  </span>
29
31
  <% end %>
30
32
  <% else %>
31
- <em>Never expires</em>
33
+ <em>Never</em>
32
34
  <% end %>
33
35
  </td>
34
36
 
@@ -35,6 +35,14 @@
35
35
  </div>
36
36
 
37
37
 
38
+ <p class="api-keys-token-expiration">
39
+ <% if api_key.expires_at %>
40
+ This key expires on <strong title="<%= api_key.expires_at.strftime('%Y-%m-%d %H:%M:%S %Z') %>"><%= api_key.expires_at.strftime(ApiKeys::ExpirationOptions::DATE_LABEL) %></strong>.
41
+ <% else %>
42
+ This key never expires.
43
+ <% end %>
44
+ </p>
45
+
38
46
  <% displayed_scopes = api_keys_displayed_scopes(api_key) %>
39
47
  <% if displayed_scopes.present? %>
40
48
  <div class="api-keys-token-scopes">
@@ -50,7 +50,7 @@
50
50
  --api-keys-border-radius: 8px;
51
51
 
52
52
  /* Typography */
53
- --api-keys-font-family: inherit;
53
+ --api-keys-font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
54
54
  --api-keys-code-font-size: 0.8em;
55
55
  }
56
56
 
@@ -96,7 +96,7 @@
96
96
  font: inherit;
97
97
  }
98
98
 
99
- input[type="text"], select {
99
+ input[type="text"], input[type="date"], select {
100
100
  width: 100%;
101
101
  padding: 0.65rem;
102
102
  border: 1px solid var(--color-grey, #bbb);
@@ -181,6 +181,17 @@
181
181
  margin-top: 2.5em;
182
182
  }
183
183
 
184
+ form label {
185
+ display: block;
186
+ margin-bottom: 0.4em;
187
+ font-weight: 600;
188
+ }
189
+
190
+ form .form-check-label {
191
+ display: inline;
192
+ font-weight: normal;
193
+ }
194
+
184
195
  a {
185
196
  color: var(--font-color);
186
197
  }
@@ -191,6 +202,7 @@
191
202
 
192
203
  .api-keys-action-buttons button {
193
204
  background: none;
205
+ border: 0;
194
206
  padding: 0;
195
207
  color: var(--api-keys-danger-color);
196
208
  }
@@ -198,6 +210,8 @@
198
210
  [hidden] { display: none !important; }
199
211
  .api-keys-form-errors { color: var(--api-keys-danger-color); }
200
212
  .api-keys-form-help { display: block; color: var(--color-darkGrey, #666); }
213
+ [data-api-keys-expiration-hint] { margin-top: 0.5em; }
214
+ .api-keys-custom-expiration { margin-top: 1em; }
201
215
  .api-keys-refusal-notice {
202
216
  padding: 0.8em 1em;
203
217
  border-left: 4px solid var(--api-keys-warning-color);
@@ -56,6 +56,22 @@ module ApiKeys
56
56
  attr_reader :default_max_keys_per_owner, :require_key_name
57
57
  attr_reader :expire_after, :default_scopes, :track_requests_count
58
58
 
59
+ # Expiration choices
60
+ #
61
+ # @!attribute [rw] expiration_options
62
+ # @return [Array<ActiveSupport::Duration, Symbol>] What the expiration
63
+ # picker offers when someone creates a key, in order: durations (whole
64
+ # hours, days, weeks, months or years, up to ten years), `:never`, and
65
+ # `:custom` (a date picker). Take `:never` out to make every key expire.
66
+ # While `config.expire_after` is set, `:never` is offered under that
67
+ # lifetime's name ("90 days (default)"), because such a key expires anyway.
68
+ # The stock dashboard enforces this list; a controller of your own
69
+ # checks a submitted preset with `ApiKeys::ExpirationOptions.offered?`.
70
+ # Default: `[1.day, 7.days, 30.days, 1.year, :never, :custom]`.
71
+ # @example Every key expires within 90 days
72
+ # config.expiration_options = [1.day, 7.days, 30.days, 90.days, :custom]
73
+ attr_reader :expiration_options
74
+
59
75
  # Performance
60
76
  attr_reader :cache_ttl, :stats_update_interval
61
77
 
@@ -249,6 +265,20 @@ module ApiKeys
249
265
  @expire_after = value
250
266
  end
251
267
 
268
+ def expiration_options=(value)
269
+ choices = Array(value).map { |choice| choice.is_a?(String) ? choice.to_sym : choice } if value.is_a?(Array)
270
+ options = ApiKeys::Helpers::ExpirationOptions
271
+ valid = choices.present? && choices.uniq.length == choices.length && choices.all? do |choice|
272
+ options::CHOICES.include?(choice) || options.preset_for(choice)
273
+ end
274
+ unless valid
275
+ raise ArgumentError, "expiration_options must list durations (whole hours, days, weeks, months or years, " \
276
+ "up to ten years), :never and :custom, each once"
277
+ end
278
+
279
+ @expiration_options = choices.freeze
280
+ end
281
+
252
282
  def default_scopes=(value)
253
283
  unless value.is_a?(Array) && value.length <= MAX_CONFIGURED_SCOPES && value.all? { |scope| valid_scope_name?(scope) }
254
284
  raise ArgumentError, "default_scopes must be a bounded Array of safe scope strings"
@@ -684,6 +714,7 @@ module ApiKeys
684
714
  @default_max_keys_per_owner = nil # No global key limit per owner
685
715
  @require_key_name = false # Don't require names for keys globally
686
716
  @expire_after = nil # Keys do not expire by default (e.g., 90.days)
717
+ @expiration_options = [1.day, 7.days, 30.days, 1.year, :never, :custom].freeze # The picker, like OpenAI's
687
718
  @default_scopes = [].freeze # No default scopes assigned globally
688
719
 
689
720
  # Performance
@@ -5,6 +5,12 @@ module ApiKeys
5
5
  # Base error class for all ApiKeys errors
6
6
  class BaseError < StandardError; end
7
7
 
8
+ # Raised when a key's expiration cannot be understood: "Custom" without a
9
+ # readable date, or a date past the ten-year limit. An ArgumentError, as
10
+ # every invalid expiration preset has always been; its message is written
11
+ # for the person filling in the form.
12
+ class InvalidExpirationError < ArgumentError; end
13
+
8
14
  # Raised when attempting to revoke or destroy a non-revocable key
9
15
  class KeyNotRevocableError < BaseError
10
16
  def initialize(message = "This API key cannot be revoked or deleted")
@@ -11,8 +11,8 @@ module ApiKeys
11
11
  # ActionView::Helpers::FormBuilder.include(ApiKeys::FormBuilderExtensions)
12
12
  # end
13
13
  #
14
- # @example Expiration select
15
- # <%= form.api_key_expiration_select(class: "my-select-class") %>
14
+ # @example Expiration picker
15
+ # <%= form.api_key_expiration_select({}, class: "my-select-class") %>
16
16
  #
17
17
  # @example Scopes checkboxes with block for custom rendering
18
18
  # <%= form.api_key_scopes_checkboxes(@scopes) do |scope, checked| %>
@@ -25,34 +25,62 @@ module ApiKeys
25
25
  # clearing every box submits "no scopes" instead of nothing.)
26
26
  #
27
27
  module FormBuilderExtensions
28
- # Renders a select field for API key expiration presets.
28
+ # Renders the expiration picker: 1 day, 7 days, 30 days, 1 year, Never
29
+ # (config.expiration_options). Like OpenAI's, it asks for a choice
30
+ # ("Select an expiration", required) instead of defaulting to one, and
31
+ # each option carries the date it means (`data-api-keys-expires-on`).
29
32
  #
30
- # @param options [Hash] Options passed to the select helper
31
- # @param html_options [Hash] HTML attributes for the select element
33
+ # @param options [Hash] Options passed to the select helper, plus:
34
+ # - :selected [String] Preselect a preset ("30_days"); no prompt then.
35
+ # - :prompt [String, false] The placeholder (default "Select an expiration").
36
+ # - :custom [Boolean] Offer "Custom" too (default false). Render
37
+ # `api_key_expiration_date_field` with it, and show that field when
38
+ # Custom is chosen.
39
+ # @param html_options [Hash] HTML attributes for the select element.
40
+ # `required: true` unless you pass `required: false`.
32
41
  # @return [String] HTML select element
33
42
  #
34
43
  # @example Basic usage
35
44
  # <%= form.api_key_expiration_select %>
36
45
  #
37
46
  # @example With Tailwind classes
38
- # <%= form.api_key_expiration_select(class: "w-full px-4 py-3 border rounded-lg") %>
47
+ # <%= form.api_key_expiration_select({}, class: "w-full px-4 py-3 border rounded-lg") %>
39
48
  #
40
- # @example With custom default
41
- # <%= form.api_key_expiration_select(selected: "30_days") %>
49
+ # @example With a custom date
50
+ # <%= form.api_key_expiration_select(custom: true) %>
51
+ # <%= form.api_key_expiration_date_field %>
42
52
  #
43
53
  def api_key_expiration_select(options = {}, html_options = {})
44
- # expires_at_preset is a form-only param, not a model attribute
45
- # So we only use the provided :selected option or default
46
- selected = options.delete(:selected) || ApiKeys::ExpirationOptions.default_value
54
+ # expires_at_preset is a form-only param, not a model attribute, so the
55
+ # selection comes from :selected, never from the object.
56
+ options = options.dup
57
+ custom = options.delete(:custom) || false
58
+ selected = options.delete(:selected)
59
+ prompt = options.key?(:prompt) ? options.delete(:prompt) : "Select an expiration"
60
+ options[:prompt] = prompt if prompt && selected.nil?
47
61
 
48
62
  select(
49
63
  :expires_at_preset,
50
- @template.options_for_select(ApiKeys::ExpirationOptions.for_select, selected),
64
+ @template.options_for_select(ApiKeys::ExpirationOptions.choices(include_custom: custom, preview: true), selected),
51
65
  options,
52
- html_options
66
+ { required: true }.merge(html_options)
53
67
  )
54
68
  end
55
69
 
70
+ # Renders the date field for the picker's "Custom" choice
71
+ # (`api_key[expires_on]`), from tomorrow up to ten years out. The key
72
+ # expires at the end of the chosen day.
73
+ #
74
+ # @param html_options [Hash] HTML attributes for the input.
75
+ # @return [String] HTML date input
76
+ #
77
+ # @example
78
+ # <%= form.api_key_expiration_date_field(class: "form-input") %>
79
+ #
80
+ def api_key_expiration_date_field(html_options = {})
81
+ date_field(:expires_on, ApiKeys::ExpirationOptions.custom_date_range.merge(html_options))
82
+ end
83
+
56
84
  # Renders checkboxes for API key scopes.
57
85
  #
58
86
  # If a block is given, yields each scope and its checked state for custom rendering.
@@ -2,136 +2,278 @@
2
2
 
3
3
  module ApiKeys
4
4
  module Helpers
5
- # Helper for handling API key expiration presets.
5
+ # The expiration picker: what a new key's form offers, and how each choice
6
+ # becomes an `expires_at`.
6
7
  #
7
- # Provides a consistent set of expiration options for use in forms,
8
- # and parsing logic to convert preset strings to actual dates.
8
+ # The choices come from `config.expiration_options`, which defaults to the
9
+ # picker OpenAI and most API dashboards use:
9
10
  #
10
- # @example In your view (form select)
11
- # <%= form.select :expires_at_preset,
12
- # ApiKeys::Helpers::ExpirationOptions.for_select %>
11
+ # 1 day · 7 days · 30 days · 1 year · Never · Custom
12
+ #
13
+ # A choice travels through the form as a preset string: "1_day",
14
+ # "30_days", "1_year", "12_hours", "no_expiration" (or "never"), and
15
+ # "custom", which takes the date the key expires.
16
+ #
17
+ # @example In your view
18
+ # <%= form.select :expires_at_preset, ApiKeys::ExpirationOptions.for_select %>
13
19
  #
14
20
  # @example In your controller
15
- # expires_at = ApiKeys::Helpers::ExpirationOptions.parse(params[:expires_at_preset])
16
- # @api_key = current_org.create_api_key!(expires_at: expires_at, ...)
21
+ # expires_at = ApiKeys::ExpirationOptions.parse(params[:expires_at_preset])
22
+ # ApiKeys::ExpirationOptions.parse("custom", on: "2027-01-31") # => end of that day
17
23
  #
18
24
  class ExpirationOptions
19
- # Default preset options with human-readable labels
20
- DEFAULT_PRESETS = [
21
- { label: "No Expiration", value: "no_expiration", days: nil },
22
- { label: "7 days", value: "7_days", days: 7 },
23
- { label: "30 days", value: "30_days", days: 30 },
24
- { label: "60 days", value: "60_days", days: 60 },
25
- { label: "90 days", value: "90_days", days: 90 },
26
- { label: "1 year", value: "365_days", days: 365 }
27
- ].map(&:freeze).freeze
25
+ # A for_select preset given in whole days, as before 0.10.
26
+ LegacyDays = Struct.new(:days)
27
+ private_constant :LegacyDays
28
+
29
+ # The longest a key can be set to live, in days (about ten years).
30
+ MAX_DAYS = 3650
31
+ # The symbols config.expiration_options takes beside durations.
32
+ CHOICES = %i[never custom].freeze
33
+ NEVER = "no_expiration"
34
+ CUSTOM = "custom"
35
+ # The units a preset can name, smallest first.
36
+ UNITS = %w[hour day week month year].freeze
37
+ PRESET_FORMAT = /\A(\d{1,6})_(#{UNITS.join('|')})s?\z/
38
+ DATE_FORMAT = /\A\d{4}-\d{2}-\d{2}\z/
39
+ DATE_LABEL = "%B %-d, %Y"
40
+ # What for_select offered before 0.10, in whole days.
41
+ LEGACY_PRESETS = [7, 30, 60, 90, 365].freeze
28
42
 
29
43
  class << self
30
- # Returns options suitable for a Rails select helper.
44
+ # The picker's options, in the order `config.expiration_options`
45
+ # lists them, as [label, value] pairs for a Rails select helper. Ask
46
+ # for a choice with a prompt (see `form.api_key_expiration_select`),
47
+ # since a browser preselects the first option.
31
48
  #
32
- # @param include_no_expiration [Boolean] Whether to include "No Expiration" option (default: true)
33
- # @param presets [Array<Integer>, nil] Custom list of days to include (e.g., [7, 30, 90])
34
- # If nil, uses DEFAULT_PRESETS
35
- # @return [Array<Array>] Array of [label, value] pairs for select helper
49
+ # @param include_no_expiration [Boolean] Offer the never option
50
+ # (default: true). While `config.expire_after` is set it names that
51
+ # lifetime ("90 days (default)") instead of promising "Never": its
52
+ # value, "no_expiration", has always meant "no expiration of my own".
53
+ # @param include_custom [Boolean] Offer "Custom" (default: false). Only
54
+ # a form that also renders the date field (`expires_on`) can use it.
55
+ # @param preview [Boolean] Add each choice's expiration date as a
56
+ # `data-api-keys-expires-on` attribute, so the form can show it.
57
+ # @return [Array<Array>]
36
58
  #
37
- # @example Default options
38
- # ExpirationOptions.for_select
39
- # # => [["No Expiration", "no_expiration"], ["7 days", "7_days"], ...]
59
+ # @example
60
+ # ExpirationOptions.choices
61
+ # # => [["1 day", "1_day"], ["7 days", "7_days"], ["30 days", "30_days"],
62
+ # # ["1 year", "1_year"], ["Never", "no_expiration"]]
63
+ #
64
+ def choices(include_no_expiration: true, include_custom: false, preview: false)
65
+ build_options(ApiKeys.configuration.expiration_options, include_no_expiration, include_custom, preview)
66
+ end
67
+
68
+ # The options forms were built on before 0.10, unchanged: No
69
+ # Expiration first, then 7, 30, 60 and 90 days and 1 year. It does not
70
+ # follow `config.expiration_options` (see .choices), so a form that
71
+ # preselects "365_days" or "90_days", or relies on the first option,
72
+ # keeps working exactly as it did.
40
73
  #
41
- # @example Custom presets
42
- # ExpirationOptions.for_select(presets: [7, 30, 365])
43
- # # => [["No Expiration", "no_expiration"], ["7 days", "7_days"], ["30 days", "30_days"], ["1 year", "365_days"]]
74
+ # @param include_no_expiration [Boolean] Offer "No Expiration" (default: true).
75
+ # @param presets [Array<Integer, ActiveSupport::Duration>, nil] Offer
76
+ # these instead: whole days ("30_days") or durations ("1_year").
77
+ # @param include_custom [Boolean] Add "Custom" at the end (default: false).
78
+ # @param preview [Boolean] Add each choice's date (see .choices).
79
+ # @return [Array<Array>]
44
80
  #
45
- # @example Without "No Expiration"
46
- # ExpirationOptions.for_select(include_no_expiration: false)
47
- # # => [["7 days", "7_days"], ["30 days", "30_days"], ...]
81
+ # @example
82
+ # ExpirationOptions.for_select
83
+ # # => [["No Expiration", "no_expiration"], ["7 days", "7_days"], ["30 days", "30_days"],
84
+ # # ["60 days", "60_days"], ["90 days", "90_days"], ["1 year", "365_days"]]
48
85
  #
49
- def for_select(include_no_expiration: true, presets: nil)
50
- options = if presets
51
- build_custom_presets(presets, include_no_expiration)
52
- else
53
- filter_default_presets(include_no_expiration)
54
- end
55
-
56
- options.map { |opt| [opt[:label], opt[:value]] }
86
+ def for_select(include_no_expiration: true, presets: nil, include_custom: false, preview: false)
87
+ configured = choices_from_presets(presets || LEGACY_PRESETS)
88
+ configured += [:custom] if include_custom
89
+ build_options(configured, include_no_expiration, include_custom, preview, never_label: "No Expiration")
57
90
  end
58
91
 
59
- # Parse an expiration preset string into an actual datetime.
92
+ # Turns a preset into the moment the key expires.
60
93
  #
61
- # @param preset [String, nil] The preset value (e.g., "30_days", "no_expiration")
62
- # @return [ActiveSupport::TimeWithZone, nil] The expiration date, or nil for no expiration
94
+ # @param preset [String, nil] "30_days", "1_year", "no_expiration", "custom"...
95
+ # @param on [String, Date, nil] With "custom": the day the key expires
96
+ # ("2027-01-31"). The key expires at 23:59:59 that day, in the
97
+ # app's time zone.
98
+ # @return [ActiveSupport::TimeWithZone, nil] nil means the key never expires.
99
+ # @raise [ArgumentError] for anything else, so a typo never makes a
100
+ # key permanent. A missing or out-of-range custom date raises
101
+ # ApiKeys::Errors::InvalidExpirationError (an ArgumentError) with a
102
+ # message a person can act on.
63
103
  #
64
104
  # @example
65
- # ExpirationOptions.parse("30_days") # => 30.days.from_now
66
- # ExpirationOptions.parse("no_expiration") # => nil
67
- # ExpirationOptions.parse(nil) # => nil
68
- # ExpirationOptions.parse("invalid") # => raises ArgumentError
105
+ # ExpirationOptions.parse("30_days") # => 30.days.from_now
106
+ # ExpirationOptions.parse("never") # => nil
107
+ # ExpirationOptions.parse("custom", on: "2027-01-31") # => 2027-01-31 23:59:59
69
108
  #
70
- def parse(preset)
109
+ def parse(preset, on: nil)
71
110
  return nil if preset.nil? || preset == ""
72
111
  unless preset.is_a?(String) && preset.valid_encoding? && preset.bytesize <= 32
73
112
  raise ArgumentError, "Invalid API key expiration preset"
74
113
  end
75
- return nil if preset.blank? || preset == "no_expiration"
114
+ return nil if preset == NEVER || preset == "never"
115
+ return custom_date(on) if preset == CUSTOM
76
116
 
77
- # Try to extract days from the preset string (e.g., "30_days" => 30)
78
- if preset =~ /\A(\d+)_days?\z/
79
- days = ::Regexp.last_match(1).to_i
80
- # Reasonable max: ~10 years to prevent overflow issues
81
- return days.days.from_now if days.positive? && days <= 3650
82
- end
117
+ duration = duration_for(preset)
118
+ raise ArgumentError, "Invalid API key expiration preset" unless duration
119
+
120
+ duration.from_now
121
+ end
122
+
123
+ # Whether the form offers this preset ("never" counts as "no_expiration").
124
+ #
125
+ # @param preset [String]
126
+ # @param include_custom [Boolean] Whether the form offers "Custom".
127
+ # @return [Boolean]
128
+ def offered?(preset, include_custom: false)
129
+ return false unless preset.is_a?(String)
130
+
131
+ preset = NEVER if preset == "never"
132
+ choices(include_custom: include_custom).any? { |_label, value| value == preset }
133
+ end
134
+
135
+ # Whether `config.expiration_options` offers a custom date.
136
+ def custom_offered?
137
+ ApiKeys.configuration.expiration_options.include?(:custom)
138
+ end
139
+
140
+ # Whether `config.expiration_options` offers the never option (named
141
+ # after `config.expire_after` while that is set).
142
+ def never_offered?
143
+ ApiKeys.configuration.expiration_options.include?(:never)
144
+ end
145
+
146
+ # The earliest and latest day a custom date can be, as the date
147
+ # field's min and max.
148
+ #
149
+ # @return [Hash] { min: "2026-11-14", max: "2036-11-10" }
150
+ def custom_date_range
151
+ { min: (Date.current + 1).iso8601, max: (Date.current + MAX_DAYS).iso8601 }
152
+ end
153
+
154
+ # The preset string for a duration, or nil when the picker cannot
155
+ # offer it (not a whole number of one unit, not positive, or longer
156
+ # than ten years).
157
+ #
158
+ # @param duration [ActiveSupport::Duration]
159
+ # @return [String, nil] "1_day", "2_weeks", "1_year"...
160
+ def preset_for(duration)
161
+ return nil unless duration.is_a?(ActiveSupport::Duration) && duration.parts.size == 1
83
162
 
84
- # Check against known presets
85
- known = DEFAULT_PRESETS.find { |p| p[:value] == preset }
86
- return known[:days].days.from_now if known && known[:days]
163
+ unit, amount = duration.parts.first
164
+ unit = unit.to_s.delete_suffix("s")
165
+ return nil unless UNITS.include?(unit) && amount.is_a?(Integer)
87
166
 
88
- raise ArgumentError, "Invalid API key expiration preset"
167
+ preset = "#{amount}_#{unit.pluralize(amount)}"
168
+ preset if duration_for(preset)
89
169
  end
90
170
 
91
- # Returns the default preset value (useful for form defaults)
171
+ # The default selection of forms written before 0.10.
92
172
  #
93
- # @return [String] The default preset value
173
+ # @return [String] "no_expiration"
94
174
  def default_value
95
- "no_expiration"
175
+ NEVER
96
176
  end
97
177
 
98
178
  private
99
179
 
100
- def filter_default_presets(include_no_expiration)
101
- if include_no_expiration
102
- DEFAULT_PRESETS
103
- else
104
- DEFAULT_PRESETS.reject { |p| p[:value] == "no_expiration" }
180
+ def build_options(configured, include_no_expiration, include_custom, preview, never_label: nil)
181
+ configured = configured.reject { |choice| choice == :never } unless include_no_expiration
182
+ configured = configured.reject { |choice| choice == :custom } unless include_custom
183
+
184
+ configured.map do |choice|
185
+ option = [choice == :never && never_label ? never_label : label_for(choice), value_for(choice)]
186
+ expires_at = preview_time(choice)
187
+ option << { "data-api-keys-expires-on" => expires_at.strftime(DATE_LABEL) } if preview && expires_at
188
+ option
105
189
  end
106
190
  end
107
191
 
108
- def build_custom_presets(days_list, include_no_expiration)
109
- unless days_list.is_a?(Array) && days_list.all? { |days| days.is_a?(Integer) && days.between?(1, 3650) }
110
- raise ArgumentError, "Expiration presets must be an array of integers between 1 and 3650"
111
- end
192
+ # When a choice expires a key made now, or nil (Never, Custom).
193
+ def preview_time(choice)
194
+ return choice.days.days.from_now if choice.is_a?(LegacyDays)
195
+ return choice.from_now if choice.is_a?(ActiveSupport::Duration)
112
196
 
113
- options = []
197
+ ApiKeys.configuration.expire_after&.from_now if choice == :never
198
+ end
199
+
200
+ def duration_for(preset)
201
+ match = PRESET_FORMAT.match(preset)
202
+ return nil unless match
203
+
204
+ amount = match[1].to_i
205
+ duration = amount.public_send(match[2].pluralize)
206
+ duration if amount.positive? && duration.to_i <= MAX_DAYS.days.to_i
207
+ end
114
208
 
115
- if include_no_expiration
116
- options << { label: "No Expiration", value: "no_expiration", days: nil }
209
+ def custom_date(on)
210
+ date = case on
211
+ when Date then on
212
+ when String then parse_date(on.strip)
213
+ end
214
+ raise ApiKeys::Errors::InvalidExpirationError, "Pick the date the key expires." unless date
215
+ if date > Date.current + MAX_DAYS
216
+ raise ApiKeys::Errors::InvalidExpirationError, "A key can expire at most 10 years from now."
117
217
  end
118
218
 
119
- days_list.each do |days|
120
- options << preset_for_days(days)
219
+ # 23:59:59 sharp: a fractional end_of_day would round up to the next
220
+ # midnight in a datetime column without sub-second precision (MySQL).
221
+ (Time.zone || Time.find_zone!("UTC")).local(date.year, date.month, date.day, 23, 59, 59)
222
+ end
223
+
224
+ def parse_date(text)
225
+ Date.iso8601(text) if text.valid_encoding? && text.match?(DATE_FORMAT)
226
+ rescue Date::Error
227
+ nil
228
+ end
229
+
230
+ def label_for(choice)
231
+ case choice
232
+ when :never then never_label
233
+ when :custom then "Custom"
234
+ when LegacyDays then legacy_days_label(choice.days)
235
+ else
236
+ unit, amount = choice.parts.first
237
+ unit = unit.to_s.delete_suffix("s")
238
+ "#{amount} #{unit.pluralize(amount)}"
121
239
  end
240
+ end
241
+
242
+ # config.expire_after gives a key without an expiration of its own
243
+ # that lifetime, so the never option names it.
244
+ def never_label
245
+ expire_after = ApiKeys.configuration.expire_after
246
+ return "Never" if expire_after.nil?
247
+
248
+ lifetime = expire_after.is_a?(ActiveSupport::Duration) ? expire_after : expire_after.seconds
249
+ "#{lifetime.inspect} (default)"
250
+ end
251
+
252
+ def legacy_days_label(days)
253
+ return "#{days / 365} #{'year'.pluralize(days / 365)}" if (days % 365).zero?
254
+
255
+ "#{days} #{'day'.pluralize(days)}"
256
+ end
122
257
 
123
- options
258
+ def value_for(choice)
259
+ case choice
260
+ when :never then NEVER
261
+ when :custom then CUSTOM
262
+ when LegacyDays then "#{choice.days}_days"
263
+ else preset_for(choice)
264
+ end
124
265
  end
125
266
 
126
- def preset_for_days(days)
127
- label = case days
128
- when 1 then "1 day"
129
- when 365 then "1 year"
130
- when ->(d) { d % 365 == 0 } then "#{days / 365} years"
131
- else "#{days} days"
132
- end
267
+ # Whole days (as before 0.10) or durations, with "Never" first.
268
+ def choices_from_presets(presets)
269
+ # A Duration answers is_a?(Integer) with true, so ask about it first.
270
+ # Whole days stay LegacyDays, so they keep 0.9's "N_days" values.
271
+ durations = presets.map { |days| days.is_a?(ActiveSupport::Duration) || !days.is_a?(Integer) ? days : LegacyDays.new(days) } if presets.is_a?(Array)
272
+ unless durations&.all? { |duration| duration.is_a?(LegacyDays) ? duration_for("#{duration.days}_days") : preset_for(duration) }
273
+ raise ArgumentError, "Expiration presets must be whole days or durations, from 1 day up to ten years"
274
+ end
133
275
 
134
- { label: label, value: "#{days}_days", days: days }
276
+ [:never, *durations]
135
277
  end
136
278
  end
137
279
  end
@@ -53,6 +53,21 @@ module ApiKeys
53
53
  REFUSAL_REASONS.fetch(api_key.last_refusal_code.to_s, UNKNOWN_REFUSAL_REASON)
54
54
  end
55
55
 
56
+ # Says when a key expires, in plain English.
57
+ #
58
+ # @param api_key [ApiKeys::ApiKey] The API key
59
+ # @return [String] "Expires on December 13, 2026", "Expired on
60
+ # November 1, 2026", or "Never expires"
61
+ #
62
+ # @example
63
+ # api_key_expiration_label(@key) # => "Expires on December 13, 2026"
64
+ #
65
+ def api_key_expiration_label(api_key)
66
+ return "Never expires" if api_key.expires_at.nil?
67
+
68
+ "#{api_key.expired? ? 'Expired' : 'Expires'} on #{api_key.expires_at.strftime(ApiKeys::Helpers::ExpirationOptions::DATE_LABEL)}"
69
+ end
70
+
56
71
  # Returns the status of an API key as a symbol.
57
72
  #
58
73
  # @param api_key [ApiKeys::ApiKey] The API key
@@ -70,7 +70,9 @@ module ApiKeys
70
70
  # validations) and no update_column can name another one. A backfill of
71
71
  # keys made before the columns existed writes them with SQL (update_all).
72
72
  attr_readonly :created_by_type, :created_by_id
73
- attr_accessor :expires_at_preset
73
+ # Form-only: what the expiration picker submitted, kept so a form that
74
+ # failed to save shows the same choice again.
75
+ attr_accessor :expires_at_preset, :expires_on
74
76
 
75
77
  # JSON attributes (:scopes, :metadata) are defined in the engine initializer
76
78
  # using ActiveSupport.on_load(:active_record) to ensure DB connection is ready.
@@ -212,8 +212,16 @@ module ApiKeys
212
212
  # When key_type is specified, scopes are filtered to only include those allowed
213
213
  # by the key type's permissions ceiling. Blank values are automatically removed.
214
214
  # @param expires_at [Time, nil] Optional expiration timestamp.
215
- # @param expires_at_preset [String, nil] Convenience param: "7_days", "30_days", "no_expiration", etc.
216
- # If provided, this is parsed into expires_at. Takes precedence over expires_at if both given.
215
+ # @param expires_in [ActiveSupport::Duration, nil] How long the key lives:
216
+ # `expires_in: 30.days`. Whole hours, days, weeks, months or years, up
217
+ # to ten years. Pass it or expires_at, not both.
218
+ # @param expires_at_preset [String, nil] What the expiration picker
219
+ # submitted: "1_day", "30_days", "1_year", "never", "custom"... (see
220
+ # ApiKeys::ExpirationOptions). Takes precedence over expires_at if both given.
221
+ # @param expires_on [String, Date, nil] The day the key expires, at
222
+ # 23:59:59 ("2027-01-31"): the picker's "Custom" date. Used alone or
223
+ # with expires_at_preset: "custom"; beside another preset it is
224
+ # ignored, as a form submits the field whatever was chosen.
217
225
  # @param metadata [Hash, nil] Optional metadata hash.
218
226
  # @param key_type [Symbol, nil] The key type (e.g., :publishable, :secret).
219
227
  # Must be defined in ApiKeys.configuration.key_types if provided.
@@ -230,19 +238,16 @@ module ApiKeys
230
238
  # @return [ApiKeys::ApiKey] The newly created ApiKey instance. The plaintext token
231
239
  # is available via the `#token` attribute on this instance
232
240
  # *only until it's reloaded*.
233
- def create_api_key!(name: nil, scopes: nil, expires_at: nil, expires_at_preset: nil, metadata: nil,
234
- key_type: nil, environment: nil, restrictions: nil, allowed_origins: nil, allowed_ips: nil,
235
- created_by: nil)
241
+ def create_api_key!(name: nil, scopes: nil, expires_at: nil, expires_in: nil, expires_at_preset: nil,
242
+ expires_on: nil, metadata: nil, key_type: nil, environment: nil, restrictions: nil,
243
+ allowed_origins: nil, allowed_ips: nil, created_by: nil)
236
244
  config = ApiKeys.configuration
237
245
 
238
246
  if created_by && !ApiKeys::ApiKey.created_by_columns?
239
247
  raise ApiKeys::Errors::CreatedByMigrationRequiredError
240
248
  end
241
249
 
242
- # Parse expires_at_preset if provided (takes precedence over expires_at)
243
- if expires_at_preset.present?
244
- expires_at = ApiKeys::Helpers::ExpirationOptions.parse(expires_at_preset)
245
- end
250
+ expires_at = resolve_expiration(expires_at, expires_in, expires_at_preset, expires_on)
246
251
 
247
252
  # Auto-clean scopes: remove blank values from arrays (common when using form checkboxes)
248
253
  if scopes.is_a?(Array)
@@ -334,6 +339,34 @@ module ApiKeys
334
339
  config.key_types.present? && config.key_types.any?
335
340
  end
336
341
 
342
+ # The one expiration the caller asked for. expires_at_preset wins over
343
+ # expires_at, as it always has. expires_on: is the picker's Custom
344
+ # date: a form submits it ("" or a date) whatever was chosen, so it
345
+ # counts only with the "custom" preset or alone, and a blank one is
346
+ # no date at all. expires_in: combines with nothing, and expires_on:
347
+ # alone combines with nothing, so a key never quietly gets an
348
+ # expiration its caller did not mean.
349
+ def resolve_expiration(expires_at, expires_in, preset, expires_on)
350
+ custom = ApiKeys::Helpers::ExpirationOptions::CUSTOM
351
+ preset = preset.presence
352
+ expires_on = nil if expires_on.respond_to?(:empty?) && expires_on.to_s.strip.empty?
353
+ expires_on = nil unless preset.nil? || preset == custom
354
+ preset ||= custom unless expires_on.nil?
355
+
356
+ conflicting = (!expires_in.nil? && !(preset.nil? && expires_at.nil?)) ||
357
+ (!expires_on.nil? && !expires_at.nil?)
358
+ raise ArgumentError, "Pass one expiration: expires_at, expires_in, expires_at_preset, or expires_on" if conflicting
359
+
360
+ return ApiKeys::Helpers::ExpirationOptions.parse(preset, on: expires_on) if preset
361
+ return expires_at if expires_in.nil?
362
+
363
+ unless ApiKeys::Helpers::ExpirationOptions.preset_for(expires_in)
364
+ raise ArgumentError, "expires_in must be whole hours, days, weeks, months or years, up to ten years (e.g. 30.days)"
365
+ end
366
+
367
+ expires_in.from_now
368
+ end
369
+
337
370
  def validate_key_type!(key_type, config)
338
371
  return unless key_types_feature_enabled?(config)
339
372
 
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ApiKeys
4
- VERSION = "0.9.0"
4
+ VERSION = "0.10.0"
5
5
  end
@@ -248,6 +248,14 @@ ApiKeys.configure do |config|
248
248
  # Default: nil
249
249
  # config.expire_after = 90.days
250
250
 
251
+ # What the expiration picker offers when someone creates a key, in order:
252
+ # durations (whole hours, days, weeks, months or years, up to ten years),
253
+ # :never, and :custom (a date picker). Leave out :never to make every key
254
+ # created from the dashboard expire. While expire_after is set, :never shows
255
+ # that lifetime instead ("90 days (default)").
256
+ # Default: [1.day, 7.days, 30.days, 1.year, :never, :custom]
257
+ # config.expiration_options = [1.day, 7.days, 30.days, 90.days, :custom]
258
+
251
259
  # Default scopes to assign to newly created keys if none are specified.
252
260
  # Can be overridden per-model with `default_scopes` in the `has_api_keys` block.
253
261
  # Default: []
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: api_keys
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.9.0
4
+ version: 0.10.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - rameerez
8
8
  bindir: exe
9
9
  cert_chain: []
10
- date: 2026-11-09 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: rails
@@ -71,6 +71,9 @@ files:
71
71
  - README.md
72
72
  - SECURITY.md
73
73
  - api_keys_dashboard.webp
74
+ - api_keys_expiration.webp
75
+ - api_keys_expiration_custom.webp
76
+ - api_keys_expiration_list.webp
74
77
  - api_keys_permissions.webp
75
78
  - api_keys_token.webp
76
79
  - app/controllers/api_keys/application_controller.rb
@@ -167,7 +170,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
167
170
  - !ruby/object:Gem::Version
168
171
  version: '0'
169
172
  requirements: []
170
- rubygems_version: 3.6.2
173
+ rubygems_version: 3.6.9
171
174
  specification_version: 4
172
175
  summary: Gate your Rails API with secure, self-serve API keys in minutes
173
176
  test_files: []