omniauth-vitsme 0.3.0 → 0.5.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 8d349b546c14e9d6f7ec72ccd03a9aac7e8db44d711523c12d904a210cb65c1c
4
- data.tar.gz: 839203e14305b75c1bdec348436be83745a9c582cf9dc37360d2421a6dbce54d
3
+ metadata.gz: fe1046427776ebdb907dcc848a56718b386960ea66222aa903a1e1a63876049b
4
+ data.tar.gz: 86549c0e17bfbb4359c131818c5058748a2af1ccc37c96625b7d2a28cc6f1e40
5
5
  SHA512:
6
- metadata.gz: 645645d4761352f621b88994d6d95d53a9d9ef882b5e878b68f137153cd95ed13a514507dbcc070ce4c352381aeb9fe19da415716678c5781030cb7793d99659
7
- data.tar.gz: 90749983f5c6ba32121b08bebcf34d36fbeaf387d7fb5bd7268a3312fc589b9345300238f9b1e60f43a62211953de22c180a0b3fff998c06936918dfb1b81704
6
+ metadata.gz: 6f9e23e6f7bc5c05da65f0fe17151929a94b2cfa4c2a081e2321f614e8bc7fb65a952b7d1d9ff9dda460d0efa558923f886d3acee31a8aa382b0b8243fa7725d
7
+ data.tar.gz: b577a1d0cd8d69dc49e082c6e71638b7e3e649cc1f703f9fb916651cec7e32cb434fa777394d1e3c8751dcc3165143e55c9e5a377421b5f4d8ff7028534fd5a6
data/AGENTS.md CHANGED
@@ -30,8 +30,8 @@ person's verified details to another.
30
30
  6. **`fluid_` means unverified.** Without the `fluid` scope you never see one. With it, give such
31
31
  people a limited, tentative account and merge it when `extra.fluid_uids` shows up on a verified
32
32
  sign-in.
33
- 7. **Read everything in the callback.** Tokens live 5 seconds and there is no refresh token. Nothing
34
- can be fetched later.
33
+ 7. **Read everything in the callback.** Tokens live 5 seconds and there is no refresh token. Keep
34
+ `auth.credentials.id_token`: it is the hint a partner needs (rule 12).
35
35
  8. **Find returning people by `extra.lookup_uids`** (plus `fluid_uids` with FLUID), current first, and
36
36
  move a record found under an older uid to `auth.uid`.
37
37
  9. **User-facing copy says "verified"**, not "vits.me-verified". There is no need to name vits.me to
@@ -42,6 +42,17 @@ person's verified details to another.
42
42
  11. **Ask only for scopes the site registered.** Its page at vits.me/developer sets which it may ask
43
43
  for, and vits.me refuses a request for any other. `il_government_id_number` is enabled by vits.me
44
44
  on request, per site.
45
+ 12. **Partners (KNOTs) are asked directly, not through vits.me.** Use `provider :vitsme_partner` with the
46
+ partner's issuer as vits.me lists it (`OmniAuth::Vitsme::Partner.listing`), its own scope names from its
47
+ documentation, and `id_token:` returning the vits.me ID token you kept for the signed-in person. Never ask
48
+ a partner vits.me does not list as active, never send the ID token unencrypted (the strategy encrypts
49
+ it), and never treat the partner's `uid` as the vits.me one: it is the partner's own identifier for the
50
+ person at your site. Ask from a button, when you need it. A scope the person did not give comes back as
51
+ an empty list. Refresh with `OmniAuth::Vitsme::Partner.fresh_claims` and keep the next refresh token;
52
+ `Refused` means the consent ended: let go of what you had.
53
+ 13. **Verify every partner event** with `OmniAuth::Vitsme::Events.verify!(token, partner:, client_id:)`
54
+ before acting on it, answer `202`, and treat it as idempotent. It never carries values: refetch on
55
+ `:claims_changed`, forget on `:consent_withdrawn`.
45
56
 
46
57
  ## Doing the work
47
58
 
data/CHANGELOG.md CHANGED
@@ -7,6 +7,55 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.5.0] - 2026-11-13
11
+
12
+ ### Changed (breaking)
13
+
14
+ - Partners of vits.me (KNOTs) are asked directly, as their own OAuth servers, not through vits.me. The new
15
+ `vitsme_partner` strategy pushes the request (RFC 9126) with PKCE and the person's hint, the vits.me ID
16
+ token you kept for them encrypted to vits.me's `use: enc` key, and sends the person to the partner. The
17
+ callback redeems the code and fetches the claims, verified against the partner's keys, issuer and your
18
+ client id: `uid` is the partner's identifier for the person at your site, `extra.claims` the answer, and
19
+ `credentials.refresh_token` is there when the partner keeps a standing consent.
20
+ - `OmniAuth::Vitsme::Partner`: `listing` and `trusted!` (vits.me's list of partners, and only active
21
+ ones are asked or believed), `metadata`, `software_statement`, `register` (RFC 7591), `fresh_claims`.
22
+ - `OmniAuth::Vitsme::Events.verify!` now verifies a partner's event: `partner:` and `client_id:`, with
23
+ the person named by the partner's own identifier (`sub_id` format `opaque`).
24
+ - `OmniAuth::Vitsme::Test.mock_partner` and `.partner_auth_hash`.
25
+
26
+ ### Removed
27
+
28
+ - KNOT scopes on the vits.me sign-in (`knot:<knot>:<name>`), `extra.knot_claims`, `extra.knot_errors`,
29
+ `OmniAuth::Vitsme::Knot` (`scopes`, `resolve`, `fresh_claims`) and `Test.mock_auth(knot_claims:)`:
30
+ vits.me no longer introduces sites to partners or relays their events.
31
+
32
+
33
+ ## [0.4.0] - 2026-11-10
34
+
35
+ ### Added
36
+
37
+ - KNOT claims, from partner services. The gem knows no partner: any `knot:<knot>:<name>` scope passes
38
+ the boot-time scope check, and vits.me refuses one your site wasn't granted. When UserInfo carries
39
+ KNOT sources, the strategy fetches each partner's answer during the callback, verifies its signature
40
+ against the source's `jwks_uri`, issuer, audience (your client_id) and `knot_txn`, and puts the claims
41
+ in `extra.knot_claims` as sent. A partner that can't be asked shows in `extra.knot_errors` and doesn't
42
+ fail the sign-in.
43
+ - `OmniAuth::Vitsme::Knot.scopes` reads the active KNOT scopes as vits.me describes them now (what each
44
+ answer holds, and a documentation link).
45
+ - `OmniAuth::Vitsme::Knot.fresh_claims` asks for KNOT claims again without the person, while their
46
+ standing consent holds, raising `ConsentRequired` once it doesn't.
47
+ - `OmniAuth::Vitsme::Events.verify!` verifies the change events vits.me pushes to a site's change
48
+ notifications URL: `:claims_changed`, and `:consent_withdrawn` with a `reason` of `withdrawn` or
49
+ `retired` (the partner or scope left).
50
+ - `OmniAuth::Vitsme::Test.mock_auth(knot_claims:)`.
51
+ - `data/claims.json` has a generic `knots` section and the introduction's 30-second lifetime
52
+ (catalog 3). It lists no partner.
53
+
54
+ ### Changed
55
+
56
+ - `extra.raw_info` no longer carries `_claim_names`, `_claim_sources` or `knot_txn`: they are spent
57
+ during the callback.
58
+
10
59
  ## [0.3.0] - 2026-11-05
