omniauth-vitsme 0.4.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: 6b035cc18e25e105be04f7bb8f4a97ab65ae642cf4496efed8029311f73bcd8d
4
- data.tar.gz: 44f4d03aecd52c51abf90fead1e1326508791192563149ebe854101f4409fcf6
3
+ metadata.gz: fe1046427776ebdb907dcc848a56718b386960ea66222aa903a1e1a63876049b
4
+ data.tar.gz: 86549c0e17bfbb4359c131818c5058748a2af1ccc37c96625b7d2a28cc6f1e40
5
5
  SHA512:
6
- metadata.gz: 8ae6b954c46918c6e03104a3d81f153add7d6c44a1d3a227a9fd534f03566b37c330a70d2a76a63111830113b29e3a98ff0556dfb99a7aa01c7becee82980df6
7
- data.tar.gz: 8ea8e3002b36594fb4c998be15515887b8801c26bcde6a57d17dda4c4fc7add6d0c06d1dcf04248b9dc919e2ec200088e0a10fbd821474c772df6fc048f1f8a4
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. The one
34
- exception is KNOT claims, below.
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,15 +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. **KNOT claims come from partners, and partners come and go.** Don't hard-code a partner or the
46
- shape of its claims from memory: read the scope's description and documentation link from
47
- `OmniAuth::Vitsme::Knot.scopes` (or the site's page at vits.me/developer). Claims arrive in
48
- `extra.knot_claims`, already verified; missing is unknown, and a partner that can't be asked shows
49
- in `extra.knot_errors` without failing the sign-in. While the person's consent stands, refresh with
50
- `OmniAuth::Vitsme::Knot.fresh_claims`, and handle `ConsentRequired` by letting go of what you had.
51
- 13. **Verify every change event** with `OmniAuth::Vitsme::Events.verify!` before acting on it, answer
52
- `202`, and treat it as idempotent. It never carries values: refetch on `:claims_changed`, forget on
53
- `:consent_withdrawn`, whose `reason` is `withdrawn` (the person) or `retired` (the partner left).
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`.
54
56
 
55
57
  ## Doing the work
56
58
 
data/CHANGELOG.md CHANGED
@@ -7,6 +7,29 @@ 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
+
10
33
  ## [0.4.0] - 2026-11-10
11
34
 
12
35
  ### 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.4"
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,59 +158,89 @@ 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 (KNOT claims)
161
+ ## Partner services (KNOTs)
162
162
 
163
- Some facts come from partner services rather than vits.me. Partners come and go, so this gem knows none
164
- of them: it handles whatever KNOT scopes your site chose to work with. The active ones, each with what its
165
- answer holds and a documentation link, are listed by vits.me; choose them under Partners on your site's
166
- form at vits.me/developer, and its page there shows the ones it holds:
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:
167
169
 
168
170
  ```ruby
169
- OmniAuth::Vitsme::Knot.scopes # [{ "scope" => "knot:<knot>:<name>", "knot" => "…", "claim" => "…",
170
- # "title" => {…}, "description" => {…}, "documentation_url" => "…" }]
171
+ OmniAuth::Vitsme::Partner.listing(OmniAuth::Vitsme.issuer(:production))
172
+ # [{ "name" => "…", "issuer" => "https://…", "status" => "active", "scopes" => [{ "name" => "…", "title" => {…}, … }] }]
171
173
  ```
172
174
 
173
- Ask for one like any other scope:
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:
174
183
 
175
184
  ```ruby
176
- provider :vitsme, client_id: ENV["VITSME_APP_ID"], client_secret: ENV["VITSME_APP_SECRET"],
177
- scope: %i[openid knot:<knot>:<name>]
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
178
192
  ```
179
193
 
180
- The person agrees on vits.me's consent screen. During the callback the strategy fetches the partner's
181
- answer, verifies its signature, and hands you the claims as the partner sent them:
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:
182
198
 
183
199
  ```ruby
184
- auth.extra.knot_claims # { "<claim>" => <the partner's answer> }; its shape is in the partner's documentation
185
- auth.extra.knot_errors # { "<knot>" => "HTTP 503" } when a partner could not be asked
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 }
186
206
  ```
187
207
 
188
- A claim missing from `knot_claims` is unknown, never false. A partner that cannot be reached never
189
- fails the sign-in.
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:
190
210
 
191
- **Fresh claims, without the person.** While they keep the consent (a year from their last agreement),
192
- ask again:
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:
193
222
 
194
223
  ```ruby
