-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchallenges.go
More file actions
446 lines (369 loc) · 14.1 KB
/
challenges.go
File metadata and controls
446 lines (369 loc) · 14.1 KB
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
package challenges
import (
"errors"
"time"
"context"
"net/http"
"github.com/sirupsen/logrus"
"github.com/gin-gonic/gin"
"golang.org/x/oauth2"
"github.com/opensentry/idp/app"
"github.com/opensentry/idp/config"
"github.com/opensentry/idp/gateway/idp"
"github.com/opensentry/idp/client"
E "github.com/opensentry/idp/client/errors"
aap "github.com/opensentry/aap/client"
bulkyClient "github.com/charmixer/bulky/client"
bulky "github.com/charmixer/bulky/server"
)
type ConfirmTemplateData struct {
Challenge string
Id string
Code string
Sender string
Email string
}
func GetChallenges(env *app.Environment) gin.HandlerFunc {
fn := func(c *gin.Context) {
ctx := context.TODO() // FIXME
log := c.MustGet(env.Constants.LogKey).(*logrus.Entry)
log = log.WithFields(logrus.Fields{
"func": "GetChallenges",
})
var requests []client.ReadChallengesRequest
err := c.BindJSON(&requests)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var handleRequests = func(iRequests []*bulky.Request) {
tx, err := env.Driver.BeginTx(ctx, nil)
if err != nil {
bulky.FailAllRequestsWithInternalErrorResponse(iRequests)
log.Debug(err.Error())
return
}
// requestor := c.MustGet("sub").(string)
// var requestedBy *idp.Identity
// if requestor != "" {
// identities, err := idp.FetchIdentities(ctx, tx, []idp.Identity{ {Id:requestor} })
// if err != nil {
// bulky.FailAllRequestsWithInternalErrorResponse(iRequests)
// log.Debug(err.Error())
// return
// }
// if len(identities) > 0 {
// requestedBy = &identities[0]
// }
// }
for _, request := range iRequests {
var dbChallenges []idp.Challenge
var err error
var ok client.ReadChallengesResponse
if request.Input == nil {
dbChallenges, err = idp.FetchChallenges(ctx, tx, nil)
} else {
r := request.Input.(client.ReadChallengesRequest)
log = log.WithFields(logrus.Fields{"otp_challenge": r.OtpChallenge})
dbChallenges, err = idp.FetchChallenges(ctx, tx, []idp.Challenge{ {Id: r.OtpChallenge} })
}
if err != nil {
e := tx.Rollback()
if e != nil {
log.Debug(e.Error())
}
bulky.FailAllRequestsWithServerOperationAbortedResponse(iRequests) // Fail all with abort
request.Output = bulky.NewInternalErrorResponse(request.Index) // Specify error on failed one
log.Debug(err.Error())
return
}
if len(dbChallenges) > 0 {
for _, d := range dbChallenges {
ok = append(ok, client.Challenge{
OtpChallenge: d.Id,
Subject: d.Subject,
Audience: d.Audience,
IssuedAt: d.IssuedAt,
ExpiresAt: d.ExpiresAt,
TTL: d.ExpiresAt - d.IssuedAt,
RedirectTo: d.RedirectTo,
CodeType: d.CodeType,
VerifiedAt: d.VerifiedAt,
Data: d.Data,
})
}
request.Output = bulky.NewOkResponse(request.Index, ok)
continue
}
// Deny by default
request.Output = bulky.NewClientErrorResponse(request.Index, E.CHALLENGE_NOT_FOUND)
}
err = bulky.OutputValidateRequests(iRequests)
if err == nil {
tx.Commit()
return
}
// Deny by default
tx.Rollback()
}
responses := bulky.HandleRequest(requests, handleRequests, bulky.HandleRequestParams{EnableEmptyRequest: true})
c.JSON(http.StatusOK, responses)
}
return gin.HandlerFunc(fn)
}
func PostChallenges(env *app.Environment) gin.HandlerFunc {
fn := func(c *gin.Context) {
ctx := context.TODO() // FIXME
log := c.MustGet(env.Constants.LogKey).(*logrus.Entry)
log = log.WithFields(logrus.Fields{
"func": "PostChallenges",
})
var requests []client.CreateChallengesRequest
err := c.BindJSON(&requests)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// This is required to be here but should be garantueed by the authenticationRequired function.
t, accessTokenExists := c.Get(env.Constants.AccessTokenKey)
if accessTokenExists == false {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Missing access token"})
return
}
var token *oauth2.Token = t.(*oauth2.Token)
var handleRequests = func(iRequests []*bulky.Request) {
tx, err := env.Driver.BeginTx(ctx, nil)
if err != nil {
bulky.FailAllRequestsWithInternalErrorResponse(iRequests)
log.Debug(err.Error())
return
}
// requestor := c.MustGet("sub").(string)
// var requestedBy *idp.Identity
// if requestor != "" {
// identities, err := idp.FetchIdentities(ctx, tx, []idp.Identity{ {Id:requestor} })
// if err != nil {
// bulky.FailAllRequestsWithInternalErrorResponse(iRequests)
// log.Debug(err.Error())
// return
// }
// if len(identities) > 0 {
// requestedBy = &identities[0]
// }
// }
challengeTypeRequiredScopes := map[idp.ChallengeType][]string{
idp.ChallengeAuthenticate: []string{"idp:create:challenge.authenticate"},
idp.ChallengeRecover: []string{"idp:create:challenge.recover"},
idp.ChallengeDelete: []string{"idp:create:challenge.delete"},
}
for _, request := range iRequests {
r := request.Input.(client.CreateChallengesRequest)
ct := translateConfirmationTypeToChallengeType(r.ConfirmationType)
if ct == idp.ChallengeNotSupported {
e := tx.Rollback()
if e != nil {
log.Debug(e.Error())
}
bulky.FailAllRequestsWithServerOperationAbortedResponse(iRequests) // Fail all with abort
request.Output = bulky.NewClientErrorResponse(request.Index, E.CHALLENGE_CONFIRMATION_TYPE_INVALID)
return
}
// Call judge to test if allowed to call endpoint for challenge type
requiredScopes := challengeTypeRequiredScopes[ct]
valid, err := judgeRequiredScope(env, c, log, token, requiredScopes...)
if err != nil {
e := tx.Rollback()
if e != nil {
log.Debug(e.Error())
}
bulky.FailAllRequestsWithServerOperationAbortedResponse(iRequests) // Fail all with abort
request.Output = bulky.NewInternalErrorResponse(request.Index) // Specify error on failed one
log.Debug(err.Error())
return
}
// Judgement!
if valid == false {
e := tx.Rollback()
if e != nil {
log.Debug(e.Error())
}
bulky.FailAllRequestsWithServerOperationAbortedResponse(iRequests) // Fail all with abort
request.Output = bulky.NewErrorResponse(request.Index, http.StatusForbidden, E.HUMAN_TOKEN_INVALID)
return
}
newChallenge := idp.Challenge{
JwtRegisteredClaims: idp.JwtRegisteredClaims{
Subject: r.Subject,
Issuer: config.GetString("idp.public.issuer"),
Audience: config.GetString("idp.public.url") + config.GetString("idp.public.endpoints.challenges.verify"),
ExpiresAt: time.Now().Unix() + r.TTL,
},
RedirectTo: r.RedirectTo,
CodeType: r.CodeType,
}
var otpCode idp.ChallengeCode
var challenge idp.Challenge
if client.OTPType(newChallenge.CodeType) == client.TOTP {
challenge, err = idp.CreateChallengeUsingTotp(ctx, tx, ct, newChallenge)
} else {
challenge, otpCode, err = idp.CreateChallengeUsingOtp(ctx, tx, ct, newChallenge)
}
if err == nil && challenge.Id != "" {
if otpCode.Code != "" && r.Email != "" {
// Sent challenge to requested email
emailTemplate := (*env.TemplateMap)[ct]
if emailTemplate == (app.EmailTemplate{}) {
e := tx.Rollback()
if e != nil {
log.Debug(e.Error())
}
bulky.FailAllRequestsWithServerOperationAbortedResponse(iRequests) // Fail all with abort
request.Output = bulky.NewInternalErrorResponse(request.Index) // Specify error on failed one
log.WithFields(logrus.Fields{ "challenge_type":ct.String() }).Debug("Email template not found")
return
}
var data = ConfirmTemplateData{
Challenge: challenge.Id,
Sender: emailTemplate.Sender.Name,
Id: challenge.Subject,
Email: r.Email,
Code: otpCode.Code, // Note this is the clear text generated code and not the hashed one stored in DB.
}
smtpConfig := idp.SMTPConfig{
Host: config.GetString("mail.smtp.host"),
Username: config.GetString("mail.smtp.user"),
Password: config.GetString("mail.smtp.password"),
Sender: emailTemplate.Sender,
SkipTlsVerify: config.GetInt("mail.smtp.skip_tls_verify"),
}
_, err = idp.SendEmailUsingTemplate(smtpConfig, r.Email, r.Email, emailTemplate.Subject, emailTemplate.File, data)
if err != nil {
e := tx.Rollback()
if e != nil {
log.Debug(e.Error())
}
bulky.FailAllRequestsWithServerOperationAbortedResponse(iRequests) // Fail all with abort
request.Output = bulky.NewInternalErrorResponse(request.Index) // Specify error on failed one
log.Debug(err.Error())
return
}
}
confirmationType := translateChallengeTypeToConfirmationType(challenge.ChallengeType)
request.Output = bulky.NewOkResponse(request.Index, client.CreateChallengesResponse{
OtpChallenge: challenge.Id,
ConfirmationType: int(confirmationType),
Subject: challenge.Subject,
Audience: challenge.Audience,
IssuedAt: challenge.IssuedAt,
ExpiresAt: challenge.ExpiresAt,
TTL: challenge.ExpiresAt - challenge.IssuedAt,
RedirectTo: challenge.RedirectTo,
CodeType: challenge.CodeType,
Code: challenge.Code,
})
continue
}
// Deny by default
e := tx.Rollback()
if e != nil {
log.Debug(e.Error())
}
bulky.FailAllRequestsWithServerOperationAbortedResponse(iRequests) // Fail all with abort
request.Output = bulky.NewInternalErrorResponse(request.Index) // Specify error on failed one
log.Debug(err.Error())
return
}
err = bulky.OutputValidateRequests(iRequests)
if err == nil {
tx.Commit()
return
}
// Deny by default
tx.Rollback()
}
responses := bulky.HandleRequest(requests, handleRequests, bulky.HandleRequestParams{MaxRequests: 1})
c.JSON(http.StatusOK, responses)
}
return gin.HandlerFunc(fn)
}
func judgeRequiredScope(env *app.Environment, c *gin.Context, log *logrus.Entry, token *oauth2.Token, requiredScopes ...string) (valid bool, err error) {
// Check that access token has required scopes
v, exists := c.Get("scope") // scope from introspection call
if exists == false {
return false, errors.New("Missing scope in context")
}
scope := v.(string)
// TODO: Check the access token for required scopes.
log.Debug(scope)
// Check that subject is granted scopes.
v, exists = c.Get("sub") // sub from introspection call
if exists == false {
return false, errors.New("Missing sub in context")
}
sub := v.(string)
publisherId := config.GetString("id") // Resource Server (this)
var judgeRequests []aap.ReadEntitiesJudgeRequest
for _, scope := range requiredScopes {
judgeRequests = append(judgeRequests, aap.ReadEntitiesJudgeRequest{
AccessToken: token.AccessToken,
Publisher: publisherId,
Scope: scope,
Owners: []string{ sub },
})
}
aapClient := aap.NewAapClient(env.AapConfig)
url := config.GetString("aap.public.url") + config.GetString("aap.public.endpoints.entities.judge")
status, responses, err := aap.ReadEntitiesJudge(aapClient, url, judgeRequests)
if err != nil {
return false, err
}
if status == http.StatusOK {
var verdict aap.ReadEntitiesJudgeResponse
status, restErr := bulkyClient.Unmarshal(0, responses, &verdict)
if restErr != nil {
log.Debug(restErr)
return false, errors.New("Unmarshal ReadEntitiesJudgeResponse failed")
}
if status == http.StatusOK {
if verdict.Granted == true {
// log.WithFields(logrus.Fields{"sub": sub, "scope": strRequiredScopes}).Debug("Authorized")
return true, nil // Authenticated
}
}
}
// Deny by default
return false, nil
}
func translateConfirmationTypeToChallengeType(confirmationType int) (challengeType idp.ChallengeType) {
ct := client.ConfirmationType(confirmationType)
switch ct {
case client.ConfirmIdentity:
return idp.ChallengeAuthenticate
case client.ConfirmIdentityDeletion:
return idp.ChallengeDelete
case client.ConfirmIdentityRecovery:
return idp.ChallengeRecover
case client.ConfirmIdentityControlOfEmail:
return idp.ChallengeEmailConfirm
case client.ConfirmIdentityControlOfEmailDuringChange:
return idp.ChallengeEmailChange
default:
return idp.ChallengeNotSupported
}
}
func translateChallengeTypeToConfirmationType(challengeType idp.ChallengeType) (confirmationType client.ConfirmationType) {
switch challengeType {
case idp.ChallengeAuthenticate:
return client.ConfirmIdentity
case idp.ChallengeDelete:
return client.ConfirmIdentityDeletion
case idp.ChallengeRecover:
return client.ConfirmIdentityRecovery
case idp.ChallengeEmailConfirm:
return client.ConfirmIdentityControlOfEmail
case idp.ChallengeEmailChange:
return client.ConfirmIdentityControlOfEmailDuringChange
default:
return client.ConfirmationType(0)
}
}