11
60
 
12
61
  ### Added
data/README.md CHANGED
@@ -26,7 +26,7 @@ rules built in.
26
26
 
27
27
  ```ruby
28
28
  # Gemfile
29
- gem "omniauth-vitsme", "~> 0.3"
29
+ gem "omniauth-vitsme", "~> 0.5"
30
30
  gem "omniauth-rails_csrf_protection" # OmniAuth 2 starts sign-in by POST only
31
31
  ```
32
32
 
@@ -158,6 +158,97 @@ is still pending can sign in too:
158
158
  `extra.fluid_uids`. Merge the tentative account into the verified one, and drop tentative accounts
159
159
  nobody claimed after a week.
160
160
 
161
+ ## Partner services (KNOTs)
162
+
163
+ Some facts come from partner services rather than vits.me: the organizations a person acts for, the groups
164
+ they belong to, a verified email address. Each partner is an OAuth server of its own. Your site asks it
165
+ directly, as its client, and gets the answer straight from it. vits.me is not on the way: it signs the
166
+ person in at the partner, with their pincode, and makes sure it is the person your site means. Partners
167
+ come and go, so this gem knows none of them. vits.me lists the active ones, and each partner documents its
168
+ own scopes:
169
+
170
+ ```ruby
171
+ OmniAuth::Vitsme::Partner.listing(OmniAuth::Vitsme.issuer(:production))
172
+ # [{ "name" => "…", "issuer" => "https://…", "status" => "active", "scopes" => [{ "name" => "…", "title" => {…}, … }] }]
173
+ ```
174
+
175
+ **Keep the ID token.** When your site signs a person in, keep `auth.credentials.id_token` with them. It is
176
+ the hint you send a partner: encrypted to vits.me, so the partner cannot read it, and vits.me then lets
177
+ nobody but that person answer. Without one there is nobody to ask about.
178
+
179
+ **Register your site's callback for the partner** among its redirect addresses at vits.me/developer:
180
+ partners send codes only to an address vits.me lists for your site. A partner that takes registrations
181
+ (its metadata has a `registration_endpoint`) wants your site registered there once, with a software
182
+ statement vits.me signs for it:
183
+
184
+ ```ruby
185
+ statement = OmniAuth::Vitsme::Partner.software_statement(vitsme_issuer: OmniAuth::Vitsme.issuer(:production),
186
+ client_id: ENV["VITSME_APP_ID"],
187
+ client_secret: ENV["VITSME_APP_SECRET"],
188
+ audience: "https://partner.example")
189
+ OmniAuth::Vitsme::Partner.register(partner: "https://partner.example", software_statement: statement,
190
+ events_uri: "https://your.site/partner/events")
191
+ # => { "client_id" => …, "client_secret" => "…" } keep the secret: it is shown once
192
+ ```
193
+
194
+ A partner that takes none (`software_statement_required` in its metadata) gets a fresh statement with each
195
+ request, which the strategy fetches for you.
196
+
197
+ **Ask from a button of your own**, when you need what the partner holds, with your own explanation:
198
+
199
+ ```ruby
200
+ provider :vitsme_partner, name: :contacts,
201
+ partner: "https://partner.example", # its issuer, as vits.me lists it
202
+ scope: %w[email], # its own scope names
203
+ client_id: ENV["VITSME_APP_ID"], client_secret: ENV["VITSME_APP_SECRET"],
204
+ partner_secret: ENV["PARTNER_SECRET"], # only if you registered there
205
+ id_token: ->(env) { Person.find_by(id: env["rack.session"]["person_id"])&.vitsme_id_token }
206
+ ```
207
+
208
+ The person signs in at the partner with their pincode, sees what your site asks for, turns on what to give
209
+ and selects which. The callback hands you the answer, verified:
210
+
211
+ ```ruby
212
+ auth.uid # the partner's own identifier for the person at your site (never their vits.me uid)
213
+ auth.extra.claims # { "<scope>" => <the partner's answer> }, an empty list for one they did not give
214
+ auth.credentials.refresh_token # when the partner keeps a standing consent; nil otherwise
215
+ ```
216
+
217
+ Failures are `:not_signed_in` (no ID token), `:partner_untrusted` (vits.me does not list it as active),
218
+ `:partner_unavailable`, `:partner_refused`, `:partner_mixup` (an answer from another issuer) and
219
+ `:access_denied`.
220
+
221
+ **Fresh claims, without the person.** While their standing consent at the partner holds:
222
+
223
+ ```ruby
224
+ result = OmniAuth::Vitsme::Partner.fresh_claims(partner: "https://partner.example", client_id: ENV["VITSME_APP_ID"],
225
+ partner_secret: ENV["PARTNER_SECRET"], refresh_token: person.partner_refresh_token,
226
+ vitsme_issuer: OmniAuth::Vitsme.issuer(:production))
227
+ result.claims # as above
228
+ result.refresh_token # keep it: the one you used is spent
229
+ # raises OmniAuth::Vitsme::Partner::Refused once the consent no longer holds: let go of what you had
230
+ ```
231
+
232
+ **Change events.** A partner that keeps standing consents POSTs to the events address you registered
233
+ with it when something changed for someone, or they stopped it. Verify each one:
234
+
235
+ ```ruby
236
+ class PartnerEventsController < ActionController::API
237
+ def create
238
+ event = OmniAuth::Vitsme::Events.verify!(request.raw_post, partner: "https://partner.example",
239
+ client_id: ENV["VITSME_APP_ID"], environment: Rails.env)
240
+ link = PartnerLink.find_by(subject: event.uid) # the uid the partner's answer gave you
241
+ case event.type
242
+ when :claims_changed then RefreshPartnerClaimsJob.perform_later(link.id) if link
243
+ when :consent_withdrawn then link&.destroy
244
+ end
245
+ head :accepted
246
+ rescue OmniAuth::Vitsme::Events::Invalid
247
+ head :bad_request
248
+ end
249
+ end
250
+ ```
251
+
161
252
  ## Finding a returning person
