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.
Files changed (29) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +79 -0
  3. data/LICENSE +22 -0
  4. data/README.md +128 -0
  5. data/Rakefile +12 -0
  6. data/app/models/standard_id/void_which_binds/login.rb +14 -0
  7. data/app/models/standard_id/void_which_binds/received_event.rb +26 -0
  8. data/app/models/standard_id/void_which_binds/subject.rb +48 -0
  9. data/config/routes.rb +9 -0
  10. data/db/migrate/20261005000000_create_standard_id_void_which_binds_tables.rb +64 -0
  11. data/lib/generators/standard_id/void_which_binds/install/install_generator.rb +81 -0
  12. data/lib/generators/standard_id/void_which_binds/install/templates/initializer.rb.erb +28 -0
  13. data/lib/standard_id/void_which_binds/configuration.rb +275 -0
  14. data/lib/standard_id/void_which_binds/current.rb +18 -0
  15. data/lib/standard_id/void_which_binds/engine.rb +44 -0
  16. data/lib/standard_id/void_which_binds/errors.rb +48 -0
  17. data/lib/standard_id/void_which_binds/events_endpoint.rb +92 -0
  18. data/lib/standard_id/void_which_binds/id_token.rb +178 -0
  19. data/lib/standard_id/void_which_binds/jose.rb +258 -0
  20. data/lib/standard_id/void_which_binds/logins.rb +54 -0
  21. data/lib/standard_id/void_which_binds/providers/void_which_binds.rb +243 -0
  22. data/lib/standard_id/void_which_binds/receiver.rb +192 -0
  23. data/lib/standard_id/void_which_binds/security_event.rb +270 -0
  24. data/lib/standard_id/void_which_binds/staff_policy.rb +72 -0
  25. data/lib/standard_id/void_which_binds/testing.rb +65 -0
  26. data/lib/standard_id/void_which_binds/validators.rb +128 -0
  27. data/lib/standard_id/void_which_binds/version.rb +7 -0
  28. data/lib/standard_id/void_which_binds.rb +25 -0
  29. metadata +131 -0
