-
Notifications
You must be signed in to change notification settings - Fork 1
/
validate.go
72 lines (62 loc) · 1.88 KB
/
validate.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
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
mapset "github.com/deckarep/golang-set/v2"
)
func validate(input []byte) []byte {
var validationRequest RawValidationRequest
validationRequest.Settings = Settings{
// this is required to make the unmarshal work
ValidUsers: mapset.NewSet[string](),
ValidActions: mapset.NewSet[string](),
ValidResources: mapset.NewSet[string](),
}
decoder := json.NewDecoder(strings.NewReader(string(input)))
decoder.DisallowUnknownFields()
err := decoder.Decode(&validationRequest)
if err != nil {
//nolint: mnd
return marshalValidationResponseOrFail(
RejectRequest(
Message(fmt.Sprintf("Error deserializing validation request: %v", err)),
Code(400)))
}
return marshalValidationResponseOrFail(
validateRequest(validationRequest.Settings, validationRequest.Request))
}
func marshalValidationResponseOrFail(response ValidationResponse) []byte {
responseBytes, err := json.Marshal(&response)
if err != nil {
log.Fatalf("cannot marshal validation response: %v", err)
}
return responseBytes
}
func validateRequest(settings Settings, request Request) ValidationResponse {
if settings.ValidUsers.Contains(request.User) &&
settings.ValidActions.Contains(request.Action) &&
settings.ValidResources.Contains(request.Resource) {
return AcceptRequest()
}
if !settings.ValidUsers.Contains(request.User) {
//nolint: mnd
return RejectRequest(
Message(fmt.Sprintf("User '%s' is not allowed", request.User)),
Code(403))
}
if !settings.ValidActions.Contains(request.Action) {
//nolint: mnd
return RejectRequest(
Message(fmt.Sprintf("Action '%s' is not allowed", request.Action)),
Code(403))
}
if !settings.ValidResources.Contains(request.Resource) {
//nolint: mnd
return RejectRequest(
Message(fmt.Sprintf("Resource '%s' is not allowed", request.Resource)),
Code(403))
}
return AcceptRequest()
}