162
253
 
163
254
  Look a person up by `extra.lookup_uids`, current uid first, plus `extra.fluid_uids` if you use FLUID.
@@ -200,7 +291,7 @@ OmniAuth sends failures to `OmniAuth.config.on_failure` (in Rails, `/auth/failur
200
291
  lookup_uids: ["solid_…", "solid_<earlier>"],
201
292
  fluid_uids: [],
202
293
  claims: { "name" => "Jane D.", "age__over_18" => true }, # typed, shared claims only
203
- raw_info: { "sub" => "solid_…", … } # the UserInfo response, verbatim
294
+ raw_info: { "sub" => "solid_…", … } # the UserInfo response
204
295
  }
205
296
  }
206
297
  ```
data/data/claims.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "catalog_version": 2,
2
+ "catalog_version": 3,
3
3
  "about": "Every scope, claim, gate and refusal reason a vits.me relying party can use. Source of truth for omniauth-vitsme (OmniAuth::Vitsme::Catalog) and for agents and developers choosing scopes. Mirrors the vits.me server: config/initializers/doorkeeper.rb (scopes), config/initializers/doorkeeper_openid_connect.rb (claims), config/initializers/authorizations_controller_extension.rb (value domains, gates, refusals).",
4
4
  "conventions": {
5
5
  "delivery": "Every claim except sub comes from the UserInfo endpoint, never the ID token. omniauth-vitsme fetches UserInfo on every sign-in.",
@@ -149,6 +149,12 @@
149
149
  "incompatible_with": ["fluid"]
150
150
  }
151
151
  },
152
+ "knots": {
153
+ "description": "Claims from a partner service (a KNOT) that verifies what vits.me does not. Partners are OAuth servers of their own, asked directly with the vitsme_partner strategy, never through vits.me: none is listed here. GET <issuer>/knot/partners lists them with their status; only an active one is asked or believed (OmniAuth::Vitsme::Partner.listing). Each documents its own scopes.",
154
+ "auth_hash": "uid is the partner's own identifier for the person at your site; extra.claims holds its answer, an empty list for a scope not given; credentials.refresh_token when it keeps a standing consent.",
155
+ "fresh_claims": "While the standing consent holds: OmniAuth::Vitsme::Partner.fresh_claims(partner:, client_id:, partner_secret:, refresh_token:, vitsme_issuer:). Raises Refused once it does not.",
156
+ "events": "Register an events address with the partner; verify each POST with OmniAuth::Vitsme::Events.verify!(token, partner:, client_id:) (claims_changed, consent_withdrawn) and answer 202."
157
+ },
152
158
  "refusals": {
153
159
  "nationality_gate": {
154
160
  "error": "access_denied",
@@ -175,6 +181,7 @@
175
181
  "authorization_code": 5,
176
182
  "access_token": 5,
177
183
  "id_token": 5,
184
+ "knot_introduction": 30,
178
185
  "refresh_token": null
179
186
  }
180
187
  }
@@ -17,6 +17,8 @@ module OmniAuth
17
17
  # expected_uid: ->(env) { ... }, # "details about a signed-in person" only
18
18
  # require_verified: true # refuse pending (fluid_) identities
19
19
  #
20
+ # A partner of vits.me (a KNOT) is asked with the vitsme_partner strategy, not here.
21
+ #
20
22
  # See README.md for the auth hash, the failure types and the rules (the uid is private).
21
23
  class Vitsme < OpenIDConnect
22
24
  option :name, 'vitsme'
@@ -84,7 +86,8 @@ module OmniAuth
84
86
  end
85
87
 
86
88
  # vits.me issues no refresh token and its access token lapses five seconds after issue: everything
87
- # it can tell you is already in `info` and `extra`.
89
+ # it can tell you is already in `info` and `extra`. Keep the ID token: it is what you send a partner
90
+ # as the hint (the vitsme_partner strategy's `id_token`).
88
91
  def credentials
