-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathhelpers.go
More file actions
389 lines (312 loc) · 9.24 KB
/
Copy pathhelpers.go
File metadata and controls
389 lines (312 loc) · 9.24 KB
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package model
import (
_ "embed"
"encoding/json"
"maps"
"slices"
"sort"
"strings"
"sync"
openfga "github.com/openfga/go-sdk"
language "github.com/openfga/language/pkg/go/transformer"
"github.com/pkg/errors"
"google.golang.org/protobuf/encoding/protojson"
"github.com/theopenlane/core/fga/generate/modelparse"
)
const (
// relationPartsCount is the expected number of parts when splitting a relation like "can_view_object"
relationPartsCount = 3
// scopePartsCount is the expected number of parts when splitting a scope like "control:write"
scopePartsCount = 2
)
//go:embed generated/crud.fga
var embeddedCrudModel []byte
//go:embed roles/roles.fga
var embeddedRolesModel []byte
var (
// CanView allows read-only access to an object
CanView = "can_view"
// CanEdit allows read and write access to an object
CanEdit = "can_edit"
// CanDelete allows deletion of an object
CanDelete = "can_delete"
)
var (
// Read is an alias for can_view
Read = "read"
// Write is an alias for can_edit
Write = "write"
// Delete is an alias for can_delete
Delete = "delete"
)
var (
aliasToRelation = map[string]string{
"read": CanView,
"write": CanEdit,
"delete": CanDelete,
}
crudOnce sync.Once
crudModel *openfga.AuthorizationModel
crudErr error
rolesOnce sync.Once
rolesModel *openfga.AuthorizationModel
rolesErr error
organizationRolesOnce sync.Once
organizationRoles []modelparse.OrganizationRole
organizationRolesParseErr error
)
func parseAuthorizationModel(embeddedModel []byte) (*openfga.AuthorizationModel, error) {
protoModel, err := language.TransformDSLToProto(string(embeddedModel))
if err != nil {
return nil, errors.Wrap(err, "parse fga model dsl")
}
rawJSON, err := protojson.Marshal(protoModel)
if err != nil {
return nil, errors.Wrap(err, "marshal fga model")
}
var model openfga.AuthorizationModel
if err := json.Unmarshal(rawJSON, &model); err != nil {
return nil, errors.Wrap(err, "decode fga model json")
}
return &model, nil
}
// GetCrudAuthorizationModel returns the parsed embedded authorization model
func GetCrudAuthorizationModel() (*openfga.AuthorizationModel, error) {
crudOnce.Do(func() {
crudModel, crudErr = parseAuthorizationModel(embeddedCrudModel)
})
return crudModel, crudErr
}
func GetRolesAuthorizationModel() (*openfga.AuthorizationModel, error) {
rolesOnce.Do(func() {
rolesModel, rolesErr = parseAuthorizationModel(embeddedRolesModel)
})
return rolesModel, rolesErr
}
// RelationsForService returns relations shaped like can_<verb>_<object> that directly accept service subjects.
func RelationsForService() ([]string, error) {
model, err := GetCrudAuthorizationModel()
if err != nil {
return nil, err
}
var relations []string
for _, td := range model.GetTypeDefinitions() {
if td.Metadata == nil || td.Metadata.Relations == nil {
continue
}
for rel := range *td.Metadata.Relations {
parts := strings.SplitN(rel, "_", relationPartsCount)
if len(parts) != relationPartsCount || parts[0] != "can" {
continue
}
relations = append(relations, rel)
}
}
sort.Strings(relations)
return relations, nil
}
// getRelations is a helper that returns relations for a given verb (e.g., "manage" or "create") shaped like can_<verb>_<object>
func getRelations(relationType string, modelName string) ([]string, error) {
var model *openfga.AuthorizationModel
var err error
switch modelName {
case "crud":
model, err = GetCrudAuthorizationModel()
case "role":
model, err = GetRolesAuthorizationModel()
default:
return nil, errors.Errorf("invalid model name: %s", modelName) //nolint:err113
}
if err != nil {
return nil, err
}
var relations []string
for _, td := range model.GetTypeDefinitions() {
if td.Metadata == nil || td.Metadata.Relations == nil {
continue
}
for rel := range *td.Metadata.Relations {
parts := strings.SplitN(rel, "_", relationPartsCount)
if len(parts) == relationPartsCount && parts[0] == "can" && parts[1] == relationType {
relations = append(relations, rel)
}
}
}
sort.Strings(relations)
return relations, nil
}
// roleRelations returns relations shaped like can_manage_<role> that indicates role management
func roleRelations() ([]string, error) {
return getRelations("manage", "role")
}
// createRelations returns relations shaped like can_create_<object> that are used for group-based creation access
func createRelations() ([]string, error) {
return getRelations("create", "crud")
}
// DefaultServiceScopeSet returns the default service scopes as a set
func DefaultServiceScopeSet() (map[string]struct{}, error) {
scopes, err := RelationsForService()
if err != nil {
return nil, err
}
set := make(map[string]struct{}, len(scopes))
for _, s := range scopes {
set[s] = struct{}{}
}
return set, nil
}
// NormalizeScope returns the relation name for a provided scope, handling common aliases
// Accepts object:verb (e.g., control:write) and simple verbs (read/write/delete)
func NormalizeScope(scope string) string {
raw := strings.TrimSpace(scope)
if raw == "" {
return ""
}
normalized := strings.ToLower(raw)
mapVerb := func(verb string) string {
if rel, ok := aliasToRelation[verb]; ok {
return rel
}
return verb
}
if parts := strings.SplitN(normalized, ":", scopePartsCount); len(parts) == scopePartsCount && parts[1] != "" {
return mapVerb(parts[1]) + "_" + parts[0]
}
if rel := mapVerb(normalized); rel != "" {
return rel
}
return normalized
}
// ScopeAliases returns a copy of the supported alias mapping
func ScopeAliases() map[string]string {
aliases := make(map[string]string, len(aliasToRelation))
maps.Copy(aliases, aliasToRelation)
return aliases
}
// ScopeOptions groups available scopes by object (verb mapped back via alias map)
func ScopeOptions() (map[string][]string, error) {
rels, err := RelationsForService()
if err != nil {
return nil, err
}
relToVerb := map[string]string{}
for verb, rel := range aliasToRelation {
relToVerb[rel] = verb
}
opts := make(map[string][]string)
for _, rel := range rels {
parts := strings.SplitN(rel, "_", relationPartsCount)
if len(parts) != relationPartsCount || parts[0] != "can" {
continue
}
verb, ok := relToVerb[strings.Join(parts[0:2], "_")]
if !ok {
continue
}
obj := parts[2]
if obj == "" {
continue
}
opts[obj] = append(opts[obj], verb)
}
for obj := range opts {
sort.Strings(opts[obj])
}
return opts, nil
}
func getRelationsOptionsForObject(rels []string) ([]string, error) {
objs := make([]string, 0, len(rels))
for _, rel := range rels {
parts := strings.SplitN(rel, "_", relationPartsCount)
obj := parts[2]
if obj == "" {
continue
}
objs = append(objs, obj)
}
sort.Strings(objs)
return objs, nil
}
// CreateOptions returns objects with verbs that support creation
func CreateOptions() ([]string, error) {
rels, err := createRelations()
if err != nil {
return nil, err
}
return getRelationsOptionsForObject(rels)
}
// RoleOptions returns objects with verbs that support roles
func RoleOptions() ([]string, error) {
rels, err := roleRelations()
if err != nil {
return nil, err
}
if len(rels) == 0 {
return nil, err
}
return getRelationsOptionsForObject(rels)
}
// OrganizationRoles returns the roles parsed from fga
func OrganizationRoles() ([]modelparse.OrganizationRole, error) {
organizationRolesOnce.Do(func() {
if _, err := GetRolesAuthorizationModel(); err != nil {
organizationRolesParseErr = err
return
}
roleInfo, err := modelparse.ParseRoleAnnotationsData(embeddedRolesModel)
if err != nil {
organizationRolesParseErr = err
return
}
organizationRoles = roleInfo.OrganizationRoles
sort.Slice(organizationRoles, func(i, j int) bool {
return organizationRoles[i].ID < organizationRoles[j].ID
})
})
if organizationRolesParseErr != nil {
return nil, organizationRolesParseErr
}
roles := make([]modelparse.OrganizationRole, len(organizationRoles))
copy(roles, organizationRoles)
return roles, nil
}
// FilterOrganizationRoles ensures the assigned role is an organizational role and returns
// a filtered list of OrganizationRoles
func FilterOrganizationRoles(roles []modelparse.OrganizationRole, assigned []string) []modelparse.OrganizationRole {
filtered := make([]modelparse.OrganizationRole, 0, len(assigned))
for _, role := range roles {
if slices.Contains(assigned, role.ID) {
filtered = append(filtered, role)
}
}
return filtered
}
// GetOrganizationRoleStrings takes assigned roles and filters non organization roles and returns a string list of role names
func GetOrganizationRoleStrings(roles []modelparse.OrganizationRole, assigned []string) []string {
filtered := make([]string, 0, len(assigned))
for _, role := range roles {
if slices.Contains(assigned, role.ID) {
filtered = append(filtered, role.Name)
}
}
return filtered
}
func getRoleIDs() ([]string, error) {
roles, err := OrganizationRoles()
if err != nil {
return nil, err
}
ids := make([]string, 0, len(roles))
for _, role := range roles {
ids = append(ids, role.ID)
}
return ids, nil
}
// IsOrganizationRole checks if a role is valid before it can be assigned or removed from a subject
func IsOrganizationRole(roleID string) (bool, error) {
ids, err := getRoleIDs()
if err != nil {
return false, err
}
return slices.Contains(ids, roleID), nil
}