-
Notifications
You must be signed in to change notification settings - Fork 279
/
grammar.go
306 lines (270 loc) · 6.9 KB
/
grammar.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package parser
import (
"encoding/json"
"fmt"
"sort"
"strings"
)
// A Policy is a policy made up of multiple allow or deny rules.
type Policy struct {
Rules []Rule
}
// MarshalJSON marshals the policy as JSON.
func (p *Policy) MarshalJSON() ([]byte, error) {
return json.Marshal(p.ToJSON())
}
// String converts the policy to a string.
func (p *Policy) String() string {
str, _ := p.MarshalJSON()
return string(str)
}
// ToJSON converts the policy to JSON.
func (p *Policy) ToJSON() Value {
var root Array
for _, r := range p.Rules {
root = append(root, r.ToJSON())
}
return root
}
// PolicyFromValue converts a value into a Policy.
func PolicyFromValue(v Value) (*Policy, error) {
rules, err := RulesFromValue(v)
if err != nil {
return nil, fmt.Errorf("invalid rules in policy: %w", err)
}
return &Policy{
Rules: rules,
}, nil
}
// A Rule is a policy rule with a corresponding action ("allow" or "deny"),
// and conditionals to determine if the rule matches or not.
type Rule struct {
Action Action
And []Criterion
Or []Criterion
Not []Criterion
Nor []Criterion
}
// RulesFromValue converts a Value into a slice of Rules. Only Arrays or Objects
// are supported.
func RulesFromValue(v Value) ([]Rule, error) {
switch t := v.(type) {
case Array:
return RulesFromArray(t)
case Object:
return RulesFromObject(t)
default:
return nil, fmt.Errorf("unsupported type for rule: %T", v)
}
}
// RulesFromArray converts an Array into a slice of Rules. Each element of the Array is
// converted using RulesFromObject and merged together.
func RulesFromArray(a Array) ([]Rule, error) {
var rules []Rule
for _, v := range a {
switch t := v.(type) {
case Object:
inner, err := RulesFromObject(t)
if err != nil {
return nil, err
}
rules = append(rules, inner...)
default:
return nil, fmt.Errorf("unsupported type for rules array: %T", v)
}
}
return rules, nil
}
// RulesFromObject converts an Object into a slice of Rules.
//
// One form is supported:
//
// 1. An object where the keys are the actions and the values are an object with "and", "or", or "not" fields:
// `{ "allow": { "and": [ {"groups": "group1"} ] } }`
func RulesFromObject(o Object) ([]Rule, error) {
var rules []Rule
for k, v := range o {
action, err := ActionFromValue(String(k))
if err != nil {
return nil, fmt.Errorf("invalid action in rule: %w", err)
}
oo, ok := v.(Object)
if !ok {
return nil, fmt.Errorf("invalid value for action in rule, expected Object, got %T", v)
}
rule := Rule{
Action: action,
}
err = rule.fillConditionalsFromObject(oo)
if err != nil {
return nil, err
}
rules = append(rules, rule)
}
// sort by action for deterministic ordering
sort.Slice(rules, func(i, j int) bool {
return rules[i].Action < rules[j].Action
})
return rules, nil
}
// MarshalJSON marshals the rule as JSON.
func (r *Rule) MarshalJSON() ([]byte, error) {
return json.Marshal(r.ToJSON())
}
// String converts the rule to a string.
func (r *Rule) String() string {
str, _ := r.MarshalJSON()
return string(str)
}
// ToJSON converts the rule to JSON.
func (r *Rule) ToJSON() Value {
body := Object{}
for _, op := range []struct {
operator string
criteria []Criterion
}{
{"and", r.And},
{"or", r.Or},
{"not", r.Not},
{"nor", r.Nor},
} {
if len(op.criteria) == 0 {
continue
}
var criteria Array
for _, c := range op.criteria {
criteria = append(criteria, c.ToJSON())
}
body[op.operator] = criteria
}
return Object{
string(r.Action): body,
}
}
func (r *Rule) fillConditionalsFromObject(o Object) error {
conditionals := []struct {
Name string
Criteria *[]Criterion
}{
{"and", &r.And},
{"or", &r.Or},
{"not", &r.Not},
{"nor", &r.Nor},
}
for _, cond := range conditionals {
if rawCriteria, ok := o[cond.Name]; ok {
criteria, err := CriteriaFromValue(rawCriteria)
if err != nil {
return fmt.Errorf("invalid criteria in \"%s\"): %w", cond.Name, err)
}
*cond.Criteria = criteria
}
}
for k := range o {
switch k {
case "and", "or", "not", "nor", "action":
default:
return fmt.Errorf("unsupported conditional \"%s\", only and, or, not, nor and action are allowed", k)
}
}
return nil
}
// A Criterion is used by a rule to determine if the rule matches or not.
//
// Criteria RegoRulesGenerators are registered based on the specified name.
// Data is arbitrary JSON data sent to the generator.
type Criterion struct {
Name string
SubPath string
Data Value
}
// CriteriaFromValue converts a Value into Criteria. Only Arrays are supported.
func CriteriaFromValue(v Value) ([]Criterion, error) {
switch t := v.(type) {
case Array:
return CriteriaFromArray(t)
default:
return nil, fmt.Errorf("unsupported type for criteria: %T", v)
}
}
// CriteriaFromArray converts an Array into Criteria. Each element of the Array is
// converted using CriterionFromObject.
func CriteriaFromArray(a Array) ([]Criterion, error) {
var criteria []Criterion
for _, v := range a {
switch t := v.(type) {
case Object:
inner, err := CriterionFromObject(t)
if err != nil {
return nil, err
}
criteria = append(criteria, *inner)
default:
return nil, fmt.Errorf("unsupported type for criteria array: %T", v)
}
}
return criteria, nil
}
// CriterionFromObject converts an Object into a Criterion.
//
// One form is supported:
//
// 1. An object where the keys are the names with a sub path and the values are the corresponding
// data for each Criterion: `{ "groups": "group1" }`
func CriterionFromObject(o Object) (*Criterion, error) {
if len(o) != 1 {
return nil, fmt.Errorf("each criteria may only contain a single key and value")
}
for k, v := range o {
name := k
subPath := ""
if idx := strings.Index(k, "/"); idx >= 0 {
name, subPath = k[:idx], k[idx+1:]
}
return &Criterion{
Name: name,
SubPath: subPath,
Data: v,
}, nil
}
// this can't happen
panic("each criteria may only contain a single key and value")
}
// MarshalJSON marshals the criterion as JSON.
func (c *Criterion) MarshalJSON() ([]byte, error) {
return json.Marshal(c.ToJSON())
}
// String converts the criterion to a string.
func (c *Criterion) String() string {
str, _ := c.MarshalJSON()
return string(str)
}
// ToJSON converts the criterion to JSON.
func (c *Criterion) ToJSON() Value {
nm := c.Name
if c.SubPath != "" {
nm += "/" + c.SubPath
}
return Object{nm: c.Data}
}
// An Action describe what to do when a rule matches, either "allow" or "deny".
type Action string
// ActionFromValue converts a Value into an Action.
func ActionFromValue(value Value) (Action, error) {
s, ok := value.(String)
if !ok {
return "", fmt.Errorf("unsupported type for action: %T", value)
}
switch Action(s) {
case ActionAllow:
return ActionAllow, nil
case ActionDeny:
return ActionDeny, nil
}
return "", fmt.Errorf("unsupported action: %s", s)
}
// Actions
const (
ActionAllow Action = "allow"
ActionDeny Action = "deny"
)