89
92
  { id_token: access_token.id_token, scope: access_token.scope }
90
93
  end
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'omniauth'
4
+ require 'securerandom'
5
+ require 'omniauth/vitsme/issuers'
6
+ require 'omniauth/vitsme/partner'
7
+
8
+ module OmniAuth
9
+ module Strategies
10
+ # Ask a partner of vits.me (a KNOT) about the person signed in to your site.
11
+ #
12
+ # provider :vitsme_partner, name: :contacts,
13
+ # partner: 'https://contacts.mattyr.com', # its issuer, as vits.me lists it
14
+ # scope: %w[email], # its own scope names
15
+ # client_id: ..., client_secret: ..., # your site at vits.me
16
+ # partner_secret: ..., # yours at the partner, if it takes registrations
17
+ # id_token: ->(env) { ...the vits.me ID token you keep for the signed-in person... }
18
+ #
19
+ # The person is sent to the partner, signs in there with their pincode (vits.me lets only the person
20
+ # you mean), and answers on the partner's own page. The callback has `uid`, the partner's identifier
21
+ # for them at your site, `extra.claims`, what they agreed to (an empty list for what they did not),
22
+ # and `credentials.refresh_token` when the partner keeps a standing consent (ask again with
23
+ # OmniAuth::Vitsme::Partner.fresh_claims). Ask from a button of your own, when you need it.
24
+ class VitsmePartner
25
+ include OmniAuth::Strategy
26
+
27
+ SESSION_KEY = 'omniauth.vitsme_partner'
28
+
29
+ option :name, 'vitsme_partner'
30
+ option :partner, nil
31
+ option :scope, []
32
+ option :client_id, nil
33
+ option :client_secret, nil
34
+ option :partner_secret, nil
35
+ option :id_token, nil
36
+ option :ui_locales, nil
37
+ option :environment, :production
38
+ option :issuer, nil
39
+
40
+ FAILURES = %i[not_signed_in partner_untrusted partner_unavailable partner_refused partner_mixup
41
+ access_denied].freeze
42
+
43
+ def request_phase
44
+ id_token = options.id_token&.call(env).to_s
45
+ return fail!(:not_signed_in) if id_token.empty?
46
+
47
+ OmniAuth::Vitsme::Partner.trusted!(options.partner, vitsme_issuer)
48
+ redirect OmniAuth::Vitsme::Partner.push(options.partner, push_params(id_token), basic: partner_basic)
49
+ rescue OmniAuth::Vitsme::Partner::Untrusted => e
50
+ fail!(:partner_untrusted, e)
51
+ rescue OmniAuth::Vitsme::Partner::Unavailable, OmniAuth::Vitsme::Keys::Unavailable => e
52
+ fail!(:partner_unavailable, e)
53
+ rescue OmniAuth::Vitsme::Partner::Refused => e
54
+ fail!(:partner_refused, e)
55
+ end
56
+
57
+ def callback_phase
58
+ stored = session.delete("#{SESSION_KEY}.#{name}") || {}
59
+ refusal = callback_refusal(stored)
60
+ return fail!(refusal) if refusal
61
+
62
+ @result = redeem(stored)
63
+ super
64
+ rescue OmniAuth::Vitsme::Partner::Refused => e
65
+ fail!(:partner_refused, e)
66
+ rescue OmniAuth::Vitsme::Partner::Unavailable, OmniAuth::Vitsme::JWS::Invalid,
67
+ OmniAuth::Vitsme::Keys::Unavailable => e
68
+ fail!(:partner_unavailable, e)
69
+ end
70
+
71
+ uid { @result.subject }
72
+
73
+ extra { { 'partner' => options.partner, 'claims' => @result.claims, 'scopes' => @result.scopes } }
74
+
75
+ credentials { { 'refresh_token' => @result.refresh_token }.compact }
76
+
77
+ # Without the query OmniAuth would add: the partner sends codes only to the exact address vits.me
78
+ # lists for your site.
79
+ def callback_url = full_host + callback_path
80
+
81
+ private
82
+
83
+ def callback_refusal(stored)
84
+ return :csrf_detected unless stored['state'] && secure_compare(request.params['state'].to_s,
85
+ stored['state'])
86
+ return :access_denied if request.params['error']
87
+
88
+ :partner_mixup if request.params['iss'] && request.params['iss'] != options.partner
89
+ end
90
+
91
+ def redeem(stored)
92
+ OmniAuth::Vitsme::Partner.finish(partner: options.partner, client_id: options.client_id,
93
+ code: request.params['code'], redirect_uri: callback_url,
94
+ code_verifier: stored['verifier'], basic: partner_basic)
95
+ end
96
+
97
+ def push_params(id_token)
98
+ verifier, challenge = OmniAuth::Vitsme::Partner.pkce
99
+ state = SecureRandom.urlsafe_base64(24)
100
+ session["#{SESSION_KEY}.#{name}"] = { 'state' => state, 'verifier' => verifier }
101
+ params = { response_type: 'code', client_id: options.client_id, redirect_uri: callback_url,
102
+ scope: Array(options.scope).join(' '), state: state, code_challenge: challenge,
103
+ code_challenge_method: 'S256', ui_locales: ui_locales,
104
+ id_token_hint: OmniAuth::Vitsme::Partner.hint(id_token, vitsme_issuer) }.compact
105
+ if OmniAuth::Vitsme::Partner.metadata(options.partner)['software_statement_required']
106
+ statement = software_statement
107
+ end
108
+ statement ? params.merge(software_statement: statement) : params
109
+ end
110
+
111
+ def software_statement
112
+ OmniAuth::Vitsme::Partner.software_statement(vitsme_issuer: vitsme_issuer, client_id: options.client_id,
113
+ client_secret: options.client_secret, audience: options.partner)
114
+ end
115
+
116
+ def ui_locales
117
+ options.ui_locales.respond_to?(:call) ? options.ui_locales.call(env) : options.ui_locales
118
+ end
119
+
120
+ def partner_basic = options.partner_secret ? [options.client_id, options.partner_secret] : nil
121
+
122
+ def vitsme_issuer = options.issuer || OmniAuth::Vitsme.issuer(options.environment)
123
+
124
+ def secure_compare(given, expected)
125
+ given.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(given, expected)
126
+ end
127
+ end
128
+ end
129
+ end
@@ -31,6 +31,7 @@ module OmniAuth
31
31
  GATE_PATTERN.match?(scope.to_s)
