Compare commits

..

No commits in common. "main" and "v0.1.2" have entirely different histories.
main ... v0.1.2

2 changed files with 17 additions and 30 deletions

View File

@ -11,5 +11,6 @@ testData:
- userId1
- userId2
paths:
- base: /v1/users
path: /testValue
- prefix: /v1/users
mustContain: testValue
- prefix: /v1/organizations

42
main.go
View File

@ -8,13 +8,9 @@ import (
"strings"
)
type Rule struct {
AllowedSubPaths []string `json:"allowedSubPaths,omitempty"`
}
type Path struct {
Path string `json:"base,omitempty"`
Rule Rule `json:"rule,omitempty"`
Prefix string `json:"prefix,omitempty"`
MustContain string `json:"mustContain,omitempty"`
}
type Config struct {
@ -42,8 +38,8 @@ func New(ctx context.Context, next http.Handler, config *Config, name string) (h
}
for _, path := range config.Paths {
if path.Path == "" {
return nil, fmt.Errorf("Paths.Path cannot be empty")
if path.Prefix == "" {
return nil, fmt.Errorf("Paths.Prefix cannot be empty")
}
}
@ -58,8 +54,11 @@ func New(ctx context.Context, next http.Handler, config *Config, name string) (h
func (a *UsersBlocker) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
userId := req.Header["X-Auth-User-Id"][0]
message := fmt.Sprintf("{requestPath: %s, userId: %s}\n", req.URL.Path, userId)
os.Stdout.WriteString(message)
os.Stdout.WriteString("\n request Path ->")
os.Stdout.WriteString(req.URL.Path + "\n")
os.Stdout.WriteString("\n userId ->")
os.Stdout.WriteString(userId + "\n")
var isUserBlocked bool
@ -75,29 +74,16 @@ func (a *UsersBlocker) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
}
for _, path := range a.paths {
isPathMatched := strings.HasPrefix(req.URL.Path, path.Path)
isPathBlocked := strings.HasPrefix(req.URL.Path, path.Prefix)
if !isPathMatched {
a.next.ServeHTTP(rw, req)
return
if isPathBlocked && path.MustContain != "" {
isPathBlocked = !strings.Contains(req.URL.Path, path.MustContain)
}
if len(path.Rule.AllowedSubPaths) == 0 {
message := fmt.Sprintf("blocked path %s (matched with %s) for user %s", req.URL.Path, path.Path, userId)
os.Stdout.WriteString(message)
http.Error(rw, message, http.StatusForbidden)
if isPathBlocked {
http.Error(rw, "Forbidden", http.StatusForbidden)
return
}
for _, allowedSubPath := range path.Rule.AllowedSubPaths {
isAllowedSubPathMatched := strings.HasPrefix(req.URL.Path, path.Path+allowedSubPath)
if !isAllowedSubPathMatched {
message := fmt.Sprintf("blocked path %s (matched with %s) for user %s", req.URL.Path, path.Path+path.Path+allowedSubPath, userId)
os.Stdout.WriteString(message)
http.Error(rw, message, http.StatusForbidden)
return
}
}
}
a.next.ServeHTTP(rw, req)