rails_api_keys 0.1.0 → 0.3.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 +29 -2
- data/README.md +41 -21
- data/app/models/rails_api_keys/api_key.rb +25 -10
- data/db/migrate/20261125120000_add_allowed_ips_to_rails_api_keys_api_keys.rb +7 -0
- data/lib/generators/rails_api_keys/install/templates/create_rails_api_keys_api_keys.rb.tt +1 -0
- data/lib/generators/rails_api_keys/install/templates/initializer.rb.tt +2 -1
- data/lib/rails_api_keys/authentication.rb +29 -12
- data/lib/rails_api_keys/configuration.rb +4 -9
- data/lib/rails_api_keys/engine.rb +6 -0
- data/lib/rails_api_keys/ip_allowlist.rb +70 -0
- data/lib/rails_api_keys/owner.rb +31 -0
- data/lib/rails_api_keys/version.rb +1 -1
- data/lib/rails_api_keys.rb +20 -0
- metadata +8 -5
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: c45e1c9af06f5623758b70a9b538d6b4d4b00bc866306e7c32d00cc80d3f61ec
|
|
4
|
+
data.tar.gz: 83fdf46bdd6c33ccb772c119cea2e2ff2d4a385e4d02a668b41fd5c39878a134
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: afbb1d31a939d90b11b3d8b7ef9c6653d2059a7c73eef84d1541ccbe7271a47209574edcbf0974799926996b4d1dc02b23f121685555b421b675afb5f365d919
|
|
7
|
+
data.tar.gz: d7388c243e87098b920df8fafea2cbad71345f24759b00c302dc0837ebe611b51c063baed435afb615c9504b293645b524195b3c58389122b2afe92c1ddfc414
|
data/CHANGELOG.md
CHANGED
|
@@ -3,10 +3,35 @@
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
-
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0/).
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.3.0] - 2026-11-25
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Optional `allowed_ips` column (`json`, default `[]`) on `rails_api_keys_api_keys` supporting single IPv4/IPv6 addresses and CIDR ranges via `IPAddr`
|
|
15
|
+
- `allowed_ips:` optional keyword argument on `RailsApiKeys::ApiKey.generate_for!` and `owner.create_api_key!`
|
|
16
|
+
- `RailsApiKeys::ApiKey#allows_ip?` and IP allowlist enforcement in `authenticate_api_key!` (renders `403 Forbidden` without updating `last_used_at` when a request comes from a disallowed IP)
|
|
17
|
+
- `touch_last_used:` optional keyword argument on `RailsApiKeys::ApiKey.authenticate`
|
|
18
|
+
|
|
19
|
+
## [0.2.0] - 2026-08-10
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- `has_api_keys` — Active Record macro for owner models (`User`, `Company`, etc.); registers allowed polymorphic owners
|
|
24
|
+
- `create_api_key!` — instance helper on owners that call `has_api_keys` (wraps `ApiKey.generate_for!`)
|
|
25
|
+
|
|
26
|
+
### Changed
|
|
27
|
+
|
|
28
|
+
- `authenticate_api_key!` now enforces permissions from the HTTP method: GET/HEAD require read; other methods require write
|
|
29
|
+
|
|
30
|
+
### Removed
|
|
31
|
+
|
|
32
|
+
- `require_api_permission!` — hosts no longer call this separately
|
|
33
|
+
- `config.owner_class` — replaced by opt-in `has_api_keys` on each owner model
|
|
34
|
+
|
|
10
35
|
## [0.1.0] - 2026-08-10
|
|
11
36
|
|
|
12
37
|
### Added
|
|
@@ -16,5 +41,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
16
41
|
- `RailsApiKeys.configure` — optional `owner_class`, `token_prefix`, and `owner_active`
|
|
17
42
|
- Install generator (`rails_api_keys:install`) for migration and initializer
|
|
18
43
|
|
|
19
|
-
[Unreleased]: https://github.com/rubyroidlabs/rails_api_keys/compare/v0.
|
|
44
|
+
[Unreleased]: https://github.com/rubyroidlabs/rails_api_keys/compare/v0.3.0...HEAD
|
|
45
|
+
[0.3.0]: https://github.com/rubyroidlabs/rails_api_keys/compare/v0.2.0...v0.3.0
|
|
46
|
+
[0.2.0]: https://github.com/rubyroidlabs/rails_api_keys/compare/v0.1.0...v0.2.0
|
|
20
47
|
[0.1.0]: https://github.com/rubyroidlabs/rails_api_keys/releases/tag/v0.1.0
|
data/README.md
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# rails_api_keys
|
|
2
2
|
|
|
3
3
|
[](https://github.com/rubyroidlabs/rails_api_keys/actions/workflows/ci.yml)
|
|
4
|
+
[](https://badge.fury.io/rb/rails_api_keys)
|
|
4
5
|
|
|
5
6
|
Reusable Rails engine for personal API keys: create (reveal once), hash at rest, revoke, and authenticate via `Authorization: Bearer <token>`.
|
|
6
7
|
|
|
@@ -9,6 +10,7 @@ Host apps own UI, routes, and domain APIs. This gem stays thin on purpose.
|
|
|
9
10
|
## What this gem includes
|
|
10
11
|
|
|
11
12
|
- `RailsApiKeys::ApiKey` — issue, authenticate, revoke
|
|
13
|
+
- `has_api_keys` — opt-in owner macro with `create_api_key!` (supports multiple models)
|
|
12
14
|
- `RailsApiKeys::Authentication` — controller concern for Bearer tokens
|
|
13
15
|
- Install generator (migration + initializer)
|
|
14
16
|
|
|
@@ -29,32 +31,42 @@ bin/rails generate rails_api_keys:install
|
|
|
29
31
|
bin/rails db:migrate
|
|
30
32
|
```
|
|
31
33
|
|
|
32
|
-
|
|
34
|
+
## Host setup
|
|
35
|
+
|
|
36
|
+
Opt in on each owner model with `has_api_keys` (any number of models):
|
|
33
37
|
|
|
34
38
|
```ruby
|
|
35
|
-
|
|
36
|
-
|
|
39
|
+
class User < ApplicationRecord
|
|
40
|
+
has_api_keys
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
class Company < ApplicationRecord
|
|
44
|
+
has_api_keys
|
|
45
|
+
end
|
|
37
46
|
```
|
|
38
47
|
|
|
39
|
-
|
|
48
|
+
That declares `has_many :api_keys` and allows the model to own keys. Build your own controllers/UI to create keys (show the raw token once), list them, and revoke — or use the optional companion gem below.
|
|
49
|
+
|
|
50
|
+
## Optional UI
|
|
51
|
+
|
|
52
|
+
For a ready-made HTML/JSON management UI (create, reveal once + copy, list active keys, revoke), install the companion gem [`rails_api_keys-ui`](https://github.com/rubyroidlabs/rails_api_keys-ui):
|
|
40
53
|
|
|
41
|
-
|
|
54
|
+

|
|
42
55
|
|
|
43
56
|
```ruby
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
57
|
+
# Gemfile
|
|
58
|
+
gem "rails_api_keys"
|
|
59
|
+
gem "rails_api_keys-ui"
|
|
47
60
|
```
|
|
48
61
|
|
|
49
|
-
|
|
62
|
+
See that repo for install generators, route helpers, embeddable panel, and configuration.
|
|
50
63
|
|
|
51
64
|
## Configuration
|
|
52
65
|
|
|
53
|
-
Defaults suit a typical Devise `User` host
|
|
66
|
+
Defaults suit a typical Devise `User` host; multiple owners are supported via `has_api_keys`:
|
|
54
67
|
|
|
55
68
|
| Option | Default | Purpose |
|
|
56
69
|
| --- | --- | --- |
|
|
57
|
-
| `owner_class` | `"User"` | Expected owner class name |
|
|
58
70
|
| `token_prefix` | `"#{AppName.downcase}_ak_"` | Prefix on generated raw tokens |
|
|
59
71
|
| `owner_active` | `active_for_authentication?` when present | Reject keys whose owner is inactive |
|
|
60
72
|
|
|
@@ -64,7 +76,6 @@ Override only what you need:
|
|
|
64
76
|
# config/initializers/rails_api_keys.rb
|
|
65
77
|
RailsApiKeys.configure do |config|
|
|
66
78
|
# config.token_prefix = "myapp_ak_"
|
|
67
|
-
# config.owner_class = "Admin"
|
|
68
79
|
# config.owner_active = ->(owner) { owner.active? }
|
|
69
80
|
end
|
|
70
81
|
```
|
|
@@ -72,14 +83,16 @@ end
|
|
|
72
83
|
## Usage
|
|
73
84
|
|
|
74
85
|
```ruby
|
|
75
|
-
key, raw =
|
|
76
|
-
owner: current_user,
|
|
86
|
+
key, raw = current_user.create_api_key!(
|
|
77
87
|
name: "Zapier",
|
|
78
|
-
permission: :read
|
|
88
|
+
permission: :read,
|
|
89
|
+
allowed_ips: [ "203.0.113.10", "10.0.0.0/24" ] # optional; empty allows any IP
|
|
79
90
|
)
|
|
80
91
|
# Show `raw` once — it cannot be recovered later.
|
|
81
92
|
|
|
82
93
|
RailsApiKeys::ApiKey.authenticate(raw) # => key or nil
|
|
94
|
+
key.allows_ip?("203.0.113.10") # => true
|
|
95
|
+
key.update!(allowed_ips: [ "10.0.0.0/24" ])
|
|
83
96
|
key.revoke!
|
|
84
97
|
```
|
|
85
98
|
|
|
@@ -88,7 +101,6 @@ class Api::V1::BaseController < ActionController::API
|
|
|
88
101
|
include RailsApiKeys::Authentication
|
|
89
102
|
|
|
90
103
|
before_action :authenticate_api_key!
|
|
91
|
-
before_action -> { require_api_permission!(:read) }
|
|
92
104
|
|
|
93
105
|
# current_api_key / current_api_owner are available after authenticate
|
|
94
106
|
end
|
|
@@ -100,18 +112,20 @@ Clients send:
|
|
|
100
112
|
Authorization: Bearer <raw_token>
|
|
101
113
|
```
|
|
102
114
|
|
|
115
|
+
`authenticate_api_key!` rejects missing/invalid tokens with 401, then checks `allowed_ips` against `request.remote_ip` and enforces permission from the HTTP method: GET/HEAD require read; other methods require write (403 if the IP or permission is disallowed, without updating `last_used_at`).
|
|
116
|
+
|
|
103
117
|
## Permissions
|
|
104
118
|
|
|
105
|
-
| Permission |
|
|
119
|
+
| Permission | GET/HEAD | Other methods |
|
|
106
120
|
| --- | --- | --- |
|
|
107
|
-
| `read` |
|
|
108
|
-
| `read_write` |
|
|
121
|
+
| `read` | allowed | forbidden |
|
|
122
|
+
| `read_write` | allowed | allowed |
|
|
109
123
|
|
|
110
|
-
Permissions are immutable after create. Revoke with `revoke!` (sets `revoked_at`).
|
|
124
|
+
Permissions are immutable after create. `allowed_ips` accepts single IPv4/IPv6 addresses or CIDR ranges (or a comma/newline-separated string), defaults to `[]` (unrestricted), and can be updated after create. Revoke with `revoke!` (sets `revoked_at`).
|
|
111
125
|
|
|
112
126
|
## Security notes
|
|
113
127
|
|
|
114
|
-
- Raw tokens are returned only from `generate_for!` and never stored
|
|
128
|
+
- Raw tokens are returned only from `create_api_key!` / `generate_for!` and never stored
|
|
115
129
|
- Digests use SHA-256 (`token_digest`); UI can show `token_display_prefix`
|
|
116
130
|
- Soft revoke via `revoked_at`; authentication ignores revoked keys
|
|
117
131
|
|
|
@@ -125,6 +139,12 @@ bin/rubocop
|
|
|
125
139
|
|
|
126
140
|
See [CHANGELOG.md](./CHANGELOG.md) for release notes. Agent-oriented notes live in [`AGENTS.md`](./AGENTS.md).
|
|
127
141
|
|
|
142
|
+
## Contributing
|
|
143
|
+
|
|
144
|
+
Bug reports and pull requests are welcome. See [CONTRIBUTING.md](./CONTRIBUTING.md) and the [Code of Conduct](./CODE_OF_CONDUCT.md).
|
|
145
|
+
|
|
146
|
+
To report a security vulnerability privately, see [SECURITY.md](./SECURITY.md).
|
|
147
|
+
|
|
128
148
|
## License
|
|
129
149
|
|
|
130
150
|
This project is licensed under the [MIT License](./LICENSE).
|
|
@@ -21,34 +21,37 @@ module RailsApiKeys
|
|
|
21
21
|
|
|
22
22
|
validates :name, :token_digest, :token_display_prefix, :permission, presence: true
|
|
23
23
|
validates :token_digest, uniqueness: true
|
|
24
|
-
validate :
|
|
24
|
+
validate :owner_declares_has_api_keys
|
|
25
25
|
validate :permission_immutable, on: :update
|
|
26
|
+
validate :allowed_ips_must_be_valid
|
|
26
27
|
|
|
27
28
|
scope :active, -> { where(revoked_at: nil) }
|
|
28
29
|
|
|
29
30
|
class << self
|
|
30
31
|
# Creates a key and returns +[record, raw_token]+. Show +raw_token+ once.
|
|
31
|
-
def generate_for!(owner:, name:, permission:)
|
|
32
|
+
def generate_for!(owner:, name:, permission:, allowed_ips: [])
|
|
32
33
|
raw_token = build_raw_token
|
|
33
34
|
record = create!(
|
|
34
35
|
owner: owner,
|
|
35
36
|
name: name,
|
|
36
37
|
permission: permission,
|
|
38
|
+
allowed_ips: allowed_ips,
|
|
37
39
|
token_digest: digest(raw_token),
|
|
38
40
|
token_display_prefix: display_prefix_for(raw_token)
|
|
39
41
|
)
|
|
40
42
|
[ record, raw_token ]
|
|
41
43
|
end
|
|
42
44
|
|
|
43
|
-
# Returns an active key for +raw_token+, or +nil+. Touches +last_used_at
|
|
44
|
-
|
|
45
|
+
# Returns an active key for +raw_token+, or +nil+. Touches +last_used_at+
|
|
46
|
+
# unless +touch_last_used: false+.
|
|
47
|
+
def authenticate(raw_token, touch_last_used: true)
|
|
45
48
|
return if raw_token.blank?
|
|
46
49
|
|
|
47
50
|
key = active.find_by(token_digest: digest(raw_token))
|
|
48
51
|
return unless key
|
|
49
52
|
return unless RailsApiKeys.configuration.owner_active?(key.owner)
|
|
50
53
|
|
|
51
|
-
key.touch_last_used!
|
|
54
|
+
key.touch_last_used! if touch_last_used
|
|
52
55
|
key
|
|
53
56
|
end
|
|
54
57
|
|
|
@@ -65,6 +68,10 @@ module RailsApiKeys
|
|
|
65
68
|
end
|
|
66
69
|
end
|
|
67
70
|
|
|
71
|
+
def allowed_ips=(value)
|
|
72
|
+
super(IpAllowlist.new(value).entries)
|
|
73
|
+
end
|
|
74
|
+
|
|
68
75
|
# Soft-revokes the key so {.authenticate} no longer accepts it.
|
|
69
76
|
def revoke!
|
|
70
77
|
update!(revoked_at: Time.current)
|
|
@@ -86,19 +93,27 @@ module RailsApiKeys
|
|
|
86
93
|
read_write?
|
|
87
94
|
end
|
|
88
95
|
|
|
96
|
+
def allows_ip?(ip)
|
|
97
|
+
IpAllowlist.new(allowed_ips).allows?(ip)
|
|
98
|
+
end
|
|
99
|
+
|
|
89
100
|
def touch_last_used!
|
|
90
101
|
update_column(:last_used_at, Time.current)
|
|
91
102
|
end
|
|
92
103
|
|
|
93
104
|
private
|
|
94
105
|
|
|
95
|
-
def
|
|
96
|
-
|
|
106
|
+
def allowed_ips_must_be_valid
|
|
107
|
+
IpAllowlist.new(allowed_ips).invalid_entries.each do |entry|
|
|
108
|
+
errors.add(:allowed_ips, "contains invalid IP address or CIDR: #{entry}")
|
|
109
|
+
end
|
|
110
|
+
end
|
|
97
111
|
|
|
98
|
-
|
|
99
|
-
return if owner.
|
|
112
|
+
def owner_declares_has_api_keys
|
|
113
|
+
return if owner.blank?
|
|
114
|
+
return if RailsApiKeys.owner_class?(owner.class)
|
|
100
115
|
|
|
101
|
-
errors.add(:owner, "must
|
|
116
|
+
errors.add(:owner, "must declare has_api_keys")
|
|
102
117
|
end
|
|
103
118
|
|
|
104
119
|
def permission_immutable
|
|
@@ -7,6 +7,7 @@ class CreateRailsApiKeysApiKeys < ActiveRecord::Migration[<%= ActiveRecord::Migr
|
|
|
7
7
|
t.string :token_digest, null: false
|
|
8
8
|
t.string :token_display_prefix, null: false
|
|
9
9
|
t.string :permission, null: false, default: "read"
|
|
10
|
+
t.json :allowed_ips, null: false, default: []
|
|
10
11
|
t.references :owner, polymorphic: true, null: false, index: true
|
|
11
12
|
t.datetime :revoked_at
|
|
12
13
|
t.datetime :last_used_at
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
# Defaults:
|
|
3
|
+
# Defaults: token_prefix "<AppName>_ak_",
|
|
4
4
|
# owner_active via active_for_authentication? when available.
|
|
5
|
+
# Owner models opt in with +has_api_keys+.
|
|
5
6
|
# Uncomment to override:
|
|
6
7
|
#
|
|
7
8
|
# RailsApiKeys.configure do |config|
|
|
@@ -5,9 +5,10 @@ require "active_support/concern"
|
|
|
5
5
|
module RailsApiKeys
|
|
6
6
|
# Controller concern for +ActionController::API+.
|
|
7
7
|
#
|
|
8
|
-
# Include and call {#authenticate_api_key!}
|
|
9
|
-
#
|
|
10
|
-
#
|
|
8
|
+
# Include and call {#authenticate_api_key!} from +before_action+. After a
|
|
9
|
+
# successful authenticate, +current_api_key+ and +current_api_owner+ are set.
|
|
10
|
+
# Permission is enforced from the HTTP method: GET/HEAD require read; other
|
|
11
|
+
# methods require write.
|
|
11
12
|
#
|
|
12
13
|
# Expects +Authorization: Bearer <raw_token>+.
|
|
13
14
|
module Authentication
|
|
@@ -19,10 +20,11 @@ module RailsApiKeys
|
|
|
19
20
|
|
|
20
21
|
private
|
|
21
22
|
|
|
22
|
-
# Authenticates the Bearer token
|
|
23
|
+
# Authenticates the Bearer token and enforces IP allowlist and method-based permission.
|
|
24
|
+
# Renders 401 on auth failure, 403 when the IP or permission is disallowed.
|
|
23
25
|
def authenticate_api_key!
|
|
24
26
|
token = bearer_token
|
|
25
|
-
key = RailsApiKeys::ApiKey.authenticate(token)
|
|
27
|
+
key = RailsApiKeys::ApiKey.authenticate(token, touch_last_used: false)
|
|
26
28
|
|
|
27
29
|
unless key
|
|
28
30
|
render_api_unauthorized
|
|
@@ -31,21 +33,32 @@ module RailsApiKeys
|
|
|
31
33
|
|
|
32
34
|
@current_api_key = key
|
|
33
35
|
@current_api_owner = key.owner
|
|
36
|
+
|
|
37
|
+
return false unless enforce_api_ip!
|
|
38
|
+
return false unless enforce_api_permission!
|
|
39
|
+
|
|
40
|
+
current_api_key.touch_last_used!
|
|
34
41
|
true
|
|
35
42
|
end
|
|
36
43
|
|
|
37
|
-
|
|
38
|
-
|
|
44
|
+
def enforce_api_ip!
|
|
45
|
+
return true if current_api_key.allows_ip?(request.remote_ip)
|
|
46
|
+
|
|
47
|
+
render_api_forbidden
|
|
48
|
+
false
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def enforce_api_permission!
|
|
39
52
|
allowed =
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
53
|
+
if request.get? || request.head?
|
|
54
|
+
current_api_key.allows_read?
|
|
55
|
+
else
|
|
56
|
+
current_api_key.allows_write?
|
|
44
57
|
end
|
|
45
58
|
|
|
46
59
|
return true if allowed
|
|
47
60
|
|
|
48
|
-
|
|
61
|
+
render_api_forbidden
|
|
49
62
|
false
|
|
50
63
|
end
|
|
51
64
|
|
|
@@ -59,5 +72,9 @@ module RailsApiKeys
|
|
|
59
72
|
def render_api_unauthorized
|
|
60
73
|
render json: { error: "Unauthorized" }, status: :unauthorized
|
|
61
74
|
end
|
|
75
|
+
|
|
76
|
+
def render_api_forbidden
|
|
77
|
+
render json: { error: "Forbidden" }, status: :forbidden
|
|
78
|
+
end
|
|
62
79
|
end
|
|
63
80
|
end
|
|
@@ -3,14 +3,13 @@
|
|
|
3
3
|
module RailsApiKeys
|
|
4
4
|
# Optional host overrides. Set via {RailsApiKeys.configure}.
|
|
5
5
|
#
|
|
6
|
-
# Defaults: +
|
|
7
|
-
#
|
|
8
|
-
#
|
|
6
|
+
# Defaults: +token_prefix+ derives from the app name, and +owner_active+ uses
|
|
7
|
+
# Devise-style +active_for_authentication?+ when available.
|
|
8
|
+
# Owner models opt in with {Owner.has_api_keys}.
|
|
9
9
|
class Configuration
|
|
10
|
-
attr_accessor :
|
|
10
|
+
attr_accessor :token_prefix, :owner_active
|
|
11
11
|
|
|
12
12
|
def initialize
|
|
13
|
-
@owner_class = "User"
|
|
14
13
|
@token_prefix = nil
|
|
15
14
|
@owner_active = ->(owner) {
|
|
16
15
|
if owner.respond_to?(:active_for_authentication?)
|
|
@@ -27,10 +26,6 @@ module RailsApiKeys
|
|
|
27
26
|
"#{Rails.application.class.module_parent_name.downcase}_ak_"
|
|
28
27
|
end
|
|
29
28
|
|
|
30
|
-
def owner_class_name
|
|
31
|
-
owner_class.to_s
|
|
32
|
-
end
|
|
33
|
-
|
|
34
29
|
def owner_active?(owner)
|
|
35
30
|
owner_active.call(owner)
|
|
36
31
|
end
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "ipaddr"
|
|
4
|
+
|
|
5
|
+
module RailsApiKeys
|
|
6
|
+
# Normalizes, validates, and matches IPv4/IPv6 addresses and CIDR ranges.
|
|
7
|
+
class IpAllowlist
|
|
8
|
+
attr_reader :entries
|
|
9
|
+
|
|
10
|
+
def initialize(raw_entries)
|
|
11
|
+
@entries = normalize(raw_entries)
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
def invalid_entries
|
|
15
|
+
entries.reject { |entry| valid_entry?(entry) }
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def valid?
|
|
19
|
+
invalid_entries.empty?
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def allows?(ip)
|
|
23
|
+
return true if entries.empty?
|
|
24
|
+
return false if ip.blank?
|
|
25
|
+
|
|
26
|
+
candidate = parse_candidate(ip)
|
|
27
|
+
return false unless candidate
|
|
28
|
+
|
|
29
|
+
entries.any? { |entry| matches_entry?(entry, candidate) }
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
private
|
|
33
|
+
|
|
34
|
+
def normalize(value)
|
|
35
|
+
raw =
|
|
36
|
+
case value
|
|
37
|
+
when nil
|
|
38
|
+
[]
|
|
39
|
+
when String
|
|
40
|
+
value.split(/[\r\n,]+/)
|
|
41
|
+
when Array
|
|
42
|
+
value
|
|
43
|
+
else
|
|
44
|
+
[ value ]
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
raw.filter_map { |entry| entry.to_s.strip.presence }.uniq
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def valid_entry?(entry)
|
|
51
|
+
IPAddr.new(entry.to_s)
|
|
52
|
+
true
|
|
53
|
+
rescue IPAddr::InvalidAddressError, IPAddr::InvalidPrefixError
|
|
54
|
+
false
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def parse_candidate(ip)
|
|
58
|
+
candidate = IPAddr.new(ip.to_s)
|
|
59
|
+
candidate.ipv4_mapped? ? candidate.native : candidate
|
|
60
|
+
rescue IPAddr::InvalidAddressError, IPAddr::InvalidPrefixError
|
|
61
|
+
nil
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def matches_entry?(entry, candidate)
|
|
65
|
+
IPAddr.new(entry).include?(candidate)
|
|
66
|
+
rescue IPAddr::InvalidAddressError, IPAddr::InvalidPrefixError
|
|
67
|
+
false
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
end
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RailsApiKeys
|
|
4
|
+
# Mixes {.has_api_keys} into Active Record so host models can opt in as key owners.
|
|
5
|
+
module Owner
|
|
6
|
+
extend ActiveSupport::Concern
|
|
7
|
+
|
|
8
|
+
class_methods do
|
|
9
|
+
# Declares a polymorphic +has_many :api_keys+ and registers this class as an
|
|
10
|
+
# allowed owner for {RailsApiKeys::ApiKey}.
|
|
11
|
+
def has_api_keys(dependent: :destroy)
|
|
12
|
+
has_many :api_keys,
|
|
13
|
+
as: :owner,
|
|
14
|
+
class_name: "RailsApiKeys::ApiKey",
|
|
15
|
+
dependent: dependent
|
|
16
|
+
|
|
17
|
+
RailsApiKeys.register_owner_class!(self)
|
|
18
|
+
|
|
19
|
+
# Creates a key for this owner and returns +[record, raw_token]+.
|
|
20
|
+
define_method(:create_api_key!) do |name:, permission:, allowed_ips: []|
|
|
21
|
+
RailsApiKeys::ApiKey.generate_for!(
|
|
22
|
+
owner: self,
|
|
23
|
+
name: name,
|
|
24
|
+
permission: permission,
|
|
25
|
+
allowed_ips: allowed_ips
|
|
26
|
+
)
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
end
|
data/lib/rails_api_keys.rb
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "set"
|
|
3
4
|
require "rails_api_keys/version"
|
|
4
5
|
require "rails_api_keys/configuration"
|
|
6
|
+
require "rails_api_keys/ip_allowlist"
|
|
5
7
|
require "rails_api_keys/authentication"
|
|
8
|
+
require "rails_api_keys/owner"
|
|
6
9
|
require "rails_api_keys/engine"
|
|
7
10
|
|
|
8
11
|
# Thin Rails engine for personal API key authentication.
|
|
@@ -21,8 +24,25 @@ module RailsApiKeys
|
|
|
21
24
|
end
|
|
22
25
|
|
|
23
26
|
# Resets configuration to defaults (primarily for tests).
|
|
27
|
+
# Does not clear {.owner_class_names}; those are registered at model load via {Owner#has_api_keys}.
|
|
24
28
|
def reset_configuration!
|
|
25
29
|
@configuration = Configuration.new
|
|
26
30
|
end
|
|
31
|
+
|
|
32
|
+
# Records +klass+ as an allowed API key owner (idempotent).
|
|
33
|
+
def register_owner_class!(klass)
|
|
34
|
+
owner_class_names << klass.name
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# @return [Boolean] whether +klass+ (or its name) called {Owner#has_api_keys}
|
|
38
|
+
def owner_class?(klass)
|
|
39
|
+
name = klass.is_a?(Module) ? klass.name : klass.to_s
|
|
40
|
+
owner_class_names.include?(name)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# @return [Set<String>] registered owner class names
|
|
44
|
+
def owner_class_names
|
|
45
|
+
@owner_class_names ||= Set.new
|
|
46
|
+
end
|
|
27
47
|
end
|
|
28
48
|
end
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: rails_api_keys
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.3.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Pavel Pershko
|
|
@@ -43,6 +43,7 @@ files:
|
|
|
43
43
|
- app/models/rails_api_keys/application_record.rb
|
|
44
44
|
- config/routes.rb
|
|
45
45
|
- db/migrate/20260810120000_create_rails_api_keys_api_keys.rb
|
|
46
|
+
- db/migrate/20261125120000_add_allowed_ips_to_rails_api_keys_api_keys.rb
|
|
46
47
|
- lib/generators/rails_api_keys/install/install_generator.rb
|
|
47
48
|
- lib/generators/rails_api_keys/install/templates/create_rails_api_keys_api_keys.rb.tt
|
|
48
49
|
- lib/generators/rails_api_keys/install/templates/initializer.rb.tt
|
|
@@ -50,16 +51,18 @@ files:
|
|
|
50
51
|
- lib/rails_api_keys/authentication.rb
|
|
51
52
|
- lib/rails_api_keys/configuration.rb
|
|
52
53
|
- lib/rails_api_keys/engine.rb
|
|
54
|
+
- lib/rails_api_keys/ip_allowlist.rb
|
|
55
|
+
- lib/rails_api_keys/owner.rb
|
|
53
56
|
- lib/rails_api_keys/version.rb
|
|
54
57
|
homepage: https://github.com/rubyroidlabs/rails_api_keys
|
|
55
58
|
licenses:
|
|
56
59
|
- MIT
|
|
57
60
|
metadata:
|
|
58
61
|
homepage_uri: https://github.com/rubyroidlabs/rails_api_keys
|
|
59
|
-
source_code_uri: https://github.com/rubyroidlabs/rails_api_keys/tree/v0.
|
|
60
|
-
changelog_uri: https://github.com/rubyroidlabs/rails_api_keys/blob/v0.
|
|
62
|
+
source_code_uri: https://github.com/rubyroidlabs/rails_api_keys/tree/v0.3.0
|
|
63
|
+
changelog_uri: https://github.com/rubyroidlabs/rails_api_keys/blob/v0.3.0/CHANGELOG.md
|
|
61
64
|
bug_tracker_uri: https://github.com/rubyroidlabs/rails_api_keys/issues
|
|
62
|
-
documentation_uri: https://www.rubydoc.info/gems/rails_api_keys/0.
|
|
65
|
+
documentation_uri: https://www.rubydoc.info/gems/rails_api_keys/0.3.0
|
|
63
66
|
rubygems_mfa_required: 'true'
|
|
64
67
|
allowed_push_host: https://rubygems.org
|
|
65
68
|
rdoc_options: []
|
|
@@ -76,7 +79,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
|
76
79
|
- !ruby/object:Gem::Version
|
|
77
80
|
version: '0'
|
|
78
81
|
requirements: []
|
|
79
|
-
rubygems_version: 4.0.
|
|
82
|
+
rubygems_version: 4.0.20
|
|
80
83
|
specification_version: 4
|
|
81
84
|
summary: Reusable Rails engine for personal API key authentication.
|
|
82
85
|
test_files: []
|