forked from movio/bramble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
335 lines (293 loc) · 10 KB
/
auth.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package bramble
import (
"encoding/json"
"fmt"
"sort"
"strings"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/gqlerror"
)
// AllowedFields is a recursive set of allowed fields.
type AllowedFields struct {
AllowAll bool
AllowedSubfields map[string]AllowedFields
}
// IsAllowed returns whether the sub field is allowed along with the
// permissions for its own subfields
func (a AllowedFields) IsAllowed(fieldName string) (bool, AllowedFields) {
if fieldName == "__schema" || fieldName == "__type" {
return true, AllowedFields{AllowAll: true}
}
if fieldName == "__typename" {
return true, AllowedFields{}
}
if f, ok := a.AllowedSubfields[fieldName]; ok {
return true, f
}
return false, AllowedFields{}
}
// OperationPermissions represents the user permissions for all operation types
type OperationPermissions struct {
AllowedRootQueryFields AllowedFields `json:"query"`
AllowedRootMutationFields AllowedFields `json:"mutation"`
AllowedRootSubscriptionFields AllowedFields `json:"subscription"`
}
type fieldList []string
func (f fieldList) Len() int {
return len(f)
}
func (f fieldList) Less(i, j int) bool {
return f[i] < f[j]
}
func (f fieldList) Swap(i, j int) {
f[i], f[j] = f[j], f[i]
}
// MarshalJSON marshals to a JSON representation.
func (a AllowedFields) MarshalJSON() ([]byte, error) {
if a.AllowAll {
return json.Marshal("*")
}
fields := make(fieldList, 0, len(a.AllowedSubfields))
for field, subfields := range a.AllowedSubfields {
if !subfields.AllowAll {
return json.Marshal(a.AllowedSubfields)
}
fields = append(fields, field)
}
// ensure a deterministic order
sort.Sort(fields)
return json.Marshal(fields)
}
// UnmarshalJSON unmarshals from a JSON representation.
func (a *AllowedFields) UnmarshalJSON(input []byte) error {
a.AllowAll = false
var str string
if err := json.Unmarshal(input, &str); err == nil && str == "*" {
a.AllowAll = true
return nil
}
var fields []string
if err := json.Unmarshal(input, &fields); err == nil {
if a.AllowedSubfields == nil {
a.AllowedSubfields = map[string]AllowedFields{}
}
for _, field := range fields {
a.AllowedSubfields[field] = AllowedFields{AllowAll: true}
}
return nil
}
return json.Unmarshal(input, &a.AllowedSubfields)
}
// MarshalJSON marshals to a JSON representation.
func (o OperationPermissions) MarshalJSON() ([]byte, error) {
m := make(map[string]AllowedFields)
if o.AllowedRootQueryFields.AllowAll || o.AllowedRootQueryFields.AllowedSubfields != nil {
m["query"] = o.AllowedRootQueryFields
}
if o.AllowedRootMutationFields.AllowAll || o.AllowedRootMutationFields.AllowedSubfields != nil {
m["mutation"] = o.AllowedRootMutationFields
}
if o.AllowedRootSubscriptionFields.AllowAll || o.AllowedRootSubscriptionFields.AllowedSubfields != nil {
m["subscription"] = o.AllowedRootSubscriptionFields
}
return json.Marshal(m)
}
// FilterAuthorizedFields filters the operation's selection set and removes all
// fields that are not explicitly authorized.
// Every unauthorized field is returned as an error.
func (o *OperationPermissions) FilterAuthorizedFields(op *ast.OperationDefinition) gqlerror.List {
var res ast.SelectionSet
var errs gqlerror.List
switch op.Operation {
case ast.Query:
res, errs = filterFields([]string{"query"}, op.SelectionSet, o.AllowedRootQueryFields)
case ast.Mutation:
res, errs = filterFields([]string{"mutation"}, op.SelectionSet, o.AllowedRootMutationFields)
case ast.Subscription:
res, errs = filterFields([]string{"subscription"}, op.SelectionSet, o.AllowedRootSubscriptionFields)
default:
panic(fmt.Sprintf("invalid operation %q in operation filtering", op.Operation))
}
op.SelectionSet = res
return errs
}
// FilterSchema returns a copy of the given schema stripped of any unauthorized
// fields and types
func (o *OperationPermissions) FilterSchema(schema *ast.Schema) *ast.Schema {
newSchema := *schema
newSchema.Types = make(map[string]*ast.Definition)
newSchema.Query = filterDefinition(schema, nil, newSchema.Types, schema.Query, o.AllowedRootQueryFields)
if newSchema.Query != nil {
newSchema.Types["Query"] = newSchema.Query
}
newSchema.Mutation = filterDefinition(schema, nil, newSchema.Types, schema.Mutation, o.AllowedRootMutationFields)
if newSchema.Mutation != nil {
newSchema.Types["Mutation"] = newSchema.Mutation
}
newSchema.Subscription = filterDefinition(schema, nil, newSchema.Types, schema.Subscription, o.AllowedRootSubscriptionFields)
if newSchema.Subscription != nil {
newSchema.Types["Subscription"] = newSchema.Subscription
}
return &newSchema
}
func filterDefinition(sourceSchema *ast.Schema, visited map[string]bool, types map[string]*ast.Definition, def *ast.Definition, allowedFields AllowedFields) *ast.Definition {
if def == nil {
return nil
}
resDef := *def
resDef.Fields = nil
if allowedFields.AllowAll {
if visited == nil {
// visited keeps track of already visited subfields, so that we
// don't enter into an infinite recursion
visited = make(map[string]bool)
}
resDef.Fields = def.Fields
// copy recursively all the subtypes for every field into the result schema
for _, f := range def.Fields {
typeName := f.Type.Name()
if visited[def.Name+f.Name] {
continue
}
visited[def.Name+f.Name] = true
typ := sourceSchema.Types[typeName]
if typ == nil {
// Node interface is not defined in the merged schema
continue
}
if typ.IsAbstractType() {
for _, pt := range sourceSchema.PossibleTypes[typ.Name] {
types[pt.Name] = pt
_ = filterDefinition(sourceSchema, visited, types, pt, AllowedFields{AllowAll: true})
}
}
types[typeName] = typ
for _, a := range f.Arguments {
types[a.Type.Name()] = sourceSchema.Types[a.Type.Name()]
_ = filterDefinition(sourceSchema, visited, types, sourceSchema.Types[a.Type.Name()], AllowedFields{AllowAll: true})
}
_ = filterDefinition(sourceSchema, visited, types, sourceSchema.Types[typeName], AllowedFields{AllowAll: true})
}
return &resDef
}
for _, f := range def.Fields {
if allowedSubFields, ok := allowedFields.AllowedSubfields[f.Name]; ok {
resDef.Fields = append(resDef.Fields, f)
typename := f.Type.Name()
typ := sourceSchema.Types[typename]
if typ == nil {
// Node interface is not defined in the merged schema
continue
}
// if the type is abstract we filter all the possible types
if typ.IsAbstractType() {
for _, pt := range sourceSchema.PossibleTypes[typ.Name] {
newTypeDef := filterDefinition(sourceSchema, visited, types, pt, allowedSubFields)
if typeDef, ok := types[pt.Name]; ok {
addFields(typeDef, newTypeDef)
} else {
types[pt.Name] = newTypeDef
}
}
}
newTypeDef := filterDefinition(sourceSchema, visited, types, typ, allowedSubFields)
if typeDef, ok := types[typename]; ok {
// a type could be accessed through multiple paths, so we need
// to merge the fields
addFields(typeDef, newTypeDef)
} else {
types[typename] = newTypeDef
}
// add input types
for _, a := range f.Arguments {
types[a.Type.Name()] = sourceSchema.Types[a.Type.Name()]
_ = filterDefinition(sourceSchema, visited, types, sourceSchema.Types[a.Type.Name()], AllowedFields{AllowAll: true})
}
}
}
return &resDef
}
func addFields(a, b *ast.Definition) {
for _, f := range b.Fields {
if a.Fields.ForName(f.Name) == nil {
a.Fields = append(a.Fields, f)
}
}
}
// filterFields filters allowed fields and returns a new selection set
func filterFields(path []string, ss ast.SelectionSet, allowedFields AllowedFields) (ast.SelectionSet, gqlerror.List) {
res := make(ast.SelectionSet, 0, len(ss))
var errs gqlerror.List
if allowedFields.AllowAll {
return ss, nil
}
for _, s := range ss {
switch s := s.(type) {
case *ast.Field:
if allowed, fieldsPerms := allowedFields.IsAllowed(s.Name); allowed {
if fieldsPerms.AllowAll {
res = append(res, s)
continue
}
var ferrs gqlerror.List
fieldPath := append(path, s.Name)
s.SelectionSet, ferrs = filterFields(fieldPath, s.SelectionSet, fieldsPerms)
res = append(res, s)
errs = append(errs, ferrs...)
} else {
errs = append(errs, gqlerror.Errorf("user do not have permission to access field %s.%s", strings.Join(path, "."), s.Name))
}
case *ast.FragmentSpread:
var ferrs gqlerror.List
s.Definition.SelectionSet, ferrs = filterFields(path, s.Definition.SelectionSet, allowedFields)
res = append(res, s)
errs = append(errs, ferrs...)
case *ast.InlineFragment:
var ferrs gqlerror.List
s.SelectionSet, ferrs = filterFields(path, s.SelectionSet, allowedFields)
res = append(res, s)
errs = append(errs, ferrs...)
}
}
return res, errs
}
// MergePermissions merges the given permissions. The result permissions are the
// union of the given permissions (allow everything that is allowed in any of the given permissions).
func MergePermissions(perms ...OperationPermissions) OperationPermissions {
var queries []AllowedFields
var mutations []AllowedFields
var subscriptions []AllowedFields
for _, p := range perms {
queries = append(queries, p.AllowedRootQueryFields)
mutations = append(mutations, p.AllowedRootMutationFields)
subscriptions = append(subscriptions, p.AllowedRootSubscriptionFields)
}
return OperationPermissions{
AllowedRootQueryFields: MergeAllowedFields(queries...),
AllowedRootMutationFields: MergeAllowedFields(mutations...),
AllowedRootSubscriptionFields: MergeAllowedFields(subscriptions...),
}
}
// MergeAllowedFields merges the given AllowedFields. The result is the union of
// all the allowed fields.
func MergeAllowedFields(allowedFields ...AllowedFields) AllowedFields {
res := AllowedFields{
AllowedSubfields: make(map[string]AllowedFields),
}
for _, af := range allowedFields {
if af.AllowAll {
return AllowedFields{
AllowAll: true,
}
}
for f, sf := range af.AllowedSubfields {
resSubFields, ok := res.AllowedSubfields[f]
if !ok {
res.AllowedSubfields[f] = sf
continue
}
res.AllowedSubfields[f] = MergeAllowedFields(sf, resSubFields)
}
}
return res
}