32
32
  end
33
33
 
34
+ # A partner's scopes are not asked of vits.me: they go to the partner (the vitsme_partner strategy).
34
35
  def known_scope?(scope)
35
36
  scopes.include?(scope.to_s) || gate_scope?(scope)
36
37
  end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'omniauth/vitsme/jws'
4
+ require 'omniauth/vitsme/issuers'
5
+ require 'omniauth/vitsme/partner'
6
+
7
+ module OmniAuth
8
+ module Vitsme
9
+ # Change events a partner of vits.me (a KNOT) pushes to the events address you registered with it
10
+ # (Security Event Tokens, RFC 8417, pushed per RFC 8935): only partners that keep a standing consent
11
+ # send them, and only about people who gave your site one.
12
+ #
13
+ # :claims_changed what the partner would tell you about them changed: ask again
14
+ # (Partner.fresh_claims with the refresh token you hold)
15
+ # :consent_withdrawn they stopped it, or their account ended: forget what you had, and the refresh token
16
+ #
17
+ # An event names the person by the partner's identifier for them at your site (the `uid` its answers
18
+ # gave you), never says what changed, and may arrive twice. Answer 202.
19
+ module Events
20
+ TYPES = {
21
+ 'https://vits.me/secevent/knot/claims-changed' => :claims_changed,
22
+ 'https://vits.me/secevent/knot/consent-withdrawn' => :consent_withdrawn
23
+ }.freeze
24
+ CONTENT_TYPE = 'application/secevent+jwt'
25
+ MAX_AGE = 300
26
+
27
+ class Invalid < StandardError; end
28
+
29
+ Event = Struct.new(:type, :uid, :scopes, :id, :issued_at, keyword_init: true)
30
+
31
+ module_function
32
+
33
+ # Verifies an event from `partner` (its issuer) addressed to your site, and that vits.me still lists
34
+ # the partner as active.
35
+ def verify!(token, partner:, client_id:, environment: :production, issuer: nil, now: Time.now)
36
+ Partner.trusted!(partner, issuer || Vitsme.issuer(environment))
37
+ claims = JWS.verify!(token, jwks_uri: Partner.metadata(partner).fetch('jwks_uri'), iss: partner, aud: client_id,
38
+ typ: 'secevent+jwt', expiring: false, now: now)
39
+ raise Invalid, 'stale or future event' unless (claims['iat'].to_i - now.to_i).abs <= MAX_AGE
40
+
41
+ event(claims)
42
+ rescue JWS::Invalid, Keys::Unavailable, Partner::Unavailable, Partner::Untrusted, KeyError => e
43
+ raise Invalid, e.message
44
+ end
45
+
46
+ def event(claims)
47
+ sub_id = claims['sub_id']
48
+ unless sub_id.is_a?(Hash) && sub_id['format'] == 'opaque' && sub_id['id'].to_s != ''
49
+ raise Invalid,
50
+ 'unsupported subject'
51
+ end
52
+
53
+ type_uri, body = Hash(claims['events']).find { |uri, _| TYPES.key?(uri) }
54
+ raise Invalid, 'unsupported event' unless type_uri
55
+
56
+ Event.new(type: TYPES[type_uri], uid: sub_id['id'], scopes: Hash(body)['scope'].to_s.split, id: claims['jti'],
57
+ issued_at: Time.at(claims['iat'].to_i))
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'net/http'
5
+ require 'uri'
6
+
7
+ module OmniAuth
8
+ module Vitsme
9
+ # The few HTTPS calls the gem makes outside the OpenID Connect flow: KNOT claims, fresh introductions
10
+ # and published keys. Short timeouts; any transport failure is HTTP::Unavailable.
11
+ module HTTP
12
+ TIMEOUT = 5
13
+
14
+ class Unavailable < StandardError; end
15
+
16
+ Response = Struct.new(:status, :body) do
17
+ def ok? = status.between?(200, 299)
18
+ def json = JSON.parse(body)
19
+ end
20
+
21
+ module_function
22
+
23
+ def get(url, headers = {})
24
+ request(Net::HTTP::Get.new(URI(url), headers))
25
+ end
26
+
27
+ def post_form(url, form, basic: nil, headers: {})
28
+ req = Net::HTTP::Post.new(URI(url), headers)
29
+ req.set_form_data(form)
30
+ req.basic_auth(*basic) if basic
31
+ request(req)
32
+ end
33
+
34
+ def post_json(url, body, headers: {})
35
+ req = Net::HTTP::Post.new(URI(url),
36
+ headers.merge('Content-Type' => 'application/json', 'Accept' => 'application/json'))
37
+ req.body = JSON.generate(body)
38
+ request(req)
39
+ end
40
+
41
+ def request(req)
42
+ uri = req.uri
43
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https',
44
+ open_timeout: TIMEOUT, read_timeout: TIMEOUT) do |http|
45
+ http.request(req)
46
+ end
47
+ Response.new(response.code.to_i, response.body.to_s)
48
+ rescue SocketError, SystemCallError, IOError, Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError => e
49
+ raise Unavailable, e.class.name
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json/jwt'
4
+ require 'omniauth/vitsme/keys'
5
+
6
+ module OmniAuth
7
+ module Vitsme
8
+ # Verifies a signed JWT from vits.me or a KNOT: RS256 against the keys at `jwks_uri`, then the claims
9
+ # the caller names. Raises JWS::Invalid with a short reason.
10
+ module JWS
11
+ LEEWAY = 30
12
+
13
+ class Invalid < StandardError; end
14
+
15
+ module_function
16
+
17
+ # The verified claims, as a Hash with string keys.
18
+ def verify!(token, jwks_uri:, iss:, aud:, typ: nil, expiring: true, now: Time.now)
19
+ claims = signed_claims(token, jwks_uri: jwks_uri, typ: typ)
20
+ raise Invalid, 'unexpected issuer' unless claims['iss'] == iss
21
+ raise Invalid, 'not addressed to you' unless Array(claims['aud']).include?(aud)
22
+ raise Invalid, 'expired' if expiring && claims['exp'].to_i + LEEWAY < now.to_i
23
+
24
+ claims
25
+ end
26
+
27
+ # The payload once the signature checks out. `alg: none` and every algorithm but RS256 are refused.
28
+ def signed_claims(token, jwks_uri:, typ:)
29
+ header = JSON::JWT.decode(token.to_s, :skip_verification).header
30
+ raise Invalid, 'unexpected type' if typ && header['typ'] != typ
31
+
32
+ keys = Keys.for(jwks_uri, kid: header['kid'])
33
+ JSON::JWT.decode(token.to_s, keys, [:RS256]).to_h.transform_keys(&:to_s)
34
+ rescue JSON::JWT::Exception => e
35
+ raise Invalid, e.class.name.split('::').last
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json/jwt'
4
+ require 'omniauth/vitsme/http'
5
+
6
+ module OmniAuth
7
+ module Vitsme
8
+ # Published signing keys (a JWKS URL's JSON::JWK::Set), cached per URL for TTL seconds and fetched again
9
+ # once when a token names a key the cache does not hold (rotation).
10
+ module Keys
11
+ TTL = 600
12
+
13
+ class Unavailable < StandardError; end
14
+
15
+ @cache = {}
16
+ @mutex = Mutex.new
17
+
18
+ class << self
19
+ def for(jwks_uri, kid:)
20
+ set = cached(jwks_uri)
21
+ return set if kid.nil? || set.any? { |jwk| jwk[:kid] == kid }
22
+
23
+ fetch(jwks_uri)
24
+ end
25
+
26
+ def clear!
27
+ @mutex.synchronize { @cache.clear }
28
+ end
29
+
30
+ private
31
+
32
+ def cached(jwks_uri)
33
+ entry = @mutex.synchronize { @cache[jwks_uri] }
34
+ return entry[:set] if entry && entry[:at] > Time.now - TTL
35
+
36
+ fetch(jwks_uri)
37
+ end
38
+
39
+ def fetch(jwks_uri)
40
+ response = HTTP.get(jwks_uri, 'Accept' => 'application/json')
41
+ raise Unavailable, "keys: HTTP #{response.status}" unless response.ok?
42
+
43
+ set = JSON::JWK::Set.new(response.json)
44
+ @mutex.synchronize { @cache[jwks_uri] = { set: set, at: Time.now } }
45
+ set
46
+ rescue JSON::ParserError, HTTP::Unavailable => e
47
+ raise Unavailable, "keys: #{e.message}"
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'base64'
4
+ require 'digest'
5
+ require 'json/jwt'
6
+ require 'securerandom'
7
+ require 'omniauth/vitsme/http'
8
+ require 'omniauth/vitsme/jws'
9
+ require 'omniauth/vitsme/keys'
10
+ require 'omniauth/vitsme/partner_directory'
11
+
12
+ module OmniAuth
13
+ module Vitsme
14
+ # Asking a partner of vits.me (a KNOT) about a person signed in to your site. Partners are OAuth servers
15
+ # of their own: your site is their client, asks them directly, and gets their answer straight from them.
16
+ # vits.me only signs the person in there and makes sure it is the person you mean, from the hint you
17
+ # send: the ID token vits.me gave you for them, encrypted to vits.me, so the partner cannot read it.
18
+ #
19
+ # The browser part is the `vitsme_partner` strategy (OmniAuth::Strategies::VitsmePartner). This module
20
+ # is the rest: whom to trust, the partner's endpoints, and asking again with a refresh token.
21
+ module Partner
22
+ STATEMENT_TYPE = 'software-statement+jwt'
23
+
24
+ # The partner refused: an OAuth error, with its description.
25
+ class Refused < StandardError; end
26
+
27
+ Result = Struct.new(:claims, :subject, :refresh_token, :scopes, keyword_init: true)
28
+
29
+ class << self
30
+ # Whom to trust and where its endpoints are (PartnerDirectory).
31
+ def listing(vitsme_issuer) = PartnerDirectory.listing(vitsme_issuer)
32
+ def trusted!(partner, vitsme_issuer) = PartnerDirectory.trusted!(partner, vitsme_issuer)
33
+ def metadata(partner) = PartnerDirectory.metadata(partner)
34
+ def clear! = PartnerDirectory.clear!
35
+
36
+ # The ID token you hold for the person, encrypted to vits.me's own key (use: enc in its JWKS), anew
37
+ # each time, so the partner can neither read it nor match one person's requests.
38
+ def hint(id_token, vitsme_issuer)
39
+ key = Keys.for("#{vitsme_issuer}/oauth/discovery/keys", kid: nil).find { |jwk| jwk[:use] == 'enc' }
40
+ raise Unavailable, 'vits.me publishes no encryption key' unless key
41
+
42
+ jwe = JSON::JWE.new(id_token.to_s)
43
+ jwe.alg = :'RSA-OAEP'
44
+ jwe.enc = :A256GCM
45
+ jwe.header[:cty] = 'JWT'
46
+ jwe.kid = key[:kid]
47
+ jwe.encrypt!(key.to_key)
48
+ jwe.to_s
49
+ end
50
+
51
+ # What vits.me says about your site, made out to one partner, for a partner that takes no
52
+ # registrations (it asks for one with each request) or for registering at one that does.
53
+ def software_statement(vitsme_issuer:, client_id:, client_secret:, audience:)
54
+ response = HTTP.post_form("#{vitsme_issuer}/oauth/software_statement", { audience: audience },
55
+ basic: [client_id, client_secret], headers: { 'Accept' => 'application/json' })
56
+ raise Refused, "vits.me: HTTP #{response.status}" unless response.ok?
57
+
58
+ response.json.fetch('software_statement')
59
+ end
60
+
61
+ # Registers your site at a partner that takes registrations (RFC 7591). Returns its answer: keep
62
+ # `client_secret`, which it shows once.
63
+ def register(partner:, software_statement:, events_uri: nil, app_roles: nil)
64
+ endpoint = metadata(partner)['registration_endpoint'] or raise Refused, "#{partner} takes no registrations"
65
+ body = { software_statement: software_statement, events_uri: events_uri, app_roles: app_roles }.compact
66
+ response = HTTP.post_json(endpoint, body)
67
+ raise Refused, refusal(response) unless response.status == 201
68
+
69
+ response.json
70
+ end
71
+
72
+ def pkce
73
+ verifier = SecureRandom.urlsafe_base64(48)
74
+ [verifier, Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)]
75
+ end
76
+
77
+ # Pushes the request (RFC 9126) and returns where to send the person.
78
+ def push(partner, params, basic: nil)
79
+ meta = metadata(partner)
80
+ response = HTTP.post_form(meta.fetch('pushed_authorization_request_endpoint'), params,
81
+ basic: basic, headers: { 'Accept' => 'application/json' })
82
+ raise Refused, refusal(response) unless response.status == 201
83
+
84
+ uri = URI(meta.fetch('authorization_endpoint'))
85
+ uri.query = URI.encode_www_form(client_id: params[:client_id],
86
+ request_uri: response.json.fetch('request_uri'))
87
+ uri.to_s
88
+ end
89
+
90
+ # Redeems the code the partner sent back, and fetches what the person agreed to.
91
+ def finish(partner:, client_id:, code:, redirect_uri:, code_verifier:, basic: nil)
92
+ tokens = token(partner, { grant_type: 'authorization_code', code: code, redirect_uri: redirect_uri,
93
+ code_verifier: code_verifier, client_id: client_id }, basic: basic)
94
+ result(partner, client_id, tokens)
95
+ end
96
+
97
+ # Asks again without the person, while their standing consent at the partner holds. Returns a
98
+ # Result with the next refresh token: the one you used is spent. Raises Refused when it does not
99
+ # hold any more: let go of what you had.
100
+ def fresh_claims(partner:, client_id:, partner_secret:, refresh_token:, vitsme_issuer:)
101
+ trusted!(partner, vitsme_issuer)
102
+ tokens = token(partner, { grant_type: 'refresh_token', refresh_token: refresh_token },
103
+ basic: [client_id, partner_secret])
104
+ result(partner, client_id, tokens)
105
+ end
106
+
107
+ private
108
+
109
+ def token(partner, form, basic:)
110
+ response = HTTP.post_form(metadata(partner).fetch('token_endpoint'), form,
111
+ basic: basic, headers: { 'Accept' => 'application/json' })
112
+ raise Refused, refusal(response) unless response.ok?
113
+
114
+ response.json
115
+ end
116
+
117
+ def result(partner, client_id, tokens)
118
+ meta = metadata(partner)
119
+ bearer = "Bearer #{tokens.fetch('access_token')}"
120
+ response = HTTP.get(meta.fetch('claims_endpoint'), 'Authorization' => bearer, 'Accept' => 'application/jwt')
121
+ raise Unavailable, "#{partner}: HTTP #{response.status}" unless response.ok?
122
+
123
+ claims = JWS.verify!(response.body, jwks_uri: meta.fetch('jwks_uri'), iss: partner, aud: client_id)
124
+ told = claims.except('iss', 'aud', 'sub', 'iat', 'exp')
125
+ Result.new(claims: told, subject: claims.fetch('sub'), refresh_token: tokens['refresh_token'],
126
+ scopes: tokens['scope'].to_s.split)
127
+ end
128
+
129
+ def refusal(response)
130
+ body = response.json
131
+ [body['error'], body['error_description']].compact.join(': ')
132
+ rescue JSON::ParserError
133
+ "HTTP #{response.status}"
134
+ end
135
+ end
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'omniauth/vitsme/http'
4
+
5
+ module OmniAuth
6
+ module Vitsme
7
+ module Partner
8
+ class Unavailable < StandardError; end
9
+ # vits.me does not list the partner as active: ask it nothing, and trust nothing it says.
10
+ class Untrusted < StandardError; end
11
+ end
12
+
13
+ # Whom to trust, and where each partner's endpoints are: vits.me's listing of partners, and each
14
+ # partner's own authorization server metadata (RFC 8414), both cached. Partner delegates to it.
15
+ module PartnerDirectory
16
+ LISTING_TTL = 300
17
+ METADATA_TTL = 3600
18
+
19
+ @cache = {}
20
+ @mutex = Mutex.new
21
+
22
+ class << self
23
+ # vits.me's listing of partners (GET /knot/partners), cached for minutes.
24
+ def listing(vitsme_issuer)
25
+ cached("listing #{vitsme_issuer}", LISTING_TTL) do
26
+ response = HTTP.get("#{vitsme_issuer}/knot/partners", 'Accept' => 'application/json')
27
+ raise Partner::Unavailable, "vits.me: HTTP #{response.status}" unless response.ok?
28
+
29
+ response.json.fetch('partners')
30
+ end
31
+ end
32
+
33
+ def trusted!(partner, vitsme_issuer)
34
+ entry = listing(vitsme_issuer).find { |listed| listed['issuer'] == partner }
35
+ unless entry && entry['status'] == 'active'
36
+ raise Partner::Untrusted, "#{partner} is not an active partner of vits.me"
37
+ end
38
+
39
+ entry
40
+ end
41
+
42
+ # The partner's metadata, cached for an hour, and only if it is about the partner itself.
43
+ def metadata(partner)
44
+ cached("metadata #{partner}", METADATA_TTL) do
45
+ response = HTTP.get("#{partner}/.well-known/oauth-authorization-server", 'Accept' => 'application/json')
46
+ raise Partner::Unavailable, "#{partner}: HTTP #{response.status}" unless response.ok?
47
+
48
+ document = response.json
49
+ raise Partner::Unavailable, "#{partner}: metadata for another issuer" unless document['issuer'] == partner
50
+
51
+ document
52
+ end
53
+ end
54
+
55
+ def clear!
56
+ @mutex.synchronize { @cache.clear }
57
+ end
58
+
59
+ private
60
+
61
+ def cached(key, ttl)
62
+ entry = @mutex.synchronize { @cache[key] }
63
+ return entry[:value] if entry && entry[:at] > Time.now - ttl
64
+
65
+ value = yield
66
+ @mutex.synchronize { @cache[key] = { value: value, at: Time.now } }
67
+ value
68
+ rescue HTTP::Unavailable, JSON::ParserError, KeyError => e
69
+ raise Partner::Unavailable, e.message
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
@@ -13,6 +13,7 @@ module OmniAuth
13
13
  # OmniAuth::Vitsme::Test.mock_auth(claims: { age__over_18: true }) # provider :vitsme
