-
-
Notifications
You must be signed in to change notification settings - Fork 932
/
hook.go
245 lines (214 loc) · 8.16 KB
/
hook.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
// Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package registration
import (
"context"
"fmt"
"net/http"
"time"
"github.com/pkg/errors"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"github.com/ory/x/httpx"
"github.com/ory/x/otelx/semconv"
"github.com/ory/x/sqlcon"
"github.com/ory/kratos/driver/config"
"github.com/ory/kratos/hydra"
"github.com/ory/kratos/identity"
"github.com/ory/kratos/schema"
"github.com/ory/kratos/selfservice/flow"
"github.com/ory/kratos/session"
"github.com/ory/kratos/x"
)
type (
PreHookExecutor interface {
ExecuteRegistrationPreHook(w http.ResponseWriter, r *http.Request, a *Flow) error
}
PreHookExecutorFunc func(w http.ResponseWriter, r *http.Request, a *Flow) error
PostHookPostPersistExecutor interface {
ExecutePostRegistrationPostPersistHook(w http.ResponseWriter, r *http.Request, a *Flow, s *session.Session) error
}
PostHookPostPersistExecutorFunc func(w http.ResponseWriter, r *http.Request, a *Flow, s *session.Session) error
PostHookPrePersistExecutor interface {
ExecutePostRegistrationPrePersistHook(w http.ResponseWriter, r *http.Request, a *Flow, i *identity.Identity) error
}
PostHookPrePersistExecutorFunc func(w http.ResponseWriter, r *http.Request, a *Flow, i *identity.Identity) error
HooksProvider interface {
PreRegistrationHooks(ctx context.Context) []PreHookExecutor
PostRegistrationPrePersistHooks(ctx context.Context, credentialsType identity.CredentialsType) []PostHookPrePersistExecutor
PostRegistrationPostPersistHooks(ctx context.Context, credentialsType identity.CredentialsType) []PostHookPostPersistExecutor
}
)
func PostHookPostPersistExecutorNames(e []PostHookPostPersistExecutor) []string {
names := make([]string, len(e))
for k, ee := range e {
names[k] = fmt.Sprintf("%T", ee)
}
return names
}
func (f PreHookExecutorFunc) ExecuteRegistrationPreHook(w http.ResponseWriter, r *http.Request, a *Flow) error {
return f(w, r, a)
}
func (f PostHookPostPersistExecutorFunc) ExecutePostRegistrationPostPersistHook(w http.ResponseWriter, r *http.Request, a *Flow, s *session.Session) error {
return f(w, r, a, s)
}
func (f PostHookPrePersistExecutorFunc) ExecutePostRegistrationPrePersistHook(w http.ResponseWriter, r *http.Request, a *Flow, i *identity.Identity) error {
return f(w, r, a, i)
}
type (
executorDependencies interface {
config.Provider
identity.ManagementProvider
identity.ValidationProvider
session.PersistenceProvider
session.ManagementProvider
HooksProvider
hydra.HydraProvider
x.CSRFTokenGeneratorProvider
x.HTTPClientProvider
x.LoggingProvider
x.WriterProvider
}
HookExecutor struct {
d executorDependencies
}
HookExecutorProvider interface {
RegistrationExecutor() *HookExecutor
}
)
func NewHookExecutor(d executorDependencies) *HookExecutor {
return &HookExecutor{d: d}
}
func (e *HookExecutor) PostRegistrationHook(w http.ResponseWriter, r *http.Request, ct identity.CredentialsType, a *Flow, i *identity.Identity) error {
e.d.Logger().
WithRequest(r).
WithField("identity_id", i.ID).
WithField("flow_method", ct).
Debug("Running PostRegistrationPrePersistHooks.")
for k, executor := range e.d.PostRegistrationPrePersistHooks(r.Context(), ct) {
if err := executor.ExecutePostRegistrationPrePersistHook(w, r, a, i); err != nil {
if errors.Is(err, ErrHookAbortFlow) {
e.d.Logger().
WithRequest(r).
WithField("executor", fmt.Sprintf("%T", executor)).
WithField("executor_position", k).
WithField("executors", PostHookPostPersistExecutorNames(e.d.PostRegistrationPostPersistHooks(r.Context(), ct))).
WithField("identity_id", i.ID).
WithField("flow_method", ct).
Debug("A ExecutePostRegistrationPrePersistHook hook aborted early.")
return nil
}
var traits identity.Traits
if i != nil {
traits = i.Traits
}
return flow.HandleHookError(w, r, a, traits, ct.ToUiNodeGroup(), err, e.d, e.d)
}
e.d.Logger().WithRequest(r).
WithField("executor", fmt.Sprintf("%T", executor)).
WithField("executor_position", k).
WithField("executors", PostHookPostPersistExecutorNames(e.d.PostRegistrationPostPersistHooks(r.Context(), ct))).
WithField("identity_id", i.ID).
WithField("flow_method", ct).
Debug("ExecutePostRegistrationPrePersistHook completed successfully.")
}
// We need to make sure that the identity has a valid schema before passing it down to the identity pool.
if err := e.d.IdentityValidator().Validate(r.Context(), i); err != nil {
return err
// We're now creating the identity because any of the hooks could trigger a "redirect" or a "session" which
// would imply that the identity has to exist already.
} else if err := e.d.IdentityManager().Create(r.Context(), i); err != nil {
if errors.Is(err, sqlcon.ErrUniqueViolation) {
return schema.NewDuplicateCredentialsError()
}
return err
}
// Verify the redirect URL before we do any other processing.
c := e.d.Config()
returnTo, err := x.SecureRedirectTo(r, c.SelfServiceBrowserDefaultReturnTo(r.Context()),
x.SecureRedirectReturnTo(a.ReturnTo),
x.SecureRedirectUseSourceURL(a.RequestURL),
x.SecureRedirectAllowURLs(c.SelfServiceBrowserAllowedReturnToDomains(r.Context())),
x.SecureRedirectAllowSelfServiceURLs(c.SelfPublicURL(r.Context())),
x.SecureRedirectOverrideDefaultReturnTo(c.SelfServiceFlowRegistrationReturnTo(r.Context(), ct.String())),
)
if err != nil {
return err
}
e.d.Audit().
WithRequest(r).
WithField("identity_id", i.ID).
Info("A new identity has registered using self-service registration.")
trace.SpanFromContext(r.Context()).AddEvent(
semconv.EventIdentityCreated,
trace.WithAttributes(
attribute.String(semconv.AttrIdentityID, i.ID.String()),
attribute.String(semconv.AttrNID, i.NID.String()),
attribute.String(semconv.AttrClientIP, httpx.ClientIP(r)),
attribute.String("flow", string(a.Type)),
),
)
s, err := session.NewActiveSession(r, i, e.d.Config(), time.Now().UTC(), ct, identity.AuthenticatorAssuranceLevel1)
if err != nil {
return err
}
e.d.Logger().
WithRequest(r).
WithField("identity_id", i.ID).
WithField("flow_method", ct).
Debug("Running PostRegistrationPostPersistHooks.")
for k, executor := range e.d.PostRegistrationPostPersistHooks(r.Context(), ct) {
if err := executor.ExecutePostRegistrationPostPersistHook(w, r, a, s); err != nil {
if errors.Is(err, ErrHookAbortFlow) {
e.d.Logger().
WithRequest(r).
WithField("executor", fmt.Sprintf("%T", executor)).
WithField("executor_position", k).
WithField("executors", PostHookPostPersistExecutorNames(e.d.PostRegistrationPostPersistHooks(r.Context(), ct))).
WithField("identity_id", i.ID).
WithField("flow_method", ct).
Debug("A ExecutePostRegistrationPostPersistHook hook aborted early.")
return nil
}
var traits identity.Traits
if i != nil {
traits = i.Traits
}
return flow.HandleHookError(w, r, a, traits, ct.ToUiNodeGroup(), err, e.d, e.d)
}
e.d.Logger().WithRequest(r).
WithField("executor", fmt.Sprintf("%T", executor)).
WithField("executor_position", k).
WithField("executors", PostHookPostPersistExecutorNames(e.d.PostRegistrationPostPersistHooks(r.Context(), ct))).
WithField("identity_id", i.ID).
WithField("flow_method", ct).
Debug("ExecutePostRegistrationPostPersistHook completed successfully.")
}
e.d.Logger().
WithRequest(r).
WithField("flow_method", ct).
WithField("identity_id", i.ID).
Debug("Post registration execution hooks completed successfully.")
if a.Type == flow.TypeAPI || x.IsJSONRequest(r) {
e.d.Writer().Write(w, r, &APIFlowResponse{Identity: i})
return nil
}
finalReturnTo := returnTo.String()
if a.OAuth2LoginChallenge.Valid {
cr, err := e.d.Hydra().AcceptLoginRequest(r.Context(), a.OAuth2LoginChallenge.UUID, i.ID.String(), s.AMR)
if err != nil {
return err
}
finalReturnTo = cr
}
x.ContentNegotiationRedirection(w, r, s.Declassify(), e.d.Writer(), finalReturnTo)
return nil
}
func (e *HookExecutor) PreRegistrationHook(w http.ResponseWriter, r *http.Request, a *Flow) error {
for _, executor := range e.d.PreRegistrationHooks(r.Context()) {
if err := executor.ExecuteRegistrationPreHook(w, r, a); err != nil {
return err
}
}
return nil
}