-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathmodel.go
More file actions
461 lines (355 loc) · 11.7 KB
/
Copy pathmodel.go
File metadata and controls
461 lines (355 loc) · 11.7 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/*
Copyright © 2023 OpenFGA
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package authorizationmodel
import (
"encoding/json"
"errors"
"fmt"
"math"
"path/filepath"
"time"
"github.com/oklog/ulid/v2"
openfgav1 "github.com/openfga/api/proto/openfga/v1"
openfga "github.com/openfga/go-sdk"
language "github.com/openfga/language/pkg/go/transformer"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"github.com/openfga/cli/internal/safefile"
"github.com/openfga/cli/internal/slices"
)
// readModelFile reads a file belonging to a modular model. When containBase is
// non-empty the read is contained to that directory, so a contents entry cannot
// escape it; otherwise the file is read directly. Either way the target must be
// a regular file.
func readModelFile(filePath string, containBase string) ([]byte, error) {
if containBase == "" {
return safefile.ReadExternal(filePath) //nolint:wrapcheck
}
rel, err := filepath.Rel(containBase, filePath)
if err != nil {
return nil, fmt.Errorf("unable to resolve %q against %q: %w", filePath, containBase, err)
}
return safefile.ReadContained(containBase, rel) //nolint:wrapcheck
}
func getCreatedAtFromModelID(id string) (*time.Time, error) {
modelID, err := ulid.Parse(id)
if err != nil {
return nil, fmt.Errorf("error parsing model id %w", err)
}
createdAt := ulid.Time(modelID.Time()).UTC()
return &createdAt, nil
}
type AuthzModelList struct {
AuthorizationModels []AuthzModel `json:"authorization_models"`
}
type AuthzModel struct {
ID *string `json:"id,omitempty"`
CreatedAt *time.Time `json:"created_at,omitempty"`
SizeKB *float64 `json:"size_kb,omitempty"`
SchemaVersion *string `json:"schema_version,omitempty"`
TypeDefinitions *[]openfga.TypeDefinition `json:"type_definitions,omitempty"`
Conditions map[string]*openfga.Condition `json:"conditions,omitempty"`
}
func (model *AuthzModel) GetID() string {
if model == nil || model.ID == nil {
var ret string
return ret
}
return *model.ID
}
func (model *AuthzModel) GetSchemaVersion() string {
if model == nil || model.SchemaVersion == nil {
var ret string
return ret
}
return *model.SchemaVersion
}
func (model *AuthzModel) GetTypeDefinitions() []openfga.TypeDefinition {
if model == nil || model.TypeDefinitions == nil {
var ret []openfga.TypeDefinition
return ret
}
return *model.TypeDefinitions
}
func (model *AuthzModel) GetConditions() *map[string]openfga.Condition {
conditions := make(map[string]openfga.Condition)
if model == nil || model.Conditions == nil {
return &conditions
}
for conditionName, condition := range model.Conditions {
conditions[conditionName] = *condition
}
return &conditions
}
func (model *AuthzModel) GetProtoModel() *openfgav1.AuthorizationModel {
if model == nil {
return nil
}
var pbModel openfgav1.AuthorizationModel
jsonModel, err := model.GetAsJSONString()
if err != nil {
return nil
}
if err = (protojson.UnmarshalOptions{DiscardUnknown: true}).Unmarshal([]byte(*jsonModel), &pbModel); err != nil {
return nil
}
return &pbModel
}
func (model *AuthzModel) GetSizeInKB() float64 {
return ProtoModelSizeInKB(model.GetProtoModel())
}
// ProtoModelSizeInKB returns the protobuf-serialized size of the model in KB,
// rounded to two decimal places. Returns 0 for a nil model.
func ProtoModelSizeInKB(pbModel *openfgav1.AuthorizationModel) float64 {
if pbModel == nil {
return 0
}
sizeKB := float64(proto.Size(pbModel)) / 1024.0 //nolint:mnd
return math.Round(sizeKB*100) / 100 //nolint:mnd
}
func (model *AuthzModel) GetCreatedAt() *time.Time {
if model == nil {
return nil
}
if model.CreatedAt != nil {
return model.CreatedAt
}
if model.ID != nil {
createdAt, _ := getCreatedAtFromModelID(model.GetID())
model.CreatedAt = createdAt
return createdAt
}
return nil
}
func (model *AuthzModel) Set(authzModel openfga.AuthorizationModel) {
model.ID = &authzModel.Id
model.SchemaVersion = &authzModel.SchemaVersion
model.TypeDefinitions = &authzModel.TypeDefinitions
if model.ID != nil {
model.setCreatedAt()
}
conditions := authzModel.GetConditions()
if len(conditions) > 0 {
model.Conditions = make(map[string]*openfga.Condition, len(conditions))
for k, v := range conditions {
condition := v
model.Conditions[k] = &condition
}
}
}
func (model *AuthzModel) ReadFromJSONString(jsonString string) error {
jsonAuthModel := &openfga.AuthorizationModel{}
err := json.Unmarshal([]byte(jsonString), jsonAuthModel)
if err != nil {
return fmt.Errorf("failed to parse input as json due to %w", err)
}
model.Set(*jsonAuthModel)
return nil
}
func (model *AuthzModel) ReadFromDSLString(dslString string) error {
parsedAuthModel, err := language.TransformDSLToProto(dslString)
if err != nil {
return fmt.Errorf("failed to transform due to %w", err)
}
bytes, err := protojson.Marshal(parsedAuthModel)
if err != nil {
return fmt.Errorf("failed to transform due to %w", err)
}
jsonAuthModel := openfga.AuthorizationModel{}
err = json.Unmarshal(bytes, &jsonAuthModel)
if err != nil {
return fmt.Errorf("failed to transform due to %w", err)
}
model.Set(jsonAuthModel)
return nil
}
// ReadModelFromModFGA reads a modular model from modFile, resolving its
// contents entries relative to the directory holding modFile with no
// containment. It is used when the user names the fga.mod file directly.
func (model *AuthzModel) ReadModelFromModFGA(modFile string) error {
return model.readModelFromModFGA(modFile, "")
}
// ReadModelFromModFGAContained reads a modular model from modFile and contains
// every file it references to containBase. A contents entry that escapes
// containBase (via "..", an absolute path, or a symlink) is rejected, so a
// modular model referenced from a store file cannot read files the store file
// itself could not.
func (model *AuthzModel) ReadModelFromModFGAContained(modFile string, containBase string) error {
return model.readModelFromModFGA(modFile, containBase)
}
func (model *AuthzModel) ReadModelFromString(input string, format ModelFormat) error {
return model.ReadModelFromStringContained(input, format, "")
}
// ReadModelFromStringContained is ReadModelFromString, but for a modular model
// it contains every file the fga.mod references to containBase. Pass an empty
// containBase to read without containment.
func (model *AuthzModel) ReadModelFromStringContained(
input string,
format ModelFormat,
containBase string,
) error {
if input == "" {
return nil
}
switch format {
case ModelFormatJSON:
if err := model.ReadFromJSONString(input); err != nil {
return err
}
return nil
case ModelFormatFGA, ModelFormatDefault:
if err := model.ReadFromDSLString(input); err != nil {
return err
}
return nil
case ModelFormatModular:
if err := model.readModelFromModFGA(input, containBase); err != nil {
return err
}
return nil
}
return nil
}
func (model *AuthzModel) GetAsJSONString() (*string, error) {
bytes, err := json.Marshal(model)
if err != nil {
return nil, fmt.Errorf("failed to marshal due to %w", err)
}
jsonString := string(bytes)
return &jsonString, nil
}
func (model *AuthzModel) DisplayAsJSON(fields []string) AuthzModel {
newModel := AuthzModel{}
if len(fields) < 1 {
fields = append(fields, "model")
}
if slices.Contains(fields, "id") {
newModel.ID = model.ID
}
if slices.Contains(fields, "created_at") {
newModel.CreatedAt = model.CreatedAt
}
if slices.Contains(fields, "model") {
newModel.SchemaVersion = model.SchemaVersion
newModel.TypeDefinitions = model.TypeDefinitions
newModel.Conditions = model.Conditions
}
if slices.Contains(fields, "size") {
size := model.GetSizeInKB()
newModel.SizeKB = &size
}
return newModel
}
func (model *AuthzModel) DisplayAsDSL(fields []string) (*string, error) {
modelPb := openfgav1.AuthorizationModel{}
if len(fields) < 1 {
fields = append(fields, "model")
}
dslModel := model.buildDSLMetadata(fields)
if slices.Contains(fields, "model") {
modelJSON, err := model.GetAsJSONString()
if err != nil {
return nil, err
}
err = protojson.UnmarshalOptions{DiscardUnknown: true}.Unmarshal([]byte(*modelJSON), &modelPb)
if err != nil {
return nil, fmt.Errorf("unable to unmarshal model json string due to: %w", err)
}
transformedJSON, err := language.TransformJSONProtoToDSL(&modelPb, language.WithIncludeSourceInformation(true))
if err != nil {
return nil, fmt.Errorf("error transforming from JSON due to: %w", err)
}
dslModel += fmt.Sprintf("%v\n", transformedJSON)
}
return &dslModel, nil
}
// readModelFromModFGA reads a modular model. When containBase is non-empty, the
// fga.mod file and each of its contents entries must resolve inside it.
func (model *AuthzModel) readModelFromModFGA(modFile string, containBase string) error {
modFileContents, err := readModelFile(modFile, containBase)
if err != nil {
return fmt.Errorf("failed to read fga.mod file due to %w", err)
}
parsedModFile, err := language.TransformModFile(string(modFileContents))
if err != nil {
return fmt.Errorf("failed to transform fga.mod file due to %w", err)
}
moduleFiles := []language.ModuleFile{}
var fileReadErrors []error
// modFile is an OS filesystem path, while a contents entry inside fga.mod is
// always slash-separated, so each entry is converted before being joined.
directory := filepath.Dir(modFile)
for _, fileName := range parsedModFile.Contents.Value {
filePath := filepath.Join(directory, filepath.FromSlash(fileName.Value))
fileContents, err := readModelFile(filePath, containBase)
if err != nil {
fileReadErrors = append(
fileReadErrors,
fmt.Errorf("failed to read module file %s due to %w", fileName.Value, err),
)
continue
}
moduleFiles = append(moduleFiles, language.ModuleFile{
Name: fileName.Value,
Contents: string(fileContents),
})
}
if len(fileReadErrors) != 0 {
return errors.Join(fileReadErrors...)
}
parsedAuthModel, err := language.TransformModuleFilesToModel(moduleFiles, parsedModFile.Schema.Value)
if err != nil {
return fmt.Errorf("failed to transform module to model due to %w", err)
}
bytes, err := protojson.Marshal(parsedAuthModel)
if err != nil {
return fmt.Errorf("failed to transform due to %w", err)
}
jsonAuthModel := openfga.AuthorizationModel{}
err = json.Unmarshal(bytes, &jsonAuthModel)
if err != nil {
return fmt.Errorf("failed to transform due to %w", err)
}
model.Set(jsonAuthModel)
return nil
}
func (model *AuthzModel) buildDSLMetadata(fields []string) string {
metadata := ""
if slices.Contains(fields, "id") {
if model.ID != nil {
metadata += fmt.Sprintf("# Model ID: %v\n", *model.ID)
} else {
metadata += fmt.Sprintf("# Model ID: %v\n", "N/A")
}
}
if slices.Contains(fields, "created_at") {
if model.CreatedAt != nil {
metadata += fmt.Sprintf("# Created At: %v\n", *model.CreatedAt)
} else {
metadata += fmt.Sprintf("# Created At: %v\n", "N/A")
}
}
if slices.Contains(fields, "size") {
metadata += fmt.Sprintf("# Size: %.2f KB\n", model.GetSizeInKB())
}
return metadata
}
func (model *AuthzModel) setCreatedAt() {
if *model.ID != "" {
modelID, err := ulid.Parse(*model.ID)
if err == nil {
createdAt := ulid.Time(modelID.Time()).UTC()
model.CreatedAt = &createdAt
}
}
}