-
-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathcoverage.go
367 lines (321 loc) · 11.6 KB
/
coverage.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
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
package coverage
import (
"fmt"
"golang.org/x/exp/slices"
"github.com/Permify/permify/pkg/attribute"
"github.com/Permify/permify/pkg/development/file"
"github.com/Permify/permify/pkg/dsl/compiler"
"github.com/Permify/permify/pkg/dsl/parser"
base "github.com/Permify/permify/pkg/pb/base/v1"
"github.com/Permify/permify/pkg/tuple"
)
// SchemaCoverageInfo - Schema coverage info
type SchemaCoverageInfo struct {
EntityCoverageInfo []EntityCoverageInfo
TotalRelationshipsCoverage int
TotalAttributesCoverage int
TotalAssertionsCoverage int
}
// EntityCoverageInfo - Entity coverage info
type EntityCoverageInfo struct {
EntityName string
UncoveredRelationships []string
CoverageRelationshipsPercent int
UncoveredAttributes []string
CoverageAttributesPercent int
UncoveredAssertions map[string][]string
CoverageAssertionsPercent map[string]int
}
// SchemaCoverage
//
// schema:
//
// entity user {}
//
// entity organization {
// // organizational roles
// relation admin @user
// relation member @user
// }
//
// entity repository {
// // represents repositories parent organization
// relation parent @organization
//
// // represents owner of this repository
// relation owner @user @organization#admin
//
// // permissions
// permission edit = parent.admin or owner
// permission delete = owner
// }
//
// - relationships coverage
//
// organization#admin@user
// organization#member@user
// repository#parent@organization
// repository#owner@user
// repository#owner@organization#admin
//
// - assertions coverage
//
// repository#edit
// repository#delete
type SchemaCoverage struct {
EntityName string
Relationships []string
Attributes []string
Assertions []string
}
func Run(shape file.Shape) SchemaCoverageInfo {
p, err := parser.NewParser(shape.Schema).Parse()
if err != nil {
return SchemaCoverageInfo{}
}
definitions, _, err := compiler.NewCompiler(true, p).Compile()
if err != nil {
return SchemaCoverageInfo{}
}
schemaCoverageInfo := SchemaCoverageInfo{}
var refs []SchemaCoverage
for _, en := range definitions {
refs = append(refs, references(en))
}
// Iterate through the schema coverage references
for _, ref := range refs {
// Initialize EntityCoverageInfo for the current entity
entityCoverageInfo := EntityCoverageInfo{
EntityName: ref.EntityName,
UncoveredRelationships: []string{},
UncoveredAttributes: []string{},
CoverageAssertionsPercent: map[string]int{},
UncoveredAssertions: map[string][]string{},
CoverageRelationshipsPercent: 0,
CoverageAttributesPercent: 0,
}
// Calculate relationships coverage
er := relationships(ref.EntityName, shape.Relationships)
for _, relationship := range ref.Relationships {
if !slices.Contains(er, relationship) {
entityCoverageInfo.UncoveredRelationships = append(entityCoverageInfo.UncoveredRelationships, relationship)
}
}
entityCoverageInfo.CoverageRelationshipsPercent = calculateCoveragePercent(
ref.Relationships,
entityCoverageInfo.UncoveredRelationships,
)
// Calculate attributes coverage
at := attributes(ref.EntityName, shape.Attributes)
for _, attr := range ref.Attributes {
if !slices.Contains(at, attr) {
entityCoverageInfo.UncoveredAttributes = append(entityCoverageInfo.UncoveredAttributes, attr)
}
}
entityCoverageInfo.CoverageAttributesPercent = calculateCoveragePercent(
ref.Attributes,
entityCoverageInfo.UncoveredAttributes,
)
// Calculate assertions coverage for each scenario
for _, s := range shape.Scenarios {
ca := assertions(ref.EntityName, s.Checks, s.EntityFilters)
for _, assertion := range ref.Assertions {
if !slices.Contains(ca, assertion) {
entityCoverageInfo.UncoveredAssertions[s.Name] = append(entityCoverageInfo.UncoveredAssertions[s.Name], assertion)
}
}
entityCoverageInfo.CoverageAssertionsPercent[s.Name] = calculateCoveragePercent(
ref.Assertions,
entityCoverageInfo.UncoveredAssertions[s.Name],
)
}
schemaCoverageInfo.EntityCoverageInfo = append(schemaCoverageInfo.EntityCoverageInfo, entityCoverageInfo)
}
// Calculate and assign the total relationships and assertions coverage to the schemaCoverageInfo
relationshipsCoverage, attributesCoverage, assertionsCoverage := calculateTotalCoverage(schemaCoverageInfo.EntityCoverageInfo)
schemaCoverageInfo.TotalRelationshipsCoverage = relationshipsCoverage
schemaCoverageInfo.TotalAttributesCoverage = attributesCoverage
schemaCoverageInfo.TotalAssertionsCoverage = assertionsCoverage
return schemaCoverageInfo
}
// calculateCoveragePercent - Calculate coverage percentage based on total and uncovered elements
func calculateCoveragePercent(totalElements, uncoveredElements []string) int {
coveragePercent := 100
totalCount := len(totalElements)
if totalCount != 0 {
coveredCount := totalCount - len(uncoveredElements)
coveragePercent = (coveredCount * 100) / totalCount
}
return coveragePercent
}
// calculateTotalCoverage - Calculate total relationships and assertions coverage
func calculateTotalCoverage(entities []EntityCoverageInfo) (int, int, int) {
totalRelationships := 0
totalCoveredRelationships := 0
totalAttributes := 0
totalCoveredAttributes := 0
totalAssertions := 0
totalCoveredAssertions := 0
// Iterate over each entity in the list
for _, entity := range entities {
totalRelationships++
totalCoveredRelationships += entity.CoverageRelationshipsPercent
totalAttributes++
totalCoveredAttributes += entity.CoverageAttributesPercent
for _, assertionsPercent := range entity.CoverageAssertionsPercent {
totalAssertions++
totalCoveredAssertions += assertionsPercent
}
}
// Calculate the coverage percentages
totalRelationshipsCoverage := totalCoveredRelationships / totalRelationships
totalAttributesCoverage := totalCoveredAttributes / totalAttributes
totalAssertionsCoverage := totalCoveredAssertions / totalAssertions
// Return the coverage percentages
return totalRelationshipsCoverage, totalAttributesCoverage, totalAssertionsCoverage
}
// References - Get references for a given entity
func references(entity *base.EntityDefinition) (coverage SchemaCoverage) {
// Set the entity name in the coverage struct
coverage.EntityName = entity.GetName()
// Iterate over all relations in the entity
for _, relation := range entity.GetRelations() {
// Iterate over all references within each relation
for _, reference := range relation.GetRelationReferences() {
if reference.GetRelation() != "" {
// Format and append the relationship to the coverage struct
formattedRelationship := fmt.Sprintf("%s#%s@%s#%s", entity.GetName(), relation.GetName(), reference.GetType(), reference.GetRelation())
coverage.Relationships = append(coverage.Relationships, formattedRelationship)
} else {
formattedRelationship := fmt.Sprintf("%s#%s@%s", entity.GetName(), relation.GetName(), reference.GetType())
coverage.Relationships = append(coverage.Relationships, formattedRelationship)
}
}
}
// Iterate over all attributes in the entity
for _, attr := range entity.GetAttributes() {
// Format and append the attribute to the coverage struct
formattedAttribute := fmt.Sprintf("%s#%s", entity.GetName(), attr.GetName())
coverage.Attributes = append(coverage.Attributes, formattedAttribute)
}
// Iterate over all permissions in the entity
for _, permission := range entity.GetPermissions() {
// Format and append the permission to the coverage struct
formattedPermission := fmt.Sprintf("%s#%s", entity.GetName(), permission.GetName())
coverage.Assertions = append(coverage.Assertions, formattedPermission)
conditionsAssertions(permission.GetChild(), entity.GetName(), &coverage.Assertions)
}
// Return the coverage struct
return
}
// Get assertions from permission condition
func conditionsAssertions(child *base.Child, entityName string, assertions *[]string) {
leaf := child.GetLeaf()
if leaf != nil {
compUserSet := leaf.GetComputedUserSet()
if compUserSet != nil {
relation := fmt.Sprintf("%s#%s", entityName, compUserSet.GetRelation())
if !slices.Contains(*assertions, relation) {
*assertions = append(*assertions, relation)
}
}
tupleToUserSet := leaf.GetTupleToUserSet()
if tupleToUserSet != nil {
tupComp := tupleToUserSet.GetComputed()
if tupComp != nil {
relation := fmt.Sprintf("%s#%s", entityName, tupComp.GetRelation())
if !slices.Contains(*assertions, relation) {
*assertions = append(*assertions, relation)
}
}
tupSet := tupleToUserSet.GetTupleSet()
if tupSet != nil {
relation := fmt.Sprintf("%s#%s", entityName, tupSet.GetRelation())
if !slices.Contains(*assertions, relation) {
*assertions = append(*assertions, relation)
}
}
}
}
rewrite := child.GetRewrite()
if rewrite != nil {
children := rewrite.GetChildren()
for _, child := range children {
conditionsAssertions(child, entityName, assertions)
}
}
}
// relationships - Get relationships for a given entity
func relationships(en string, relationships []string) []string {
var rels []string
for _, relationship := range relationships {
tup, err := tuple.Tuple(relationship)
if err != nil {
return []string{}
}
if tup.GetEntity().GetType() != en {
continue
}
// Check if the reference has a relation name
if tup.GetSubject().GetRelation() != "" {
// Format and append the relationship to the coverage struct
rels = append(rels, fmt.Sprintf("%s#%s@%s#%s", tup.GetEntity().GetType(), tup.GetRelation(), tup.GetSubject().GetType(), tup.GetSubject().GetRelation()))
} else {
rels = append(rels, fmt.Sprintf("%s#%s@%s", tup.GetEntity().GetType(), tup.GetRelation(), tup.GetSubject().GetType()))
}
// Format ad append the relationship without the relation name to the coverage struct
}
return rels
}
// attributes - Get attributes for a given entity
func attributes(en string, attributes []string) []string {
var attrs []string
for _, attr := range attributes {
a, err := attribute.Attribute(attr)
if err != nil {
return []string{}
}
if a.GetEntity().GetType() != en {
continue
}
attrs = append(attrs, fmt.Sprintf("%s#%s", a.GetEntity().GetType(), a.GetAttribute()))
}
return attrs
}
// assertions - Get assertions for a given entity
func assertions(en string, checks []file.Check, filters []file.EntityFilter) []string {
// Initialize an empty slice to store the resulting assertions
var asrts []string
// Iterate over each check in the checks slice
for _, assertion := range checks {
// Get the corresponding entity object for the current assertion
ca, err := tuple.E(assertion.Entity)
if err != nil {
// If there's an error, return an empty slice
return []string{}
}
// If the current entity type doesn't match the given entity type, continue to the next check
if ca.GetType() != en {
continue
}
// Iterate over the keys (permissions) in the Assertions map
for permission := range assertion.Assertions {
// Append the formatted permission string to the asrts slice
asrts = append(asrts, fmt.Sprintf("%s#%s", ca.GetType(), permission))
}
}
// Iterate over each entity filter in the filters slice
for _, assertion := range filters {
// If the current entity type doesn't match the given entity type, continue to the next filter
if assertion.EntityType != en {
continue
}
// Iterate over the keys (permissions) in the Assertions map
for permission := range assertion.Assertions {
// Append the formatted permission string to the asrts slice
asrts = append(asrts, fmt.Sprintf("%s#%s", assertion.EntityType, permission))
}
}
// Return the asrts slice containing the collected assertions
return asrts
}