195
- result = OmniAuth::Vitsme::Knot.fresh_claims(uid: person.vitsme_uid, scopes: %w[knot:<knot>:<name>],
196
- client_id: ENV["VITSME_APP_ID"], client_secret: ENV["VITSME_APP_SECRET"])
197
- result.claims # as above
198
- # raises OmniAuth::Vitsme::Knot::ConsentRequired once they no longer share it
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
199
230
  ```
200
231
 
201
- **Change events.** Set a change notifications URL on your site's page, and vits.me POSTs to it when a
202
- partner says something changed for someone, when they stop sharing, or when a partner or scope leaves.
203
- Verify each one:
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:
204
234
 
205
235
  ```ruby
206
- class VitsmeEventsController < ActionController::API
236
+ class PartnerEventsController < ActionController::API
207
237
  def create
208
- event = OmniAuth::Vitsme::Events.verify!(request.raw_post, client_id: ENV["VITSME_APP_ID"],
209
- environment: Rails.env)
210
- person = Person.find_by(vitsme_uid: event.uid)
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
211
241
  case event.type
212
- when :claims_changed then RefreshPartnerClaimsJob.perform_later(person.id, event.scopes) if person
213
- when :consent_withdrawn then person&.forget_partner_claims!(event.scopes) # event.reason: "withdrawn" or "retired"
242
+ when :claims_changed then RefreshPartnerClaimsJob.perform_later(link.id) if link
243
+ when :consent_withdrawn then link&.destroy
214
244
  end
215
245
  head :accepted
216
246
  rescue OmniAuth::Vitsme::Events::Invalid
@@ -219,8 +249,6 @@ class VitsmeEventsController < ActionController::API
219
249
  end
220
250
  ```
221
251
 
222
- Events never carry values, may arrive twice, and are retried until you answer `202`.
223
-
224
252
  ## Finding a returning person
225
253
 
226
254
  Look a person up by `extra.lookup_uids`, current uid first, plus `extra.fluid_uids` if you use FLUID.
@@ -263,9 +291,7 @@ OmniAuth sends failures to `OmniAuth.config.on_failure` (in Rails, `/auth/failur
263
291
  lookup_uids: ["solid_…", "solid_<earlier>"],
264
292
  fluid_uids: [],
265
293
  claims: { "name" => "Jane D.", "age__over_18" => true }, # typed, shared claims only
266
- knot_claims: { "<claim>" => … }, # from partner services, verified
267
- knot_errors: {}, # partners that could not be asked
268
- raw_info: { "sub" => "solid_…", … } # the UserInfo response, without KNOT sources
294
+ raw_info: { "sub" => "solid_…", … } # the UserInfo response
269
295
  }
270
296
  }
