-
Notifications
You must be signed in to change notification settings - Fork 18
/
check.go
531 lines (456 loc) · 14.8 KB
/
check.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
//Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
//Licensed under the Universal Permissive License (UPL) Version 1.0 as shown at http://oss.oracle.com/licenses/upl.
package adsrest
import (
"encoding/json"
"net/http"
"reflect"
"time"
adsapi "github.com/teramoby/speedle-plus/api/ads"
"github.com/teramoby/speedle-plus/pkg/cfg"
"github.com/teramoby/speedle-plus/pkg/errors"
"github.com/teramoby/speedle-plus/pkg/eval"
"github.com/teramoby/speedle-plus/pkg/httputils"
"github.com/teramoby/speedle-plus/pkg/logging"
"github.com/teramoby/speedle-plus/pkg/svcs"
log "github.com/sirupsen/logrus"
)
type JsonAttribute struct {
Name string `json:"name"`
Type string `json:"type"`
Value interface{} `json:"value"`
}
type JsonPrincipal struct {
Type string `json:"type,omitempty"`
Name string `json:"name,omitempty"`
IDD string `json:"idd,omitempty"`
}
type JsonSubject struct {
Principals []*JsonPrincipal `json:"principals,omitempty"`
TokenType string `json:"tokenType"`
Token string `json:"token"`
}
type JsonContext struct {
Subject *JsonSubject `json:"subject"`
ServiceName string `json:"serviceName"`
Resource string `json:"resource"`
Action string `json:"action"`
Attributes []*JsonAttribute `json:"attributes"`
}
type RESTService struct {
Evaluator eval.InternalEvaluator
}
type IsAllowedResponse struct {
Allowed bool `json:"allowed"`
Reason int32 `json:"reason"`
ErrorMessage string `json:"errorMessage,omitempty"`
}
type AuditEvaluationResult struct {
Allowed string `json:"allowed"`
Reason string `json:"reason"`
}
type PermissionResponse struct {
Resource string `json:"resource"`
Actions []string `json:"actions"`
}
type PolicyResponse struct {
Status string `json:"status,omitempty"`
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Effect string `json:"effect,omitempty"`
Permissions []Permission `json:"permissions,omitempty"`
Principals [][]string `json:"principals,omitempty"`
Condition EvaluatedCondition `json:"condition,omitempty"`
}
type RolePolicyResponse struct {
Status string `json:"status,omitempty"`
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Effect string `json:"effect,omitempty"`
Roles []string `json:"roles,omitempty"`
Principals []string `json:"principals,omitempty"`
Resources []string `json:"resources,omitempty"`
ResourceExpressions []string `json:"resourceExpressions,omitempty"`
Condition EvaluatedCondition `json:"condition,omitempty"`
}
type Permission struct {
Resource string `json:"resource,omitempty"`
ResourceExpression string `json:"resourceExpression,omitempty"`
Actions []string `json:"actions,omitempty"`
}
type EvaluatedCondition struct {
ConditionExpression string `json:"conditionExpression,omitempty"`
EvaluationResult string `json:"evaluationResult,omitempty"`
}
// Should we add Both of ReasonCode and ReasonMessage
type EvaluationDebugResponse struct {
Allowed bool `json:"allowed"`
Reason string `json:"reason"`
RequestContext JsonContext `json:"requestContext,omitempty"`
Attributes map[string]interface{} `json:"attributes,omitempty"`
GrantedRoles []string `json:"grantedRoles,omitempty"`
RolePolicies []RolePolicyResponse `json:"rolePolicies,omitempty"`
Policies []PolicyResponse `json:"policies,omitempty"`
}
func NewRESTService(conf *cfg.Config) (*RESTService, error) {
Evaluator, err := eval.NewFromConfig(conf)
if err != nil {
return nil, err
}
return &RESTService{
Evaluator: Evaluator,
}, nil
}
func NewRESTServiceWithEvaluator(evaluator eval.InternalEvaluator) (*RESTService, error) {
return &RESTService{
Evaluator: evaluator,
}, nil
}
func DecodeJSONContext(r *http.Request) (*JsonContext, error) {
decoder := json.NewDecoder(r.Body)
var request JsonContext
if err := decoder.Decode(&request); err != nil {
return nil, errors.Wrap(err, errors.InvalidRequest, "unable to decode request")
}
return &request, nil
}
func DuplicateAttributeMap(attrs map[string]interface{}) map[string]interface{} {
if attrs == nil {
return nil
}
ret := make(map[string]interface{})
for key, value := range attrs {
ret[key] = value
}
return ret
}
func VerifyAttributeName(attrName string) error {
// Currently don't verify attribute name
return nil
}
// Key is data type in json
// Value is the data type in go
var dataTypeMap = map[string]string{
"string": "string",
"numeric": "float64",
"bool": "bool",
"datetime": "string",
}
var supportDateTimeLayout = []string{
time.RFC3339Nano,
time.RubyDate,
time.UnixDate,
}
func ParseDateTime(value string) (*time.Time, error) {
for _, layout := range supportDateTimeLayout {
ret, err := time.Parse(layout, value)
if err == nil {
return &ret, nil
}
}
return nil, errors.Errorf(errors.InvalidRequest, "value %q is not a supported date time", value)
}
func ConvSingleValue(dataType string, value interface{}) (interface{}, error) {
if len(dataType) == 0 {
// If data type is empty, return value directly
return value, nil
}
valueType, ok := dataTypeMap[dataType]
if !ok {
// Data type is not match
return nil, errors.Errorf(errors.InvalidRequest, "inputted data type %s is not supported", dataType)
}
if valueType != reflect.TypeOf(value).String() {
return nil, errors.Errorf(errors.InvalidRequest, "value data type %T is not equals to inputted data type %s", value, dataType)
}
switch dataType {
case "datetime":
strValue, _ := value.(string)
retTime, err := ParseDateTime(strValue)
if err != nil {
return nil, err
}
return float64(retTime.Unix()), nil
}
return value, nil
}
func ConvMultipleValues(dataType string, values interface{}) (interface{}, error) {
v := reflect.ValueOf(values)
ret := []interface{}{}
var prevType string
for i := 0; i < v.Len(); i = i + 1 {
vi := v.Index(i)
item, err := ConvSingleValue(dataType, vi.Interface())
if err != nil {
return nil, err
}
if i == 0 {
prevType = reflect.TypeOf(item).String()
} else if prevType != reflect.TypeOf(item).String() {
return nil, errors.New(errors.InvalidRequest, "types of all items in a array should be same")
}
ret = append(ret, item)
}
return ret, nil
}
func ConvValue(dataType string, value interface{}) (interface{}, error) {
if value == nil {
return nil, errors.New(errors.InvalidRequest, "null value is not allowed")
}
if reflect.TypeOf(value).Kind() == reflect.Slice {
return ConvMultipleValues(dataType, value)
}
return ConvSingleValue(dataType, value)
}
func DumpRequestAttributes(attrs []*JsonAttribute) (map[string]interface{}, error) {
// No attributes found
if attrs == nil || len(attrs) == 0 {
return nil, nil
}
attrMap := make(map[string]interface{})
for _, attr := range attrs {
if err := VerifyAttributeName(attr.Name); err != nil {
return nil, err
}
value, err := ConvValue(attr.Type, attr.Value)
if err != nil {
return nil, err
}
attrMap[attr.Name] = value
}
return attrMap, nil
}
func DumpPrincipals(principals []*JsonPrincipal) []*adsapi.Principal {
if principals == nil {
return nil
}
ret := []*adsapi.Principal{}
for _, princ := range principals {
ret = append(ret, &adsapi.Principal{
Type: princ.Type,
Name: princ.Name,
IDD: princ.IDD,
})
}
return ret
}
func ConvertJSONRequestToContext(ctxContext *JsonContext) (*adsapi.RequestContext, error) {
subject := adsapi.Subject{}
if ctxContext.Subject != nil {
apiPrincipals := DumpPrincipals(ctxContext.Subject.Principals)
subject = adsapi.Subject{
Principals: apiPrincipals,
TokenType: ctxContext.Subject.TokenType,
Token: ctxContext.Subject.Token,
}
}
contextAttr, err := DumpRequestAttributes(ctxContext.Attributes)
if err != nil {
return nil, err
}
context := adsapi.RequestContext{
Subject: &subject,
ServiceName: ctxContext.ServiceName,
Resource: ctxContext.Resource,
Action: ctxContext.Action,
Attributes: contextAttr,
}
return &context, nil
}
func constructEvaluationResultForAudit(allowed bool, reason adsapi.Reason) *AuditEvaluationResult {
evaResult := "denied"
if allowed {
evaResult = "allowed"
}
auditResult := AuditEvaluationResult{
Allowed: evaResult,
Reason: reason.String(),
}
return &auditResult
}
func (e *RESTService) IsAllowed(w http.ResponseWriter, r *http.Request) {
jsonRequest, err := DecodeJSONContext(r)
if err != nil {
httputils.HandleError(w, err)
return
}
context, err := ConvertJSONRequestToContext(jsonRequest)
if err != nil {
httputils.HandleError(w, err)
return
}
result, reason, err := e.Evaluator.IsAllowed(*context)
response := IsAllowedResponse{
Allowed: result,
Reason: int32(reason),
}
// Audit log
responseForAudit := constructEvaluationResultForAudit(result, reason)
//Token assertion is done in e.Evaluator.IsAllowed(). Now context has been populated with subject info
if len(context.Subject.Principals) > 0 {
for _, principal := range context.Subject.Principals {
if principal.Type == adsapi.PRINCIPAL_TYPE_USER {
w.Header().Add(svcs.PrincipalsHeader, principal.Name)
break
}
}
}
if err != nil {
response.ErrorMessage = err.Error()
logging.WriteFailedAuditLog("IsAllowed", log.Fields{"requestContext": context, "evaluationResult": responseForAudit}, response.ErrorMessage)
} else {
logging.WriteSucceededAuditLog("IsAllowed", log.Fields{"requestContext": context}, log.Fields{"evaluationResult": responseForAudit})
}
httputils.SendOKResponse(w, &response)
}
func (e *RESTService) GetAllGrantedRoles(w http.ResponseWriter, r *http.Request) {
jsonRequest, err := DecodeJSONContext(r)
if err != nil {
httputils.HandleError(w, err)
return
}
context, err := ConvertJSONRequestToContext(jsonRequest)
if err != nil {
httputils.HandleError(w, err)
return
}
roles, err := e.Evaluator.GetAllGrantedRoles(*context)
if err != nil {
httputils.HandleError(w, err)
// Audit log
logging.WriteFailedAuditLog("GetAllGrantedRoles", log.Fields{"requestContext": context}, err.Error())
return
}
// Audit log
logging.WriteSucceededAuditLog("GetAllGrantedRoles", log.Fields{"requestContext": context}, log.Fields{"roles": roles})
if len(roles) == 0 {
httputils.SendEmptyListResponse(w)
return
}
httputils.SendOKResponse(w, roles)
}
func (e *RESTService) GetAllGrantedPermissions(w http.ResponseWriter, r *http.Request) {
jsonRequest, err := DecodeJSONContext(r)
if err != nil {
httputils.HandleError(w, err)
return
}
context, err := ConvertJSONRequestToContext(jsonRequest)
if err != nil {
httputils.HandleError(w, err)
return
}
permissions, err := e.Evaluator.GetAllGrantedPermissions(*context)
if err != nil {
httputils.HandleError(w, err)
// Audit log
logging.WriteFailedAuditLog("GetAllGrantedPermissions", log.Fields{"requestContext": context}, err.Error())
return
}
var retPermissions []PermissionResponse
for _, permission := range permissions {
retPermissions = append(retPermissions, PermissionResponse{
Resource: permission.Resource,
Actions: permission.Actions,
})
}
// Audit log
logging.WriteSucceededAuditLog("GetAllGrantedPermissions", log.Fields{"requestContext": context}, log.Fields{"permissions": retPermissions})
if len(retPermissions) == 0 {
httputils.SendEmptyListResponse(w)
return
}
httputils.SendOKResponse(w, retPermissions)
}
func ConvertAPIPolicy2PolicyResponse(apiPolicy *adsapi.EvaluatedPolicy, policyResp *PolicyResponse) {
if apiPolicy == nil || policyResp == nil {
// It shouldn't happen
return
}
var retPermission []Permission
for _, permission := range apiPolicy.Permissions {
retPermission = append(retPermission, Permission{
Resource: permission.Resource,
Actions: permission.Actions,
ResourceExpression: permission.ResourceExpression,
})
}
policyResp.Status = apiPolicy.Status
policyResp.ID = apiPolicy.ID
policyResp.Name = apiPolicy.Name
policyResp.Effect = apiPolicy.Effect
policyResp.Permissions = retPermission
policyResp.Principals = apiPolicy.Principals
if apiPolicy.Condition != nil {
policyResp.Condition = EvaluatedCondition{
ConditionExpression: apiPolicy.Condition.ConditionExpression,
EvaluationResult: apiPolicy.Condition.EvaluationResult,
}
}
}
func ConvertAPIRolePolicy2RolePolicyResponse(apiRolePolicy *adsapi.EvaluatedRolePolicy, rolePolicyResp *RolePolicyResponse) {
if apiRolePolicy == nil || rolePolicyResp == nil {
// It shouldn't happen
return
}
rolePolicyResp.Status = apiRolePolicy.Status
rolePolicyResp.ID = apiRolePolicy.ID
rolePolicyResp.Name = apiRolePolicy.Name
rolePolicyResp.Effect = apiRolePolicy.Effect
rolePolicyResp.Roles = apiRolePolicy.Roles
rolePolicyResp.Principals = apiRolePolicy.Principals
rolePolicyResp.Resources = apiRolePolicy.Resources
rolePolicyResp.ResourceExpressions = apiRolePolicy.ResourceExpressions
if apiRolePolicy.Condition != nil {
rolePolicyResp.Condition = EvaluatedCondition{
ConditionExpression: apiRolePolicy.Condition.ConditionExpression,
EvaluationResult: apiRolePolicy.Condition.EvaluationResult,
}
}
}
func (e *RESTService) Diagnose(w http.ResponseWriter, r *http.Request) {
jsonRequest, err := DecodeJSONContext(r)
if err != nil {
httputils.HandleError(w, err)
return
}
context, err := ConvertJSONRequestToContext(jsonRequest)
if err != nil {
httputils.HandleError(w, err)
return
}
evaResult, err := e.Evaluator.Diagnose(*context)
if err != nil {
httputils.HandleError(w, err)
// Audit log
logging.WriteSimpleFailedAuditLog("Diagnose", context, err.Error())
return
}
// Convert all the returned policies
var retPolicies []PolicyResponse
for _, policy := range evaResult.Policies {
var policyResp PolicyResponse
ConvertAPIPolicy2PolicyResponse(policy, &policyResp)
retPolicies = append(retPolicies, policyResp)
}
// Convert all the returned role policies
var retRolePolicies []RolePolicyResponse
for _, rolePolicy := range evaResult.RolePolicies {
var rolePolicyResp RolePolicyResponse
ConvertAPIRolePolicy2RolePolicyResponse(rolePolicy, &rolePolicyResp)
retRolePolicies = append(retRolePolicies, rolePolicyResp)
}
// Construct & return the response
response := EvaluationDebugResponse{
Allowed: evaResult.Allowed,
Reason: evaResult.Reason.String(),
RequestContext: *jsonRequest,
Attributes: evaResult.Attributes,
GrantedRoles: evaResult.GrantedRoles,
RolePolicies: retRolePolicies,
Policies: retPolicies,
}
// Audit log
logging.WriteSimpleSucceededAuditLog("Diagnose", context, &response)
httputils.SendOKResponse(w, &response)
}