@@ -0,0 +1,192 @@
1
+ # frozen_string_literal: true
2
+
3
+ module StandardId
4
+ module VoidWhichBinds
5
+ # The RFC 8935 push receiver's logic (ADR-0023, "The RP's contract"):
6
+ # verify the SET, deduplicate its jti, apply it by watermark, and only then
7
+ # let the endpoint answer 202. Everything step 3 writes (the jti, the
8
+ # watermark, the revocations, the disabled link, the staff lock) commits in
9
+ # ONE transaction before the answer, so a crash or rollback after a 202
10
+ # can never lose a revocation moneta now treats as acknowledged.
11
+ module Receiver
12
+ PROVIDER = Providers::VoidWhichBinds::PROVIDER_NAME
13
+ REVOCATION_REASON_PREFIX = "void_which_binds."
14
+
15
+ Result = Struct.new(:outcome, :set, keyword_init: true) do
16
+ # :applied, :acknowledged (stale, or nothing to apply) or :duplicate.
17
+ def applied? = outcome == :applied
18
+ end
19
+
20
+ module_function
21
+
22
+ # Verifies `token` against this app's configuration.
23
+ # @raise [Refusal, ExpectError, ConfigurationError]
24
+ def verify(token, now: Time.now.to_i)
25
+ Broker.with_pins do |pins|
26
+ SecurityEvent.verify(token, SecurityEvent::Expect.new(
27
+ issuer: Configuration.issuer,
28
+ audience: Configuration.client_id.to_s,
29
+ pins: pins,
30
+ now: now,
31
+ max_age: SecurityEvent::MAX_AGE
32
+ ))
33
+ end
34
+ end
35
+
36
+ # Verifies and applies `token`; returns a Result. Raises on a refusal
37
+ # (see SecurityEvent.response for the RFC 8935 answer) and on a database
38
+ # error (answered 500, retried by moneta).
39
+ def receive(token, now: Time.now.to_i)
40
+ apply!(verify(token, now: now))
41
+ end
42
+
43
+ # Applies a verified SET in one transaction.
44
+ def apply!(set)
45
+ ActiveRecord::Base.transaction do
46
+ event = record_jti(set)
47
+ next Result.new(outcome: :duplicate, set: set) if event.nil?
48
+
49
+ subject = Subject.lock_for!(set.iss, set.sub)
50
+ applied =
51
+ if set.session_revoked?
52
+ apply_session_revoked(subject, set)
53
+ else
54
+ apply_account_disabled(subject, set)
55
+ end
56
+ event.update!(outcome: applied ? "applied" : "acknowledged")
57
+ Result.new(outcome: applied ? :applied : :acknowledged, set: set)
58
+ end
59
+ end
60
+
61
+ # The jti row, or nil when this (iss, jti) was already received. Its own
62
+ # savepoint, so a losing concurrent insert does not abort the transaction.
63
+ def record_jti(set)
64
+ return nil if ReceivedEvent.exists?(iss: set.iss, jti: set.jti)
65
+
66
+ ReceivedEvent.transaction(requires_new: true) do
67
+ ReceivedEvent.create!(iss: set.iss, jti: set.jti, sub: set.sub, event_type: set.event, iat: set.iat,
68
+ toe: set.toe, txn: set.txn, outcome: "acknowledged")
69
+ end
70
+ rescue ActiveRecord::RecordNotUnique
71
+ nil
72
+ end
73
+
74
+ # session-revoked: raise the subject's watermark (for an unknown subject
75
+ # too) and revoke the sessions whose ID token was issued at or before
76
+ # toe (newer ones are untouched), cascading to their refresh tokens.
77
+ def apply_session_revoked(subject, set)
78
+ subject.advance_watermark!(set.toe)
79
+
80
+ session_ids = Login.where(iss: set.iss, sub: set.sub).where(login_iat: ..set.toe).pluck(:session_id)
81
+ revoke_sessions(StandardId::Session.where(id: session_ids, revoked_at: nil), reason(set))
82
+ revoke_sessionless_refresh_tokens(linked_account_ids(set.sub))
83
+ true
84
+ end
85
+
86
+ # account-disabled: applies only when toe >= the subject's newest login
87
+ # (otherwise a newer login exists, which moneta minted only after a
88
+ # re-add, and the event is acknowledged without being applied). Then the
89
+ # link is disabled at toe, every session and refresh token of the linked
90
+ # account is revoked, and a staff account is locked.
91
+ def apply_account_disabled(subject, set)
92
+ return false unless SecurityEvent.disables_link?(set.toe, subject.last_login_iat || 0)
93
+
94
+ subject.update!(disabled_toe: set.toe) if subject.disabled_toe.nil? || set.toe > subject.disabled_toe
95
+ linked_account_ids(set.sub).each do |account_id|
96
+ StandardId::Session.revoke_all_for!(account_id, reason: reason(set))
97
+ StandardId::RefreshToken.where(account_id: account_id, revoked_at: nil).update_all(revoked_at: Time.current)
98
+ lock_staff_account(account_id)
99
+ end
100
+ true
101
+ end
102
+
103
+ def revoke_sessions(scope, reason)
104
+ sessions = scope.to_a
105
+ sessions.group_by(&:account_id).each_value do |group|
106
+ StandardId::Session.revoke_sessions!(group, reason: reason)
107
+ end
108
+ end
109
+
110
+ # Refresh tokens minted from a void_which_binds login that carry no
111
+ # session (a host OAuth flow without a session_type_resolver) have no
112
+ # login_iat to compare, so they are revoked: failing closed costs that
113
+ # client one re-authorization.
114
+ def revoke_sessionless_refresh_tokens(account_ids)
115
+ return 0 if account_ids.empty?
116
+ return 0 unless StandardId::RefreshToken.column_names.include?("auth_provider")
117
+
118
+ StandardId::RefreshToken
119
+ .where(account_id: account_ids, session_id: nil, auth_provider: PROVIDER, revoked_at: nil)
120
+ .update_all(revoked_at: Time.current)
121
+ end
122
+
123
+ # Accounts linked to this sub through standard_id's (provider, sub) row.
124
+ # One issuer per app in v1: standard_id keys the link by provider name.
125
+ def linked_account_ids(sub)
126
+ return [] unless StandardId::SocialIdentity.available?
127
+
128
+ StandardId::SocialIdentity.where(provider: PROVIDER, subject: sub).distinct.pluck(:account_id)
129
+ end
130
+
131
+ # Locks a staff account through StandardId::AccountLocking's
132
+ # `lock!(reason:)`. Every Active Record model also has the unrelated
133
+ # pessimistic-locking `lock!`, so the capability is checked by the
134
+ # concern, never by respond_to?. An account class without the concern
135
+ # cannot be locked: the revocations still commit (they are what ends the
136
+ # person's access, and failing them would make every retry a 500), and
137
+ # the gap is logged and reported here and refused at boot
138
+ # (Receiver.staff_lock_configuration_error).
139
+ def lock_staff_account(account_id)
140
+ predicate = staff_lock_predicate
141
+ return if predicate.nil?
142
+
143
+ account = StandardId.account_class.find_by(id: account_id)
144
+ return if account.nil? || !predicate.call(account)
145
+
146
+ unless account_locking?(account.class)
147
+ report_lock_unsupported(account.class)
148
+ return
149
+ end
150
+
151
+ account.lock!(reason: "#{REVOCATION_REASON_PREFIX}account_disabled")
152
+ end
153
+
154
+ # The staff predicate the lock applies, or nil when the staff lock is
155
+ # off: the configured one, else the one the installed staff_policy holds.
156
+ def staff_lock_predicate
157
+ return nil unless Configuration.require_for_staff?
158
+
159
+ predicate = Configuration.staff_predicate
160
+ policy = StandardId.config.login_method_policy
161
+ predicate ||= policy.staff_predicate if policy.is_a?(StaffPolicy)
162
+ predicate.respond_to?(:call) ? predicate : nil
163
+ end
164
+
165
+ def account_locking?(klass)
166
+ klass.is_a?(Class) && klass <= StandardId::AccountLocking
167
+ end
168
+
169
+ # Why the staff lock cannot work with this app's account class, or nil.
170
+ def staff_lock_configuration_error
171
+ return nil if staff_lock_predicate.nil?
172
+
173
+ klass = StandardId.account_class
174
+ return nil if account_locking?(klass)
175
+
176
+ "a staff lock is configured (void_which_binds_require_for_staff with a staff predicate) but " \
177
+ "#{klass.name} does not include StandardId::AccountLocking, so a roster removal cannot lock a staff account"
178
+ end
179
+
180
+ def report_lock_unsupported(klass)
181
+ message = "[StandardId::VoidWhichBinds] staff account not locked: #{klass.name} does not include StandardId::AccountLocking"
182
+ StandardId.logger&.error(message)
183
+ Rails.error.report(ConfigurationError.new(message), handled: true, source: "standard_id-void_which_binds")
184
+ end
185
+
186
+ def reason(set)
187
+ cause = set.session_revoked? ? set.reason : "account_disabled"
188
+ "#{REVOCATION_REASON_PREFIX}#{cause}"
189
+ end
190
+ end
191
+ end
192
+ end
@@ -0,0 +1,270 @@
1
+ # frozen_string_literal: true
2
+
3
+ module StandardId
4
+ module VoidWhichBinds
5
+ # ADR-0023's Security Event Tokens: the RFC 8417 SET (profiled by OpenID
6
+ # SSF 1.0) moneta pushes to each relying party, its verification here, the
7
+ # RFC 8935 answer, and the watermark rules a verified SET is applied by. A
8
+ # port of void-which-binds-go's secevent package.
9
+ #
10
+ # A SET is a compact JWS with the header exactly
11
+ # {"alg":"EdDSA","kid":"<thumbprint>","typ":"secevent+jwt"}, signed by the
12
+ # same `assert` key as the ID token and verified under the same pins. Its
13
+ # payload is, in byte order:
14
+ #
15
+ # {"iss","aud","jti","iat","toe","txn","sub_id":{"format":"iss_sub","iss","sub"},
16
+ # "events":{"<one event type URI>":{...}}}
17
+ #
18
+ # with no JWT sub, no exp and exactly one event.
19
+ module SecurityEvent
20
+ TYP = "secevent+jwt"
21
+ CONTENT_TYPE = "application/secevent+jwt"
22
+
23
+ SESSION_REVOKED = "https://schemas.openid.net/secevent/caep/event-type/session-revoked"
24
+ ACCOUNT_DISABLED = "https://schemas.openid.net/secevent/risc/event-type/account-disabled"
25
+
26
+ # The causes a session-revoked SET's reason_admin {"en": ...} carries.
27
+ CAUSES = %w[roster_remove role_expired role_changed key_removed code_replayed regenesis].freeze
28
+ ENTITIES = %w[admin user policy].freeze
29
+
30
+ # The oldest iat accepted, and how long a jti must be remembered: 7 days.
31
+ MAX_AGE = 7 * 24 * 60 * 60
32
+ # How far in the future an iat may be: 60 s.
33
+ FUTURE_LEEWAY = 60
34
+ # A jti is 16 random bytes, base64url.
35
+ JTI_LEN = 16
36
+
37
+ # The RFC 8935 §2.4 error codes.
38
+ CODE_INVALID_REQUEST = "invalid_request"
39
+ CODE_INVALID_KEY = "invalid_key"
40
+ CODE_INVALID_ISSUER = "invalid_issuer"
41
+ CODE_INVALID_AUDIENCE = "invalid_audience"
42
+ CODE_AUTHENTICATION_FAILED = "authentication_failed"
43
+ CODE_ACCESS_DENIED = "access_denied"
44
+ RETRYABLE_CODES = [CODE_INVALID_KEY, CODE_INVALID_ISSUER, CODE_INVALID_AUDIENCE,
45
+ CODE_AUTHENTICATION_FAILED, CODE_ACCESS_DENIED].freeze
46
+ KEY_VERDICTS = %w[kid_not_pinned key_not_published kid_thumbprint_mismatch key_not_ed25519 bad_signature alg].freeze
47
+
48
+ # A verified SET. `event` is the one event type URI; `initiating_entity`
49
+ # and `reason` are session-revoked's (nil for account-disabled).
50
+ SET = Struct.new(:iss, :aud, :jti, :iat, :toe, :txn, :sub_iss, :sub, :event, :initiating_entity, :reason,
51
+ keyword_init: true) do
52
+ def session_revoked?
53
+ event == SESSION_REVOKED
54
+ end
55
+
56
+ def account_disabled?
57
+ event == ACCOUNT_DISABLED
58
+ end
59
+ end
60
+
61
+ # What an RP expects of a SET. Every field is required.
62
+ Expect = Struct.new(:issuer, :audience, :pins, :now, :max_age, keyword_init: true)
63
+
64
+ module_function
65
+
66
+ # Step 1 and the window half of step 2 of ADR-0023's RP contract. In
67
+ # order it refuses: the JWS layer (malformed, typ other than
68
+ # "secevent+jwt", alg, kid not pinned, the pinned key, bad signature); a
69
+ # JWT sub, exp or nonce; an aud array; malformed claims; a missing toe;
70
+ # iss and aud not as expected; a sub_id that is not iss_sub of this
71
+ # issuer; anything but exactly one known, well-formed event; toe > iat;
72
+ # iat older than max_age or more than 60 s ahead. The caller then
73
+ # deduplicates the jti and applies the event by watermark.
74
+ #
75
+ # @raise [Refusal] on any refusal
76
+ # @raise [ExpectError] on an incomplete expectation
77
+ def verify(token, expect)
78
+ validate_expect!(expect)
79
+
80
+ m = Jose.verify(token, TYP, expect.pins).claims
81
+ %w[sub exp nonce].each do |name|
82
+ raise Refusal.new("forbidden_claim", name) if m.key?(name)
83
+ end
84
+ raise Refusal.new("wrong_audience", "aud is an array") if m["aud"].is_a?(Array)
85
+
86
+ strings = %w[iss aud jti].to_h do |name|
87
+ [name, Jose.string(m[name]) || raise(Refusal.new("malformed", "#{name} is missing or not a string"))]
88
+ end
89
+ raise Refusal.new("malformed", "jti is not #{JTI_LEN} bytes of base64url") unless Jose.decode(strings["jti"])&.bytesize == JTI_LEN
90
+
91
+ iat = Jose.int(m["iat"]) || raise(Refusal.new("malformed", "iat is missing or not a non-negative integer"))
92
+ raise Refusal, "toe_missing" unless m.key?("toe")
93
+
94
+ toe = Jose.int(m["toe"]) || raise(Refusal.new("malformed", "toe is not a non-negative integer"))
95
+ # A zero toe would revoke nothing and set the watermark to 0, yet be
96
+ # answered 202: treated as missing, as the minter does.
97
+ raise Refusal.new("toe_missing", "toe is 0") if toe.zero?
98
+
99
+ txn = nil
100
+ if m.key?("txn")
101
+ txn = Jose.string(m["txn"]) || raise(Refusal.new("malformed", "txn is not a string"))
102
+ end
103
+
104
+ raise Refusal, "wrong_issuer" if strings["iss"] != expect.issuer
105
+ raise Refusal, "wrong_audience" if strings["aud"] != expect.audience
106
+
107
+ sub = parse_sub_id(m["sub_id"], strings["iss"])
108
+ event, entity, reason = parse_event(m["events"], toe)
109
+
110
+ raise Refusal, "toe_after_iat" if toe > iat
111
+ raise Refusal, "iat_too_old" if iat < expect.now - expect.max_age
112
+ raise Refusal, "iat_future" if iat > expect.now + FUTURE_LEEWAY
113
+
114
+ SET.new(iss: strings["iss"], aud: strings["aud"], jti: strings["jti"], iat: iat, toe: toe, txn: txn,
115
+ sub_iss: strings["iss"], sub: sub, event: event, initiating_entity: entity, reason: reason)
116
+ end
117
+
118
+ def validate_expect!(expect)
119
+ ok = expect.is_a?(Expect) &&
120
+ [expect.issuer, expect.audience].all? { |v| v.is_a?(String) && !v.empty? } &&
121
+ expect.now.is_a?(Integer) && expect.now.positive? &&
122
+ expect.max_age.is_a?(Integer) && expect.max_age.positive? && expect.max_age <= MAX_AGE
123
+ raise ExpectError, "invalid SET verification expectation" unless ok
124
+ end
125
+
126
+ def parse_sub_id(raw, iss)
127
+ raise Refusal.new("sub_id", "not a three-member object") unless raw.is_a?(Hash) && raw.size == 3
128
+
129
+ format = raw["format"]
130
+ sub_iss = Jose.string(raw["iss"])
131
+ sub = Jose.string(raw["sub"])
132
+ raise Refusal.new("sub_id", "format is not iss_sub") if format != "iss_sub" || sub_iss.nil? || sub.nil?
133
+ raise Refusal.new("sub_id", "sub_id.iss is not iss") if sub_iss != iss
134
+ raise Refusal.new("sub_id", "sub is not a person id") unless Validators.person_id?(sub)
135
+
136
+ sub
137
+ end
138
+
139
+ def parse_event(raw, toe)
140
+ raise Refusal.new("events", "#{raw.is_a?(Hash) ? raw.size : 0} events") unless raw.is_a?(Hash) && raw.size == 1
141
+
142
+ uri, payload = raw.first
143
+ raise Refusal.new("events", "the event payload is not an object") unless payload.is_a?(Hash)
144
+
145
+ case uri
146
+ when ACCOUNT_DISABLED
147
+ # The profile's payload is exactly {}: a RISC reason or any other
148
+ # member is outside it.
149
+ raise Refusal.new("events", "the account-disabled payload is not {}") unless payload.empty?
150
+
151
+ [uri, nil, nil]
152
+ when SESSION_REVOKED
153
+ entity = Jose.string(payload["initiating_entity"])
154
+ reasons = payload["reason_admin"]
155
+ reason = reasons.is_a?(Hash) ? Jose.string(reasons["en"]) : nil
156
+ raise Refusal.new("events", "event_timestamp is not toe") unless Jose.int(payload["event_timestamp"]) == toe
157
+ raise Refusal.new("events", "initiating_entity") unless ENTITIES.include?(entity)
158
+ unless payload.size == 3 && reasons.is_a?(Hash) && reasons.size == 1 && CAUSES.include?(reason)
159
+ raise Refusal.new("events", "reason_admin.en")
160
+ end
161
+ raise Refusal.new("events", "role_expired is initiated by policy") if reason == "role_expired" && entity != "policy"
162
+
163
+ [uri, entity, reason]
164
+ else
165
+ raise Refusal.new("unknown_event", uri.inspect)
166
+ end
167
+ end
168
+
169
+ # The RP's RFC 8935 answer to a verify outcome: [status, err]. nil is
170
+ # 202. An ExpectError is the RP's own misconfiguration: 500, which moneta
171
+ # retries. A refusal of the key, algorithm or signature is invalid_key
172
+ # (the rotation pin gap is one), a wrong iss invalid_issuer, a wrong aud
173
+ # invalid_audience, and anything else invalid_request (dead-lettered).
174
+ def response(error)
175
+ case error
176
+ when nil then [202, ""]
177
+ when ExpectError then [500, ""]
178
+ when Refusal
179
+ return [400, CODE_INVALID_KEY] if KEY_VERDICTS.include?(error.verdict)
180
+ return [400, CODE_INVALID_ISSUER] if error.verdict == "wrong_issuer"
181
+ return [400, CODE_INVALID_AUDIENCE] if error.verdict == "wrong_audience"
182
+
183
+ [400, CODE_INVALID_REQUEST]
184
+ else
185
+ [400, CODE_INVALID_REQUEST]
186
+ end
187
+ end
188
+
189
+ # Whether a 400 with this RFC 8935 code is retried by the transmitter.
190
+ def retryable?(code)
191
+ RETRYABLE_CODES.include?(code)
192
+ end
193
+
194
+ # The transmitter's classification of one delivery attempt's response
195
+ # (moneta's outbox; replayed here so both sides agree on the table):
196
+ # :delivered, :retry or :dead_letter.
197
+ def classify(status, body)
198
+ return :delivered if status == 202
199
+ return :retry unless status == 400
200
+
201
+ begin
202
+ object = Jose.strict_object(body.to_s)
203
+ rescue Refusal
204
+ return :dead_letter
205
+ end
206
+ retryable?(Jose.string(object["err"])) ? :retry : :dead_letter
207
+ end
208
+
209
+ # The watermark rules (the RP's contract, step 3). Every argument is a
210
+ # stamp from moneta's monotonic clock, so the RP's clock plays no part.
211
+ # A tie revokes: failing closed costs one re-login.
212
+
213
+ # A session-revoked SET at toe revokes a session created by an ID token
214
+ # issued at login_iat: login_iat <= toe.
215
+ def revokes_session?(toe, login_iat)
216
+ login_iat <= toe
217
+ end
218
+
219
+ # An account-disabled SET at toe applies to a link whose newest login was
220
+ # issued at last_login_iat: toe >= last_login_iat. Otherwise it is
221
+ # acknowledged without being applied (a newer login exists only if the
222
+ # person was re-added).
223
+ def disables_link?(toe, last_login_iat)
224
+ toe >= last_login_iat
225
+ end
226
+
227
+ # A login whose ID token was issued at login_iat re-enables a link
228
+ # disabled at disabled_toe: login_iat > disabled_toe.
229
+ def reenables_link?(disabled_toe, login_iat)
230
+ login_iat > disabled_toe
231
+ end
232
+
233
+ # Mints a SET (tests and tooling only; moneta is the real transmitter),
234
+ # refusing one ADR-0023 does not define, as void-which-binds-go's Sign
235
+ # does. The kid is taken from the key.
236
+ def sign(private_key, set)
237
+ raise Refusal.new("malformed", "iss") if Validators.issuer_error(set.iss)
238
+ raise Refusal.new("malformed", "aud") if Validators.client_id_error(set.aud)
239
+ raise Refusal.new("malformed", "jti") unless Jose.decode(set.jti.to_s)&.bytesize == JTI_LEN
240
+ raise Refusal.new("malformed", "toe and iat are required") unless set.toe.to_i.positive? && set.iat.to_i.positive?
241
+ raise Refusal, "toe_after_iat" if set.toe > set.iat
242
+ raise Refusal.new("malformed", "txn is empty") if set.txn.to_s.empty?
243
+ raise Refusal, "sub_id" if set.sub_iss != set.iss || !Validators.person_id?(set.sub)
244
+
245
+ event =
246
+ case set.event
247
+ when SESSION_REVOKED
248
+ unless CAUSES.include?(set.reason) && ENTITIES.include?(set.initiating_entity)
249
+ raise Refusal.new("events", "session-revoked needs a known cause and initiating entity")
250
+ end
251
+ raise Refusal.new("events", "role_expired is initiated by policy") if set.reason == "role_expired" && set.initiating_entity != "policy"
252
+
253
+ { "event_timestamp" => set.toe, "initiating_entity" => set.initiating_entity, "reason_admin" => { "en" => set.reason } }
254
+ when ACCOUNT_DISABLED
255
+ raise Refusal.new("events", "account-disabled carries no cause") if set.reason || set.initiating_entity
256
+
257
+ {}
258
+ else
259
+ raise Refusal, "unknown_event"
260
+ end
261
+ payload = {
262
+ "iss" => set.iss, "aud" => set.aud, "jti" => set.jti, "iat" => set.iat, "toe" => set.toe, "txn" => set.txn,
263
+ "sub_id" => { "format" => "iss_sub", "iss" => set.sub_iss, "sub" => set.sub },
264
+ "events" => { set.event => event }
265
+ }
266
+ Jose.sign(private_key, TYP, Jose.marshal(payload))
267
+ end
268
+ end
269
+ end
270
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module StandardId
4
+ module VoidWhichBinds
5
+ # A `login_method_policy` (standard_id >= 0.45) that refuses every way into
6
+ # a staff account except a void_which_binds sign-in, so removing someone
7
+ # from the org's roster removes their way into the app:
8
+ #
9
+ # StandardId.configure do |c|
10
+ # c.login_method_policy = StandardId::VoidWhichBinds.staff_policy(
11
+ # staff_predicate: ->(account) { account.staff? }
12
+ # )
13
+ # end
14
+ #
15
+ # standard_id consults it before any session or token exists, in every
16
+ # flow (web password, passwordless, remember-me, other social providers,
17
+ # the OAuth grants, and each refresh with the original sign-in's method).
18
+ # Non-staff accounts pass through to `fallback`, if given (another policy
19
+ # with the same keyword contract), and are otherwise allowed.
20
+ #
21
+ # Enforced while `social.void_which_binds_require_for_staff` is true (the
22
+ # default), so the switch can be staged without redeploying the policy.
23
+ # `staff_predicate` falls back to `social.void_which_binds_staff_predicate`;
24
+ # with neither, every staff decision fails closed (raises).
25
+ class StaffPolicy
26
+ MESSAGE = "Staff accounts must sign in with the organisation's Void-Which-Binds broker"
27
+
28
+ # The predicate given to staff_policy (nil: the configured one is used).
29
+ attr_reader :staff_predicate
30
+
31
+ def initialize(staff_predicate: nil, fallback: nil)
32
+ @staff_predicate = staff_predicate
33
+ @fallback = fallback
34
+ end
35
+
36
+ def call(account:, auth_method:, provider:, request: nil, flow: nil)
37
+ # A staff account is decided here, and only here: it is admitted by
38
+ # void_which_binds and refused any other way. The fallback is never
39
+ # consulted for it, so a fallback that refuses social logins cannot
40
+ # lock staff out of the one method they are allowed.
41
+ if Configuration.require_for_staff? && staff?(account)
42
+ raise StandardId::LoginMethodDenied, MESSAGE unless void_which_binds?(auth_method, provider)
43
+
44
+ return true
45
+ end
46
+ return true if @fallback.nil?
47
+
48
+ context = { account:, auth_method:, provider:, request:, flow: }
49
+ @fallback.call(**StandardId::Utils::CallableParameterFilter.filter(@fallback, context))
50
+ end
51
+
52
+ def staff?(account)
53
+ predicate = @staff_predicate || Configuration.staff_predicate
54
+ unless predicate.respond_to?(:call)
55
+ raise StandardId::ConfigurationError, "StandardId::VoidWhichBinds.staff_policy needs a staff_predicate (or social.void_which_binds_staff_predicate)"
56
+ end
57
+
58
+ account.present? && predicate.call(account) ? true : false
59
+ end
60
+
61
+ private
62
+
63
+ def void_which_binds?(auth_method, provider)
64
+ auth_method&.to_sym == :social && provider.to_s == Providers::VoidWhichBinds::PROVIDER_NAME
65
+ end
66
+ end
67
+
68
+ def self.staff_policy(staff_predicate: nil, fallback: nil)
69
+ StaffPolicy.new(staff_predicate: staff_predicate, fallback: fallback)
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "standard_id/void_which_binds"
4
+
5
+ module StandardId
6
+ module VoidWhichBinds
7
+ # Test support for host apps: mint ID tokens and SETs the way moneta does,
8
+ # under a test-only key, so request specs can drive a real sign-in and a
9
+ # real deprovisioning push without a broker.
10
+ #
11
+ # require "standard_id/void_which_binds/testing"
12
+ #
13
+ # key = StandardId::VoidWhichBinds::Testing.key("current")
14
+ # StandardId.config.social.void_which_binds_jwks = StandardId::VoidWhichBinds::Testing.jwks(key)
15
+ # StandardId.config.social.void_which_binds_jwks_pins = [StandardId::VoidWhichBinds::Testing.thumbprint(key)]
16
+ #
17
+ # Never use these keys outside tests: the seed is derived from a public
18
+ # label.
19
+ module Testing
20
+ module_function
21
+
22
+ # The Ed25519 key void-which-binds-go's golden vectors use for `label`:
23
+ # its seed is SHA-256("void-which-binds/testvectors/adr-0023/" + label).
24
+ def key(label)
25
+ seed_key([Digest::SHA256.hexdigest("void-which-binds/testvectors/adr-0023/#{label}")].pack("H*"))
26
+ end
27
+
28
+ # The Ed25519 private key for a raw 32-byte seed.
29
+ def seed_key(seed)
30
+ OpenSSL::PKey.new_raw_private_key("ED25519", seed)
31
+ end
32
+
33
+ def jwk(key)
34
+ Jose.public_jwk(key.raw_public_key)
35
+ end
36
+
37
+ def thumbprint(key)
38
+ jwk(key)["kid"]
39
+ end
40
+
41
+ def jwks(*keys)
42
+ { "keys" => keys.map { |k| jwk(k) } }
43
+ end
44
+
45
+ # An ID token for `claims` (a Hash of IdToken::Claims members). exp
46
+ # defaults to iat + 300 and auth_time to iat.
47
+ def id_token(key, **claims)
48
+ claims[:exp] ||= claims[:iat] + IdToken::LIFETIME
49
+ claims[:auth_time] ||= claims[:iat]
50
+ claims[:amr] ||= IdToken::AMR_PASSKEY
51
+ claims[:role] ||= "member"
52
+ IdToken.sign(key, IdToken::Claims.new(**claims))
53
+ end
54
+
55
+ # A SET (SecurityEvent::SET members). sub_iss defaults to iss and txn to
56
+ # a fixed string; jti to 16 random bytes.
57
+ def security_event(key, **fields)
58
+ fields[:sub_iss] ||= fields[:iss]
59
+ fields[:txn] ||= "test-txn"
60
+ fields[:jti] ||= Jose.encode(SecureRandom.random_bytes(SecurityEvent::JTI_LEN))
61
+ SecurityEvent.sign(key, SecurityEvent::SET.new(**fields))
62
+ end
63
+ end
64
+ end
65
+ end