271
297
  ```
data/data/claims.json CHANGED
@@ -150,12 +150,10 @@
150
150
  }
151
151
  },
152
152
  "knots": {
153
- "scope_pattern": "^knot:[^:\\s]+:\\S+$",
154
- "scope_format": "knot:<knot>:<name>",
155
- "description": "Claims from a partner service (a KNOT) that verifies what vits.me does not, served to your site directly. Partners come and go, so none is listed here: GET <issuer>/knot/scopes lists the active KNOT scopes, each with what its answer holds and a documentation URL (OmniAuth::Vitsme::Knot.scopes), and your site's page at vits.me/developer shows the ones staff granted it. The person agrees on vits.me's consent screen; left on, the agreement stands for a year and can be withdrawn at any time. When a partner leaves, its consents end and you get consent_withdrawn with reason retired.",
156
- "auth_hash": "extra.knot_claims (by claim name, fetched and verified during the callback) and extra.knot_errors (by source). Missing is unknown, never false.",
157
- "fresh_claims": "While the consent stands: OmniAuth::Vitsme::Knot.fresh_claims(uid:, scopes:, client_id:, client_secret:). Raises ConsentRequired once it no longer does.",
158
- "events": "Set a change notifications URL on your registration; verify each POST with OmniAuth::Vitsme::Events.verify! (types claims_changed, consent_withdrawn with reason withdrawn or retired) and answer 202."
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."
159
157
  },
160
158
  "refusals": {
161
159
  "nationality_gate": {
@@ -17,8 +17,7 @@ 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 KNOT scope (knot:<knot>:<name>) asks a partner service; its claims arrive verified in
21
- # extra.knot_claims (OmniAuth::Vitsme::Knot).
20
+ # A partner of vits.me (a KNOT) is asked with the vitsme_partner strategy, not here.
22
21
  #
23
22
  # See README.md for the auth hash, the failure types and the rules (the uid is private).
24
23
  class Vitsme < OpenIDConnect
@@ -83,21 +82,12 @@ module OmniAuth
83
82
  end
84
83
 
85
84
  def extra
86
- OmniAuth::Vitsme::AuthShape.extra(uid, raw_info, knot: knot)
87
- end
88
-
89
- # The KNOT sources in UserInfo, fetched and verified now: their introductions live 30 seconds.
90
- def knot
91
- return @knot if defined?(@knot)
92
-
93
- @knot = (if raw_info['_claim_sources']
94
- OmniAuth::Vitsme::Knot.resolve(raw_info,
95
- client_id: client_options.identifier)
96
- end)
85
+ OmniAuth::Vitsme::AuthShape.extra(uid, raw_info)
97
86
  end
98
87
 
99
88
  # vits.me issues no refresh token and its access token lapses five seconds after issue: everything
100
- # 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`).
101
91
  def credentials
102
92
  { id_token: access_token.id_token, scope: access_token.scope }
103
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
@@ -7,8 +7,6 @@ module OmniAuth
7
7
  module AuthShape
8
8
  SOLID_PREFIX = 'solid_'
9
9
  FLUID_PREFIX = 'fluid_'
10
- # Spent as soon as the strategy fetched them, and none of your app's business afterwards.
11
- KNOT_SOURCE_KEYS = %w[_claim_names _claim_sources knot_txn].freeze
12
10
 
13
11
  module_function
14
12
 
@@ -26,9 +24,7 @@ module OmniAuth
26
24
  }.compact
27
25
  end
28
26
 
29
- # `knot` is the Knot::Result for this sign-in's KNOT sources, if it had any.
30
- def extra(uid, raw_info, knot: nil)
31
- knot ||= Knot::Result.empty
27
+ def extra(uid, raw_info)
32
28
  {
33
29
  identity: identity_kind(uid),
34
30
  # Look a returning person up by every one of these, current first: a record keyed by a defunct
@@ -37,11 +33,7 @@ module OmniAuth
37
33
  # Tentative accounts (keyed by a pending signup's FLUID) to merge into this person.
38
34
  fluid_uids: Array(raw_info['fluid']),
39
35
  claims: claims(raw_info),
40
- # Claims from KNOTs, by claim name, already fetched and verified ({ "<claim>" => <answer> }),
41
- # and why a KNOT could not be asked, by source. A claim missing here is unknown, never false.
42
- knot_claims: knot.claims,
43
- knot_errors: knot.errors,
44
- raw_info: raw_info.except(*KNOT_SOURCE_KEYS)
36
+ raw_info: raw_info
45
37
  }
46
38
  end
47
39
 
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'json'
4
- require 'omniauth/vitsme/knot'
5
4
 
6
5
  module OmniAuth
7
6
  module Vitsme
@@ -32,10 +31,9 @@ module OmniAuth
32
31
  GATE_PATTERN.match?(scope.to_s)
33
32
  end
34
33
 
35
- # KNOT scopes (knot:<knot>:<name>) are registered data on vits.me, not catalog entries: any well-formed
36
- # one is accepted here, and vits.me refuses one your site was not granted.
34
+ # A partner's scopes are not asked of vits.me: they go to the partner (the vitsme_partner strategy).
37
35
  def known_scope?(scope)
