Compare commits

..

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

2 changed files with 12 additions and 32 deletions

View File

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

39
main.go
View File

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