14
14
  # OmniAuth::Vitsme::Test.mock_auth(:verify, uid: person.vitsme_uid, claims: { name: 'Jane D.' })
15
15
  # OmniAuth::Vitsme::Test.mock_failure(:vitsme, :nationality_gate_refused)
16
+ # OmniAuth::Vitsme::Test.mock_partner(:contacts, partner: 'https://contacts.example', claims: { email: [...] })
16
17
  #
17
18
  # The auth hash is built by the same code as the real strategy's (AuthShape), so `info`, `extra`
18
19
  # and the typed claims look exactly as they will in production. Test mode skips the trip to vits.me
@@ -57,6 +58,21 @@ module OmniAuth
57
58
  OmniAuth.config.mock_auth[provider.to_sym] = auth_hash(provider, **)
58
59
  end
59
60
 
61
+ # A partner's answer (the vitsme_partner strategy), as your callback gets it. `claims` is whatever the
62
+ # partner says, passed through as it is; `subject` stands for the partner's identifier for the person.
63
+ def partner_auth_hash(provider, partner:, claims: {}, subject: nil, refresh_token: nil)
64
+ claims = claims.transform_keys(&:to_s)
65
+ subject ||= "ks_#{SecureRandom.urlsafe_base64(32)}"
66
+ OmniAuth::AuthHash.new(provider: provider.to_s, uid: subject, info: {},
67
+ credentials: { refresh_token: refresh_token }.compact,
68
+ extra: { partner: partner, claims: claims, scopes: claims.keys })
69
+ end
70
+
71
+ # Makes the next callback for a vitsme_partner `provider` succeed with this answer.
72
+ def mock_partner(provider, **)
73
+ OmniAuth.config.mock_auth[provider.to_sym] = partner_auth_hash(provider, **)
74
+ end
75
+
60
76
  # Makes the next callback for `provider` fail with `type` (e.g. :identity_mismatch, :not_signed_in,