38
- scopes.include?(scope.to_s) || gate_scope?(scope) || Knot.scope?(scope)
36
+ scopes.include?(scope.to_s) || gate_scope?(scope)
39
37
  end
40
38
 
41
39
  # The OmniAuth failure type for a `vitsme_error` refusal reason, or nil for an unknown one.
@@ -2,22 +2,20 @@
2
2
 
3
3
  require 'omniauth/vitsme/jws'
4
4
  require 'omniauth/vitsme/issuers'
5
+ require 'omniauth/vitsme/partner'
5
6
 
6
7
  module OmniAuth
7
8
  module Vitsme
8
- # The change events vits.me POSTs to your site's change notifications URL (Security Event Tokens,
9
- # RFC 8417, pushed per RFC 8935 with Content-Type application/secevent+jwt), while someone keeps a
10
- # standing consent with your site:
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.
11
12
  #
12
- # :claims_changed what a KNOT would tell you about them changed: ask again (Knot.fresh_claims)
13
- # :consent_withdrawn they stopped sharing (reason "withdrawn"), or the partner or scope left
14
- # (reason "retired"): let go of what you were given
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
15
16
  #
16
- # An event never carries values. Answer 202; anything else is retried. Events are idempotent and may
17
- # arrive twice.
18
- #
19
- # event = OmniAuth::Vitsme::Events.verify!(request.raw_post, client_id: ENV['VITSME_APP_ID'])
20
- # person = Person.find_by(vitsme_uid: event.uid) # the uid is private, as everywhere
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.
21
19
  module Events
22
20
  TYPES = {
23
21
  'https://vits.me/secevent/knot/claims-changed' => :claims_changed,
@@ -28,24 +26,26 @@ module OmniAuth
28
26
 
29
27
  class Invalid < StandardError; end
30
28
 
31
- Event = Struct.new(:type, :uid, :scopes, :reason, :id, :issued_at, keyword_init: true)
29
+ Event = Struct.new(:type, :uid, :scopes, :id, :issued_at, keyword_init: true)
32
30
 
33
31
  module_function
34
32
 
35
- def verify!(token, client_id:, environment: :production, issuer: nil, now: Time.now)
36
- issuer ||= Vitsme.issuer(environment)
37
- claims = JWS.verify!(token, jwks_uri: "#{issuer}/oauth/discovery/keys", iss: issuer, aud: client_id,
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
38
  typ: 'secevent+jwt', expiring: false, now: now)
39
39
  raise Invalid, 'stale or future event' unless (claims['iat'].to_i - now.to_i).abs <= MAX_AGE
40
40
 
41
- event(claims, issuer)
42
- rescue JWS::Invalid, Keys::Unavailable => e
41
+ event(claims)
42
+ rescue JWS::Invalid, Keys::Unavailable, Partner::Unavailable, Partner::Untrusted, KeyError => e
43
43
  raise Invalid, e.message
44
44
  end
45
45
 
46
- def event(claims, issuer)
46
+ def event(claims)
47
47
  sub_id = claims['sub_id']
48
- unless sub_id.is_a?(Hash) && sub_id['format'] == 'iss_sub' && sub_id['iss'] == issuer
48
+ unless sub_id.is_a?(Hash) && sub_id['format'] == 'opaque' && sub_id['id'].to_s != ''
49
49
  raise Invalid,
50
50
  'unsupported subject'
51
51
  end
@@ -53,9 +53,8 @@ module OmniAuth
53
53
  type_uri, body = Hash(claims['events']).find { |uri, _| TYPES.key?(uri) }
54
54
  raise Invalid, 'unsupported event' unless type_uri
55
55
 
56
- body = Hash(body)
57
- Event.new(type: TYPES[type_uri], uid: sub_id['sub'], scopes: body['scope'].to_s.split, reason: body['reason'],
58
- id: claims['jti'], issued_at: Time.at(claims['iat'].to_i))
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))
59
58
  end
60
59
  end
61
60
  end
@@ -31,6 +31,13 @@ module OmniAuth
31
31
  request(req)
