-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
459 lines (402 loc) · 12.9 KB
/
handler.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
// Copyright 2015 realglobe, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// TA 間連携受け入れ代行。
package coop
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/realglobe-Inc/edo-auth/database/token"
keydb "github.com/realglobe-Inc/edo-id-provider/database/key"
idpdb "github.com/realglobe-Inc/edo-idp-selector/database/idp"
idperr "github.com/realglobe-Inc/edo-idp-selector/error"
"github.com/realglobe-Inc/edo-lib/jwk"
"github.com/realglobe-Inc/edo-lib/jwt"
logutil "github.com/realglobe-Inc/edo-lib/log"
"github.com/realglobe-Inc/edo-lib/rand"
"github.com/realglobe-Inc/edo-lib/server"
"github.com/realglobe-Inc/edo-lib/strset/strsetutil"
"github.com/realglobe-Inc/go-lib/erro"
"github.com/realglobe-Inc/go-lib/rglog/level"
)
type handler struct {
stopper *server.Stopper
selfId string
sigAlg string
sigKid string
sessLabel string
sessLen int
tokTagLen int
tokDbExpIn time.Duration
jtiLen int
jtiExpIn time.Duration
keyDb keydb.Db
idpDb idpdb.Db
tokDb token.Db
idGen rand.Generator
conn *http.Client
cookPath string
cookSec bool
debug bool
}
func New(
stopper *server.Stopper,
selfId string,
sigAlg string,
sigKid string,
sessLabel string,
sessLen int,
tokTagLen int,
tokDbExpIn time.Duration,
jtiLen int,
jtiExpIn time.Duration,
keyDb keydb.Db,
idpDb idpdb.Db,
tokDb token.Db,
idGen rand.Generator,
conn *http.Client,
cookPath string,
cookSec bool,
debug bool,
) http.Handler {
return &handler{
stopper,
selfId,
sigAlg,
sigKid,
sessLabel,
sessLen,
tokTagLen,
tokDbExpIn,
jtiLen,
jtiExpIn,
keyDb,
idpDb,
tokDb,
idGen,
conn,
cookPath,
cookSec,
debug,
}
}
func (this *handler) newCookie(id string, exp time.Time) *http.Cookie {
return &http.Cookie{
Name: this.sessLabel,
Value: id,
Path: this.cookPath,
Expires: exp,
Secure: this.cookSec,
HttpOnly: true,
}
}
func (this *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var logPref string
// panic 対策。
defer func() {
if rcv := recover(); rcv != nil {
w.Header().Set(tagX_edo_cooperation_error, fmt.Sprint(rcv))
idperr.RespondJson(w, r, erro.New(rcv), logPref)
return
}
}()
if this.stopper != nil {
this.stopper.Stop()
defer this.stopper.Unstop()
}
logPref = server.ParseSender(r) + ": "
server.LogRequest(level.DEBUG, r, this.debug, logPref)
log.Info(logPref, "Received cooperation request")
defer log.Info(logPref, "Handled cooperation request")
if err := (&environment{this, logPref}).serve(w, r); err != nil {
w.Header().Set(tagX_edo_cooperation_error, idperr.From(err).ErrorDescription())
idperr.RespondJson(w, r, erro.Wrap(err), logPref)
return
}
}
// environment のメソッドは idperr.Error を返す。
type environment struct {
*handler
logPref string
}
func (this *environment) serve(w http.ResponseWriter, r *http.Request) error {
req, err := parseRequest(r)
if err != nil {
return erro.Wrap(idperr.New(idperr.Invalid_request, erro.Unwrap(err).Error(), http.StatusBadRequest, err))
}
var acntTag string
tags := map[string]bool{}
var refHash string
type idpUnit struct {
idp idpdb.Element
codTok *codeToken
}
units := []*idpUnit{}
for _, rawCodTok := range req.codeTokens() {
codTok, err := parseCodeToken(rawCodTok)
if err != nil {
return erro.Wrap(idperr.New(idperr.Invalid_request, erro.Unwrap(err).Error(), http.StatusBadRequest, err))
} else if !codTok.audience()[this.selfId] {
return erro.Wrap(idperr.New(idperr.Invalid_request, "invalid audience", http.StatusBadRequest, nil))
} else if codTok.referralHash() == "" && len(req.codeTokens()) > 1 {
return erro.Wrap(idperr.New(idperr.Invalid_request, "no referral hash", http.StatusBadRequest, nil))
} else if codTok.accountTag() != "" {
if acntTag != "" {
return erro.Wrap(idperr.New(idperr.Invalid_request, "two main token", http.StatusBadRequest, nil))
}
acntTag = codTok.accountTag()
log.Debug(this.logPref, "Main account tag is "+acntTag)
if codTok.fromTa() == "" {
return erro.Wrap(idperr.New(idperr.Invalid_request, "no from-TA in main token", http.StatusBadRequest, nil))
}
log.Debug(this.logPref, "From-TA is "+codTok.fromTa())
} else if len(codTok.accountTags()) == 0 {
return erro.Wrap(idperr.New(idperr.Invalid_request, "no account tags in sub token", http.StatusBadRequest, nil))
}
for tag := range codTok.accountTags() {
if tags[tag] {
return erro.Wrap(idperr.New(idperr.Invalid_request, "tag "+tag+" overlaps", http.StatusBadRequest, nil))
}
tags[tag] = true
log.Debug(this.logPref, "Account tag is "+tag)
}
if codTok.referralHash() != "" {
if refHash == "" {
refHash = codTok.referralHash()
} else if codTok.referralHash() != refHash {
return erro.Wrap(idperr.New(idperr.Invalid_request, "invalid referral hash", http.StatusBadRequest, nil))
}
}
var idp idpdb.Element
if idp, err = this.idpDb.Get(codTok.idProvider()); err != nil {
return erro.Wrap(err)
} else if idp == nil {
return erro.Wrap(idperr.New(idperr.Invalid_request, "ID provider "+codTok.idProvider()+" is not exist", http.StatusBadRequest, nil))
}
log.Debug(this.logPref, "ID provider "+idp.Id()+" is exist")
if err := codTok.verify(idp.Keys()); err != nil {
return erro.Wrap(idperr.New(idperr.Invalid_request, erro.Unwrap(err).Error(), http.StatusBadRequest, err))
}
log.Debug(this.logPref, "Verified cooperation code")
units = append(units, &idpUnit{idp, codTok})
}
if acntTag == "" {
return erro.Wrap(idperr.New(idperr.Invalid_request, "no main account tag", http.StatusBadRequest, nil))
}
log.Debug(this.logPref, "Cooperation codes are OK")
var tok *token.Element
var mainAttrs map[string]interface{}
tagToAttrs := map[string]map[string]interface{}{}
var frTa string
for _, unit := range units {
var tToA map[string]map[string]interface{}
var fT string
if unit.codTok.accountTag() != "" {
fT, tok, tToA, err = this.getInfoFromMainIdProvider(unit.idp, unit.codTok)
if err != nil {
return erro.Wrap(err)
}
log.Debug(this.logPref, "Got account info from main ID provider "+unit.idp.Id())
} else {
fT, tToA, err = this.getInfoFromSubIdProvider(unit.idp, unit.codTok)
if err != nil {
return erro.Wrap(err)
}
log.Debug(this.logPref, "Got account info from sub ID provider "+unit.idp.Id())
}
for tag, attrs := range tToA {
if tag == acntTag {
attrs[tagIss] = unit.idp.Id()
attrs[tagAt_tag] = tok.Tag()
attrs[tagAt_exp] = tok.Expires().Unix()
mainAttrs = attrs
} else {
attrs[tagIss] = unit.idp.Id()
tagToAttrs[tag] = attrs
}
}
if frTa == "" {
frTa = fT
} else if frTa != fT {
return erro.Wrap(idperr.New(idperr.Invalid_request, "two from-TA ID", http.StatusBadRequest, nil))
}
}
log.Debug(this.logPref, "Got all account info")
jt := jwt.New()
jt.SetHeader(tagAlg, tagNone)
for k, v := range mainAttrs {
jt.SetClaim(k, v)
}
mainInfo, err := jt.Encode()
if err != nil {
return erro.Wrap(err)
}
var relInfo []byte
sessFlag := true
if len(tagToAttrs) > 0 {
jt = jwt.New()
jt.SetHeader(tagAlg, tagNone)
for acntTag, attrs := range tagToAttrs {
jt.SetClaim(acntTag, attrs)
if sessFlag {
for k := range attrs {
if !sessionEnable(k) {
sessFlag = false
}
}
}
}
relInfo, err = jt.Encode()
if err != nil {
return erro.Wrap(err)
}
}
w.Header().Set(tagX_auth_user, string(mainInfo))
w.Header().Set(tagX_auth_user_tag, acntTag)
w.Header().Set(tagX_auth_from_id, frTa)
if relInfo != nil {
w.Header().Set(tagX_auth_users, string(relInfo))
}
if sessFlag {
sessId := this.idGen.String(this.sessLen)
http.SetCookie(w, this.handler.newCookie(sessId, tok.Expires()))
log.Debug(this.logPref, "Report session "+logutil.Mosaic(sessId))
}
return nil
}
func (this *environment) getInfoFromMainIdProvider(idp idpdb.Element, codTok *codeToken) (frTa string, tok *token.Element, tagToAttrs map[string]map[string]interface{}, err error) {
return this.getInfo(true, idp, codTok)
}
func (this *environment) getInfoFromSubIdProvider(idp idpdb.Element, codTok *codeToken) (frTa string, tagToAttrs map[string]map[string]interface{}, err error) {
frTa, _, tagToAttrs, err = this.getInfo(false, idp, codTok)
return frTa, tagToAttrs, err
}
func (this *environment) getInfo(isMain bool, idp idpdb.Element, codTok *codeToken) (frTa string, tok *token.Element, tagToAttrs map[string]map[string]interface{}, err error) {
params := map[string]interface{}{}
// grant_type
params[tagGrant_type] = tagCooperation_code
// code
params[tagCode] = codTok.code()
// claims
if isMain {
// TODO 受け取り方を考えないと。
}
// user_claims
// TODO 受け取り方を考えないと。
// client_assertion_type
params[tagClient_assertion_type] = cliAssTypeJwt_bearer
// client_assertion
keys, err := this.keyDb.Get()
if err != nil {
return "", nil, nil, erro.Wrap(err)
}
ass, err := makeAssertion(this.handler, keys, idp.CoopToUri())
if err != nil {
return "", nil, nil, erro.Wrap(err)
}
params[tagClient_assertion] = string(ass)
data, err := json.Marshal(params)
if err != nil {
return "", nil, nil, erro.Wrap(err)
}
r, err := http.NewRequest("POST", idp.CoopToUri(), bytes.NewReader(data))
r.Header.Set(tagContent_type, contTypeJson)
log.Debug(this.logPref, "Made main cooperation-to request")
server.LogRequest(level.DEBUG, r, this.debug, this.logPref)
resp, err := this.conn.Do(r)
if err != nil {
return "", nil, nil, erro.Wrap(err)
}
defer resp.Body.Close()
server.LogResponse(level.DEBUG, resp, this.debug, this.logPref)
if resp.StatusCode != http.StatusOK {
var buff struct {
Error string
Error_description string
}
if err := json.NewDecoder(resp.Body).Decode(&buff); err != nil {
return "", nil, nil, erro.Wrap(err)
}
return "", nil, nil, erro.Wrap(idperr.New(buff.Error, buff.Error_description, resp.StatusCode, nil))
}
coopResp, err := parseCoopResponse(resp)
if err != nil {
return "", nil, nil, erro.Wrap(idperr.New(idperr.Access_denied, erro.Unwrap(err).Error(), http.StatusForbidden, err))
}
idsTok, err := parseIdsToken(coopResp.idsToken())
if err != nil {
return "", nil, nil, erro.Wrap(idperr.New(idperr.Access_denied, erro.Unwrap(err).Error(), http.StatusForbidden, err))
} else if err := idsTok.verify(idp.Keys()); err != nil {
return "", nil, nil, erro.Wrap(idperr.New(idperr.Access_denied, erro.Unwrap(err).Error(), http.StatusForbidden, err))
}
tagToAttrs = map[string]map[string]interface{}{}
for acntTag := range codTok.accountTags() {
attrs := idsTok.attributes()[acntTag]
if attrs == nil {
return "", nil, nil, erro.Wrap(idperr.New(idperr.Access_denied, "cannot get sub account tagged by "+acntTag, http.StatusForbidden, nil))
}
tagToAttrs[acntTag] = attrs
}
if isMain {
attrs := idsTok.attributes()[codTok.accountTag()]
if attrs == nil {
return "", nil, nil, erro.Wrap(idperr.New(idperr.Access_denied, "cannot get main account tagged by "+codTok.accountTag(), http.StatusForbidden, nil))
}
tagToAttrs[codTok.accountTag()] = attrs
if coopResp.token() == "" {
return "", nil, nil, erro.Wrap(idperr.New(idperr.Access_denied, "cannot get token", http.StatusForbidden, nil))
}
now := time.Now()
tok = token.New(coopResp.token(), this.idGen.String(this.tokTagLen), now.Add(coopResp.expiresIn()), idsTok.idProvider(), coopResp.scope())
log.Info(this.logPref, "Got access token "+logutil.Mosaic(tok.Id()))
if err := this.tokDb.Save(tok, now.Add(this.tokDbExpIn)); err != nil {
return "", nil, nil, erro.Wrap(err)
}
log.Info(this.logPref, "Saved access token "+logutil.Mosaic(tok.Id()))
}
return idsTok.fromTa(), tok, tagToAttrs, nil
}
// TA 認証用署名をつくる。
func makeAssertion(hndl *handler, keys []jwk.Key, aud string) ([]byte, error) {
ass := jwt.New()
ass.SetHeader(tagAlg, hndl.sigAlg)
if hndl.sigKid != "" {
ass.SetHeader(tagKid, hndl.sigKid)
}
ass.SetClaim(tagIss, hndl.selfId)
ass.SetClaim(tagSub, hndl.selfId)
ass.SetClaim(tagAud, aud)
ass.SetClaim(tagJti, hndl.idGen.String(hndl.jtiLen))
now := time.Now()
ass.SetClaim(tagExp, now.Add(hndl.jtiExpIn).Unix())
ass.SetClaim(tagIat, now.Unix())
if err := ass.Sign(keys); err != nil {
return nil, erro.Wrap(err)
}
data, err := ass.Encode()
if err != nil {
return nil, erro.Wrap(err)
}
return data, nil
}
// セッションを発行しても良い属性かどうか。
func sessionEnable(attrName string) bool {
return sessEnAttrs[attrName]
}
var sessEnAttrs = strsetutil.New(
tagIss,
tagSub,
)