-
Notifications
You must be signed in to change notification settings - Fork 14
/
scope.go
109 lines (97 loc) · 2.5 KB
/
scope.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
package accesscontrol
import (
"net/http"
"github.com/avenga/couper/config/request"
"github.com/avenga/couper/errors"
)
var supportedOperations = []string{
http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodConnect,
http.MethodOptions,
http.MethodTrace,
}
type requiredScope struct {
scopes map[string][]string
}
func newRequiredScope() requiredScope {
return requiredScope{scopes: make(map[string][]string)}
}
func (r *requiredScope) addScopeMap(scopeMap map[string]string) {
otherScope, otherMethodExists := scopeMap["*"]
for _, op := range supportedOperations {
scope, exists := scopeMap[op]
if exists {
r.addScopeForOperation(op, scope)
} else if otherMethodExists {
r.addScopeForOperation(op, otherScope)
} else {
delete(r.scopes, op)
}
}
}
func (r *requiredScope) addScopeForOperation(operation, scope string) {
scopes, exists := r.scopes[operation]
if !exists {
if scope == "" {
// method permitted without scope
r.scopes[operation] = []string{}
return
}
// method permitted with required scope
r.scopes[operation] = []string{scope}
return
}
// no additional scope required
if scope == "" {
return
}
// add scope to required scopes for this operation
r.scopes[operation] = append(scopes, scope)
}
var _ AccessControl = &ScopeControl{}
type ScopeControl struct {
required requiredScope
}
func NewScopeControl(scopeMaps []map[string]string) *ScopeControl {
rs := newRequiredScope()
for _, scopeMap := range scopeMaps {
if scopeMap != nil {
rs.addScopeMap(scopeMap)
}
}
return &ScopeControl{required: rs}
}
// Validate validates the scope values provided by access controls against the required scope values.
func (s *ScopeControl) Validate(req *http.Request) error {
if len(s.required.scopes) == 0 {
return nil
}
requiredScopes, exists := s.required.scopes[req.Method]
if !exists {
return errors.BetaOperationDenied.Messagef("operation %s not permitted", req.Method)
}
ctx := req.Context()
grantedScope, ok := ctx.Value(request.Scopes).([]string)
if !ok && len(requiredScopes) > 0 {
return errors.BetaInsufficientScope.Messagef("no scope granted")
}
for _, rs := range requiredScopes {
if !hasGrantedScope(grantedScope, rs) {
return errors.BetaInsufficientScope.Messagef("required scope %q not granted", rs)
}
}
return nil
}
func hasGrantedScope(grantedScope []string, scope string) bool {
for _, gs := range grantedScope {
if gs == scope {
return true
}
}
return false
}