standard_id-void_which_binds 0.1.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 +7 -0
- data/CHANGELOG.md +79 -0
- data/LICENSE +22 -0
- data/README.md +128 -0
- data/Rakefile +12 -0
- data/app/models/standard_id/void_which_binds/login.rb +14 -0
- data/app/models/standard_id/void_which_binds/received_event.rb +26 -0
- data/app/models/standard_id/void_which_binds/subject.rb +48 -0
- data/config/routes.rb +9 -0
- data/db/migrate/20261005000000_create_standard_id_void_which_binds_tables.rb +64 -0
- data/lib/generators/standard_id/void_which_binds/install/install_generator.rb +81 -0
- data/lib/generators/standard_id/void_which_binds/install/templates/initializer.rb.erb +28 -0
- data/lib/standard_id/void_which_binds/configuration.rb +275 -0
- data/lib/standard_id/void_which_binds/current.rb +18 -0
- data/lib/standard_id/void_which_binds/engine.rb +44 -0
- data/lib/standard_id/void_which_binds/errors.rb +48 -0
- data/lib/standard_id/void_which_binds/events_endpoint.rb +92 -0
- data/lib/standard_id/void_which_binds/id_token.rb +178 -0
- data/lib/standard_id/void_which_binds/jose.rb +258 -0
- data/lib/standard_id/void_which_binds/logins.rb +54 -0
- data/lib/standard_id/void_which_binds/providers/void_which_binds.rb +243 -0
- data/lib/standard_id/void_which_binds/receiver.rb +192 -0
- data/lib/standard_id/void_which_binds/security_event.rb +270 -0
- data/lib/standard_id/void_which_binds/staff_policy.rb +72 -0
- data/lib/standard_id/void_which_binds/testing.rb +65 -0
- data/lib/standard_id/void_which_binds/validators.rb +128 -0
- data/lib/standard_id/void_which_binds/version.rb +7 -0
- data/lib/standard_id/void_which_binds.rb +25 -0
- metadata +131 -0
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "net/http"
|
|
5
|
+
require "uri"
|
|
6
|
+
|
|
7
|
+
module StandardId
|
|
8
|
+
module VoidWhichBinds
|
|
9
|
+
# Reads this plugin's `social` config fields (declared by the provider's
|
|
10
|
+
# config_schema) through StandardId.config, the same way every provider
|
|
11
|
+
# plugin reads its credentials.
|
|
12
|
+
module Configuration
|
|
13
|
+
module_function
|
|
14
|
+
|
|
15
|
+
def social
|
|
16
|
+
StandardId.config.social
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def client_id
|
|
20
|
+
presence(social.void_which_binds_client_id)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def client_secret
|
|
24
|
+
presence(social.void_which_binds_client_secret)
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# The org's broker (moneta) origin, exactly as moneta's discovery and
|
|
28
|
+
# tokens spell it: an https origin, no path, no trailing slash.
|
|
29
|
+
def issuer
|
|
30
|
+
value = presence(social.void_which_binds_issuer)
|
|
31
|
+
raise ConfigurationError, "void_which_binds_issuer is not set" if value.nil?
|
|
32
|
+
|
|
33
|
+
error = Validators.issuer_error(value)
|
|
34
|
+
raise ConfigurationError, "void_which_binds_issuer #{error}" if error
|
|
35
|
+
|
|
36
|
+
value
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# The org id ("ed25519:<64 hex>") every ID token's `org` must equal.
|
|
40
|
+
def org
|
|
41
|
+
value = presence(social.void_which_binds_org)
|
|
42
|
+
raise ConfigurationError, "void_which_binds_org is not an ed25519 org id" unless Validators.ed25519_id?(value)
|
|
43
|
+
|
|
44
|
+
value
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# The pinned RFC 7638 thumbprints: an Array, or one String separated by
|
|
48
|
+
# commas or whitespace (the ENV form).
|
|
49
|
+
def pins
|
|
50
|
+
raw = social.void_which_binds_jwks_pins
|
|
51
|
+
list = raw.is_a?(Array) ? raw.map(&:to_s) : raw.to_s.split(/[\s,]+/)
|
|
52
|
+
list = list.map(&:strip).reject(&:empty?)
|
|
53
|
+
raise ConfigurationError, "void_which_binds_jwks_pins is empty: pin at least one thumbprint" if list.empty?
|
|
54
|
+
|
|
55
|
+
list
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# The JWKS carried inline (JSON text or a Hash), or nil to fetch
|
|
59
|
+
# issuer + /.well-known/jwks.json.
|
|
60
|
+
def inline_jwks
|
|
61
|
+
value = social.void_which_binds_jwks
|
|
62
|
+
value.is_a?(String) ? presence(value) : value.presence
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def authorization_endpoint
|
|
66
|
+
presence(social.void_which_binds_authorization_endpoint)
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def token_endpoint
|
|
70
|
+
presence(social.void_which_binds_token_endpoint)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def require_for_staff?
|
|
74
|
+
social.void_which_binds_require_for_staff == true
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def staff_predicate
|
|
78
|
+
social.void_which_binds_staff_predicate
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def presence(value)
|
|
82
|
+
value.is_a?(String) ? value.strip.presence : value.presence
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# The HTTP the relying party does: discovery, the JWKS and the token
|
|
87
|
+
# endpoint, all on the configured issuer. Plain Net::HTTP with TLS
|
|
88
|
+
# verification and short timeouts. Not StandardId::HttpClient: that client
|
|
89
|
+
# refuses private addresses, and an org's broker may well sit on one (a
|
|
90
|
+
# tailnet), while every URL here comes from the host's own configuration,
|
|
91
|
+
# never from a request. It does honour the host's
|
|
92
|
+
# `StandardId.config.network_wrapper`, as HttpClient does.
|
|
93
|
+
module Http
|
|
94
|
+
OPEN_TIMEOUT = 5
|
|
95
|
+
READ_TIMEOUT = 10
|
|
96
|
+
PROVIDER = :void_which_binds
|
|
97
|
+
|
|
98
|
+
module_function
|
|
99
|
+
|
|
100
|
+
def get(url)
|
|
101
|
+
uri = https_uri(url)
|
|
102
|
+
request = Net::HTTP::Get.new(uri)
|
|
103
|
+
request["Accept"] = "application/json"
|
|
104
|
+
perform(uri, request)
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def post_form(url, form, basic_auth: nil)
|
|
108
|
+
uri = https_uri(url)
|
|
109
|
+
request = Net::HTTP::Post.new(uri)
|
|
110
|
+
request["Accept"] = "application/json"
|
|
111
|
+
request["Authorization"] = basic_auth if basic_auth
|
|
112
|
+
request.set_form_data(form)
|
|
113
|
+
perform(uri, request)
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def https_uri(url)
|
|
117
|
+
uri = URI.parse(url.to_s)
|
|
118
|
+
raise ConfigurationError, "#{url.inspect} is not an https URL" unless uri.is_a?(URI::HTTPS) && uri.host.present?
|
|
119
|
+
|
|
120
|
+
uri
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def perform(uri, request)
|
|
124
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
125
|
+
http.use_ssl = true
|
|
126
|
+
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
|
|
127
|
+
http.open_timeout = OPEN_TIMEOUT
|
|
128
|
+
http.read_timeout = READ_TIMEOUT
|
|
129
|
+
with_network_wrapper { http.start { |h| h.request(request) } }
|
|
130
|
+
rescue Timeout::Error, SystemCallError, SocketError, IOError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse,
|
|
131
|
+
Net::ProtocolError => e
|
|
132
|
+
raise BrokerUnavailable, "#{uri.host} is unreachable (#{e.class})"
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
# Runs the request through the host's `StandardId.config.network_wrapper`
|
|
136
|
+
# (standard_id releases after 0.60.0; e.g. a circuit breaker), given
|
|
137
|
+
# `provider: :void_which_binds`, or directly when there is none. On an
|
|
138
|
+
# older standard_id the setting does not exist and reading it returns
|
|
139
|
+
# nil. A transport error raised inside the wrapper still becomes
|
|
140
|
+
# BrokerUnavailable; an error the wrapper raises itself is the host's
|
|
141
|
+
# and propagates as is.
|
|
142
|
+
def with_network_wrapper(&block)
|
|
143
|
+
wrapper = StandardId.config.network_wrapper
|
|
144
|
+
return yield unless wrapper.respond_to?(:call)
|
|
145
|
+
|
|
146
|
+
wrapper.call(**StandardId::Utils::CallableParameterFilter.filter(wrapper, { provider: PROVIDER }), &block)
|
|
147
|
+
end
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# The provider's view of moneta: its endpoints (configured, or from
|
|
151
|
+
# discovery) and the pinned key set, cached in-process.
|
|
152
|
+
module Broker
|
|
153
|
+
DISCOVERY_TTL = 3600
|
|
154
|
+
JWKS_TTL = 300
|
|
155
|
+
# A key the pins name but the cached JWKS lacks triggers a refetch, at
|
|
156
|
+
# most this often (ADR-0023: moneta may publish `next` early, and the RP
|
|
157
|
+
# must see it once it is pinned).
|
|
158
|
+
JWKS_REFETCH_INTERVAL = 30
|
|
159
|
+
|
|
160
|
+
@mutex = Mutex.new
|
|
161
|
+
@cache = {}
|
|
162
|
+
|
|
163
|
+
class << self
|
|
164
|
+
# [authorization_endpoint, token_endpoint]: the configured ones, else
|
|
165
|
+
# discovery's. A discovered issuer that differs from the configured
|
|
166
|
+
# one is a hard error, and both endpoints must be on its origin.
|
|
167
|
+
def endpoints
|
|
168
|
+
issuer = Configuration.issuer
|
|
169
|
+
configured = [Configuration.authorization_endpoint, Configuration.token_endpoint]
|
|
170
|
+
# Configured endpoints are held to the issuer's origin too: the token
|
|
171
|
+
# endpoint receives the client secret.
|
|
172
|
+
list =
|
|
173
|
+
if configured.all?
|
|
174
|
+
configured
|
|
175
|
+
else
|
|
176
|
+
doc = discovery(issuer)
|
|
177
|
+
[configured[0] || doc["authorization_endpoint"], configured[1] || doc["token_endpoint"]]
|
|
178
|
+
end
|
|
179
|
+
list.each do |endpoint|
|
|
180
|
+
raise ConfigurationError, "endpoint #{endpoint.inspect} is not on #{issuer}" unless Discovery.endpoint_on_issuer?(endpoint, issuer)
|
|
181
|
+
end
|
|
182
|
+
list
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
# The pins over the inline JWKS, or over the fetched one.
|
|
186
|
+
# `refresh: true` refetches (rate-limited) when a pinned key is missing.
|
|
187
|
+
#
|
|
188
|
+
# A key set that cannot be parsed is this app's problem (its
|
|
189
|
+
# configuration, or moneta's JWKS endpoint), never the token's, so it
|
|
190
|
+
# raises ConfigurationError: the SET endpoint answers 500, which moneta
|
|
191
|
+
# retries, rather than 400 invalid_request, which it dead-letters.
|
|
192
|
+
def pins(refresh: false)
|
|
193
|
+
thumbprints = Configuration.pins
|
|
194
|
+
inline = Configuration.inline_jwks
|
|
195
|
+
return key_set("the inline JWKS (void_which_binds_jwks)") { Jose::Pins.new(inline, thumbprints) } if inline
|
|
196
|
+
|
|
197
|
+
keys = jwks(Configuration.issuer, refresh: refresh)
|
|
198
|
+
key_set("the fetched JWKS") { Jose::Pins.new(keys, thumbprints) }
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
# Verify with the cached pins; when the pinned key is not in the cached
|
|
202
|
+
# JWKS (a key pinned after the last fetch), refetch once and retry.
|
|
203
|
+
def with_pins
|
|
204
|
+
yield pins
|
|
205
|
+
rescue Refusal => e
|
|
206
|
+
raise unless e.verdict == "key_not_published" && Configuration.inline_jwks.nil?
|
|
207
|
+
|
|
208
|
+
yield pins(refresh: true)
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
def reset!
|
|
212
|
+
@mutex.synchronize { @cache = {} }
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
private
|
|
216
|
+
|
|
217
|
+
def key_set(what)
|
|
218
|
+
yield
|
|
219
|
+
rescue Refusal => e
|
|
220
|
+
raise ConfigurationError, "#{what} is unusable: #{e.message}"
|
|
221
|
+
end
|
|
222
|
+
|
|
223
|
+
def discovery(issuer)
|
|
224
|
+
cached(:discovery, issuer, DISCOVERY_TTL) do
|
|
225
|
+
response = Http.get(issuer + Discovery::PATH)
|
|
226
|
+
raise ConfigurationError, "discovery answered HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)
|
|
227
|
+
|
|
228
|
+
doc = key_set("the discovery document") { Jose.strict_object(response.body, "discovery") }
|
|
229
|
+
raise ConfigurationError, "discovered issuer differs from void_which_binds_issuer" unless doc["issuer"] == issuer
|
|
230
|
+
|
|
231
|
+
doc
|
|
232
|
+
end
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
def jwks(issuer, refresh:)
|
|
236
|
+
key = [:jwks, issuer]
|
|
237
|
+
refreshed_at = nil
|
|
238
|
+
@mutex.synchronize do
|
|
239
|
+
entry = @cache[key]
|
|
240
|
+
if entry
|
|
241
|
+
refreshed_at = entry[:refreshed_at]
|
|
242
|
+
fresh = monotonic - entry[:at] < JWKS_TTL
|
|
243
|
+
throttled = refreshed_at && monotonic - refreshed_at < JWKS_REFETCH_INTERVAL
|
|
244
|
+
return entry[:value] if fresh && (!refresh || throttled)
|
|
245
|
+
end
|
|
246
|
+
end
|
|
247
|
+
|
|
248
|
+
response = Http.get(issuer + Discovery::JWKS_PATH)
|
|
249
|
+
raise ConfigurationError, "the JWKS answered HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)
|
|
250
|
+
|
|
251
|
+
keys = key_set("the fetched JWKS") { Jose.parse_jwks(response.body) }
|
|
252
|
+
@mutex.synchronize do
|
|
253
|
+
@cache[key] = { value: keys, at: monotonic, refreshed_at: refresh ? monotonic : refreshed_at }
|
|
254
|
+
end
|
|
255
|
+
keys
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
def cached(kind, issuer, ttl)
|
|
259
|
+
key = [kind, issuer]
|
|
260
|
+
@mutex.synchronize do
|
|
261
|
+
entry = @cache[key]
|
|
262
|
+
return entry[:value] if entry && monotonic - entry[:at] < ttl
|
|
263
|
+
end
|
|
264
|
+
value = yield
|
|
265
|
+
@mutex.synchronize { @cache[key] = { value: value, at: monotonic } }
|
|
266
|
+
value
|
|
267
|
+
end
|
|
268
|
+
|
|
269
|
+
def monotonic
|
|
270
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
271
|
+
end
|
|
272
|
+
end
|
|
273
|
+
end
|
|
274
|
+
end
|
|
275
|
+
end
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "active_support/current_attributes"
|
|
4
|
+
|
|
5
|
+
module StandardId
|
|
6
|
+
module VoidWhichBinds
|
|
7
|
+
# Request-scoped state between the two places one login touches: the
|
|
8
|
+
# verified ID token (stashed by the provider's get_user_info) and the
|
|
9
|
+
# browser session standard_id then creates (recorded by the
|
|
10
|
+
# SESSION_CREATED subscriber, see Logins). Reset by the Rails executor
|
|
11
|
+
# around every request and job.
|
|
12
|
+
class Current < ActiveSupport::CurrentAttributes
|
|
13
|
+
# { iss:, sub:, iat: } of the ID token verified in this request, until a
|
|
14
|
+
# session is created from it.
|
|
15
|
+
attribute :pending_login
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
end
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module StandardId
|
|
4
|
+
module VoidWhichBinds
|
|
5
|
+
# The engine: the SET push endpoint (config/routes.rb), the models behind
|
|
6
|
+
# the watermark (app/models), the migrations (db/migrate, installed with
|
|
7
|
+
# `bin/rails standard_id_void_which_binds:install:migrations`), and the
|
|
8
|
+
# SESSION_CREATED subscriber that records each sign-in's login_iat. The
|
|
9
|
+
# callback's `iss` and the PKCE verifier come from standard_id core
|
|
10
|
+
# (0.46+), so the engine no longer hooks the callback controller.
|
|
11
|
+
class Engine < ::Rails::Engine
|
|
12
|
+
isolate_namespace StandardId::VoidWhichBinds
|
|
13
|
+
engine_name "standard_id_void_which_binds"
|
|
14
|
+
|
|
15
|
+
config.after_initialize do
|
|
16
|
+
StandardId::VoidWhichBinds::Jose.assert_strict_json!
|
|
17
|
+
StandardId::VoidWhichBinds::Engine.subscribe_session_created!
|
|
18
|
+
StandardId::VoidWhichBinds::Engine.verify_staff_lock!
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
@subscribed = false
|
|
22
|
+
|
|
23
|
+
class << self
|
|
24
|
+
# A staff lock the account class cannot perform is refused at boot
|
|
25
|
+
# rather than discovered at the first roster removal.
|
|
26
|
+
def verify_staff_lock!
|
|
27
|
+
error = StandardId::VoidWhichBinds::Receiver.staff_lock_configuration_error
|
|
28
|
+
raise StandardId::VoidWhichBinds::ConfigurationError, error if error
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# Records the login_iat of every session created from a verified
|
|
32
|
+
# void_which_binds ID token (and refuses it under the watermark).
|
|
33
|
+
def subscribe_session_created!
|
|
34
|
+
return if @subscribed
|
|
35
|
+
|
|
36
|
+
@subscribed = true
|
|
37
|
+
StandardId::Events.subscribe(StandardId::Events::SESSION_CREATED) do |event|
|
|
38
|
+
StandardId::VoidWhichBinds::Logins.record!(event[:session])
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module StandardId
|
|
4
|
+
module VoidWhichBinds
|
|
5
|
+
# Base class for everything this gem raises.
|
|
6
|
+
class Error < StandardError; end
|
|
7
|
+
|
|
8
|
+
# A token, event or request refused by one of ADR-0023's verifiers.
|
|
9
|
+
#
|
|
10
|
+
# `verdict` is the refusal named exactly as void-which-binds-go's golden
|
|
11
|
+
# vectors spell it (`malformed`, `wrong_type`, `alg`, `kid_not_pinned`,
|
|
12
|
+
# `key_not_published`, `kid_thumbprint_mismatch`, `key_not_ed25519`,
|
|
13
|
+
# `bad_signature`, `wrong_issuer`, `wrong_audience`, `wrong_org`, `nonce`,
|
|
14
|
+
# `expired`, `iat_future`, `forbidden_claim`, `pkce`, `sub_id`, `events`,
|
|
15
|
+
# `unknown_event`, `toe_missing`, `toe_after_iat`, `iat_too_old`,
|
|
16
|
+
# `session_revoked`), so a refusal is comparable with the Go reference
|
|
17
|
+
# without parsing a message.
|
|
18
|
+
class Refusal < Error
|
|
19
|
+
attr_reader :verdict
|
|
20
|
+
|
|
21
|
+
def initialize(verdict, detail = nil)
|
|
22
|
+
@verdict = verdict.to_s
|
|
23
|
+
super(detail ? "#{@verdict}: #{detail}" : @verdict)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# The verifier was asked to check against an incomplete or out-of-range
|
|
28
|
+
# expectation (an empty issuer, no pins, a leeway over 60 s, ...). It is
|
|
29
|
+
# the relying party's own misconfiguration, never the token's: the SET
|
|
30
|
+
# endpoint answers it with a 500 (retried by moneta), not a 400.
|
|
31
|
+
class ExpectError < Error
|
|
32
|
+
def verdict
|
|
33
|
+
"expect"
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# The relying party's configuration is unusable (a missing issuer, a pin
|
|
38
|
+
# that is not a SHA-256 thumbprint, a discovered issuer that differs from
|
|
39
|
+
# the configured one, ...).
|
|
40
|
+
class ConfigurationError < Error; end
|
|
41
|
+
|
|
42
|
+
# moneta could not be reached (a timeout, a refused connection, a TLS
|
|
43
|
+
# failure). Like a misconfiguration it is the relying party's side of the
|
|
44
|
+
# exchange, never the SET's: the SET endpoint answers 500, which moneta
|
|
45
|
+
# retries.
|
|
46
|
+
class BrokerUnavailable < ConfigurationError; end
|
|
47
|
+
end
|
|
48
|
+
end
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "rack/request"
|
|
5
|
+
|
|
6
|
+
module StandardId
|
|
7
|
+
module VoidWhichBinds
|
|
8
|
+
# POST /auth/void_which_binds/events: moneta's RFC 8935 push of a Security
|
|
9
|
+
# Event Token (ADR-0023, "Deprovisioning").
|
|
10
|
+
#
|
|
11
|
+
# Answers exactly as void-which-binds-go's secevent.Response: 202 with an
|
|
12
|
+
# empty body once the event's writes (the watermark included) are durable,
|
|
13
|
+
# also for a duplicate jti, an unknown subject and an event acknowledged
|
|
14
|
+
# without being applied; 400 with {"err","description"} for a refused SET
|
|
15
|
+
# (invalid_key for the key, algorithm or signature, invalid_issuer,
|
|
16
|
+
# invalid_audience, else invalid_request); 500 for this app's own
|
|
17
|
+
# misconfiguration or a database failure, which moneta retries.
|
|
18
|
+
#
|
|
19
|
+
# Attribution: only a defect in the SET itself is answered 400. Every
|
|
20
|
+
# failure on this side (configuration, an unusable or unreachable key set,
|
|
21
|
+
# the database, an unexpected error) is a 500, which moneta retries.
|
|
22
|
+
#
|
|
23
|
+
# A bare Rack endpoint, not an ActionController: a controller parses and
|
|
24
|
+
# logs params before its action runs, and for a chunked request (no
|
|
25
|
+
# Content-Length) Rails' Request#content_length reads the WHOLE body to
|
|
26
|
+
# measure it. Here the body is read at most MAX_TOKEN_LEN + 1 bytes,
|
|
27
|
+
# whatever the request claims, so an unauthenticated sender cannot make the
|
|
28
|
+
# app buffer more than that. The request carries no cookie, session or
|
|
29
|
+
# CSRF token; the SET's signature under a pinned key is its only
|
|
30
|
+
# authentication.
|
|
31
|
+
module EventsEndpoint
|
|
32
|
+
JSON_HEADERS = { "content-type" => "application/json; charset=utf-8", "cache-control" => "no-store" }.freeze
|
|
33
|
+
|
|
34
|
+
module_function
|
|
35
|
+
|
|
36
|
+
def call(env)
|
|
37
|
+
request = Rack::Request.new(env)
|
|
38
|
+
return [405, { "allow" => "POST" }, []] unless request.post?
|
|
39
|
+
unless request.media_type == SecurityEvent::CONTENT_TYPE
|
|
40
|
+
return refuse(SecurityEvent::CODE_INVALID_REQUEST, "Content-Type must be #{SecurityEvent::CONTENT_TYPE}")
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
token = bounded_body(env)
|
|
44
|
+
return refuse(SecurityEvent::CODE_INVALID_REQUEST, "the body is over #{Jose::MAX_TOKEN_LEN} bytes") if token.nil?
|
|
45
|
+
|
|
46
|
+
Receiver.receive(token)
|
|
47
|
+
[202, {}, []]
|
|
48
|
+
rescue Refusal, ExpectError => e
|
|
49
|
+
status, code = SecurityEvent.response(e)
|
|
50
|
+
log(:warn, "refused SET (#{e.verdict}): answered #{status} #{code}")
|
|
51
|
+
status == 500 ? [500, {}, []] : refuse(code, "SET refused: #{e.verdict}")
|
|
52
|
+
rescue ConfigurationError => e
|
|
53
|
+
log(:error, "misconfigured: #{e.message}")
|
|
54
|
+
[500, {}, []]
|
|
55
|
+
rescue ActiveRecord::ActiveRecordError => e
|
|
56
|
+
# Nothing was committed (the event is applied in one transaction), so
|
|
57
|
+
# moneta's retry of this 500 applies it in full.
|
|
58
|
+
log(:error, "could not apply SET: #{e.class}: #{e.message}")
|
|
59
|
+
Rails.error.report(e, handled: true, source: "standard_id-void_which_binds")
|
|
60
|
+
[500, {}, []]
|
|
61
|
+
rescue StandardError => e
|
|
62
|
+
# Anything else (a host hook or predicate raising, a bug) is this
|
|
63
|
+
# app's failure, not the SET's: 500, retried, never a 400 that moneta
|
|
64
|
+
# would dead-letter.
|
|
65
|
+
log(:error, "failed to apply SET: #{e.class}: #{e.message}")
|
|
66
|
+
Rails.error.report(e, handled: true, source: "standard_id-void_which_binds")
|
|
67
|
+
[500, {}, []]
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# The body, or nil when it is over the limit. A declared Content-Length
|
|
71
|
+
# over the limit is refused unread; otherwise at most one byte past the
|
|
72
|
+
# limit is read.
|
|
73
|
+
def bounded_body(env)
|
|
74
|
+
return nil if env["CONTENT_LENGTH"].to_i > Jose::MAX_TOKEN_LEN
|
|
75
|
+
|
|
76
|
+
input = env["rack.input"]
|
|
77
|
+
return "" if input.nil?
|
|
78
|
+
|
|
79
|
+
body = input.read(Jose::MAX_TOKEN_LEN + 1).to_s
|
|
80
|
+
body.bytesize > Jose::MAX_TOKEN_LEN ? nil : body
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def refuse(code, description)
|
|
84
|
+
[400, JSON_HEADERS.dup, [JSON.generate({ err: code, description: description })]]
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def log(level, message)
|
|
88
|
+
StandardId.logger&.public_send(level, "[StandardId::VoidWhichBinds] #{message}")
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
end
|
|
92
|
+
end
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module StandardId
|
|
4
|
+
module VoidWhichBinds
|
|
5
|
+
# ADR-0023's ID token: a compact JWS with the header exactly
|
|
6
|
+
# {"alg":"EdDSA","kid":"<thumbprint>","typ":"JWT"}, verified only under a
|
|
7
|
+
# pinned key. A port of void-which-binds-go's oidc.VerifyIDToken; every
|
|
8
|
+
# refusal is a Refusal named as the golden vectors name it.
|
|
9
|
+
module IdToken
|
|
10
|
+
TYP = "JWT"
|
|
11
|
+
# exp - iat (5 minutes).
|
|
12
|
+
LIFETIME = 300
|
|
13
|
+
# The clock-skew allowance on iat and exp. Expect#leeway may be smaller,
|
|
14
|
+
# never larger.
|
|
15
|
+
MAX_LEEWAY = 60
|
|
16
|
+
|
|
17
|
+
# The two amr sets ADR-0023 allows (RFC 8176); amr never claims hwk/swk.
|
|
18
|
+
AMR_PASSKEY = %w[mfa pop user].freeze
|
|
19
|
+
AMR_DEVICE = %w[mca pop].freeze
|
|
20
|
+
ROLES = %w[viewer member admin owner].freeze
|
|
21
|
+
|
|
22
|
+
# Every claim an ID token carries (nonce is checked by each caller).
|
|
23
|
+
Claims = Struct.new(:iss, :sub, :aud, :iat, :exp, :auth_time, :nonce, :org, :role, :amr, :email, :email_verified,
|
|
24
|
+
keyword_init: true)
|
|
25
|
+
|
|
26
|
+
# What an RP expects of an ID token: its own configuration and the
|
|
27
|
+
# session's nonce. Every field is required.
|
|
28
|
+
Expect = Struct.new(:issuer, :client_id, :org, :nonce, :pins, :now, :leeway, keyword_init: true)
|
|
29
|
+
|
|
30
|
+
module_function
|
|
31
|
+
|
|
32
|
+
# Verifies `token` and returns its Claims. In order it refuses: a
|
|
33
|
+
# malformed token, typ other than "JWT", alg other than EdDSA/Ed25519, a
|
|
34
|
+
# kid not pinned, a pinned key missing, mis-labelled or not Ed25519, a bad
|
|
35
|
+
# signature (the shared JWS layer), an `events` claim, an aud array, an
|
|
36
|
+
# absent nonce, malformed or missing claims, then iss, aud, org and nonce
|
|
37
|
+
# not as expected, exp != iat + 300, auth_time after iat, an amr outside
|
|
38
|
+
# the two sets (all malformed), exp <= now - leeway (expired) and
|
|
39
|
+
# iat >= now + leeway (iat_future).
|
|
40
|
+
#
|
|
41
|
+
# It does not burn the nonce or check the redirect's RFC 9207 `iss`; the
|
|
42
|
+
# caller does both.
|
|
43
|
+
#
|
|
44
|
+
# @param now [Integer] seconds since the epoch
|
|
45
|
+
# @raise [Refusal] on any refusal
|
|
46
|
+
# @raise [ExpectError] on an incomplete expectation
|
|
47
|
+
def verify(token, expect)
|
|
48
|
+
validate_expect!(expect)
|
|
49
|
+
|
|
50
|
+
claims = Jose.verify(token, TYP, expect.pins).claims
|
|
51
|
+
raise Refusal.new("forbidden_claim", "events") if claims.key?("events")
|
|
52
|
+
raise Refusal.new("wrong_audience", "aud is an array") if claims["aud"].is_a?(Array)
|
|
53
|
+
|
|
54
|
+
nonce = Jose.string(claims["nonce"])
|
|
55
|
+
raise Refusal.new("nonce", "absent") if nonce.nil?
|
|
56
|
+
|
|
57
|
+
c = parse(claims)
|
|
58
|
+
c.nonce = nonce
|
|
59
|
+
|
|
60
|
+
raise Refusal, "wrong_issuer" if c.iss != expect.issuer
|
|
61
|
+
raise Refusal, "wrong_audience" if c.aud != expect.client_id
|
|
62
|
+
raise Refusal, "wrong_org" if c.org != expect.org
|
|
63
|
+
raise Refusal.new("nonce", "mismatched") unless secure_equal?(c.nonce, expect.nonce)
|
|
64
|
+
raise Refusal.new("malformed", "exp must be iat + #{LIFETIME}") if c.exp != c.iat + LIFETIME
|
|
65
|
+
raise Refusal.new("malformed", "auth_time is after iat") if c.auth_time > c.iat
|
|
66
|
+
raise Refusal.new("malformed", "amr is neither of the two sets") unless amr_allowed?(c.amr)
|
|
67
|
+
raise Refusal, "expired" unless c.exp > expect.now - expect.leeway
|
|
68
|
+
raise Refusal, "iat_future" unless c.iat < expect.now + expect.leeway
|
|
69
|
+
|
|
70
|
+
c
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def validate_expect!(expect)
|
|
74
|
+
ok = expect.is_a?(Expect) &&
|
|
75
|
+
[expect.issuer, expect.client_id, expect.org, expect.nonce].all? { |v| v.is_a?(String) && !v.empty? } &&
|
|
76
|
+
expect.now.is_a?(Integer) && expect.now.positive? &&
|
|
77
|
+
expect.leeway.is_a?(Integer) && expect.leeway.between?(0, MAX_LEEWAY)
|
|
78
|
+
raise ExpectError, "invalid id token verification expectation" unless ok
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Reads every claim by its exact name, refusing a missing or mistyped
|
|
82
|
+
# one, and checks each claim's shape.
|
|
83
|
+
def parse(m)
|
|
84
|
+
values = {}
|
|
85
|
+
%w[iss sub aud org].each do |name|
|
|
86
|
+
values[name] = Jose.string(m[name]) || raise(Refusal.new("malformed", "#{name} is missing or not a string"))
|
|
87
|
+
end
|
|
88
|
+
%w[iat exp auth_time].each do |name|
|
|
89
|
+
values[name] = Jose.int(m[name]) || raise(Refusal.new("malformed", "#{name} is missing or not a non-negative integer"))
|
|
90
|
+
end
|
|
91
|
+
role = Jose.string(m["role"]) || raise(Refusal.new("malformed", "role is missing or not a string"))
|
|
92
|
+
amr = m["amr"]
|
|
93
|
+
unless amr.is_a?(Array) && !amr.empty? && amr.all? { |v| v.is_a?(String) || v.nil? }
|
|
94
|
+
raise Refusal.new("malformed", "amr is missing or not a non-empty array of strings")
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
if m.key?("email") != m.key?("email_verified")
|
|
98
|
+
raise Refusal.new("malformed", "email and email_verified come together")
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
email = nil
|
|
102
|
+
email_verified = false
|
|
103
|
+
if m.key?("email")
|
|
104
|
+
email = m["email"]
|
|
105
|
+
raise Refusal.new("malformed", "email is not a non-empty string") unless email.is_a?(String) && !email.empty?
|
|
106
|
+
|
|
107
|
+
email_verified = m["email_verified"]
|
|
108
|
+
raise Refusal.new("malformed", "email_verified is not a boolean") unless [true, false].include?(email_verified)
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
c = Claims.new(iss: values["iss"], sub: values["sub"], aud: values["aud"], org: values["org"],
|
|
112
|
+
iat: values["iat"], exp: values["exp"], auth_time: values["auth_time"],
|
|
113
|
+
role: role, amr: amr.map(&:to_s), email: email, email_verified: email_verified)
|
|
114
|
+
check!(c)
|
|
115
|
+
c
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# The shape every ID token's claims must have, minted or verified.
|
|
119
|
+
def check!(c)
|
|
120
|
+
issuer_error = Validators.issuer_error(c.iss)
|
|
121
|
+
raise Refusal.new("malformed", "iss: #{issuer_error}") if issuer_error
|
|
122
|
+
raise Refusal.new("malformed", "sub is not a person id") unless Validators.person_id?(c.sub)
|
|
123
|
+
|
|
124
|
+
client_error = Validators.client_id_error(c.aud)
|
|
125
|
+
raise Refusal.new("malformed", "aud: #{client_error}") if client_error
|
|
126
|
+
raise Refusal.new("malformed", "org is not an ed25519 id") unless Validators.ed25519_id?(c.org)
|
|
127
|
+
raise Refusal.new("malformed", "role #{c.role.inspect}") unless ROLES.include?(c.role)
|
|
128
|
+
raise Refusal.new("malformed", "amr is empty") if c.amr.nil? || c.amr.empty?
|
|
129
|
+
raise Refusal.new("malformed", "email_verified without an email") if c.email.to_s.empty? && c.email_verified
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def amr_allowed?(amr)
|
|
133
|
+
amr == AMR_PASSKEY || amr == AMR_DEVICE
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
def secure_equal?(a, b)
|
|
137
|
+
a.bytesize == b.bytesize && OpenSSL.fixed_length_secure_compare(a, b)
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# Mints an ID token for `claims` (a Claims) with an Ed25519 private key
|
|
141
|
+
# (an OpenSSL::PKey). moneta is the only real minter; this exists so the
|
|
142
|
+
# gem can re-mint the golden vectors byte for byte and so host apps can
|
|
143
|
+
# sign test tokens (see StandardId::VoidWhichBinds::Testing). It refuses
|
|
144
|
+
# claims ADR-0023 does not define, as void-which-binds-go's SignIDToken
|
|
145
|
+
# does, and takes the kid from the key.
|
|
146
|
+
def sign(private_key, claims)
|
|
147
|
+
check!(claims)
|
|
148
|
+
raise Refusal.new("malformed", "nonce is empty") if claims.nonce.to_s.empty?
|
|
149
|
+
raise Refusal.new("malformed", "exp must be iat + #{LIFETIME}") if claims.exp != claims.iat + LIFETIME
|
|
150
|
+
raise Refusal.new("malformed", "auth_time is after iat") if claims.auth_time > claims.iat
|
|
151
|
+
raise Refusal.new("malformed", "amr is neither of the two sets") unless amr_allowed?(claims.amr)
|
|
152
|
+
|
|
153
|
+
payload = {
|
|
154
|
+
"iss" => claims.iss, "sub" => claims.sub, "aud" => claims.aud, "iat" => claims.iat, "exp" => claims.exp,
|
|
155
|
+
"auth_time" => claims.auth_time, "nonce" => claims.nonce, "org" => claims.org, "role" => claims.role,
|
|
156
|
+
"amr" => claims.amr
|
|
157
|
+
}
|
|
158
|
+
unless claims.email.to_s.empty?
|
|
159
|
+
payload["email"] = claims.email
|
|
160
|
+
payload["email_verified"] = claims.email_verified == true
|
|
161
|
+
end
|
|
162
|
+
Jose.sign(private_key, TYP, Jose.marshal(payload))
|
|
163
|
+
end
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
module Jose
|
|
167
|
+
# Mints a compact JWS over `payload` with header
|
|
168
|
+
# {"alg":"EdDSA","kid","typ"}, where kid is the RFC 7638 thumbprint of
|
|
169
|
+
# the key's public half. Ed25519 is deterministic, so for the same key and
|
|
170
|
+
# bytes this reproduces a void-which-binds-go token byte for byte.
|
|
171
|
+
def self.sign(private_key, typ, payload)
|
|
172
|
+
kid = thumbprint(public_jwk(private_key.raw_public_key))
|
|
173
|
+
input = "#{encode(marshal({ "alg" => ALG_EDDSA, "kid" => kid, "typ" => typ }))}.#{encode(payload)}"
|
|
174
|
+
"#{input}.#{encode(private_key.sign(nil, input))}"
|
|
175
|
+
end
|
|
176
|
+
end
|
|
177
|
+
end
|
|
178
|
+
end
|