api_keys 0.8.1 → 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 +4 -4
- data/CHANGELOG.md +34 -0
- data/README.md +92 -22
- data/api_keys_expiration.webp +0 -0
- data/api_keys_expiration_custom.webp +0 -0
- data/api_keys_expiration_list.webp +0 -0
- data/app/controllers/api_keys/application_controller.rb +21 -1
- data/app/controllers/api_keys/keys_controller.rb +36 -15
- data/app/views/api_keys/keys/_form.html.erb +70 -16
- data/app/views/api_keys/keys/_key_row.html.erb +7 -5
- data/app/views/api_keys/keys/_show_token.html.erb +8 -0
- data/app/views/layouts/api_keys/application.html.erb +16 -2
- data/lib/api_keys/configuration.rb +50 -0
- data/lib/api_keys/errors.rb +6 -0
- data/lib/api_keys/form_builder_extensions.rb +41 -13
- data/lib/api_keys/helpers/expiration_options.rb +226 -84
- data/lib/api_keys/helpers/view_helpers.rb +15 -0
- data/lib/api_keys/models/api_key.rb +3 -1
- data/lib/api_keys/models/concerns/has_api_keys.rb +42 -9
- data/lib/api_keys/version.rb +1 -1
- data/lib/generators/api_keys/templates/initializer.rb +17 -0
- metadata +4 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 3a0f38e1872bcafaaab8195c090e3f0f6fe2de26c99ded081fa6efebf9ce350b
|
|
4
|
+
data.tar.gz: 8c66c076ecd44f4daf4419a4fb3f8504e49a7da31990276e88ee4b860d7e7a22
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 9e92633218bdd91c2beed9e4db6e76ef5963530533f97bbcf10e3308da598426d4000c4f4a0c9bc934ec481d01d60e0ab0ba27998301ff79c50aaec6e6b5cc67
|
|
7
|
+
data.tar.gz: 394dca13057ef620fe3479af766c7ba69e3fa16bfa2529d202ccbd05dc1992acd9399d90d100e25d412fd9d5cc49027b6af88e561870dbc7c303fcf847f652fb
|
data/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
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
|
+
|
|
29
|
+
## [0.9.0] - 2026-11-09
|
|
30
|
+
|
|
31
|
+
### Added
|
|
32
|
+
|
|
33
|
+
- `config.current_creator_method`. The dashboard records the signed-in person it names (e.g. `:current_user`) as each new key's `created_by`. Before, the dashboard never set `created_by`, so in an app where organizations own keys, nobody could tell who minted a key, and a `config.trusted_key_check` that reads `created_by` refused every dashboard-created key. Default nil records nobody, as before. Set but missing on the host controller, key creation fails instead of minting an unattributed key. Needs the created_by columns (0.7.0).
|
|
34
|
+
|
|
1
35
|
## [0.8.1] - 2026-10-26
|
|
2
36
|
|
|
3
37
|
Two fixes found when an app on the fleet upgraded from 0.5 to 0.8.0. The second one now covers every upgrade generator.
|
data/README.md
CHANGED
|
@@ -151,9 +151,14 @@ ApiKeys.configure do |config|
|
|
|
151
151
|
|
|
152
152
|
# Tell the dashboard how to ensure the owner is authenticated
|
|
153
153
|
config.authenticate_owner_method = :authenticate_organization!
|
|
154
|
+
|
|
155
|
+
# Record who minted each key (needs the created_by columns, 0.7.0+)
|
|
156
|
+
config.current_creator_method = :current_user
|
|
154
157
|
end
|
|
155
158
|
```
|
|
156
159
|
|
|
160
|
+
With `current_creator_method` set, every key the dashboard creates stores the signed-in person as `created_by`, so an organization can see who made each key, and `config.trusted_key_check` can judge dashboard-created keys. Left unset, the dashboard records nobody, as before 0.9.0.
|
|
161
|
+
|
|
157
162
|
These methods must exist in your `ApplicationController` (or wherever the engine is mounted). For example:
|
|
158
163
|
|
|
159
164
|
```ruby
|
|
@@ -186,6 +191,7 @@ The setting accepts a controller class or a valid constant-name string and defau
|
|
|
186
191
|
# When organizations own keys but users manage them
|
|
187
192
|
config.current_owner_method = :current_organization
|
|
188
193
|
config.authenticate_owner_method = :require_organization_member!
|
|
194
|
+
config.current_creator_method = :current_user
|
|
189
195
|
```
|
|
190
196
|
|
|
191
197
|
**Multi-tenant applications:**
|
|
@@ -206,7 +212,7 @@ config.authenticate_owner_method = :ensure_team_access!
|
|
|
206
212
|
|
|
207
213
|
Once configured, your users can:
|
|
208
214
|
- self-issue new API keys
|
|
209
|
-
-
|
|
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)
|
|
210
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)
|
|
211
217
|
- add and edit the key names
|
|
212
218
|
- lock a key to specific web origins or IP addresses
|
|
@@ -330,7 +336,8 @@ module Settings
|
|
|
330
336
|
name: api_key_params[:name],
|
|
331
337
|
key_type: :secret,
|
|
332
338
|
scopes: api_key_params[:scopes],
|
|
333
|
-
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
|
|
334
341
|
)
|
|
335
342
|
|
|
336
343
|
ApiKeys::TokenSession.store(session, @api_key)
|
|
@@ -442,8 +449,10 @@ current_org.can_create_api_key?(key_type: :publishable)
|
|
|
442
449
|
name: "My Key",
|
|
443
450
|
key_type: :secret, # or :publishable
|
|
444
451
|
scopes: ["read", "write"], # Blank values auto-removed; [] means none, omit for defaults
|
|
445
|
-
|
|
446
|
-
|
|
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
|
|
447
456
|
environment: :live, # Defaults to current_environment
|
|
448
457
|
metadata: { team: "backend" }, # Optional JSON metadata
|
|
449
458
|
allowed_origins: "example.com", # Optional: lock to web origins
|
|
@@ -571,28 +580,38 @@ None of this protects a session that has been stolen. Whoever holds a copy of th
|
|
|
571
580
|
|
|
572
581
|
### Expiration Options Helper
|
|
573
582
|
|
|
574
|
-
|
|
583
|
+
The choices of the expiration picker (`config.expiration_options`), and how each one becomes an `expires_at`:
|
|
575
584
|
|
|
576
585
|
```ruby
|
|
577
|
-
#
|
|
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)
|
|
578
591
|
ApiKeys::ExpirationOptions.for_select
|
|
579
|
-
# => [["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"]]
|
|
580
593
|
|
|
581
|
-
#
|
|
582
|
-
ApiKeys::ExpirationOptions.
|
|
583
|
-
# => "no_expiration"
|
|
594
|
+
# With "Custom", for a form that also renders the date field
|
|
595
|
+
ApiKeys::ExpirationOptions.choices(include_custom: true)
|
|
584
596
|
|
|
585
|
-
#
|
|
586
|
-
ApiKeys::ExpirationOptions.
|
|
587
|
-
# => 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)
|
|
588
599
|
|
|
589
|
-
|
|
590
|
-
# =>
|
|
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
|
|
591
605
|
|
|
592
|
-
# Exclude "
|
|
606
|
+
# Exclude "Never"
|
|
593
607
|
ApiKeys::ExpirationOptions.for_select(include_no_expiration: false)
|
|
608
|
+
|
|
609
|
+
# Did the form offer this preset?
|
|
610
|
+
ApiKeys::ExpirationOptions.offered?("60_days") # => false
|
|
594
611
|
```
|
|
595
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
|
+
|
|
596
615
|
---
|
|
597
616
|
|
|
598
617
|
### Form Builder Extensions (Opt-in)
|
|
@@ -607,19 +626,25 @@ end
|
|
|
607
626
|
|
|
608
627
|
#### `api_key_expiration_select`
|
|
609
628
|
|
|
610
|
-
Renders
|
|
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:
|
|
611
630
|
|
|
612
631
|
```erb
|
|
613
632
|
<%# Basic usage %>
|
|
614
633
|
<%= form.api_key_expiration_select %>
|
|
615
634
|
|
|
616
635
|
<%# With CSS classes (Tailwind example) %>
|
|
617
|
-
<%= 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") %>
|
|
618
637
|
|
|
619
|
-
<%#
|
|
638
|
+
<%# Preselect a choice instead of asking %>
|
|
620
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") %>
|
|
621
644
|
```
|
|
622
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
|
+
|
|
623
648
|
#### `api_key_scopes_checkboxes`
|
|
624
649
|
|
|
625
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).
|
|
@@ -773,7 +798,8 @@ end
|
|
|
773
798
|
<%= form.text_field :name, placeholder: "e.g., Production Server" %>
|
|
774
799
|
|
|
775
800
|
<%# Expiration (new keys only) %>
|
|
776
|
-
<%= 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 %>
|
|
777
803
|
|
|
778
804
|
<%# Scopes %>
|
|
779
805
|
<%= form.api_key_scopes_checkboxes(@available_scopes) do |scope, checked| %>
|
|
@@ -810,7 +836,7 @@ Based on real production integrations:
|
|
|
810
836
|
|
|
811
837
|
1. **Use RESTful routes** - `resources :api_keys` with member/collection actions, not custom route definitions.
|
|
812
838
|
|
|
813
|
-
2. **Separate form-only params** - Access `expires_at_preset` via `params.dig(:api_key,
|
|
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).
|
|
814
840
|
|
|
815
841
|
3. **Use `before_action` for shared setup** - Extract `@available_scopes` to a before_action rather than setting it in multiple actions.
|
|
816
842
|
|
|
@@ -835,7 +861,7 @@ If you want to write your own front-end instead of using the provided dashboard,
|
|
|
835
861
|
@api_key = @user.create_api_key!(
|
|
836
862
|
name: "my-key",
|
|
837
863
|
scopes: %w[read write],
|
|
838
|
-
|
|
864
|
+
expires_in: 30.days
|
|
839
865
|
)
|
|
840
866
|
|
|
841
867
|
# Get the plaintext token only available upon creation
|
|
@@ -899,6 +925,50 @@ And for any API key, you can always display a safe, user-friendly masked token t
|
|
|
899
925
|
# => "ak_demo_••••yZn9"
|
|
900
926
|
```
|
|
901
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
|
+

|
|
933
|
+
|
|
934
|
+
"Custom" opens a date picker. The key expires at 23:59:59 on that day:
|
|
935
|
+
|
|
936
|
+

|
|
937
|
+
|
|
938
|
+
The keys list shows the date each key expires:
|
|
939
|
+
|
|
940
|
+

|
|
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
|
+
|
|
902
972
|
### Scopes: define and verify API Key permissions
|
|
903
973
|
|
|
904
974
|
Users can limit what each API key does by selecting scopes, and you can define those scopes.
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -118,6 +118,22 @@ module ApiKeys
|
|
|
118
118
|
end
|
|
119
119
|
end
|
|
120
120
|
|
|
121
|
+
# The signed-in person, recorded as a new key's created_by
|
|
122
|
+
# (config.current_creator_method). nil when unconfigured. Configured but
|
|
123
|
+
# missing on the host controller fails loudly: a key minted without its
|
|
124
|
+
# creator could later fail config.trusted_key_check for everyone.
|
|
125
|
+
def current_api_keys_creator
|
|
126
|
+
creator_method = ApiKeys.configuration.current_creator_method
|
|
127
|
+
return nil unless creator_method
|
|
128
|
+
|
|
129
|
+
unless respond_to?(creator_method, true)
|
|
130
|
+
raise NoMethodError, "config.current_creator_method is #{creator_method.inspect}, " \
|
|
131
|
+
"but #{self.class.name} does not respond to it"
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
send(creator_method)
|
|
135
|
+
end
|
|
136
|
+
|
|
121
137
|
# Expose current_api_keys_owner as a helper method for views
|
|
122
138
|
helper_method :current_api_keys_owner
|
|
123
139
|
|
|
@@ -128,7 +144,11 @@ module ApiKeys
|
|
|
128
144
|
def set_api_keys_security_headers
|
|
129
145
|
response.headers["Cache-Control"] = "no-store, private"
|
|
130
146
|
response.headers["Pragma"] = "no-cache"
|
|
131
|
-
|
|
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"
|
|
132
152
|
response.headers["X-Content-Type-Options"] = "nosniff"
|
|
133
153
|
response.headers["X-Frame-Options"] = "DENY"
|
|
134
154
|
response.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()"
|
|
@@ -89,12 +89,12 @@ module ApiKeys
|
|
|
89
89
|
@api_key = current_api_keys_owner.create_api_key!(
|
|
90
90
|
name: submitted_params[:name],
|
|
91
91
|
scopes: scopes,
|
|
92
|
-
|
|
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],
|
|
96
|
-
allowed_ips: submitted_params[:allowed_ips]
|
|
97
|
-
|
|
96
|
+
allowed_ips: submitted_params[:allowed_ips],
|
|
97
|
+
created_by: current_api_keys_creator
|
|
98
98
|
)
|
|
99
99
|
|
|
100
100
|
# Store the plaintext token in session to display on the show page
|
|
@@ -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
|
-
#
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
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
|
-
|
|
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
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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
|
-
<%
|
|
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
|
-
|
|
210
|
-
|
|
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 <%=
|
|
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
|
-
|
|
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
|
|
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:
|
|
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);
|