-
-
Notifications
You must be signed in to change notification settings - Fork 934
/
strategy_settings.go
544 lines (449 loc) · 16.5 KB
/
strategy_settings.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oidc
import (
"bytes"
"context"
_ "embed"
"encoding/json"
"net/http"
"time"
"github.com/ory/x/sqlxx"
"github.com/tidwall/sjson"
"github.com/ory/kratos/continuity"
"github.com/ory/kratos/selfservice/strategy"
"github.com/ory/x/decoderx"
"github.com/ory/kratos/session"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
"github.com/ory/herodot"
"github.com/ory/jsonschema/v3"
"github.com/ory/kratos/identity"
"github.com/ory/kratos/selfservice/flow"
"github.com/ory/kratos/selfservice/flow/settings"
"github.com/ory/kratos/x"
)
//go:embed .schema/settings.schema.json
var settingsSchema []byte
var (
_ settings.Strategy = new(Strategy)
UnknownConnectionValidationError = &jsonschema.ValidationError{
Message: "can not unlink non-existing OpenID Connect connection", InstancePtr: "#/",
}
)
var ConnectionExistValidationError = &jsonschema.ValidationError{
Message: "can not link unknown or already existing OpenID Connect connection", InstancePtr: "#/",
}
var UnlinkAllFirstFactorConnectionsError = &jsonschema.ValidationError{
Message: "can not unlink OpenID Connect connection because it is the last remaining first factor credential", InstancePtr: "#/",
}
func (s *Strategy) RegisterSettingsRoutes(router *x.RouterPublic) {}
func (s *Strategy) SettingsStrategyID() string {
return s.ID().String()
}
func (s *Strategy) decoderSettings(p *updateSettingsFlowWithOidcMethod, r *http.Request) error {
ds, err := s.d.Config().DefaultIdentityTraitsSchemaURL(r.Context())
if err != nil {
return err
}
raw, err := sjson.SetBytes(settingsSchema,
"properties.traits.$ref", ds.String()+"#/properties/traits")
if err != nil {
return errors.WithStack(err)
}
compiler, err := decoderx.HTTPRawJSONSchemaCompiler(raw)
if err != nil {
return errors.WithStack(err)
}
if err := s.dec.Decode(r, &p, compiler,
decoderx.HTTPKeepRequestBody(true),
decoderx.HTTPDecoderUseQueryAndBody(),
decoderx.HTTPDecoderSetValidatePayloads(false),
decoderx.HTTPDecoderAllowedMethods("POST", "GET"),
decoderx.HTTPDecoderJSONFollowsFormFormat()); err != nil {
return errors.WithStack(err)
}
return nil
}
func (s *Strategy) linkedProviders(ctx context.Context, r *http.Request, conf *ConfigurationCollection, confidential *identity.Identity) ([]Provider, error) {
creds, ok := confidential.GetCredentials(s.ID())
if !ok {
return nil, nil
}
var available identity.CredentialsOIDC
if err := json.Unmarshal(creds.Config, &available); err != nil {
return nil, errors.WithStack(err)
}
var result []Provider
for _, p := range available.Providers {
prov, err := conf.Provider(p.Provider, s.d)
if errors.Is(err, herodot.ErrNotFound) {
continue
} else if err != nil {
return nil, err
}
result = append(result, prov)
}
return result, nil
}
func (s *Strategy) linkableProviders(ctx context.Context, r *http.Request, conf *ConfigurationCollection, confidential *identity.Identity) ([]Provider, error) {
var available identity.CredentialsOIDC
creds, ok := confidential.GetCredentials(s.ID())
if ok {
if err := json.Unmarshal(creds.Config, &available); err != nil {
return nil, errors.WithStack(err)
}
}
var result []Provider
for _, p := range conf.Providers {
var found bool
for _, pp := range available.Providers {
if pp.Provider == p.ID {
found = true
break
}
}
if !found {
prov, err := conf.Provider(p.ID, s.d)
if err != nil {
return nil, err
}
result = append(result, prov)
}
}
return result, nil
}
func (s *Strategy) PopulateSettingsMethod(r *http.Request, id *identity.Identity, sr *settings.Flow) error {
if sr.Type != flow.TypeBrowser {
return nil
}
conf, err := s.Config(r.Context())
if err != nil {
return err
}
confidential, err := s.d.PrivilegedIdentityPool().GetIdentityConfidential(r.Context(), id.ID)
if err != nil {
return err
}
linkable, err := s.linkableProviders(r.Context(), r, conf, confidential)
if err != nil {
return err
}
linked, err := s.linkedProviders(r.Context(), r, conf, confidential)
if err != nil {
return err
}
sr.UI.GetNodes().Remove("unlink", "link")
sr.UI.SetCSRF(s.d.GenerateCSRFToken(r))
for _, l := range linkable {
// We do not want to offer to link SSO providers in the settings.
if l.Config().OrganizationID != "" {
continue
}
sr.UI.GetNodes().Append(NewLinkNode(l.Config().ID))
}
count, err := s.d.IdentityManager().CountActiveFirstFactorCredentials(r.Context(), confidential)
if err != nil {
return err
}
if count > 1 {
// This means that we're able to remove a connection because it is the last configured credential. If it is
// removed, the identity is no longer able to sign in.
for _, l := range linked {
sr.UI.GetNodes().Append(NewUnlinkNode(l.Config().ID))
}
}
return nil
}
// Update Settings Flow with OpenID Connect Method
//
// swagger:model updateSettingsFlowWithOidcMethod
//
//nolint:deadcode,unused
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type updateSettingsFlowWithOidcMethod struct {
// Method
//
// Should be set to profile when trying to update a profile.
//
// required: true
Method string `json:"method"`
// Link this provider
//
// Either this or `unlink` must be set.
//
// type: string
// in: body
Link string `json:"link"`
// Unlink this provider
//
// Either this or `link` must be set.
//
// type: string
// in: body
Unlink string `json:"unlink"`
// Flow ID is the flow's ID.
//
// in: query
FlowID string `json:"flow"`
// The identity's traits
//
// in: body
Traits json.RawMessage `json:"traits"`
// UpstreamParameters are the parameters that are passed to the upstream identity provider.
//
// These parameters are optional and depend on what the upstream identity provider supports.
// Supported parameters are:
// - `login_hint` (string): The `login_hint` parameter suppresses the account chooser and either pre-fills the email box on the sign-in form, or selects the proper session.
// - `hd` (string): The `hd` parameter limits the login/registration process to a Google Organization, e.g. `mycollege.edu`.
// - `prompt` (string): The `prompt` specifies whether the Authorization Server prompts the End-User for reauthentication and consent, e.g. `select_account`.
//
// required: false
UpstreamParameters json.RawMessage `json:"upstream_parameters"`
// Transient data to pass along to any webhooks
//
// required: false
TransientPayload json.RawMessage `json:"transient_payload,omitempty" form:"transient_payload"`
}
func (p *updateSettingsFlowWithOidcMethod) GetFlowID() uuid.UUID {
return x.ParseUUID(p.FlowID)
}
func (p *updateSettingsFlowWithOidcMethod) SetFlowID(rid uuid.UUID) {
p.FlowID = rid.String()
}
func (s *Strategy) Settings(w http.ResponseWriter, r *http.Request, f *settings.Flow, ss *session.Session) (*settings.UpdateContext, error) {
var p updateSettingsFlowWithOidcMethod
if err := s.decoderSettings(&p, r); err != nil {
return nil, err
}
f.TransientPayload = p.TransientPayload
ctxUpdate, err := settings.PrepareUpdate(s.d, w, r, f, ss, settings.ContinuityKey(s.SettingsStrategyID()), &p)
if errors.Is(err, settings.ErrContinuePreviousAction) {
if !s.d.Config().SelfServiceStrategy(r.Context(), s.SettingsStrategyID()).Enabled {
return nil, errors.WithStack(herodot.ErrNotFound.WithReason(strategy.EndpointDisabledMessage))
}
if l := len(p.Link); l > 0 {
if err := s.initLinkProvider(w, r, ctxUpdate, &p); err != nil {
return nil, err
}
return ctxUpdate, nil
} else if u := len(p.Unlink); u > 0 {
if err := s.unlinkProvider(w, r, ctxUpdate, &p); err != nil {
return nil, err
}
return ctxUpdate, nil
}
return nil, s.handleSettingsError(w, r, ctxUpdate, &p, errors.WithStack(herodot.ErrInternalServerError.WithReason("Expected either link or unlink to be set when continuing flow but both are unset.")))
} else if err != nil {
return nil, s.handleSettingsError(w, r, ctxUpdate, &p, err)
}
if len(p.Link+p.Unlink) == 0 {
return nil, errors.WithStack(flow.ErrStrategyNotResponsible)
}
if !s.d.Config().SelfServiceStrategy(r.Context(), s.SettingsStrategyID()).Enabled {
return nil, errors.WithStack(herodot.ErrNotFound.WithReason(strategy.EndpointDisabledMessage))
}
if l, u := len(p.Link), len(p.Unlink); l > 0 && u > 0 {
return nil, s.handleSettingsError(w, r, ctxUpdate, &p, errors.WithStack(&jsonschema.ValidationError{
Message: "it is not possible to link and unlink providers in the same request",
InstancePtr: "#/",
}))
} else if l > 0 {
if err := s.initLinkProvider(w, r, ctxUpdate, &p); err != nil {
return nil, err
}
return ctxUpdate, nil
} else if u > 0 {
if err := s.unlinkProvider(w, r, ctxUpdate, &p); err != nil {
return nil, err
}
return ctxUpdate, nil
}
return nil, s.handleSettingsError(w, r, ctxUpdate, &p, errors.WithStack(errors.WithStack(&jsonschema.ValidationError{
Message: "missing properties: link, unlink", InstancePtr: "#/",
Context: &jsonschema.ValidationErrorContextRequired{Missing: []string{"link", "unlink"}},
})))
}
func (s *Strategy) isLinkable(r *http.Request, ctxUpdate *settings.UpdateContext, toLink string) (*identity.Identity, error) {
providers, err := s.Config(r.Context())
if err != nil {
return nil, err
}
i, err := s.d.PrivilegedIdentityPool().GetIdentityConfidential(r.Context(), ctxUpdate.Session.Identity.ID)
if err != nil {
return nil, err
}
linkable, err := s.linkableProviders(r.Context(), r, providers, i)
if err != nil {
return nil, err
}
var found bool
for _, available := range linkable {
if toLink == available.Config().ID {
found = true
}
}
if !found {
return nil, errors.WithStack(ConnectionExistValidationError)
}
return i, nil
}
func (s *Strategy) initLinkProvider(w http.ResponseWriter, r *http.Request, ctxUpdate *settings.UpdateContext, p *updateSettingsFlowWithOidcMethod) error {
if _, err := s.isLinkable(r, ctxUpdate, p.Link); err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
if ctxUpdate.Session.AuthenticatedAt.Add(s.d.Config().SelfServiceFlowSettingsPrivilegedSessionMaxAge(r.Context())).Before(time.Now()) {
return s.handleSettingsError(w, r, ctxUpdate, p, errors.WithStack(settings.NewFlowNeedsReAuth()))
}
provider, err := s.provider(r.Context(), r, p.Link)
if err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
req, err := s.validateFlow(r.Context(), r, ctxUpdate.Flow.ID)
if err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
state := generateState(ctxUpdate.Flow.ID.String())
if err := s.d.ContinuityManager().Pause(r.Context(), w, r, sessionName,
continuity.WithPayload(&AuthCodeContainer{
State: state.String(),
FlowID: ctxUpdate.Flow.ID.String(),
Traits: p.Traits,
}),
continuity.WithLifespan(time.Minute*30)); err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
var up map[string]string
if err := json.NewDecoder(bytes.NewBuffer(p.UpstreamParameters)).Decode(&up); err != nil {
return err
}
codeURL, err := getAuthRedirectURL(r.Context(), provider, req, state, up)
if err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
if x.IsJSONRequest(r) {
s.d.Writer().WriteError(w, r, flow.NewBrowserLocationChangeRequiredError(codeURL))
} else {
http.Redirect(w, r, codeURL, http.StatusSeeOther)
}
return errors.WithStack(flow.ErrCompletedByStrategy)
}
func (s *Strategy) linkProvider(w http.ResponseWriter, r *http.Request, ctxUpdate *settings.UpdateContext, token *identity.CredentialsOIDCEncryptedTokens, claims *Claims, provider Provider) error {
p := &updateSettingsFlowWithOidcMethod{
Link: provider.Config().ID, FlowID: ctxUpdate.Flow.ID.String(),
}
if ctxUpdate.Session.AuthenticatedAt.Add(s.d.Config().SelfServiceFlowSettingsPrivilegedSessionMaxAge(r.Context())).Before(time.Now()) {
return s.handleSettingsError(w, r, ctxUpdate, p, errors.WithStack(settings.NewFlowNeedsReAuth()))
}
i, err := s.isLinkable(r, ctxUpdate, p.Link)
if err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
if err := s.linkCredentials(r.Context(), i, token, provider.Config().ID, claims.Subject, provider.Config().OrganizationID); err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
if err := s.d.SettingsHookExecutor().PostSettingsHook(w, r, s.SettingsStrategyID(), ctxUpdate, i, settings.WithCallback(func(ctxUpdate *settings.UpdateContext) error {
return s.PopulateSettingsMethod(r, ctxUpdate.Session.Identity, ctxUpdate.Flow)
})); err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
return nil
}
func (s *Strategy) unlinkProvider(w http.ResponseWriter, r *http.Request, ctxUpdate *settings.UpdateContext, p *updateSettingsFlowWithOidcMethod) error {
if ctxUpdate.Session.AuthenticatedAt.Add(s.d.Config().SelfServiceFlowSettingsPrivilegedSessionMaxAge(r.Context())).Before(time.Now()) {
return s.handleSettingsError(w, r, ctxUpdate, p, errors.WithStack(settings.NewFlowNeedsReAuth()))
}
providers, err := s.Config(r.Context())
if err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
i, err := s.d.PrivilegedIdentityPool().GetIdentityConfidential(r.Context(), ctxUpdate.Session.Identity.ID)
if err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
availableProviders, err := s.linkedProviders(r.Context(), r, providers, i)
if err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
var cc identity.CredentialsOIDC
creds, err := i.ParseCredentials(s.ID(), &cc)
if err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
count, err := s.d.IdentityManager().CountActiveFirstFactorCredentials(r.Context(), i)
if err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
if count < 2 {
return s.handleSettingsError(w, r, ctxUpdate, p, errors.WithStack(UnlinkAllFirstFactorConnectionsError))
}
var found bool
var updatedProviders []identity.CredentialsOIDCProvider
var updatedIdentifiers []string
for _, available := range availableProviders {
if p.Unlink == available.Config().ID {
for _, link := range cc.Providers {
if link.Provider != p.Unlink {
updatedIdentifiers = append(updatedIdentifiers, identity.OIDCUniqueID(link.Provider, link.Subject))
updatedProviders = append(updatedProviders, link)
} else {
found = true
}
}
}
}
if !found {
return s.handleSettingsError(w, r, ctxUpdate, p, errors.WithStack(UnknownConnectionValidationError))
}
creds.Identifiers = updatedIdentifiers
creds.Config, err = json.Marshal(&identity.CredentialsOIDC{Providers: updatedProviders})
if err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, errors.WithStack(err))
}
i.Credentials[s.ID()] = *creds
if err := s.d.SettingsHookExecutor().PostSettingsHook(w, r, s.SettingsStrategyID(), ctxUpdate, i, settings.WithCallback(func(ctxUpdate *settings.UpdateContext) error {
return s.PopulateSettingsMethod(r, ctxUpdate.Session.Identity, ctxUpdate.Flow)
})); err != nil {
return s.handleSettingsError(w, r, ctxUpdate, p, err)
}
return errors.WithStack(flow.ErrCompletedByStrategy)
}
func (s *Strategy) handleSettingsError(w http.ResponseWriter, r *http.Request, ctxUpdate *settings.UpdateContext, p *updateSettingsFlowWithOidcMethod, err error) error {
if e := new(settings.FlowNeedsReAuth); errors.As(err, &e) {
if err := s.d.ContinuityManager().Pause(r.Context(), w, r,
settings.ContinuityKey(s.SettingsStrategyID()), settings.ContinuityOptions(p, ctxUpdate.Session.Identity)...); err != nil {
return err
}
}
if ctxUpdate.Flow != nil {
ctxUpdate.Flow.UI.ResetMessages()
ctxUpdate.Flow.UI.SetCSRF(s.d.GenerateCSRFToken(r))
}
return err
}
func (s *Strategy) Link(ctx context.Context, i *identity.Identity, credentialsConfig sqlxx.JSONRawMessage) error {
var credentialsOIDCConfig identity.CredentialsOIDC
if err := json.Unmarshal(credentialsConfig, &credentialsOIDCConfig); err != nil {
return err
}
if len(credentialsOIDCConfig.Providers) != 1 {
return errors.New("No oidc provider was set")
}
credentialsOIDCProvider := credentialsOIDCConfig.Providers[0]
if err := s.linkCredentials(
ctx,
i,
// The tokens in this credential are coming from the existing identity. Hence, the values are already encrypted.
credentialsOIDCProvider.GetTokens(),
credentialsOIDCProvider.Provider,
credentialsOIDCProvider.Subject,
credentialsOIDCProvider.Organization,
); err != nil {
return err
}
options := []identity.ManagerOption{identity.ManagerAllowWriteProtectedTraits}
if err := s.d.IdentityManager().Update(ctx, i, options...); err != nil {
return err
}
return nil
}