61
77
  # :unverified_identity, :nationality_gate_refused, :site_suspended, :access_denied).
62
78
  def mock_failure(provider = :vitsme, type = :access_denied)
@@ -2,6 +2,6 @@
2
2
 
3
3
  module OmniAuth
4
4
  module Vitsme
5
- VERSION = '0.3.0'
5
+ VERSION = '0.5.0'
6
6
  end
7
7
  end
@@ -4,4 +4,7 @@ require 'omniauth/vitsme/version'
4
4
  require 'omniauth/vitsme/issuers'
5
5
  require 'omniauth/vitsme/catalog'
6
6
  require 'omniauth/vitsme/auth_shape'
7
+ require 'omniauth/vitsme/partner'
8
+ require 'omniauth/vitsme/events'
7
9
  require 'omniauth/strategies/vitsme'
10
+ require 'omniauth/strategies/vitsme_partner'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: omniauth-vitsme
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Yuval Tobias
@@ -46,10 +46,17 @@ files:
46
46
  - lib/generators/omniauth_vitsme/install/templates/vitsme_callbacks_controller.rb.tt
47
47
  - lib/omniauth-vitsme.rb
48
48
  - lib/omniauth/strategies/vitsme.rb
49
+ - lib/omniauth/strategies/vitsme_partner.rb
49
50
  - lib/omniauth/vitsme.rb
50
51
  - lib/omniauth/vitsme/auth_shape.rb
51
52
  - lib/omniauth/vitsme/catalog.rb
53
+ - lib/omniauth/vitsme/events.rb
54
+ - lib/omniauth/vitsme/http.rb
52
55
  - lib/omniauth/vitsme/issuers.rb
56
+ - lib/omniauth/vitsme/jws.rb
57
+ - lib/omniauth/vitsme/keys.rb
58
+ - lib/omniauth/vitsme/partner.rb
59
+ - lib/omniauth/vitsme/partner_directory.rb
53
60
  - lib/omniauth/vitsme/test.rb
54
61
  - lib/omniauth/vitsme/version.rb
55
62
  - llms.txt