/
identity.go
352 lines (316 loc) · 13.2 KB
/
identity.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
// Copyright 2019 Google LLC
//
// 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.
package ga4gh
import (
"context"
"fmt"
"net/url"
"strings"
"github.com/GoogleCloudPlatform/healthcare-federated-access-services/lib/errutil" /* copybara-comment: errutil */
"github.com/GoogleCloudPlatform/healthcare-federated-access-services/lib/globalflags" /* copybara-comment: globalflags */
"github.com/GoogleCloudPlatform/healthcare-federated-access-services/lib/httputils" /* copybara-comment: httputils */
"github.com/GoogleCloudPlatform/healthcare-federated-access-services/lib/strutil" /* copybara-comment: strutil */
cpb "github.com/GoogleCloudPlatform/healthcare-federated-access-services/proto/common/v1" /* copybara-comment: go_proto */
)
const (
// AccessTokenVisaFormat represents an "Embedded Access Token" visa format.
// See https://bit.ly/ga4gh-aai-profile#term-embedded-access-token.
AccessTokenVisaFormat VisaFormat = "access_token"
// DocumentVisaFormat represents an "Embedded Document Token" visa format.
// See https://bit.ly/ga4gh-aai-profile#term-embedded-document-token.
DocumentVisaFormat VisaFormat = "document"
// UnspecifiedVisaFormat is used when the token cannot be read or is not available.
UnspecifiedVisaFormat VisaFormat = ""
)
// VisaFormat indicates what GA4GH embedded token format is used for a visa.
// See https://bit.ly/ga4gh-aai-profile#embedded-token-issued-by-embedded-token-issuer.
type VisaFormat string
// OldClaim represents a claim object as defined by GA4GH.
type OldClaim struct {
Value string `json:"value"`
Source string `json:"source"`
Asserted float64 `json:"asserted,omitempty"`
Expires float64 `json:"expires,omitempty"`
Condition map[string]OldClaimCondition `json:"condition,omitempty"`
By string `json:"by,omitempty"`
Issuer string `json:"issuer,omitempty"`
VisaData *VisaData `json:"-"`
TokenFormat VisaFormat `json:"-"`
}
// OldClaimCondition represents a condition object as defined by GA4GH.
type OldClaimCondition struct {
Value []string `json:"value,omitempty"`
Source []string `json:"source,omitempty"`
By []string `json:"by,omitempty"`
}
// VisaRejection is filled in by a policy engine to understand why a visa was rejected.
// Visas unrelated to the policy are not considered rejected unless they are not trusted.
type VisaRejection struct {
Reason string `json:"reason,omitempty"`
Field string `json:"field,omitempty"`
Description string `json:"msg,omitempty"`
}
// RejectedVisa provides insight into why a policy engine is not making use of visas that
// are present within the passport.
type RejectedVisa struct {
TokenFormat string `json:"tokenFormat,omitempty"`
Issuer string `json:"iss,omitempty"`
Subject string `json:"sub,omitempty"`
Assertion Assertion `json:"assertion,omitempty"`
Rejection VisaRejection `json:"rejection,omitempty"`
}
// Identity is a GA4GH identity as described by the Data Use and Researcher
// Identity stream.
type Identity struct {
Subject string `json:"sub,omitempty"`
Issuer string `json:"iss,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
Expiry int64 `json:"exp,omitempty"`
Scope string `json:"scope,omitempty"`
Scp []string `json:"scp,omitempty"`
Audiences Audiences `json:"aud,omitempty"`
AuthorizedParty string `json:"azp,omitempty"`
ID string `json:"jti,omitempty"`
TokenID string `json:"tid,omitempty"`
Nonce string `json:"nonce,omitempty"`
GA4GH map[string][]OldClaim `json:"-"` // do not emit
RejectedVisas []*RejectedVisa `json:"-"` // do not emit
IdentityProvider string `json:"idp,omitempty"`
Identities map[string][]string `json:"identities,omitempty"`
Username string `json:"preferred_username,omitempty"`
Email string `json:"email,omitempty"`
EmailVerified bool `json:"email_verified,omitempty"`
Name string `json:"name,omitempty"`
Nickname string `json:"nickname,omitempty"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
MiddleName string `json:"middle_name,omitempty"`
ZoneInfo string `json:"zoneinfo,omitempty"`
Locale string `json:"locale,omitempty"`
Picture string `json:"picture,omitempty"`
Profile string `json:"profile,omitempty"`
Realm string `json:"realm,omitempty"`
VisaJWTs []string `json:"ga4gh_passport_v1,omitempty"`
Extra map[string]interface{} `json:"ext,omitempty"`
Patient string `json:"patient,omitempty"` // SMART-on-FHIR
FhirUser string `json:"fhirUser,omitempty"` // SMART-on-FHIR
}
// CheckIdentityAllVisasLinked checks if the Visas inside the identity are linked.
// Verifies all Visas of type LinkedIdentities.
// If JWTVerifier is not nil, will call f to verify LinkedIdentities Visas.
// If JWTVerifier is nil, verification is skipped.
func CheckIdentityAllVisasLinked(ctx context.Context, i *Identity, f JWTVerifier) error {
var visas []*Visa
for _, j := range i.VisaJWTs {
v, err := NewVisaFromJWT(VisaJWT(j))
if err != nil {
return err
}
if f != nil && v.Data().Assertion.Type == LinkedIdentities {
if err := f(ctx, j, v.Data().Issuer, v.JKU()); err != nil {
return fmt.Errorf("the verification of some LinkedIdentities visa failed: %v", err)
}
}
visas = append(visas, v)
}
return CheckLinkedIDs(visas)
}
// RejectVisa adds a new RejectedVisa report to the identity (up to a maximum number of reports).
func (t *Identity) RejectVisa(visa *VisaData, format VisaFormat, reason, field, message string) {
if len(t.RejectedVisas) > 20 {
return
}
t.RejectedVisas = append(t.RejectedVisas, NewRejectedVisa(visa, format, reason, field, message))
}
// NewRejectedVisa creates a rejected visa information struct.
func NewRejectedVisa(visa *VisaData, format VisaFormat, reason, field, message string) *RejectedVisa {
if visa == nil {
visa = &VisaData{}
}
detail := VisaRejection{
Reason: reason,
Field: field,
Description: message,
}
return &RejectedVisa{
TokenFormat: string(format),
Issuer: visa.Issuer,
Subject: visa.Subject,
Assertion: visa.Assertion,
Rejection: detail,
}
}
// VisasToOldClaims populates the GA4GH claim based on visas.
// Returns a map of visa types, each having a list of OldClaims for that type.
// TODO: use new policy engine instead when it becomes available.
func VisasToOldClaims(ctx context.Context, visas []VisaJWT, f JWTVerifier) (map[string][]OldClaim, []*RejectedVisa, error) {
out := make(map[string][]OldClaim)
var rejected []*RejectedVisa
for i, j := range visas {
// Skip this visa on validation errors such that a bad visa doesn't spoil the bunch.
// But do return errors if the visas are not compatible with the old claim format.
v, err := NewVisaFromJWT(VisaJWT(j))
if err != nil {
rejected = append(rejected, NewRejectedVisa(nil, UnspecifiedVisaFormat, "invalid_visa", "", fmt.Sprintf("cannot unpack visa %d", i)))
continue
}
d := v.Data()
if len(d.Issuer) == 0 {
rejected = append(rejected, NewRejectedVisa(d, v.Format(), "iss_missing", "iss", "empty 'iss' field"))
continue
}
if reject := checkViaJKU(v); reject != nil {
rejected = append(rejected, reject)
continue
}
if f != nil {
if err := f(ctx, string(j), v.Data().Issuer, v.JKU()); err != nil {
reason := errutil.ErrorReason(err)
if len(reason) == 0 {
reason = "verify_failed"
}
rejected = append(rejected, NewRejectedVisa(d, v.Format(), reason, "", err.Error()))
continue
}
}
var cond map[string]OldClaimCondition
if len(d.Assertion.Conditions) > 0 {
// Conditions on visas are not supported in non-experimental mode.
if !globalflags.Experimental {
rejected = append(rejected, NewRejectedVisa(d, v.Format(), "condition_not_supported", "visa.condition", "visa conditions not supported"))
continue
}
cond, err = toOldClaimConditions(d.Assertion.Conditions)
if err != nil {
rejected = append(rejected, NewRejectedVisa(d, v.Format(), "condition_not_supported", "visa.condition", err.Error()))
continue
}
}
typ := string(d.Assertion.Type)
values := splitVisaValues(d.Assertion.Value, d.Assertion.Type)
for _, value := range values {
c := OldClaim{
Value: value,
Source: string(d.Assertion.Source),
Asserted: float64(d.Assertion.Asserted),
Expires: float64(d.ExpiresAt),
By: string(d.Assertion.By),
Issuer: d.Issuer,
VisaData: d,
TokenFormat: v.Format(),
Condition: cond,
}
out[typ] = append(out[typ], c)
}
}
return out, rejected, nil
}
func checkViaJKU(v *Visa) *RejectedVisa {
d := v.Data()
openid := strutil.ContainsWord(string(d.Scope), "openid")
if openid {
if len(v.JKU()) > 0 {
return NewRejectedVisa(d, v.Format(), "openid_jku", "", "visa has openid scope and jku")
}
return nil
}
if len(v.JKU()) == 0 {
return NewRejectedVisa(d, v.Format(), "no_openid_no_jku", "", "visa does not have openid scope and jku")
}
issuerURL, err := url.Parse(d.Issuer)
if err != nil {
return NewRejectedVisa(d, v.Format(), "issuer_url_parse", "", fmt.Sprintf("issuer url parse failed: %v", err))
}
jkuURL, err := url.Parse(v.JKU())
if err != nil {
return NewRejectedVisa(d, v.Format(), "jku_url_parse", "", fmt.Sprintf("jku url parse failed: %v", err))
}
if jkuURL.Host != issuerURL.Host {
return NewRejectedVisa(d, v.Format(), "jku_issuer_host", "", "jku does not have same host with visa issuer")
}
if !httputils.IsHTTPS(v.JKU()) && !httputils.IsLocalhost(v.JKU()) {
return NewRejectedVisa(d, v.Format(), "jku_https", "", "jku does not use https")
}
return nil
}
func splitVisaValues(value Value, typ Type) []string {
if typ != LinkedIdentities {
return []string{string(value)}
}
return strings.Split(string(value), ";")
}
func toOldClaimConditions(conditions Conditions) (map[string]OldClaimCondition, error) {
// Input is non-empty DNF: outer OR array with inner AND array.
if len(conditions) > 1 {
return nil, fmt.Errorf("unsupported visa condition: OR conditions are not supported")
}
out := make(map[string]OldClaimCondition)
for _, cond := range conditions[0] {
ctyp := string(cond.Type)
oldCond, ok := out[ctyp]
if ok {
// Old format only allows one sub-condition per visa type, and this
// sub-condition has already been populated, therefore the new
// condition is not compatible with the old claim format.
return nil, fmt.Errorf("unsupported visa condition: multiple conditions on the same visa type not supported")
}
if !ok {
oldCond = OldClaimCondition{}
}
if len(cond.Value) > 0 {
parts := strings.SplitN(string(cond.Value), ":", 2)
if len(parts) != 2 || parts[0] != "const" {
return nil, fmt.Errorf("unsupported visa condition: non-const condition on %q field", "value")
}
oldCond.Value = append(oldCond.Value, parts[1])
}
if len(cond.Source) > 0 {
parts := strings.SplitN(string(cond.Source), ":", 2)
if len(parts) != 2 || parts[0] != "const" {
return nil, fmt.Errorf("unsupported visa condition: non-const condition on %q field", "source")
}
oldCond.Source = append(oldCond.Source, parts[1])
}
if len(cond.By) > 0 {
parts := strings.SplitN(string(cond.By), ":", 2)
if len(parts) != 2 || parts[0] != "const" {
return nil, fmt.Errorf("unsupported visa condition: non-const condition on %q field", "by")
}
oldCond.By = append(oldCond.By, parts[1])
}
out[ctyp] = oldCond
}
return out, nil
}
func toVisaRejectionProto(in VisaRejection) *cpb.VisaRejection {
return &cpb.VisaRejection{
Reason: in.Reason,
Field: in.Field,
Description: in.Description,
}
}
// ToRejectedVisaProto convert RejectedVisa to proto.
func ToRejectedVisaProto(in *RejectedVisa) *cpb.RejectedVisa {
if in == nil {
return nil
}
return &cpb.RejectedVisa{
TokenFormat: in.TokenFormat,
Issuer: in.Issuer,
Subject: in.Subject,
Assertion: toAssertionProto(in.Assertion),
Rejection: toVisaRejectionProto(in.Rejection),
}
}