32
32
  end
33
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
+
34
41
  def request(req)
35
42
  uri = req.uri
36
43
  response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https',
@@ -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,7 +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_auth(knot_claims: { '<claim>' => <what the partner answers> })
16
+ # OmniAuth::Vitsme::Test.mock_partner(:contacts, partner: 'https://contacts.example', claims: { email: [...] })
17
17
  #
18
18
  # The auth hash is built by the same code as the real strategy's (AuthShape), so `info`, `extra`
19
19
  # and the typed claims look exactly as they will in production. Test mode skips the trip to vits.me
@@ -41,17 +41,15 @@ module OmniAuth
41
41
  info.merge(claims)
42
42
  end
43
43
 
44
- def auth_hash(provider = :vitsme, identity: :solid, uid: nil, claims: {}, defunct_uids: [], fluid_uids: [],
45
- knot_claims: {}, knot_errors: {})
44
+ def auth_hash(provider = :vitsme, identity: :solid, uid: nil, claims: {}, defunct_uids: [], fluid_uids: [])
46
45
  uid ||= self.uid(identity)
47
46
  raw = raw_info(uid: uid, claims: claims, defunct_uids: defunct_uids, fluid_uids: fluid_uids)
48
- knot = Knot::Result.new(knot_claims.transform_keys(&:to_s), knot_errors.transform_keys(&:to_s))
49
47
  OmniAuth::AuthHash.new(
50
48
  provider: provider.to_s,
51
49
  uid: uid,
52
50
  info: AuthShape.info(uid, raw),
53
51
  credentials: { id_token: 'test.id.token', scope: 'openid' },
54
- extra: AuthShape.extra(uid, raw, knot: knot)
52
+ extra: AuthShape.extra(uid, raw)
55
53
  )
56
54
  end
57
55
 
@@ -60,6 +58,21 @@ module OmniAuth
60
58
  OmniAuth.config.mock_auth[provider.to_sym] = auth_hash(provider, **)
61
59
  end
62
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
+
63
76
  # Makes the next callback for `provider` fail with `type` (e.g. :identity_mismatch, :not_signed_in,
64
77
  # :unverified_identity, :nationality_gate_refused, :site_suspended, :access_denied).
65
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.4.0'
5
+ VERSION = '0.5.0'
6
6
  end
7
7
  end
@@ -4,6 +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/knot'
7
+ require 'omniauth/vitsme/partner'
8
8
  require 'omniauth/vitsme/events'
9
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.4.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Yuval Tobias
@@ -46,6 +46,7 @@ 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
@@ -54,7 +55,8 @@ files:
54
55
  - lib/omniauth/vitsme/issuers.rb
55
56
  - lib/omniauth/vitsme/jws.rb
56
57
  - lib/omniauth/vitsme/keys.rb
57
- - lib/omniauth/vitsme/knot.rb
58
+ - lib/omniauth/vitsme/partner.rb
59
+ - lib/omniauth/vitsme/partner_directory.rb
58
60
  - lib/omniauth/vitsme/test.rb
59
61
  - lib/omniauth/vitsme/version.rb
60
62
  - llms.txt
