-
Notifications
You must be signed in to change notification settings - Fork 0
/
policydata.go
176 lines (161 loc) · 4.21 KB
/
policydata.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package policybench
import (
"encoding/csv"
"encoding/json"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"time"
"github.com/brianvoe/gofakeit/v6"
)
/*
type policyData struct {
User string `fake:"{regex:[[:word:]]{8,15}}" json:"user,omitempty"`
AllowedActions []string `fake:"skip" json:"omitempty"`
}
*/
type allowedUserActions map[string][]string
func SetUpPolicyData(newData *bool, noOfRecords uint, jsonPolFile string) allowedUserActions {
if *newData {
return NewPolicyDataMap(noOfRecords)
}
// try to read from json
pd, err := ReadJSON(jsonPolFile)
if err != nil {
// problem with the file, cant'use
*newData = true
return NewPolicyDataMap(noOfRecords)
}
return pd
}
/*
// func NewPolicyData(count uint) []*policyData {
// pd := make([]*policyData, count)
// actions := []string{"produce", "consume", "none"}
// for i := range pd {
// pd[i] = &policyData{}
// err := gofakeit.Struct(pd[i])
// if err != nil {
// log.Fatalf("failed to create test policy: %v\n", err)
// }
// pd[i].User = pd[i].User + strconv.Itoa(i) // make sure these are unique
// pd[i].AllowedActions = selectRandNof(2, actions)
// }
// return pd
// }
*/
func NewPolicyDataMap(count uint) allowedUserActions {
ua := make(map[string][]string)
actions := []string{"produce", "consume", "none"}
for i := uint(0); i < count; i++ {
userName := gofakeit.Regex("[[:word:]]{8,15}") + strconv.FormatUint(uint64(i), 10) // make sure these are unique
ua[userName] = selectRandNof(2, actions)
}
return ua
}
/*
func GetRndUser(pd []*policyData) string {
rand.Seed(time.Now().UnixNano())
rInd := rand.Intn(len(pd))
return pd[rInd].User
}
*/
func GetRndUser(ua allowedUserActions) string {
rand.Seed(time.Now().UnixNano())
rInd := rand.Intn(len(ua))
var userName string
for userName = range ua {
if rInd == 0 {
break
}
rInd--
}
return userName
}
func WriteCSV(f *os.File, ua allowedUserActions) error {
w := csv.NewWriter(f)
for userName := range ua {
for _, act := range ua[userName] {
r := []string{"p", userName, "*", act}
err := w.Write(r)
if err != nil {
return err
}
}
}
w.Flush()
return nil
}
func WriteJSON(f *os.File, ua allowedUserActions) error {
e := json.NewEncoder(f)
// { "users": { "<user1>": ["act1,..,"actn"],..,"<userN>":["act1",..,"actN"]}}
regoPolicies := map[string]interface{}{"users": ua}
err := e.Encode(regoPolicies)
if err != nil {
return err
}
return nil
}
func ReadJSON(jsonPolFile string) (allowedUserActions, error) {
f, err := os.Open(jsonPolFile)
if err != nil {
return nil, err
}
defer f.Close()
d := json.NewDecoder(f)
rr := make(map[string]allowedUserActions)
err = d.Decode(&rr)
if err != nil {
return nil, err
}
ua := rr["users"]
if ua == nil {
return nil, fmt.Errorf("wrong JSON file format, key \"users\" is missing, file %s: ", jsonPolFile)
}
return rr["users"], nil
}
//WritePolarRules creates an ACL using Polar langauge: allow("user","act","*");
func WritePolarRules(f *os.File, ua allowedUserActions) error {
for userName := range ua {
for _, act := range ua[userName] {
_, err := f.WriteString(fmt.Sprintf("allow(%q,%q,\"*\");\n", userName, act))
if err != nil {
return err
}
}
}
return nil
}
func SetUpPolicyFile(newData bool, file string, ua allowedUserActions, wf func(*os.File, allowedUserActions) error) error {
var (
pf *os.File
wErr error
)
fFlags := os.O_CREATE | os.O_WRONLY
switch _, err := os.Stat(file); {
case err == nil && !newData: //file exists & should be re-used
log.Printf("Re-using exiting policies file: %s \n", file)
return nil
// case err != nil && !newData: // wanted to re-use but file is missing
// log.Printf("Can't re-use policy file: %s, please rerun the benchmark with the 'new-data' flag\n", file)
// return err
case err == nil && newData: // file exists & should be re-written
fFlags |= os.O_TRUNC
log.Printf("Existing policy file: %s will be re-written \n", file)
fallthrough
case err != nil:
pf, err = os.OpenFile(file, fFlags, 0644)
if err != nil {
return err
}
log.Printf("Preparing to write %d policies to file %s \n", len(ua), file)
wErr = wf(pf, ua)
if wErr == nil {
log.Println("Finished writing policies!")
}
}
safeClose(pf, wErr)
return wErr
}