belt 0.6.11 → 0.6.12
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 +30 -0
- data/lib/belt/authentication/claims.rb +17 -13
- data/lib/belt/authentication/configuration.rb +17 -4
- data/lib/belt/authentication/controller.rb +6 -3
- data/lib/belt/authentication/token_verifier.rb +136 -0
- data/lib/belt/authentication.rb +1 -0
- data/lib/belt/docs/authentication.md +40 -5
- data/lib/belt/version.rb +1 -1
- metadata +2 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 5c14e759e93bb681bd3a6731e88b373a27fe7b31a16a2da03de2e481d1e45be5
|
|
4
|
+
data.tar.gz: a6e7fbbc0c17f3f5fe25b79683d95831468fe6b24e2869b86ea82c7d27b5ce03
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: '039b10e91eeb5c05b14f04e3f1cf1869f184ad91639363d2c03f66d6c0a40da305da07052789a030c805f8070e680ec5652bafed0fcd755755a24c16a2086b2b'
|
|
7
|
+
data.tar.gz: ffc6d215e223fee7179fe5918f31683de8a90ff0376a0495a0f2041d1f83a12cc6aff5756c62aab6a89b21d0ba8b6a91d083d6e4d0e7f58d4807d4d57a7e436b
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.12
|
|
4
|
+
|
|
5
|
+
### Security
|
|
6
|
+
|
|
7
|
+
- **An unsigned `Authorization: Bearer` token is no longer believed.** On a route
|
|
8
|
+
without an API Gateway authorizer, `Belt::Authentication::Claims.from_event`
|
|
9
|
+
base64-decoded the header token and returned its payload as the caller's
|
|
10
|
+
claims with no signature check, so a made-up token naming any `sub` and the
|
|
11
|
+
admin group made `current_user`, `cognito_admin?` and `authenticate_user!`
|
|
12
|
+
treat the caller as that user (and wrote the forged email, name and role to
|
|
13
|
+
their row). Header tokens are now verified by
|
|
14
|
+
`Belt::Authentication::TokenVerifier`: RS256 only, key by `kid` from the pool's
|
|
15
|
+
JWKS (cached per container), and `exp`, `iss`, `token_use == 'id'` and `aud`
|
|
16
|
+
all required. A token that can't be verified, including when no pool or
|
|
17
|
+
client id is configured, yields no claims. Routes behind `auth: :cognito`
|
|
18
|
+
were not affected and are unchanged. (Fizzy #2002)
|
|
19
|
+
|
|
20
|
+
### Added
|
|
21
|
+
|
|
22
|
+
- `config.authentication.client_ids` (default: `COGNITO_CLIENT_ID`,
|
|
23
|
+
comma-separated): the app client ids a header token may be issued for.
|
|
24
|
+
|
|
25
|
+
### Changed
|
|
26
|
+
|
|
27
|
+
- Apps that read `current_user` on a route with no authorizer must set
|
|
28
|
+
`COGNITO_USER_POOL_ID` and `COGNITO_CLIENT_ID` on the Lambda, or those
|
|
29
|
+
requests become anonymous. See UPGRADING.md.
|
|
30
|
+
- `Claims.decode` is unchanged (payload parsing, no signature check) but is no
|
|
31
|
+
longer used to establish identity.
|
|
32
|
+
|
|
3
33
|
## 0.6.11
|
|
4
34
|
|
|
5
35
|
### Added
|
|
@@ -11,13 +11,13 @@ module Belt
|
|
|
11
11
|
#
|
|
12
12
|
# 1. API Gateway Cognito authorizer — claims arrive pre-verified under
|
|
13
13
|
# requestContext.authorizer.claims, with every value flattened to a String.
|
|
14
|
-
# 2. A raw `Authorization: Bearer <id token>` header
|
|
14
|
+
# 2. A raw `Authorization: Bearer <id token>` header, on a route with no
|
|
15
|
+
# authorizer — nothing has checked it, so TokenVerifier does: signature
|
|
16
|
+
# against the pool's JWKS, then expiry, issuer, token use and audience.
|
|
15
17
|
#
|
|
16
|
-
#
|
|
17
|
-
#
|
|
18
|
-
#
|
|
19
|
-
# use), which is what stops an expired or foreign token from being waved through on
|
|
20
|
-
# routes that read the header directly.
|
|
18
|
+
# A header token that can't be verified — forged, expired, foreign, or the app has
|
|
19
|
+
# no pool configured to verify against — is no identity at all. Unverified claims
|
|
20
|
+
# are never returned from #from_event.
|
|
21
21
|
module Claims
|
|
22
22
|
# Cognito sends `cognito:groups` as a JSON array in the raw token, but API
|
|
23
23
|
# Gateway flattens it to a string — "[admins, members]" or "admins,members".
|
|
@@ -27,19 +27,19 @@ module Belt
|
|
|
27
27
|
|
|
28
28
|
class << self
|
|
29
29
|
# Claims for this request, or nil if there is no usable Cognito identity.
|
|
30
|
-
def from_event(event, issuer: nil)
|
|
30
|
+
def from_event(event, issuer: nil, client_ids: nil)
|
|
31
31
|
authorizer = event.dig('requestContext', 'authorizer', 'claims')
|
|
32
32
|
return authorizer if authorizer
|
|
33
33
|
|
|
34
34
|
token = bearer_token(event)
|
|
35
35
|
return nil unless token
|
|
36
36
|
|
|
37
|
-
|
|
37
|
+
TokenVerifier.verify(token, issuer: issuer, client_ids: client_ids)
|
|
38
38
|
end
|
|
39
39
|
|
|
40
40
|
# The raw Bearer credential, whatever it is. Callers that only want Cognito
|
|
41
|
-
# tokens rely on
|
|
42
|
-
# key scheme can share the header without special-casing here.
|
|
41
|
+
# tokens rely on TokenVerifier rejecting anything that isn't one — an app's own
|
|
42
|
+
# API key scheme can share the header without special-casing here.
|
|
43
43
|
def bearer_token(event)
|
|
44
44
|
header = authorization_header(event)
|
|
45
45
|
return nil unless header&.start_with?('Bearer ')
|
|
@@ -53,9 +53,13 @@ module Belt
|
|
|
53
53
|
headers['Authorization'] || headers['authorization']
|
|
54
54
|
end
|
|
55
55
|
|
|
56
|
-
#
|
|
57
|
-
#
|
|
58
|
-
#
|
|
56
|
+
# Parse a Cognito ID token's payload, rejecting it unless it is shaped like one.
|
|
57
|
+
#
|
|
58
|
+
# NOT an identity: the signature is not checked, so anyone can write a token
|
|
59
|
+
# that decodes. Use it only on a token something else has already verified.
|
|
60
|
+
# #from_event does not call this — it goes through TokenVerifier.
|
|
61
|
+
#
|
|
62
|
+
# Returns nil rather than raising for a token that doesn't parse.
|
|
59
63
|
def decode(token, issuer: nil)
|
|
60
64
|
payload = payload_segment(token)
|
|
61
65
|
return nil unless payload
|
|
@@ -22,9 +22,12 @@ module Belt
|
|
|
22
22
|
@user_class = nil
|
|
23
23
|
@admin_groups = nil
|
|
24
24
|
@issuer = nil
|
|
25
|
+
@client_ids = nil
|
|
25
26
|
end
|
|
26
27
|
|
|
27
|
-
attr_writer :admin_groups, :issuer
|
|
28
|
+
attr_writer :admin_groups, :issuer, :client_ids
|
|
29
|
+
|
|
30
|
+
alias client_id= client_ids=
|
|
28
31
|
|
|
29
32
|
# Accepts a class or a name. Stored as a name and resolved on demand so the
|
|
30
33
|
# setting can be declared before the model file is loaded.
|
|
@@ -52,9 +55,10 @@ module Belt
|
|
|
52
55
|
configured.empty? ? DEFAULT_ADMIN_GROUPS : configured
|
|
53
56
|
end
|
|
54
57
|
|
|
55
|
-
# Expected `iss` claim
|
|
56
|
-
#
|
|
57
|
-
#
|
|
58
|
+
# Expected `iss` claim, and where the pool's signing keys are fetched from.
|
|
59
|
+
# Derived from COGNITO_USER_POOL_ID. Nil means there is no pool to verify a
|
|
60
|
+
# Bearer header token against, so such a token is never an identity. Routes
|
|
61
|
+
# behind an API Gateway authorizer don't need it.
|
|
58
62
|
def issuer
|
|
59
63
|
return @issuer if @issuer
|
|
60
64
|
|
|
@@ -64,6 +68,15 @@ module Belt
|
|
|
64
68
|
region = ENV['COGNITO_REGION'] || ENV['AWS_REGION'] || 'us-east-1'
|
|
65
69
|
"https://cognito-idp.#{region}.amazonaws.com/#{pool_id}"
|
|
66
70
|
end
|
|
71
|
+
|
|
72
|
+
# App client ids a Bearer header token may be issued for (its `aud` claim).
|
|
73
|
+
# From COGNITO_CLIENT_ID, comma-separated when the pool has several clients
|
|
74
|
+
# (web and mobile, say). Empty means header tokens are never an identity.
|
|
75
|
+
def client_ids
|
|
76
|
+
return Array(@client_ids).map(&:to_s) if @client_ids
|
|
77
|
+
|
|
78
|
+
ENV.fetch('COGNITO_CLIENT_ID', '').to_s.split(',').map(&:strip).reject(&:empty?)
|
|
79
|
+
end
|
|
67
80
|
end
|
|
68
81
|
end
|
|
69
82
|
end
|
|
@@ -31,12 +31,15 @@ module Belt
|
|
|
31
31
|
Claims.bearer_token(event)
|
|
32
32
|
end
|
|
33
33
|
|
|
34
|
-
# The Cognito claims on this request, or nil if there aren't any.
|
|
35
|
-
#
|
|
34
|
+
# The Cognito claims on this request, or nil if there aren't any. Always
|
|
35
|
+
# verified: by the API Gateway authorizer, or — for a Bearer header on a route
|
|
36
|
+
# without one — by TokenVerifier against the pool's keys. Memoized including the
|
|
37
|
+
# nil, so a request verifies at most once.
|
|
36
38
|
def cognito_claims
|
|
37
39
|
return @cognito_claims if defined?(@cognito_claims)
|
|
38
40
|
|
|
39
|
-
|
|
41
|
+
config = belt_authentication_config
|
|
42
|
+
@cognito_claims = Claims.from_event(event, issuer: config.issuer, client_ids: config.client_ids)
|
|
40
43
|
end
|
|
41
44
|
|
|
42
45
|
def cognito_sub
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'base64'
|
|
4
|
+
require 'json'
|
|
5
|
+
require 'net/http'
|
|
6
|
+
require 'openssl'
|
|
7
|
+
require 'uri'
|
|
8
|
+
|
|
9
|
+
module Belt
|
|
10
|
+
module Authentication
|
|
11
|
+
# Verifies a Cognito ID token taken from an `Authorization: Bearer` header.
|
|
12
|
+
#
|
|
13
|
+
# A route with an API Gateway authorizer never needs this: the gateway checked the
|
|
14
|
+
# token and handed over the claims. A route without one has nothing in front of it,
|
|
15
|
+
# so a token there counts only if it was signed by the app's own pool, for one of
|
|
16
|
+
# the app's own clients. Everything is required — signature (RS256, key looked up
|
|
17
|
+
# by `kid` in the pool's JWKS), `exp`, `iss`, `token_use == 'id'` and `aud`.
|
|
18
|
+
#
|
|
19
|
+
# The key set is fetched once per Lambda container. An unknown `kid` triggers a
|
|
20
|
+
# refetch (Cognito rotates rarely), but at most once per REFETCH_INTERVAL, so a
|
|
21
|
+
# caller inventing key ids cannot make every request pay for an outbound call.
|
|
22
|
+
module TokenVerifier
|
|
23
|
+
ALGORITHM = 'RS256'
|
|
24
|
+
JWKS_TIMEOUT = 2
|
|
25
|
+
# Seconds before an unknown `kid` may trigger another fetch of a key set we hold.
|
|
26
|
+
REFETCH_INTERVAL = 60
|
|
27
|
+
# Seconds before retrying a fetch that failed outright.
|
|
28
|
+
RETRY_INTERVAL = 5
|
|
29
|
+
|
|
30
|
+
@key_sets = {}
|
|
31
|
+
@mutex = Mutex.new
|
|
32
|
+
|
|
33
|
+
class << self
|
|
34
|
+
# The verified claims, or nil. Never raises: a token that can't be verified
|
|
35
|
+
# means "no identity". Nil too when the issuer or client ids are unknown —
|
|
36
|
+
# without them there is nothing to verify against.
|
|
37
|
+
def verify(token, issuer:, client_ids:)
|
|
38
|
+
audiences = Array(client_ids).map(&:to_s).reject(&:empty?)
|
|
39
|
+
return nil if token.to_s.empty? || issuer.to_s.empty? || audiences.empty?
|
|
40
|
+
|
|
41
|
+
segments = token.to_s.split('.')
|
|
42
|
+
return nil unless segments.length == 3
|
|
43
|
+
return nil unless signed_by_pool?(segments, issuer)
|
|
44
|
+
|
|
45
|
+
claims = JSON.parse(decode_segment(segments[1]))
|
|
46
|
+
valid_claims?(claims, issuer, audiences) ? claims : nil
|
|
47
|
+
rescue StandardError
|
|
48
|
+
nil
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Test seam: supply a pool's keys ({ kid => OpenSSL::PKey::RSA }) so nothing
|
|
52
|
+
# is fetched.
|
|
53
|
+
def store_keys(issuer, keys)
|
|
54
|
+
@mutex.synchronize { @key_sets[issuer] = { keys: keys, fetch_after: monotonic_now + REFETCH_INTERVAL } }
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def reset!
|
|
58
|
+
@mutex.synchronize { @key_sets = {} }
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
private
|
|
62
|
+
|
|
63
|
+
def signed_by_pool?(segments, issuer)
|
|
64
|
+
header = JSON.parse(decode_segment(segments[0]))
|
|
65
|
+
return false unless header.is_a?(Hash) && header['alg'] == ALGORITHM
|
|
66
|
+
|
|
67
|
+
key = key_for(header['kid'], issuer)
|
|
68
|
+
return false unless key
|
|
69
|
+
|
|
70
|
+
key.verify('SHA256', decode_segment(segments[2]), "#{segments[0]}.#{segments[1]}")
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def valid_claims?(claims, issuer, audiences)
|
|
74
|
+
return false unless claims.is_a?(Hash)
|
|
75
|
+
return false unless claims['exp'].is_a?(Numeric) && claims['exp'] > Time.now.to_i
|
|
76
|
+
return false unless claims['iss'] == issuer
|
|
77
|
+
return false unless claims['token_use'] == 'id'
|
|
78
|
+
|
|
79
|
+
audiences.intersect?(Array(claims['aud']).map(&:to_s))
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def key_for(kid, issuer)
|
|
83
|
+
return nil if kid.to_s.empty?
|
|
84
|
+
|
|
85
|
+
@mutex.synchronize do
|
|
86
|
+
set = @key_sets[issuer]
|
|
87
|
+
set = @key_sets[issuer] = fetch_key_set(issuer) if refetch?(set, kid)
|
|
88
|
+
set[:keys][kid]
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
def refetch?(set, kid)
|
|
93
|
+
return true if set.nil?
|
|
94
|
+
|
|
95
|
+
!set[:keys].key?(kid) && monotonic_now >= set[:fetch_after]
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
def fetch_key_set(issuer)
|
|
99
|
+
keys = fetch_keys(issuer)
|
|
100
|
+
{ keys: keys || {}, fetch_after: monotonic_now + (keys ? REFETCH_INTERVAL : RETRY_INTERVAL) }
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# The JWKS URL comes from the configured issuer, never from the token.
|
|
104
|
+
# Returns nil when the key set could not be fetched.
|
|
105
|
+
def fetch_keys(issuer)
|
|
106
|
+
uri = URI("#{issuer}/.well-known/jwks.json")
|
|
107
|
+
options = { use_ssl: uri.scheme == 'https', open_timeout: JWKS_TIMEOUT, read_timeout: JWKS_TIMEOUT }
|
|
108
|
+
response = Net::HTTP.start(uri.host, uri.port, **options) { |http| http.get(uri.request_uri) }
|
|
109
|
+
return nil unless response.is_a?(Net::HTTPSuccess)
|
|
110
|
+
|
|
111
|
+
JSON.parse(response.body).fetch('keys', []).each_with_object({}) do |jwk, keys|
|
|
112
|
+
keys[jwk['kid']] = rsa_key(jwk) if jwk['kty'] == 'RSA'
|
|
113
|
+
end
|
|
114
|
+
rescue StandardError
|
|
115
|
+
nil
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# OpenSSL 3 keys are immutable, so build the PKCS#1 DER instead of setting n/e.
|
|
119
|
+
def rsa_key(jwk)
|
|
120
|
+
modulus = OpenSSL::BN.new(decode_segment(jwk['n']), 2)
|
|
121
|
+
exponent = OpenSSL::BN.new(decode_segment(jwk['e']), 2)
|
|
122
|
+
der = OpenSSL::ASN1::Sequence([OpenSSL::ASN1::Integer(modulus), OpenSSL::ASN1::Integer(exponent)]).to_der
|
|
123
|
+
OpenSSL::PKey::RSA.new(der)
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def decode_segment(segment)
|
|
127
|
+
Base64.urlsafe_decode64(segment + ('=' * ((4 - (segment.length % 4)) % 4)))
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def monotonic_now
|
|
131
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
end
|
data/lib/belt/authentication.rb
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
require_relative 'errors'
|
|
4
4
|
require_relative 'configuration'
|
|
5
5
|
require_relative 'authentication/configuration'
|
|
6
|
+
require_relative 'authentication/token_verifier'
|
|
6
7
|
require_relative 'authentication/claims'
|
|
7
8
|
require_relative 'authentication/cognito_authenticatable'
|
|
8
9
|
require_relative 'authentication/model_macro'
|
|
@@ -150,6 +150,7 @@ Belt.configure do |config|
|
|
|
150
150
|
config.authentication.user_class = 'Account' # default: 'User'
|
|
151
151
|
config.authentication.admin_groups = %w[staff] # default: ['admins'], or ADMIN_COGNITO_GROUPS
|
|
152
152
|
config.authentication.issuer = '...' # default: derived from COGNITO_USER_POOL_ID
|
|
153
|
+
config.authentication.client_ids = %w[...] # default: COGNITO_CLIENT_ID (comma-separated)
|
|
153
154
|
end
|
|
154
155
|
```
|
|
155
156
|
|
|
@@ -168,12 +169,46 @@ A route can be authenticated either way, and both are handled:
|
|
|
168
169
|
1. **API Gateway Cognito authorizer** — claims arrive pre-verified under
|
|
169
170
|
`requestContext.authorizer.claims`, with every value flattened to a string
|
|
170
171
|
(`"true"`, `"[admins, members]"`).
|
|
171
|
-
2. **A raw `Authorization: Bearer <id token>` header
|
|
172
|
+
2. **A raw `Authorization: Bearer <id token>` header**, on a route with no
|
|
173
|
+
authorizer — nothing has checked it, so Belt does.
|
|
172
174
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
175
|
+
For case 2 Belt verifies the token itself and returns no claims unless every check
|
|
176
|
+
passes:
|
|
177
|
+
|
|
178
|
+
- signed with RS256 by a key in your pool's JWKS (looked up by `kid`, fetched once per
|
|
179
|
+
Lambda container)
|
|
180
|
+
- `exp` present and in the future
|
|
181
|
+
- `iss` is your pool
|
|
182
|
+
- `token_use` is `id` (an access token carries no email or name)
|
|
183
|
+
- `aud` is one of your app client ids
|
|
184
|
+
|
|
185
|
+
So a token someone made up is not an identity: `current_user` is nil,
|
|
186
|
+
`cognito_admin?` is false and `authenticate_user!` answers 401.
|
|
187
|
+
|
|
188
|
+
The Lambda needs to know the pool and the client to verify against. Add both to the
|
|
189
|
+
function's environment (`config/lambda/api.yml`):
|
|
190
|
+
|
|
191
|
+
```yaml
|
|
192
|
+
env_vars:
|
|
193
|
+
COGNITO_USER_POOL_ID: ref(cognito_user_pool_id)
|
|
194
|
+
COGNITO_CLIENT_ID: ref(cognito_client_id) # comma-separated for several clients
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
and supply the refs in `infrastructure/modules/app/main.tf`:
|
|
198
|
+
|
|
199
|
+
```hcl
|
|
200
|
+
lambda_env_refs = merge(var.lambda_env_refs, {
|
|
201
|
+
cognito_user_pool_id = aws_cognito_user_pool.main.id
|
|
202
|
+
cognito_client_id = aws_cognito_user_pool_client.main.id
|
|
203
|
+
})
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
Without them a header token is never believed — Belt fails closed rather than return
|
|
207
|
+
claims it could not verify. Routes declared `auth: :cognito` need neither variable:
|
|
208
|
+
the gateway has already done the checking.
|
|
209
|
+
|
|
210
|
+
`Belt::Authentication::Claims.decode` still parses a token's payload without checking
|
|
211
|
+
its signature. It is not an identity check; don't use it as one.
|
|
177
212
|
|
|
178
213
|
Anything that isn't a Cognito ID token — including your own API key scheme sharing the
|
|
179
214
|
same header — reads as "no Cognito identity" rather than an error, so
|
data/lib/belt/version.rb
CHANGED
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: belt
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.6.
|
|
4
|
+
version: 0.6.12
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Stowzilla
|
|
@@ -110,6 +110,7 @@ files:
|
|
|
110
110
|
- lib/belt/authentication/configuration.rb
|
|
111
111
|
- lib/belt/authentication/controller.rb
|
|
112
112
|
- lib/belt/authentication/model_macro.rb
|
|
113
|
+
- lib/belt/authentication/token_verifier.rb
|
|
113
114
|
- lib/belt/cli.rb
|
|
114
115
|
- lib/belt/cli/apex_dns_sync.rb
|
|
115
116
|
- lib/belt/cli/app_detection.rb
|