@@ -1,92 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'omniauth/vitsme/http'
4
- require 'omniauth/vitsme/jws'
5
- require 'omniauth/vitsme/issuers'
6
-
7
- module OmniAuth
8
- module Vitsme
9
- # Claims from KNOTs: partner services that verify what vits.me does not (organization memberships, for
10
- # one) and serve it to sites directly, with vits.me brokering identity and consent.
11
- #
12
- # vits.me's UserInfo names each KNOT source with an `endpoint`, an `access_token` (an introduction,
13
- # encrypted to the KNOT and opaque to you), and the KNOT's `iss` and `jwks_uri`. The KNOT answers with a
14
- # JWS, `aud` your client_id and `sub` the response's `knot_txn`. Introductions live 30 seconds and work
15
- # once, so the strategy fetches them while it builds the auth hash.
16
- module Knot
17
- # Partners come and go, so the gem knows none of them: any well-formed KNOT scope is accepted, and
18
- # vits.me refuses one your site was not granted.
19
- SCOPE_PATTERN = /\Aknot:[^:\s]+:\S+\z/
20
-
21
- class ConsentRequired < StandardError; end
22
- class InvalidClient < StandardError; end
23
- class Unavailable < StandardError; end
24
-
25
- # `claims` by claim name ({ "<claim>" => <answer> }); `errors` by source, for KNOTs that could not
26
- # be asked or whose answer did not verify. A claim missing from `claims` is unknown, never false.
27
- Result = Struct.new(:claims, :errors) do
28
- def self.empty = new({}, {})
29
- end
30
-
31
- module_function
32
-
33
- def scope?(scope) = SCOPE_PATTERN.match?(scope.to_s)
34
-
35
- # The active KNOT scopes, as vits.me describes them now (GET <issuer>/knot/scopes): each one's
36
- # `scope`, `knot`, `claim`, `title`, `description` and `documentation_url`. For developers and their
37
- # tools; signing in never depends on it. Raises Unavailable.
38
- def scopes(environment: :production, issuer: nil)
39
- response = HTTP.get("#{issuer || Vitsme.issuer(environment)}/knot/scopes", 'Accept' => 'application/json')
40
- raise Unavailable, "vits.me: HTTP #{response.status}" unless response.ok?
41
-
42
- response.json.fetch('knot_scopes')
43
- rescue HTTP::Unavailable, JSON::ParserError, KeyError => e
44
- raise Unavailable, e.message
45
- end
46
-
47
- # Fetches and verifies every KNOT source in a UserInfo (or POST /knot/introductions) response.
48
- def resolve(response, client_id:)
49
- names = response['_claim_names'] || {}
50
- sources = response['_claim_sources'] || {}
51
- txn = response['knot_txn']
52
- sources.each_with_object(Result.empty) do |(source, spec), result|
53
- answer = answer(spec, client_id: client_id, txn: txn)
54
- names.each { |claim, from| result.claims[claim] = answer[claim] if from == source && answer.key?(claim) }
55
- rescue JWS::Invalid, Keys::Unavailable, HTTP::Unavailable, Unavailable => e
56
- result.errors[source] = e.message
57
- end
58
- end
59
-
60
- # Fresh KNOT claims about someone, without them present, while they keep a standing consent with your
61
- # site: vits.me introduces your site to each KNOT again. `uid` is the person's uid at your site.
62
- # Raises ConsentRequired when nothing asked for is still agreed, InvalidClient for wrong credentials,
63
- # and Unavailable when vits.me cannot be reached.
64
- def fresh_claims(uid:, scopes:, client_id:, client_secret:, environment: :production, issuer: nil)
65
- issuer ||= Vitsme.issuer(environment)
66
- response = HTTP.post_form("#{issuer}/knot/introductions", { sub: uid, scope: Array(scopes).join(' ') },
67
- basic: [client_id, client_secret], headers: { 'Accept' => 'application/json' })
68
- case response.status
69
- when 200 then resolve(response.json, client_id: client_id)
70
- when 403 then raise ConsentRequired, 'the person does not let your site be told this'
71
- when 401 then raise InvalidClient, 'vits.me did not accept the client credentials'
72
- else raise Unavailable, "vits.me: HTTP #{response.status}"
73
- end
74
- rescue HTTP::Unavailable, JSON::ParserError => e
75
- raise Unavailable, e.message
76
- end
77
-
78
- def answer(spec, client_id:, txn:)
79
- response = HTTP.get(spec.fetch('endpoint'), 'Authorization' => "Bearer #{spec.fetch('access_token')}",
80
- 'Accept' => 'application/jwt')
81
- raise Unavailable, "HTTP #{response.status}" unless response.ok?
82
-
83
- claims = JWS.verify!(response.body, jwks_uri: spec.fetch('jwks_uri'), iss: spec.fetch('iss'), aud: client_id)
84
- raise JWS::Invalid, 'answer for another transaction' unless txn && claims['sub'] == txn
85
-
86
- claims
87
- rescue KeyError
88
- raise Unavailable, 'incomplete source'
89
- end
90
- end
91
- end
92
- end