forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mw_granular_access.go
66 lines (54 loc) · 1.59 KB
/
mw_granular_access.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
package main
import (
"errors"
"net/http"
"regexp"
"github.com/Sirupsen/logrus"
)
// GranularAccessMiddleware will check if a URL is specifically enabled for the key
type GranularAccessMiddleware struct {
*BaseMiddleware
}
func (m *GranularAccessMiddleware) Name() string {
return "GranularAccessMiddleware"
}
// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
func (m *GranularAccessMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
session := ctxGetSession(r)
sessionVersionData, foundAPI := session.AccessRights[m.Spec.APIID]
if !foundAPI {
log.Debug("Version not found")
return nil, 200
}
if len(sessionVersionData.AllowedURLs) == 0 {
log.Debug("No allowed URLS")
return nil, 200
}
for _, accessSpec := range sessionVersionData.AllowedURLs {
log.Debug("Checking: ", r.URL.Path)
log.Debug("Against: ", accessSpec.URL)
asRegex, err := regexp.Compile(accessSpec.URL)
if err != nil {
log.Error("Regex error: ", err)
return nil, 200
}
match := asRegex.MatchString(r.URL.Path)
if match {
log.Debug("Match!")
for _, method := range accessSpec.Methods {
if method == r.Method {
return nil, 200
}
}
}
}
token := ctxGetAuthToken(r)
// No paths matched, disallow
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": requestIP(r),
"key": token,
"api_found": false,
}).Info("Attempted access to unauthorised endpoint (Granular).")
return errors.New("Access to this resource has been disallowed"), 403
}