ADAPT-Chase commited on
Commit
c8f6dca
·
verified ·
1 Parent(s): cf3ed5d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/conv/casbin_types.go +545 -0
  2. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/conv/casbin_types_test.go +1160 -0
  3. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/docs/auth_calls.md +80 -0
  4. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/docs/generator.go +257 -0
  5. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/errors/errors.go +69 -0
  6. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/errors/errors_test.go +52 -0
  7. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/filter/filter.go +122 -0
  8. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/filter/filter_test.go +64 -0
  9. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/mocks/authorizer.go +61 -0
  10. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/authorizer.go +171 -0
  11. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/authorizer_test.go +640 -0
  12. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/manager.go +595 -0
  13. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/manager_test.go +306 -0
  14. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/model.go +320 -0
  15. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/model_test.go +170 -0
  16. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/rbacconf/config.go +30 -0
  17. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/up_down_grades.go +105 -0
  18. platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/up_down_grades_test.go +176 -0
  19. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/chunk-1.tar.gz +3 -0
  20. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX.hnsw.commitlog.d/1689867524 +0 -0
  21. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX.indexcount +0 -0
  22. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX.proplengths +1 -0
  23. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX.version +0 -0
  24. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/dimensions/segment-1689867627555054000.bloom +0 -0
  25. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/dimensions/segment-1689867627555054000.db +0 -0
  26. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/objects/segment-1689867627551445000.bloom +0 -0
  27. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/objects/segment-1689867627551445000.cna +0 -0
  28. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/objects/segment-1689867627551445000.db +0 -0
  29. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/objects/segment-1689867627551445000.secondary.0.bloom +0 -0
  30. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property__id/segment-1689867627561328000.bloom +0 -0
  31. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property__id/segment-1689867627561328000.db +0 -0
  32. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title/segment-1689867627559163000.bloom +0 -0
  33. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title/segment-1689867627559163000.db +0 -0
  34. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title2/segment-1689867627557281000.bloom +0 -0
  35. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title2/segment-1689867627557281000.db +0 -0
  36. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title2_searchable/segment-1689867627564376000.bloom +0 -0
  37. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title2_searchable/segment-1689867627564376000.db +0 -0
  38. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title_searchable/segment-1689867627563072000.bloom +0 -0
  39. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title_searchable/segment-1689867627563072000.db +0 -0
  40. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO.hnsw.commitlog.d/1689867524 +0 -0
  41. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO.indexcount +0 -0
  42. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO.proplengths +1 -0
  43. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO.version +0 -0
  44. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/dimensions/segment-1689867537919947000.bloom +0 -0
  45. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/dimensions/segment-1689867537919947000.db +0 -0
  46. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/objects/segment-1689867537919476000.bloom +0 -0
  47. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/objects/segment-1689867537919476000.cna +0 -0
  48. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/objects/segment-1689867537919476000.db +0 -0
  49. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/objects/segment-1689867537919476000.secondary.0.bloom +0 -0
  50. platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/property__id/segment-1689867537919986000.bloom +0 -0
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/conv/casbin_types.go ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package conv
13
+
14
+ import (
15
+ "fmt"
16
+ "regexp"
17
+ "strings"
18
+
19
+ "github.com/weaviate/weaviate/usecases/auth/authentication"
20
+
21
+ "github.com/weaviate/weaviate/entities/models"
22
+ "github.com/weaviate/weaviate/entities/schema"
23
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
24
+ )
25
+
26
+ const (
27
+ // https://casbin.org/docs/rbac/#how-to-distinguish-role-from-user
28
+ // ROLE_NAME_PREFIX to prefix role to help casbin to distinguish on Enforcing
29
+ ROLE_NAME_PREFIX = "role" + PREFIX_SEPARATOR
30
+ // OIDC_GROUP_NAME_PREFIX to prefix role to help casbin to distinguish on Enforcing
31
+ OIDC_GROUP_NAME_PREFIX = "group" + PREFIX_SEPARATOR
32
+ PREFIX_SEPARATOR = ":"
33
+
34
+ // CRUD allow all actions on a resource
35
+ // this is internal for casbin to handle admin actions
36
+ CRUD = "(C)|(R)|(U)|(D)"
37
+ // CRU allow all actions on a resource except DELETE
38
+ // this is internal for casbin to handle editor actions
39
+ CRU = "(C)|(R)|(U)"
40
+ VALID_VERBS = "(C)|(R)|(U)|(D)|(A)"
41
+ // InternalPlaceHolder is a place holder to mark empty roles
42
+ InternalPlaceHolder = "wv_internal_empty"
43
+ )
44
+
45
+ var (
46
+ BuiltInPolicies = map[string]string{
47
+ authorization.Viewer: authorization.READ,
48
+ authorization.Admin: VALID_VERBS,
49
+ authorization.Root: VALID_VERBS,
50
+ authorization.ReadOnly: authorization.READ,
51
+ }
52
+ weaviate_actions_prefixes = map[string]string{
53
+ CRUD: "manage",
54
+ CRU: "manage",
55
+ authorization.ROLE_SCOPE_MATCH: "manage",
56
+ authorization.CREATE: "create",
57
+ authorization.READ: "read",
58
+ authorization.UPDATE: "update",
59
+ authorization.DELETE: "delete",
60
+ authorization.USER_AND_GROUP_ASSIGN_AND_REVOKE: "assign_and_revoke",
61
+ }
62
+ )
63
+
64
+ var resourcePatterns = []string{
65
+ fmt.Sprintf(`^%s/.*$`, authorization.GroupsDomain),
66
+ fmt.Sprintf(`^%s/[^/]+$`, authorization.GroupsDomain),
67
+ fmt.Sprintf(`^%s/.*$`, authorization.UsersDomain),
68
+ fmt.Sprintf(`^%s/[^/]+$`, authorization.UsersDomain),
69
+ fmt.Sprintf(`^%s/.*$`, authorization.RolesDomain),
70
+ fmt.Sprintf(`^%s/[^/]+$`, authorization.RolesDomain),
71
+ fmt.Sprintf(`^%s/.*$`, authorization.ClusterDomain),
72
+ fmt.Sprintf(`^%s/verbosity/minimal$`, authorization.NodesDomain),
73
+ fmt.Sprintf(`^%s/verbosity/verbose/collections/[^/]+$`, authorization.NodesDomain),
74
+ fmt.Sprintf(`^%s/verbosity/verbose/collections/[^/]+$`, authorization.NodesDomain),
75
+ fmt.Sprintf(`^%s/collections/.*$`, authorization.BackupsDomain),
76
+ fmt.Sprintf(`^%s/collections/[^/]+$`, authorization.BackupsDomain),
77
+ fmt.Sprintf(`^%s/collections/.*$`, authorization.SchemaDomain),
78
+ fmt.Sprintf(`^%s/collections/[^/]+$`, authorization.SchemaDomain),
79
+ fmt.Sprintf(`^%s/collections/[^/]+/shards/.*$`, authorization.SchemaDomain),
80
+ fmt.Sprintf(`^%s/collections/[^/]+/shards/[^/]+/objects/.*$`, authorization.DataDomain),
81
+ fmt.Sprintf(`^%s/collections/[^/]+/shards/[^/]+/objects/[^/]+$`, authorization.DataDomain),
82
+ fmt.Sprintf(`^%s/collections/[^/]+/shards/[^/]+$`, authorization.ReplicateDomain),
83
+ fmt.Sprintf(`^%s/collections/[^/]+/aliases/[^/]+$`, authorization.AliasesDomain),
84
+ }
85
+
86
+ func newPolicy(policy []string) *authorization.Policy {
87
+ return &authorization.Policy{
88
+ Resource: fromCasbinResource(policy[1]),
89
+ Verb: policy[2],
90
+ Domain: policy[3],
91
+ }
92
+ }
93
+
94
+ func fromCasbinResource(resource string) string {
95
+ return strings.ReplaceAll(resource, ".*", "*")
96
+ }
97
+
98
+ func CasbinClusters() string {
99
+ return fmt.Sprintf("%s/.*", authorization.ClusterDomain)
100
+ }
101
+
102
+ func CasbinNodes(verbosity, class string) string {
103
+ class = schema.UppercaseClassesNames(class)[0]
104
+ if verbosity == "minimal" {
105
+ return fmt.Sprintf("%s/verbosity/minimal", authorization.NodesDomain)
106
+ }
107
+ if class == "" {
108
+ class = "*"
109
+ }
110
+ class = strings.ReplaceAll(class, "*", ".*")
111
+ return fmt.Sprintf("%s/verbosity/verbose/collections/%s", authorization.NodesDomain, class)
112
+ }
113
+
114
+ func CasbinBackups(class string) string {
115
+ class = schema.UppercaseClassesNames(class)[0]
116
+ if class == "" {
117
+ class = "*"
118
+ }
119
+ class = strings.ReplaceAll(class, "*", ".*")
120
+ return fmt.Sprintf("%s/collections/%s", authorization.BackupsDomain, class)
121
+ }
122
+
123
+ func CasbinUsers(user string) string {
124
+ if user == "" {
125
+ user = "*"
126
+ }
127
+ user = strings.ReplaceAll(user, "*", ".*")
128
+ return fmt.Sprintf("%s/%s", authorization.UsersDomain, user)
129
+ }
130
+
131
+ func CasbinGroups(group string, groupType string) string {
132
+ if group == "" {
133
+ group = "*"
134
+ }
135
+ group = strings.ReplaceAll(group, "*", ".*")
136
+ return fmt.Sprintf("%s/%s/%s", authorization.GroupsDomain, groupType, group)
137
+ }
138
+
139
+ func CasbinRoles(role string) string {
140
+ if role == "" {
141
+ role = "*"
142
+ }
143
+ role = strings.ReplaceAll(role, "*", ".*")
144
+ return fmt.Sprintf("%s/%s", authorization.RolesDomain, role)
145
+ }
146
+
147
+ func CasbinSchema(collection, shard string) string {
148
+ collection = schema.UppercaseClassesNames(collection)[0]
149
+ if collection == "" {
150
+ collection = "*"
151
+ }
152
+ if shard == "" {
153
+ shard = "*"
154
+ }
155
+ collection = strings.ReplaceAll(collection, "*", ".*")
156
+ shard = strings.ReplaceAll(shard, "*", ".*")
157
+ return fmt.Sprintf("%s/collections/%s/shards/%s", authorization.SchemaDomain, collection, shard)
158
+ }
159
+
160
+ func CasbinReplicate(collection, shard string) string {
161
+ collection = schema.UppercaseClassesNames(collection)[0]
162
+ if collection == "" {
163
+ collection = "*"
164
+ }
165
+ if shard == "" {
166
+ shard = "*"
167
+ }
168
+ collection = strings.ReplaceAll(collection, "*", ".*")
169
+ shard = strings.ReplaceAll(shard, "*", ".*")
170
+ return fmt.Sprintf("%s/collections/%s/shards/%s", authorization.ReplicateDomain, collection, shard)
171
+ }
172
+
173
+ func CasbinAliases(collection, alias string) string {
174
+ if collection == "" {
175
+ collection = "*"
176
+ }
177
+ if alias == "" {
178
+ alias = "*"
179
+ }
180
+ collection = strings.ReplaceAll(collection, "*", ".*")
181
+ alias = strings.ReplaceAll(alias, "*", ".*")
182
+ return fmt.Sprintf("%s/collections/%s/aliases/%s", authorization.AliasesDomain, collection, alias)
183
+ }
184
+
185
+ func CasbinData(collection, shard, object string) string {
186
+ collection = schema.UppercaseClassesNames(collection)[0]
187
+ if collection == "" {
188
+ collection = "*"
189
+ }
190
+ if shard == "" {
191
+ shard = "*"
192
+ }
193
+ if object == "" {
194
+ object = "*"
195
+ }
196
+ collection = strings.ReplaceAll(collection, "*", ".*")
197
+ shard = strings.ReplaceAll(shard, "*", ".*")
198
+ object = strings.ReplaceAll(object, "*", ".*")
199
+ return fmt.Sprintf("%s/collections/%s/shards/%s/objects/%s", authorization.DataDomain, collection, shard, object)
200
+ }
201
+
202
+ func extractFromExtAction(inputAction string) (string, string, error) {
203
+ splits := strings.Split(inputAction, "_")
204
+ if len(splits) < 2 {
205
+ return "", "", fmt.Errorf("invalid action: %s", inputAction)
206
+ }
207
+ domain := splits[len(splits)-1]
208
+ verb := strings.ToUpper(splits[0][:1])
209
+ if verb == "M" {
210
+ verb = CRUD
211
+ }
212
+
213
+ if !validVerb(verb) {
214
+ return "", "", fmt.Errorf("invalid verb: %s", verb)
215
+ }
216
+
217
+ return verb, domain, nil
218
+ }
219
+
220
+ // casbinPolicyDomains decouples the endpoints domains
221
+ // from the casbin internal domains.
222
+ // e.g.
223
+ // [create_collections, create_tenants] -> schema domain
224
+ func casbinPolicyDomains(domain string) string {
225
+ switch domain {
226
+ case authorization.CollectionsDomain, authorization.TenantsDomain:
227
+ return authorization.SchemaDomain
228
+ default:
229
+ return domain
230
+ }
231
+ }
232
+
233
+ func policy(permission *models.Permission) (*authorization.Policy, error) {
234
+ if permission.Action == nil {
235
+ return &authorization.Policy{Resource: InternalPlaceHolder}, nil
236
+ }
237
+
238
+ verb, domain, err := extractFromExtAction(*permission.Action)
239
+ if err != nil {
240
+ return nil, err
241
+ }
242
+
243
+ var resource string
244
+ switch domain {
245
+ case authorization.GroupsDomain:
246
+ group := "*"
247
+ if permission.Groups != nil {
248
+ if permission.Groups.Group != nil {
249
+ group = *permission.Groups.Group
250
+ }
251
+ if permission.Groups.GroupType != models.GroupTypeOidc {
252
+ return nil, fmt.Errorf("invalid groups type: %v", permission.Groups.GroupType)
253
+ }
254
+ } else {
255
+ return nil, fmt.Errorf("invalid permission: %v", permission)
256
+ }
257
+ resource = CasbinGroups(group, string(models.GroupTypeOidc))
258
+ case authorization.UsersDomain:
259
+ user := "*"
260
+ if permission.Users != nil && permission.Users.Users != nil {
261
+ user = *permission.Users.Users
262
+ }
263
+ resource = CasbinUsers(user)
264
+ case authorization.RolesDomain:
265
+ role := "*"
266
+ // default verb for role to handle cases where role is nil
267
+ origVerb := verb
268
+ verb = authorization.VerbWithScope(verb, authorization.ROLE_SCOPE_MATCH)
269
+ if permission.Roles != nil && permission.Roles.Role != nil {
270
+ role = *permission.Roles.Role
271
+ if permission.Roles.Scope != nil {
272
+ verb = authorization.VerbWithScope(origVerb, strings.ToUpper(*permission.Roles.Scope))
273
+ }
274
+ }
275
+ resource = CasbinRoles(role)
276
+ case authorization.ClusterDomain:
277
+ resource = CasbinClusters()
278
+ case authorization.CollectionsDomain:
279
+ collection := "*"
280
+ tenant := "#"
281
+ if permission.Collections != nil && permission.Collections.Collection != nil {
282
+ collection = schema.UppercaseClassName(*permission.Collections.Collection)
283
+ }
284
+ resource = CasbinSchema(collection, tenant)
285
+
286
+ case authorization.TenantsDomain:
287
+ collection := "*"
288
+ tenant := "*"
289
+ if permission.Tenants != nil {
290
+ if permission.Tenants.Collection != nil {
291
+ collection = schema.UppercaseClassName(*permission.Tenants.Collection)
292
+ }
293
+
294
+ if permission.Tenants.Tenant != nil {
295
+ tenant = *permission.Tenants.Tenant
296
+ }
297
+ }
298
+ resource = CasbinSchema(collection, tenant)
299
+ case authorization.DataDomain:
300
+ collection := "*"
301
+ tenant := "*"
302
+ object := "*"
303
+ if permission.Data != nil && permission.Data.Collection != nil {
304
+ collection = schema.UppercaseClassName(*permission.Data.Collection)
305
+ }
306
+ if permission.Data != nil && permission.Data.Tenant != nil {
307
+ tenant = *permission.Data.Tenant
308
+ }
309
+ if permission.Data != nil && permission.Data.Object != nil {
310
+ object = *permission.Data.Object
311
+ }
312
+ resource = CasbinData(collection, tenant, object)
313
+ case authorization.BackupsDomain:
314
+ collection := "*"
315
+ if permission.Backups != nil {
316
+ if permission.Backups.Collection != nil {
317
+ collection = schema.UppercaseClassName(*permission.Backups.Collection)
318
+ }
319
+ }
320
+ resource = CasbinBackups(collection)
321
+ case authorization.NodesDomain:
322
+ collection := "*"
323
+ verbosity := "minimal"
324
+ if permission.Nodes != nil {
325
+ if permission.Nodes.Collection != nil {
326
+ collection = schema.UppercaseClassName(*permission.Nodes.Collection)
327
+ }
328
+ if permission.Nodes.Verbosity != nil {
329
+ verbosity = *permission.Nodes.Verbosity
330
+ }
331
+ }
332
+ resource = CasbinNodes(verbosity, collection)
333
+ case authorization.ReplicateDomain:
334
+ collection := "*"
335
+ shard := "*"
336
+ if permission.Replicate != nil {
337
+ if permission.Replicate.Collection != nil {
338
+ collection = schema.UppercaseClassName(*permission.Replicate.Collection)
339
+ }
340
+ if permission.Replicate.Shard != nil {
341
+ shard = *permission.Replicate.Shard
342
+ }
343
+ }
344
+ resource = CasbinReplicate(collection, shard)
345
+ case authorization.AliasesDomain:
346
+ collection := "*"
347
+ alias := "*"
348
+ if permission.Aliases != nil {
349
+ if permission.Aliases.Collection != nil {
350
+ collection = schema.UppercaseClassName(*permission.Aliases.Collection)
351
+ }
352
+ if permission.Aliases.Alias != nil {
353
+ alias = schema.UppercaseClassName(*permission.Aliases.Alias)
354
+ }
355
+ }
356
+ resource = CasbinAliases(collection, alias)
357
+ default:
358
+ return nil, fmt.Errorf("invalid domain: %s", domain)
359
+
360
+ }
361
+ if !validResource(resource) {
362
+ return nil, fmt.Errorf("invalid resource: %s", resource)
363
+ }
364
+
365
+ return &authorization.Policy{
366
+ Resource: resource,
367
+ Verb: verb,
368
+ Domain: casbinPolicyDomains(domain),
369
+ }, nil
370
+ }
371
+
372
+ func weaviatePermissionAction(pathLastPart, verb, domain string) string {
373
+ action := fmt.Sprintf("%s_%s", weaviate_actions_prefixes[verb], domain)
374
+ action = strings.ReplaceAll(action, "_*", "")
375
+ switch domain {
376
+ case authorization.SchemaDomain:
377
+ if pathLastPart == "#" {
378
+ // e.g
379
+ // schema/collections/ABC/shards/# collection permission
380
+ // schema/collections/ABC/shards/* tenant permission
381
+ action = fmt.Sprintf("%s_%s", weaviate_actions_prefixes[verb], authorization.CollectionsDomain)
382
+ } else {
383
+ action = fmt.Sprintf("%s_%s", weaviate_actions_prefixes[verb], authorization.TenantsDomain)
384
+ }
385
+ return action
386
+ default:
387
+ return action
388
+ }
389
+ }
390
+
391
+ func permission(policy []string, validatePath bool) (*models.Permission, error) {
392
+ mapped := newPolicy(policy)
393
+
394
+ if mapped.Resource == InternalPlaceHolder {
395
+ return &models.Permission{}, nil
396
+ }
397
+
398
+ if !validVerb(mapped.Verb) {
399
+ return nil, fmt.Errorf("invalid verb: %s", mapped.Verb)
400
+ }
401
+
402
+ permission := &models.Permission{}
403
+
404
+ splits := strings.Split(mapped.Resource, "/")
405
+
406
+ // validating the resource can be expensive (regexp!)
407
+ if validatePath && !validResource(mapped.Resource) {
408
+ return nil, fmt.Errorf("invalid resource: %s", mapped.Resource)
409
+ }
410
+
411
+ switch mapped.Domain {
412
+ case authorization.SchemaDomain:
413
+ if splits[4] == "#" {
414
+ permission.Collections = &models.PermissionCollections{
415
+ Collection: &splits[2],
416
+ }
417
+ } else {
418
+ permission.Tenants = &models.PermissionTenants{
419
+ Collection: &splits[2],
420
+ Tenant: &splits[4],
421
+ }
422
+ }
423
+ case authorization.DataDomain:
424
+ permission.Data = &models.PermissionData{
425
+ Collection: &splits[2],
426
+ Tenant: &splits[4],
427
+ Object: &splits[6],
428
+ }
429
+ case authorization.RolesDomain:
430
+ permission.Roles = &models.PermissionRoles{
431
+ Role: &splits[1],
432
+ }
433
+
434
+ verbSplits := strings.Split(mapped.Verb, "_")
435
+ mapped.Verb = verbSplits[0]
436
+ scope := strings.ToLower(verbSplits[1])
437
+ permission.Roles.Scope = &scope
438
+
439
+ case authorization.NodesDomain:
440
+ verbosity := splits[2]
441
+ var collection *string
442
+ if verbosity == "minimal" {
443
+ collection = nil
444
+ } else {
445
+ collection = &splits[4]
446
+ }
447
+ permission.Nodes = &models.PermissionNodes{
448
+ Collection: collection,
449
+ Verbosity: &verbosity,
450
+ }
451
+ case authorization.BackupsDomain:
452
+ permission.Backups = &models.PermissionBackups{
453
+ Collection: &splits[2],
454
+ }
455
+ case authorization.UsersDomain:
456
+ permission.Users = &models.PermissionUsers{
457
+ Users: &splits[1],
458
+ }
459
+ case authorization.ReplicateDomain:
460
+ permission.Replicate = &models.PermissionReplicate{
461
+ Collection: &splits[2],
462
+ Shard: &splits[4],
463
+ }
464
+ case authorization.AliasesDomain:
465
+ permission.Aliases = &models.PermissionAliases{
466
+ Collection: &splits[2],
467
+ Alias: &splits[4],
468
+ }
469
+ case authorization.GroupsDomain:
470
+ permission.Groups = &models.PermissionGroups{
471
+ Group: &splits[2],
472
+ GroupType: models.GroupType(splits[1]),
473
+ }
474
+ case *authorization.All:
475
+ permission.Backups = authorization.AllBackups
476
+ permission.Data = authorization.AllData
477
+ permission.Nodes = authorization.AllNodes
478
+ permission.Roles = authorization.AllRoles
479
+ permission.Collections = authorization.AllCollections
480
+ permission.Tenants = authorization.AllTenants
481
+ permission.Users = authorization.AllUsers
482
+ permission.Replicate = authorization.AllReplicate
483
+ permission.Aliases = authorization.AllAliases
484
+ permission.Groups = authorization.AllOIDCGroups
485
+ case authorization.ClusterDomain:
486
+ // do nothing
487
+ default:
488
+ return nil, fmt.Errorf("invalid domain: %s", mapped.Domain)
489
+ }
490
+
491
+ permission.Action = authorization.String(weaviatePermissionAction(splits[len(splits)-1], mapped.Verb, mapped.Domain))
492
+ return permission, nil
493
+ }
494
+
495
+ func validResource(input string) bool {
496
+ for _, pattern := range resourcePatterns {
497
+ matched, err := regexp.MatchString(pattern, input)
498
+ if err != nil {
499
+ return false
500
+ }
501
+ if matched {
502
+ return true
503
+ }
504
+ }
505
+ return false
506
+ }
507
+
508
+ func validVerb(input string) bool {
509
+ return regexp.MustCompile(VALID_VERBS).MatchString(input)
510
+ }
511
+
512
+ func PrefixRoleName(name string) string {
513
+ if strings.HasPrefix(name, ROLE_NAME_PREFIX) {
514
+ return name
515
+ }
516
+ return fmt.Sprintf("%s%s", ROLE_NAME_PREFIX, name)
517
+ }
518
+
519
+ func PrefixGroupName(name string) string {
520
+ if strings.HasPrefix(name, OIDC_GROUP_NAME_PREFIX) {
521
+ return name
522
+ }
523
+ return fmt.Sprintf("%s%s", OIDC_GROUP_NAME_PREFIX, name)
524
+ }
525
+
526
+ func NameHasPrefix(name string) bool {
527
+ return strings.Contains(name, PREFIX_SEPARATOR)
528
+ }
529
+
530
+ func UserNameWithTypeFromPrincipal(principal *models.Principal) string {
531
+ return fmt.Sprintf("%s:%s", principal.UserType, principal.Username)
532
+ }
533
+
534
+ func UserNameWithTypeFromId(username string, authType authentication.AuthType) string {
535
+ return fmt.Sprintf("%s:%s", authType, username)
536
+ }
537
+
538
+ func TrimRoleNamePrefix(name string) string {
539
+ return strings.TrimPrefix(name, ROLE_NAME_PREFIX)
540
+ }
541
+
542
+ func GetUserAndPrefix(name string) (string, string) {
543
+ splits := strings.Split(name, PREFIX_SEPARATOR)
544
+ return splits[1], splits[0]
545
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/conv/casbin_types_test.go ADDED
@@ -0,0 +1,1160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package conv
13
+
14
+ import (
15
+ "fmt"
16
+ "testing"
17
+
18
+ "github.com/weaviate/weaviate/usecases/auth/authentication"
19
+
20
+ "github.com/stretchr/testify/require"
21
+
22
+ "github.com/weaviate/weaviate/entities/models"
23
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
24
+ )
25
+
26
+ type innerTest struct {
27
+ permissionAction string
28
+ testDescription string
29
+ policyVerb string
30
+ }
31
+
32
+ var (
33
+ foo = authorization.String("Foo")
34
+ bar = authorization.String("bar")
35
+ baz = authorization.String("baz")
36
+
37
+ createDesc = "create"
38
+ readDesc = "read"
39
+ updateDesc = "update"
40
+ deleteDesc = "delete"
41
+ manageDesc = "manage"
42
+
43
+ createVerb = authorization.CREATE
44
+ readVerb = authorization.READ
45
+ updateVerb = authorization.UPDATE
46
+ deleteVerb = authorization.DELETE
47
+ assignAndRevokeVerb = authorization.USER_AND_GROUP_ASSIGN_AND_REVOKE
48
+ manageVerb = CRUD
49
+
50
+ rolesTestsR = []innerTest{
51
+ {permissionAction: authorization.ReadRoles, testDescription: readDesc, policyVerb: authorization.VerbWithScope(readVerb, authorization.ROLE_SCOPE_MATCH)},
52
+ }
53
+ rolesTestsCUD = []innerTest{
54
+ {permissionAction: authorization.CreateRoles, testDescription: createVerb, policyVerb: authorization.VerbWithScope(createVerb, authorization.ROLE_SCOPE_ALL)},
55
+ {permissionAction: authorization.UpdateRoles, testDescription: updateDesc, policyVerb: authorization.VerbWithScope(updateVerb, authorization.ROLE_SCOPE_ALL)},
56
+ {permissionAction: authorization.DeleteRoles, testDescription: deleteDesc, policyVerb: authorization.VerbWithScope(deleteVerb, authorization.ROLE_SCOPE_ALL)},
57
+ }
58
+ clusterTests = []innerTest{
59
+ {permissionAction: authorization.ReadCluster, testDescription: readDesc, policyVerb: readVerb},
60
+ }
61
+ nodesTests = []innerTest{
62
+ {permissionAction: authorization.ReadNodes, testDescription: readDesc, policyVerb: readVerb},
63
+ }
64
+ backupsTests = []innerTest{
65
+ {permissionAction: authorization.ManageBackups, testDescription: manageDesc, policyVerb: manageVerb},
66
+ }
67
+ collectionsTests = []innerTest{
68
+ {permissionAction: authorization.CreateCollections, testDescription: createDesc, policyVerb: createVerb},
69
+ {permissionAction: authorization.ReadCollections, testDescription: readDesc, policyVerb: readVerb},
70
+ {permissionAction: authorization.UpdateCollections, testDescription: updateDesc, policyVerb: updateVerb},
71
+ {permissionAction: authorization.DeleteCollections, testDescription: deleteDesc, policyVerb: deleteVerb},
72
+ }
73
+ objectsDataTests = []innerTest{
74
+ {permissionAction: authorization.CreateData, testDescription: createDesc, policyVerb: createVerb},
75
+ {permissionAction: authorization.ReadData, testDescription: readDesc, policyVerb: readVerb},
76
+ {permissionAction: authorization.UpdateData, testDescription: updateDesc, policyVerb: updateVerb},
77
+ {permissionAction: authorization.DeleteData, testDescription: deleteDesc, policyVerb: deleteVerb},
78
+ }
79
+ tenantsActionTests = []innerTest{
80
+ {permissionAction: authorization.CreateTenants, testDescription: createDesc, policyVerb: createVerb},
81
+ {permissionAction: authorization.ReadTenants, testDescription: readDesc, policyVerb: readVerb},
82
+ {permissionAction: authorization.UpdateTenants, testDescription: updateDesc, policyVerb: updateVerb},
83
+ {permissionAction: authorization.DeleteTenants, testDescription: deleteDesc, policyVerb: deleteVerb},
84
+ }
85
+ userTests = []innerTest{
86
+ {permissionAction: authorization.AssignAndRevokeUsers, testDescription: manageDesc, policyVerb: assignAndRevokeVerb},
87
+ {permissionAction: authorization.CreateUsers, testDescription: createDesc, policyVerb: createVerb},
88
+ {permissionAction: authorization.ReadUsers, testDescription: readDesc, policyVerb: readVerb},
89
+ {permissionAction: authorization.UpdateUsers, testDescription: updateDesc, policyVerb: updateVerb},
90
+ {permissionAction: authorization.DeleteUsers, testDescription: deleteDesc, policyVerb: deleteVerb},
91
+ }
92
+ groupTests = []innerTest{
93
+ {permissionAction: authorization.ReadGroups, testDescription: readDesc, policyVerb: readVerb},
94
+ {permissionAction: authorization.AssignAndRevokeGroups, testDescription: manageDesc, policyVerb: assignAndRevokeVerb},
95
+ }
96
+ )
97
+
98
+ func Test_policy(t *testing.T) {
99
+ tests := []struct {
100
+ name string
101
+ permission *models.Permission
102
+ policy *authorization.Policy
103
+ tests []innerTest
104
+ }{
105
+ {
106
+ name: "all roles",
107
+ permission: &models.Permission{
108
+ Roles: &models.PermissionRoles{Role: authorization.All, Scope: authorization.String(models.PermissionRolesScopeMatch)},
109
+ },
110
+ policy: &authorization.Policy{
111
+ Resource: CasbinRoles("*"),
112
+ Domain: authorization.RolesDomain,
113
+ Verb: authorization.VerbWithScope(authorization.READ, authorization.ROLE_SCOPE_MATCH),
114
+ },
115
+ tests: rolesTestsR,
116
+ },
117
+ {
118
+ name: "a role",
119
+ permission: &models.Permission{
120
+ Roles: &models.PermissionRoles{Role: authorization.String("admin"), Scope: authorization.String(models.PermissionRolesScopeMatch)},
121
+ },
122
+ policy: &authorization.Policy{
123
+ Resource: CasbinRoles("admin"),
124
+ Domain: authorization.RolesDomain,
125
+ Verb: authorization.VerbWithScope(authorization.READ, authorization.ROLE_SCOPE_MATCH),
126
+ },
127
+ tests: rolesTestsR,
128
+ },
129
+ {
130
+ name: "a role with scope all",
131
+ permission: &models.Permission{
132
+ Roles: &models.PermissionRoles{Role: authorization.String("admin"), Scope: authorization.String(models.PermissionRolesScopeAll)},
133
+ },
134
+ policy: &authorization.Policy{
135
+ Resource: CasbinRoles("admin"),
136
+ Domain: authorization.RolesDomain,
137
+ Verb: authorization.VerbWithScope(authorization.READ, authorization.ROLE_SCOPE_ALL),
138
+ },
139
+ tests: rolesTestsCUD,
140
+ },
141
+ {
142
+ name: "cluster",
143
+ permission: &models.Permission{},
144
+ policy: &authorization.Policy{
145
+ Resource: CasbinClusters(),
146
+ Domain: authorization.ClusterDomain,
147
+ },
148
+ tests: clusterTests,
149
+ },
150
+ {
151
+ name: "minimal nodes",
152
+ permission: &models.Permission{
153
+ Nodes: &models.PermissionNodes{
154
+ Verbosity: authorization.String("minimal"),
155
+ },
156
+ },
157
+ policy: &authorization.Policy{
158
+ Resource: CasbinNodes("minimal", "doesntmatter"),
159
+ Domain: authorization.NodesDomain,
160
+ },
161
+ tests: nodesTests,
162
+ },
163
+ {
164
+ name: "verbose nodes for all collections",
165
+ permission: &models.Permission{
166
+ Nodes: &models.PermissionNodes{
167
+ Verbosity: authorization.String("verbose"),
168
+ Collection: authorization.All,
169
+ },
170
+ },
171
+ policy: &authorization.Policy{
172
+ Resource: CasbinNodes("verbose", "*"),
173
+ Domain: authorization.NodesDomain,
174
+ },
175
+ tests: nodesTests,
176
+ },
177
+ {
178
+ name: "verbose nodes for one collections",
179
+ permission: &models.Permission{
180
+ Nodes: &models.PermissionNodes{
181
+ Verbosity: authorization.String("verbose"),
182
+ Collection: foo,
183
+ },
184
+ },
185
+ policy: &authorization.Policy{
186
+ Resource: CasbinNodes("verbose", "Foo"),
187
+ Domain: authorization.NodesDomain,
188
+ },
189
+ tests: nodesTests,
190
+ },
191
+ {
192
+ name: "all backends",
193
+ permission: &models.Permission{
194
+ Backups: &models.PermissionBackups{},
195
+ },
196
+ policy: &authorization.Policy{
197
+ Resource: CasbinBackups("*"),
198
+ Domain: authorization.BackupsDomain,
199
+ },
200
+ tests: backupsTests,
201
+ },
202
+ {
203
+ name: "a backend",
204
+ permission: &models.Permission{
205
+ Backups: &models.PermissionBackups{
206
+ Collection: authorization.String("ABC"),
207
+ },
208
+ },
209
+ policy: &authorization.Policy{
210
+ Resource: CasbinBackups("ABC"),
211
+ Domain: authorization.BackupsDomain,
212
+ },
213
+ tests: backupsTests,
214
+ },
215
+ {
216
+ name: "all collections",
217
+ permission: &models.Permission{
218
+ Collections: &models.PermissionCollections{},
219
+ },
220
+ policy: &authorization.Policy{
221
+ Resource: CasbinSchema("*", "#"),
222
+ Domain: authorization.SchemaDomain,
223
+ },
224
+ tests: collectionsTests,
225
+ },
226
+ {
227
+ name: "a collection",
228
+ permission: &models.Permission{
229
+ Collections: &models.PermissionCollections{
230
+ Collection: foo,
231
+ },
232
+ },
233
+ policy: &authorization.Policy{
234
+ Resource: CasbinSchema("Foo", "#"),
235
+ Domain: authorization.SchemaDomain,
236
+ },
237
+ tests: collectionsTests,
238
+ },
239
+ {
240
+ name: "all tenants in all collections",
241
+ permission: &models.Permission{
242
+ Tenants: &models.PermissionTenants{},
243
+ },
244
+ policy: &authorization.Policy{
245
+ Resource: CasbinSchema("*", "*"),
246
+ Domain: authorization.SchemaDomain,
247
+ },
248
+ tests: tenantsActionTests,
249
+ },
250
+ {
251
+ name: "all tenants in a collection",
252
+ permission: &models.Permission{
253
+ Tenants: &models.PermissionTenants{
254
+ Collection: foo,
255
+ },
256
+ },
257
+ policy: &authorization.Policy{
258
+ Resource: CasbinSchema("Foo", "*"),
259
+ Domain: authorization.SchemaDomain,
260
+ },
261
+ tests: tenantsActionTests,
262
+ },
263
+ {
264
+ name: "a tenant in all collections",
265
+ permission: &models.Permission{
266
+ Tenants: &models.PermissionTenants{
267
+ Tenant: bar,
268
+ },
269
+ },
270
+ policy: &authorization.Policy{
271
+ Resource: CasbinSchema("*", "bar"),
272
+ Domain: authorization.SchemaDomain,
273
+ },
274
+ tests: tenantsActionTests,
275
+ },
276
+ {
277
+ name: "a tenant in a collection",
278
+ permission: &models.Permission{
279
+ Tenants: &models.PermissionTenants{
280
+ Collection: foo,
281
+ Tenant: bar,
282
+ },
283
+ },
284
+ policy: &authorization.Policy{
285
+ Resource: CasbinSchema("Foo", "bar"),
286
+ Domain: authorization.SchemaDomain,
287
+ },
288
+ tests: tenantsActionTests,
289
+ },
290
+ {
291
+ name: "all objects in all collections ST",
292
+ permission: &models.Permission{
293
+ Data: &models.PermissionData{},
294
+ },
295
+ policy: &authorization.Policy{
296
+ Resource: CasbinData("*", "*", "*"),
297
+ Domain: authorization.DataDomain,
298
+ },
299
+ tests: objectsDataTests,
300
+ },
301
+ {
302
+ name: "all objects in a collection ST",
303
+ permission: &models.Permission{
304
+ Data: &models.PermissionData{
305
+ Collection: foo,
306
+ },
307
+ },
308
+ policy: &authorization.Policy{
309
+ Resource: CasbinData("Foo", "*", "*"),
310
+ Domain: authorization.DataDomain,
311
+ },
312
+ tests: objectsDataTests,
313
+ },
314
+ {
315
+ name: "an object in all collections ST",
316
+ permission: &models.Permission{
317
+ Data: &models.PermissionData{
318
+ Object: baz,
319
+ },
320
+ },
321
+ policy: &authorization.Policy{
322
+ Resource: CasbinData("*", "*", "baz"),
323
+ Domain: authorization.DataDomain,
324
+ },
325
+ tests: objectsDataTests,
326
+ },
327
+ {
328
+ name: "an object in a collection ST",
329
+ permission: &models.Permission{
330
+ Data: &models.PermissionData{
331
+ Collection: foo,
332
+ Object: baz,
333
+ },
334
+ },
335
+ policy: &authorization.Policy{
336
+ Resource: CasbinData("Foo", "*", "baz"),
337
+ Domain: authorization.DataDomain,
338
+ },
339
+ tests: objectsDataTests,
340
+ },
341
+ {
342
+ name: "all objects in all tenants in a collection MT",
343
+ permission: &models.Permission{
344
+ Data: &models.PermissionData{
345
+ Collection: foo,
346
+ },
347
+ },
348
+ policy: &authorization.Policy{
349
+ Resource: CasbinData("Foo", "*", "*"),
350
+ Domain: authorization.DataDomain,
351
+ },
352
+ tests: objectsDataTests,
353
+ },
354
+ {
355
+ name: "all objects in a tenant in all collections MT",
356
+ permission: &models.Permission{
357
+ Data: &models.PermissionData{
358
+ Tenant: bar,
359
+ },
360
+ },
361
+ policy: &authorization.Policy{
362
+ Resource: CasbinData("*", "bar", "*"),
363
+ Domain: authorization.DataDomain,
364
+ },
365
+ tests: objectsDataTests,
366
+ },
367
+ {
368
+ name: "all objects in a tenant in a collection MT",
369
+ permission: &models.Permission{
370
+ Data: &models.PermissionData{
371
+ Collection: foo,
372
+ Tenant: bar,
373
+ },
374
+ },
375
+ policy: &authorization.Policy{
376
+ Resource: CasbinData("Foo", "bar", "*"),
377
+ Domain: authorization.DataDomain,
378
+ },
379
+ tests: objectsDataTests,
380
+ },
381
+ {
382
+ name: "an object in all tenants in all collections MT",
383
+ permission: &models.Permission{
384
+ Data: &models.PermissionData{
385
+ Object: baz,
386
+ },
387
+ },
388
+ policy: &authorization.Policy{
389
+ Resource: CasbinData("*", "*", "baz"),
390
+ Domain: authorization.DataDomain,
391
+ },
392
+ tests: objectsDataTests,
393
+ },
394
+ {
395
+ name: "an object in all tenants in a collection MT",
396
+ permission: &models.Permission{
397
+ Data: &models.PermissionData{
398
+ Collection: foo,
399
+ Object: baz,
400
+ },
401
+ },
402
+ policy: &authorization.Policy{
403
+ Resource: CasbinData("Foo", "*", "baz"),
404
+ Domain: authorization.DataDomain,
405
+ },
406
+ tests: objectsDataTests,
407
+ },
408
+ {
409
+ name: "an object in a tenant in all collections MT",
410
+ permission: &models.Permission{
411
+ Data: &models.PermissionData{
412
+ Tenant: bar,
413
+ Object: baz,
414
+ },
415
+ },
416
+ policy: &authorization.Policy{
417
+ Resource: CasbinData("*", "bar", "baz"),
418
+ Domain: authorization.DataDomain,
419
+ },
420
+ tests: objectsDataTests,
421
+ },
422
+ {
423
+ name: "an object in a tenant in a collection MT",
424
+ permission: &models.Permission{
425
+ Data: &models.PermissionData{
426
+ Collection: foo,
427
+ Tenant: bar,
428
+ Object: baz,
429
+ },
430
+ },
431
+ policy: &authorization.Policy{
432
+ Resource: CasbinData("Foo", "bar", "baz"),
433
+ Domain: authorization.DataDomain,
434
+ },
435
+ tests: objectsDataTests,
436
+ },
437
+ {
438
+ name: "a tenant",
439
+ permission: &models.Permission{
440
+ Tenants: &models.PermissionTenants{
441
+ Collection: foo,
442
+ },
443
+ },
444
+ policy: &authorization.Policy{
445
+ Resource: CasbinSchema("Foo", ""),
446
+ Domain: authorization.SchemaDomain,
447
+ },
448
+ tests: tenantsActionTests,
449
+ },
450
+ {
451
+ name: "all tenants in all collections",
452
+ permission: &models.Permission{
453
+ Tenants: &models.PermissionTenants{},
454
+ },
455
+ policy: &authorization.Policy{
456
+ Resource: CasbinSchema("*", "*"),
457
+ Domain: authorization.SchemaDomain,
458
+ },
459
+ tests: tenantsActionTests,
460
+ },
461
+ {
462
+ name: "all tenants in a collection",
463
+ permission: &models.Permission{
464
+ Tenants: &models.PermissionTenants{
465
+ Collection: foo,
466
+ },
467
+ },
468
+ policy: &authorization.Policy{
469
+ Resource: CasbinSchema("Foo", "*"),
470
+ Domain: authorization.SchemaDomain,
471
+ },
472
+ tests: tenantsActionTests,
473
+ },
474
+ {
475
+ name: "a tenant in all collections",
476
+ permission: &models.Permission{
477
+ Tenants: &models.PermissionTenants{
478
+ Tenant: bar,
479
+ },
480
+ },
481
+ policy: &authorization.Policy{
482
+ Resource: CasbinSchema("*", "bar"),
483
+ Domain: authorization.SchemaDomain,
484
+ },
485
+ tests: tenantsActionTests,
486
+ },
487
+ {
488
+ name: "a tenant in a collection",
489
+ permission: &models.Permission{
490
+ Tenants: &models.PermissionTenants{
491
+ Collection: foo,
492
+ Tenant: bar,
493
+ },
494
+ },
495
+ policy: &authorization.Policy{
496
+ Resource: CasbinSchema("Foo", "bar"),
497
+ Domain: authorization.SchemaDomain,
498
+ },
499
+ tests: tenantsActionTests,
500
+ },
501
+ }
502
+ for _, tt := range tests {
503
+ for _, ttt := range tt.tests {
504
+ t.Run(fmt.Sprintf("%s %s", ttt.testDescription, tt.name), func(t *testing.T) {
505
+ tt.permission.Action = authorization.String(ttt.permissionAction)
506
+ tt.policy.Verb = ttt.policyVerb
507
+
508
+ policy, err := policy(tt.permission)
509
+ require.Nil(t, err)
510
+ require.Equal(t, tt.policy, policy)
511
+ })
512
+ }
513
+ }
514
+ }
515
+
516
+ func Test_permission(t *testing.T) {
517
+ tests := []struct {
518
+ name string
519
+ policy []string
520
+ permission *models.Permission
521
+ tests []innerTest
522
+ }{
523
+ {
524
+ name: "all roles",
525
+ policy: []string{"p", "/*", "", authorization.RolesDomain},
526
+ permission: &models.Permission{
527
+ Roles: &models.PermissionRoles{Role: authorization.String("*"), Scope: authorization.String(models.PermissionRolesScopeMatch)},
528
+ },
529
+ tests: rolesTestsR,
530
+ },
531
+ {
532
+ name: "all roles",
533
+ policy: []string{"p", "/*", authorization.ROLE_SCOPE_MATCH, authorization.RolesDomain},
534
+ permission: &models.Permission{
535
+ Roles: authorization.AllRoles,
536
+ },
537
+ tests: rolesTestsCUD,
538
+ },
539
+ {
540
+ name: "a role",
541
+ policy: []string{"p", "/custom", authorization.ROLE_SCOPE_MATCH, authorization.RolesDomain},
542
+ permission: &models.Permission{
543
+ Roles: &models.PermissionRoles{Role: authorization.String("custom"), Scope: authorization.String(models.PermissionRolesScopeMatch)},
544
+ },
545
+ tests: rolesTestsR,
546
+ },
547
+ {
548
+ name: "a role",
549
+ policy: []string{"p", "/custom", authorization.ROLE_SCOPE_MATCH, authorization.RolesDomain},
550
+ permission: &models.Permission{
551
+ Roles: &models.PermissionRoles{Role: authorization.String("custom"), Scope: authorization.String(models.PermissionRolesScopeAll)},
552
+ },
553
+ tests: rolesTestsCUD,
554
+ },
555
+ {
556
+ name: "all users",
557
+ policy: []string{"p", "/*", "", authorization.UsersDomain},
558
+ permission: &models.Permission{
559
+ Users: authorization.AllUsers,
560
+ },
561
+ tests: userTests,
562
+ },
563
+ {
564
+ name: "cluster",
565
+ policy: []string{"p", "/*", "", authorization.ClusterDomain},
566
+ permission: &models.Permission{},
567
+ tests: clusterTests,
568
+ },
569
+ {
570
+ name: "minimal nodes",
571
+ policy: []string{"p", "/verbosity/minimal", "", authorization.NodesDomain},
572
+ permission: &models.Permission{
573
+ Nodes: &models.PermissionNodes{
574
+ Verbosity: authorization.String("minimal"),
575
+ },
576
+ },
577
+ tests: nodesTests,
578
+ },
579
+ {
580
+ name: "verbose nodes over all collections",
581
+ policy: []string{"p", "/verbosity/verbose/collections/*", "", authorization.NodesDomain},
582
+ permission: &models.Permission{
583
+ Nodes: &models.PermissionNodes{
584
+ Collection: authorization.All,
585
+ Verbosity: authorization.String("verbose"),
586
+ },
587
+ },
588
+ tests: nodesTests,
589
+ },
590
+ {
591
+ name: "verbose nodes over one collection",
592
+ policy: []string{"p", "/verbosity/verbose/collections/Foo", "", authorization.NodesDomain},
593
+ permission: &models.Permission{
594
+ Nodes: &models.PermissionNodes{
595
+ Collection: authorization.String("Foo"),
596
+ Verbosity: authorization.String("verbose"),
597
+ },
598
+ },
599
+ tests: nodesTests,
600
+ },
601
+ {
602
+ name: "all tenants",
603
+ policy: []string{"p", "/collections/*/shards/*", "", authorization.SchemaDomain},
604
+ permission: &models.Permission{
605
+ Tenants: authorization.AllTenants,
606
+ },
607
+ tests: tenantsActionTests,
608
+ },
609
+ {
610
+ name: "a tenant",
611
+ policy: []string{"p", "/collections/Foo/shards/*", "", authorization.SchemaDomain},
612
+ permission: &models.Permission{
613
+ Tenants: &models.PermissionTenants{
614
+ Collection: foo,
615
+ Tenant: authorization.All,
616
+ },
617
+ },
618
+ tests: tenantsActionTests,
619
+ },
620
+ {
621
+ name: "backup all collections",
622
+ policy: []string{"p", "/collections/*", "", "backups"},
623
+ permission: &models.Permission{
624
+ Backups: authorization.AllBackups,
625
+ },
626
+ tests: backupsTests,
627
+ },
628
+ {
629
+ name: "a collection ABC",
630
+ policy: []string{"p", "/collections/ABC", "", "backups"},
631
+ permission: &models.Permission{
632
+ Backups: &models.PermissionBackups{
633
+ Collection: authorization.String("ABC"),
634
+ },
635
+ },
636
+ tests: backupsTests,
637
+ },
638
+ {
639
+ name: "all collections",
640
+ policy: []string{"p", "/collections/*/shards/#", "", authorization.SchemaDomain},
641
+ permission: &models.Permission{
642
+ Collections: authorization.AllCollections,
643
+ },
644
+ tests: collectionsTests,
645
+ },
646
+ {
647
+ name: "a collection",
648
+ policy: []string{"p", "/collections/Foo/shards/#", "", authorization.SchemaDomain},
649
+ permission: &models.Permission{
650
+ Collections: &models.PermissionCollections{
651
+ Collection: foo,
652
+ },
653
+ },
654
+ tests: collectionsTests,
655
+ },
656
+ {
657
+ name: "all tenants in all collections",
658
+ policy: []string{"p", "/collections/*/shards/*", "", authorization.SchemaDomain},
659
+ permission: &models.Permission{
660
+ Tenants: authorization.AllTenants,
661
+ },
662
+ tests: tenantsActionTests,
663
+ },
664
+ {
665
+ name: "all tenants in a collection",
666
+ policy: []string{"p", "/collections/Foo/shards/*", "", authorization.SchemaDomain},
667
+ permission: &models.Permission{
668
+ Tenants: &models.PermissionTenants{
669
+ Collection: foo,
670
+ Tenant: authorization.All,
671
+ },
672
+ },
673
+ tests: tenantsActionTests,
674
+ },
675
+ {
676
+ name: "a tenant in all collections",
677
+ policy: []string{"p", "/collections/*/shards/bar", "", authorization.SchemaDomain},
678
+ permission: &models.Permission{
679
+ Tenants: &models.PermissionTenants{
680
+ Collection: authorization.All,
681
+ Tenant: bar,
682
+ },
683
+ },
684
+ tests: tenantsActionTests,
685
+ },
686
+ {
687
+ name: "a tenant in a collection",
688
+ policy: []string{"p", "/collections/Foo/shards/bar", "", authorization.SchemaDomain},
689
+ permission: &models.Permission{
690
+ Tenants: &models.PermissionTenants{
691
+ Collection: foo,
692
+ Tenant: bar,
693
+ },
694
+ },
695
+ tests: tenantsActionTests,
696
+ },
697
+ {
698
+ name: "all objects in all collections ST",
699
+ policy: []string{"p", "/collections/*/shards/*/objects/*", "", authorization.DataDomain},
700
+ permission: &models.Permission{
701
+ Data: &models.PermissionData{
702
+ Collection: authorization.All,
703
+ Tenant: authorization.All,
704
+ Object: authorization.All,
705
+ },
706
+ },
707
+ tests: objectsDataTests,
708
+ },
709
+ {
710
+ name: "all objects in a collection ST",
711
+ policy: []string{"p", "/collections/Foo/shards/*/objects/*", "", authorization.DataDomain},
712
+ permission: &models.Permission{
713
+ Data: &models.PermissionData{
714
+ Collection: foo,
715
+ Tenant: authorization.All,
716
+ Object: authorization.All,
717
+ },
718
+ },
719
+ tests: objectsDataTests,
720
+ },
721
+ {
722
+ name: "an object in all collections ST",
723
+ policy: []string{"p", "/collections/*/shards/*/objects/baz", "", authorization.DataDomain},
724
+ permission: &models.Permission{
725
+ Data: &models.PermissionData{
726
+ Collection: authorization.All,
727
+ Tenant: authorization.All,
728
+ Object: baz,
729
+ },
730
+ },
731
+ tests: objectsDataTests,
732
+ },
733
+ {
734
+ name: "an object in a collection ST",
735
+ policy: []string{"p", "/collections/Foo/shards/*/objects/baz", "", authorization.DataDomain},
736
+ permission: &models.Permission{
737
+ Data: &models.PermissionData{
738
+ Collection: foo,
739
+ Tenant: authorization.All,
740
+ Object: baz,
741
+ },
742
+ },
743
+ tests: objectsDataTests,
744
+ },
745
+ {
746
+ name: "all objects in all tenants in all collections MT",
747
+ policy: []string{"p", "/collections/*/shards/*/objects/*", "", authorization.DataDomain},
748
+ permission: &models.Permission{
749
+ Data: authorization.AllData,
750
+ },
751
+ tests: objectsDataTests,
752
+ },
753
+ {
754
+ name: "all objects in all tenants in a collection MT",
755
+ policy: []string{"p", "/collections/Foo/shards/*/objects/*", "", authorization.DataDomain},
756
+ permission: &models.Permission{
757
+ Data: &models.PermissionData{
758
+ Collection: foo,
759
+ Tenant: authorization.All,
760
+ Object: authorization.All,
761
+ },
762
+ },
763
+ tests: objectsDataTests,
764
+ },
765
+ {
766
+ name: "all objects in a tenant in all collections MT",
767
+ policy: []string{"p", "/collections/*/shards/bar/objects/*", "", authorization.DataDomain},
768
+ permission: &models.Permission{
769
+ Data: &models.PermissionData{
770
+ Collection: authorization.All,
771
+ Tenant: bar,
772
+ Object: authorization.All,
773
+ },
774
+ },
775
+ tests: objectsDataTests,
776
+ },
777
+ {
778
+ name: "all objects in a tenant in a collection MT",
779
+ policy: []string{"p", "/collections/Foo/shards/bar/objects/*", "", authorization.DataDomain},
780
+ permission: &models.Permission{
781
+ Data: &models.PermissionData{
782
+ Collection: foo,
783
+ Tenant: bar,
784
+ Object: authorization.All,
785
+ },
786
+ },
787
+ tests: objectsDataTests,
788
+ },
789
+ {
790
+ name: "an object in all tenants in all collections MT",
791
+ policy: []string{"p", "/collections/*/shards/*/objects/baz", "", authorization.DataDomain},
792
+ permission: &models.Permission{
793
+ Data: &models.PermissionData{
794
+ Collection: authorization.All,
795
+ Tenant: authorization.All,
796
+ Object: baz,
797
+ },
798
+ },
799
+ tests: objectsDataTests,
800
+ },
801
+ {
802
+ name: "an object in all tenants in a collection MT",
803
+ policy: []string{"p", "/collections/Foo/shards/*/objects/baz", "", authorization.DataDomain},
804
+ permission: &models.Permission{
805
+ Data: &models.PermissionData{
806
+ Collection: foo,
807
+ Tenant: authorization.All,
808
+ Object: baz,
809
+ },
810
+ },
811
+ },
812
+ {
813
+ name: "an object in a tenant in all collections MT",
814
+ policy: []string{"p", "/collections/*/shards/bar/objects/baz", "", authorization.DataDomain},
815
+ permission: &models.Permission{
816
+ Data: &models.PermissionData{
817
+ Collection: authorization.All,
818
+ Tenant: bar,
819
+ Object: baz,
820
+ },
821
+ },
822
+ tests: objectsDataTests,
823
+ },
824
+ {
825
+ name: "an object in a tenant in a collection MT",
826
+ policy: []string{"p", "/collections/Foo/shards/bar/objects/baz", "", authorization.DataDomain},
827
+ permission: &models.Permission{
828
+ Data: &models.PermissionData{
829
+ Collection: foo,
830
+ Tenant: bar,
831
+ Object: baz,
832
+ },
833
+ },
834
+ tests: objectsDataTests,
835
+ },
836
+ {
837
+ name: "a user",
838
+ policy: []string{"p", "/baz", "", authorization.UsersDomain},
839
+ permission: &models.Permission{
840
+ Users: &models.PermissionUsers{
841
+ Users: baz,
842
+ },
843
+ },
844
+ tests: userTests,
845
+ },
846
+ {
847
+ name: "all users",
848
+ policy: []string{"p", "/*", "", authorization.UsersDomain},
849
+ permission: &models.Permission{
850
+ Users: &models.PermissionUsers{
851
+ Users: authorization.All,
852
+ },
853
+ },
854
+ tests: userTests,
855
+ },
856
+ {
857
+ name: "a group",
858
+ policy: []string{"p", "/oidc/baz", "", authorization.GroupsDomain},
859
+ permission: &models.Permission{
860
+ Groups: &models.PermissionGroups{
861
+ Group: baz,
862
+ GroupType: models.GroupTypeOidc,
863
+ },
864
+ },
865
+ tests: groupTests,
866
+ },
867
+ {
868
+ name: "all groups",
869
+ policy: []string{"p", "/oidc/*", "", authorization.GroupsDomain},
870
+ permission: &models.Permission{
871
+ Groups: &models.PermissionGroups{
872
+ Group: authorization.All,
873
+ GroupType: models.GroupTypeOidc,
874
+ },
875
+ },
876
+ tests: groupTests,
877
+ },
878
+ }
879
+ for _, tt := range tests {
880
+ tt.policy[1] = fmt.Sprintf("%s%s", tt.policy[3], tt.policy[1])
881
+ for _, ttt := range tt.tests {
882
+ t.Run(fmt.Sprintf("%s %s", ttt.testDescription, tt.name), func(t *testing.T) {
883
+ policyForTest := make([]string, len(tt.policy))
884
+ copy(policyForTest, tt.policy)
885
+ tt.permission.Action = authorization.String(ttt.permissionAction)
886
+ // TODO-RBAC : this test has to be rewritten and consider scopes
887
+ if policyForTest[2] == authorization.ROLE_SCOPE_MATCH {
888
+ policyForTest[2] = ttt.policyVerb + "_" + authorization.ROLE_SCOPE_MATCH
889
+ } else {
890
+ policyForTest[2] = ttt.policyVerb
891
+ }
892
+ permission, err := permission(policyForTest, true)
893
+ require.Nil(t, err)
894
+ require.Equal(t, tt.permission, permission)
895
+ })
896
+ }
897
+ }
898
+ }
899
+
900
+ func Test_pUsers(t *testing.T) {
901
+ tests := []struct {
902
+ user string
903
+ expected string
904
+ }{
905
+ {user: "", expected: fmt.Sprintf("%s/.*", authorization.UsersDomain)},
906
+ {user: "*", expected: fmt.Sprintf("%s/.*", authorization.UsersDomain)},
907
+ {user: "foo", expected: fmt.Sprintf("%s/foo", authorization.UsersDomain)},
908
+ }
909
+ for _, tt := range tests {
910
+ name := fmt.Sprintf("user: %s", tt.user)
911
+ t.Run(name, func(t *testing.T) {
912
+ p := CasbinUsers(tt.user)
913
+ require.Equal(t, tt.expected, p)
914
+ })
915
+ }
916
+ }
917
+
918
+ func Test_pGroups(t *testing.T) {
919
+ tests := []struct {
920
+ group string
921
+ expected string
922
+ }{
923
+ {group: "", expected: fmt.Sprintf("%s/%s/.*", authorization.GroupsDomain, authentication.AuthTypeOIDC)},
924
+ {group: "*", expected: fmt.Sprintf("%s/%s/.*", authorization.GroupsDomain, authentication.AuthTypeOIDC)},
925
+ {group: "foo", expected: fmt.Sprintf("%s/%s/foo", authorization.GroupsDomain, authentication.AuthTypeOIDC)},
926
+ }
927
+ for _, tt := range tests {
928
+ name := fmt.Sprintf("group: %s", tt.group)
929
+ t.Run(name, func(t *testing.T) {
930
+ p := CasbinGroups(tt.group, string(authentication.AuthTypeOIDC))
931
+ require.Equal(t, tt.expected, p)
932
+ })
933
+ }
934
+ }
935
+
936
+ func Test_pRoles(t *testing.T) {
937
+ tests := []struct {
938
+ role string
939
+ expected string
940
+ }{
941
+ {role: "", expected: fmt.Sprintf("%s/.*", authorization.RolesDomain)},
942
+ {role: "*", expected: fmt.Sprintf("%s/.*", authorization.RolesDomain)},
943
+ {role: "foo", expected: fmt.Sprintf("%s/foo", authorization.RolesDomain)},
944
+ }
945
+ for _, tt := range tests {
946
+ name := fmt.Sprintf("role: %s", tt.role)
947
+ t.Run(name, func(t *testing.T) {
948
+ p := CasbinRoles(tt.role)
949
+ require.Equal(t, tt.expected, p)
950
+ })
951
+ }
952
+ }
953
+
954
+ func Test_pCollections(t *testing.T) {
955
+ tests := []struct {
956
+ collection string
957
+ expected string
958
+ }{
959
+ {collection: "", expected: fmt.Sprintf("%s/collections/.*/shards/.*", authorization.SchemaDomain)},
960
+ {collection: "*", expected: fmt.Sprintf("%s/collections/.*/shards/.*", authorization.SchemaDomain)},
961
+ {collection: "foo", expected: fmt.Sprintf("%s/collections/Foo/shards/.*", authorization.SchemaDomain)},
962
+ }
963
+ for _, tt := range tests {
964
+ name := fmt.Sprintf("collection: %s", tt.collection)
965
+ t.Run(name, func(t *testing.T) {
966
+ p := CasbinSchema(tt.collection, "")
967
+ require.Equal(t, tt.expected, p)
968
+ })
969
+ }
970
+ }
971
+
972
+ func Test_CasbinShards(t *testing.T) {
973
+ tests := []struct {
974
+ collection string
975
+ shard string
976
+ expected string
977
+ }{
978
+ {collection: "", shard: "", expected: fmt.Sprintf("%s/collections/.*/shards/.*", authorization.SchemaDomain)},
979
+ {collection: "*", shard: "*", expected: fmt.Sprintf("%s/collections/.*/shards/.*", authorization.SchemaDomain)},
980
+ {collection: "foo", shard: "", expected: fmt.Sprintf("%s/collections/Foo/shards/.*", authorization.SchemaDomain)},
981
+ {collection: "foo", shard: "*", expected: fmt.Sprintf("%s/collections/Foo/shards/.*", authorization.SchemaDomain)},
982
+ {collection: "", shard: "bar", expected: fmt.Sprintf("%s/collections/.*/shards/bar", authorization.SchemaDomain)},
983
+ {collection: "*", shard: "bar", expected: fmt.Sprintf("%s/collections/.*/shards/bar", authorization.SchemaDomain)},
984
+ {collection: "foo", shard: "bar", expected: fmt.Sprintf("%s/collections/Foo/shards/bar", authorization.SchemaDomain)},
985
+ }
986
+ for _, tt := range tests {
987
+ name := fmt.Sprintf("collection: %s; shard: %s", tt.collection, tt.shard)
988
+ t.Run(name, func(t *testing.T) {
989
+ p := CasbinSchema(tt.collection, tt.shard)
990
+ require.Equal(t, tt.expected, p)
991
+ })
992
+ }
993
+ }
994
+
995
+ func Test_pObjects(t *testing.T) {
996
+ tests := []struct {
997
+ collection string
998
+ shard string
999
+ object string
1000
+ expected string
1001
+ }{
1002
+ {collection: "", shard: "", object: "", expected: fmt.Sprintf("%s/collections/.*/shards/.*/objects/.*", authorization.DataDomain)},
1003
+ {collection: "*", shard: "*", object: "*", expected: fmt.Sprintf("%s/collections/.*/shards/.*/objects/.*", authorization.DataDomain)},
1004
+ {collection: "foo", shard: "", object: "", expected: fmt.Sprintf("%s/collections/Foo/shards/.*/objects/.*", authorization.DataDomain)},
1005
+ {collection: "foo", shard: "*", object: "*", expected: fmt.Sprintf("%s/collections/Foo/shards/.*/objects/.*", authorization.DataDomain)},
1006
+ {collection: "", shard: "bar", object: "", expected: fmt.Sprintf("%s/collections/.*/shards/bar/objects/.*", authorization.DataDomain)},
1007
+ {collection: "*", shard: "bar", object: "*", expected: fmt.Sprintf("%s/collections/.*/shards/bar/objects/.*", authorization.DataDomain)},
1008
+ {collection: "", shard: "", object: "baz", expected: fmt.Sprintf("%s/collections/.*/shards/.*/objects/baz", authorization.DataDomain)},
1009
+ {collection: "*", shard: "*", object: "baz", expected: fmt.Sprintf("%s/collections/.*/shards/.*/objects/baz", authorization.DataDomain)},
1010
+ {collection: "foo", shard: "bar", object: "", expected: fmt.Sprintf("%s/collections/Foo/shards/bar/objects/.*", authorization.DataDomain)},
1011
+ {collection: "foo", shard: "bar", object: "*", expected: fmt.Sprintf("%s/collections/Foo/shards/bar/objects/.*", authorization.DataDomain)},
1012
+ {collection: "foo", shard: "", object: "baz", expected: fmt.Sprintf("%s/collections/Foo/shards/.*/objects/baz", authorization.DataDomain)},
1013
+ {collection: "foo", shard: "*", object: "baz", expected: fmt.Sprintf("%s/collections/Foo/shards/.*/objects/baz", authorization.DataDomain)},
1014
+ {collection: "", shard: "bar", object: "baz", expected: fmt.Sprintf("%s/collections/.*/shards/bar/objects/baz", authorization.DataDomain)},
1015
+ {collection: "*", shard: "bar", object: "baz", expected: fmt.Sprintf("%s/collections/.*/shards/bar/objects/baz", authorization.DataDomain)},
1016
+ {collection: "foo", shard: "bar", object: "baz", expected: fmt.Sprintf("%s/collections/Foo/shards/bar/objects/baz", authorization.DataDomain)},
1017
+ }
1018
+ for _, tt := range tests {
1019
+ name := fmt.Sprintf("collection: %s; shard: %s; object: %s", tt.collection, tt.shard, tt.object)
1020
+ t.Run(name, func(t *testing.T) {
1021
+ p := CasbinData(tt.collection, tt.shard, tt.object)
1022
+ require.Equal(t, tt.expected, p)
1023
+ })
1024
+ }
1025
+ }
1026
+
1027
+ func Test_CasbinBackups(t *testing.T) {
1028
+ tests := []struct {
1029
+ backend string
1030
+ expected string
1031
+ }{
1032
+ {backend: "", expected: fmt.Sprintf("%s/collections/.*", authorization.BackupsDomain)},
1033
+ {backend: "*", expected: fmt.Sprintf("%s/collections/.*", authorization.BackupsDomain)},
1034
+ {backend: "foo", expected: fmt.Sprintf("%s/collections/Foo", authorization.BackupsDomain)},
1035
+ {backend: "foo", expected: fmt.Sprintf("%s/collections/Foo", authorization.BackupsDomain)},
1036
+ {backend: "", expected: fmt.Sprintf("%s/collections/.*", authorization.BackupsDomain)},
1037
+ {backend: "*", expected: fmt.Sprintf("%s/collections/.*", authorization.BackupsDomain)},
1038
+ {backend: "foo", expected: fmt.Sprintf("%s/collections/Foo", authorization.BackupsDomain)},
1039
+ }
1040
+ for _, tt := range tests {
1041
+ name := fmt.Sprintf("backend: %s", tt.backend)
1042
+ t.Run(name, func(t *testing.T) {
1043
+ p := CasbinBackups(tt.backend)
1044
+ require.Equal(t, tt.expected, p)
1045
+ })
1046
+ }
1047
+ }
1048
+
1049
+ func Test_fromCasbinResource(t *testing.T) {
1050
+ tests := []struct {
1051
+ resource string
1052
+ expected string
1053
+ }{
1054
+ {resource: "collections/.*/shards/.*/objects/.*", expected: "collections/*/shards/*/objects/*"},
1055
+ }
1056
+ for _, tt := range tests {
1057
+ name := fmt.Sprintf("Resource: %s", tt.resource)
1058
+ t.Run(name, func(t *testing.T) {
1059
+ p := fromCasbinResource(tt.resource)
1060
+ require.Equal(t, tt.expected, p)
1061
+ })
1062
+ }
1063
+ }
1064
+
1065
+ func TestValidResource(t *testing.T) {
1066
+ tests := []struct {
1067
+ name string
1068
+ input string
1069
+ expected bool
1070
+ }{
1071
+ {
1072
+ name: "valid resource - users",
1073
+ input: fmt.Sprintf("%s/testUser", authorization.UsersDomain),
1074
+ expected: true,
1075
+ },
1076
+ {
1077
+ name: "valid resource - groups",
1078
+ input: fmt.Sprintf("%s/testGroups", authorization.GroupsDomain),
1079
+ expected: true,
1080
+ },
1081
+ {
1082
+ name: "valid resource - roles",
1083
+ input: fmt.Sprintf("%s/testRole", authorization.RolesDomain),
1084
+ expected: true,
1085
+ },
1086
+ {
1087
+ name: "valid resource - collections",
1088
+ input: fmt.Sprintf("%s/collections/testCollection", authorization.SchemaDomain),
1089
+ expected: true,
1090
+ },
1091
+ {
1092
+ name: "valid resource - objects",
1093
+ input: fmt.Sprintf("%s/collections/testCollection/shards/testShard/objects/testObject", authorization.DataDomain),
1094
+ expected: true,
1095
+ },
1096
+ {
1097
+ name: "invalid resource",
1098
+ input: "invalid/resource",
1099
+ expected: false,
1100
+ },
1101
+ {
1102
+ name: "invalid resource",
1103
+ input: "some resource",
1104
+ expected: false,
1105
+ },
1106
+ }
1107
+
1108
+ for _, tt := range tests {
1109
+ t.Run(tt.name, func(t *testing.T) {
1110
+ result := validResource(tt.input)
1111
+ require.Equal(t, tt.expected, result)
1112
+ })
1113
+ }
1114
+ }
1115
+
1116
+ func TestValidVerb(t *testing.T) {
1117
+ tests := []struct {
1118
+ name string
1119
+ input string
1120
+ expected bool
1121
+ }{
1122
+ {
1123
+ name: "valid verb - create",
1124
+ input: "C",
1125
+ expected: true,
1126
+ },
1127
+ {
1128
+ name: "valid verb - read",
1129
+ input: "R",
1130
+ expected: true,
1131
+ },
1132
+ {
1133
+ name: "valid verb - update",
1134
+ input: "U",
1135
+ expected: true,
1136
+ },
1137
+ {
1138
+ name: "valid verb - delete",
1139
+ input: "D",
1140
+ expected: true,
1141
+ },
1142
+ {
1143
+ name: "All",
1144
+ input: "CRUD",
1145
+ expected: true,
1146
+ },
1147
+ {
1148
+ name: "invalid verb",
1149
+ input: "X",
1150
+ expected: false,
1151
+ },
1152
+ }
1153
+
1154
+ for _, tt := range tests {
1155
+ t.Run(tt.name, func(t *testing.T) {
1156
+ result := validVerb(tt.input)
1157
+ require.Equal(t, tt.expected, result)
1158
+ })
1159
+ }
1160
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/docs/auth_calls.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authorization Calls
2
+ This document lists all authorization calls in the codebase.
3
+ ## Usage
4
+ To regenerate this documentation, run the following commands from the repository root:
5
+ ```bash
6
+ cd usecases/auth/authorization/docs
7
+ go run generator.go
8
+ ```
9
+ ## Statistics
10
+ - Total files found: 23162
11
+ - Files processed: 1937
12
+ - Total Authorize calls found: 79
13
+
14
+ | Function | File | Verb → Resources |
15
+ |----------|------|-----------------|
16
+ | resolveAggregate | adapters/handlers/graphql/local/aggregate/resolver.go | READ → ShardsData |
17
+ | authorizePath | adapters/handlers/graphql/local/common_filters/authz.go | READ → CollectionsData |
18
+ | AuthorizeProperty | adapters/handlers/graphql/local/common_filters/authz.go | READ → CollectionsData |
19
+ | resolveExplore | adapters/handlers/graphql/local/explore/concepts_resolver.go | READ → CollectionsData |
20
+ | resolveGet | adapters/handlers/graphql/local/get/class_builder_fields.go | READ → ShardsData |
21
+ | batchDelete | adapters/handlers/grpc/v1/service.go | DELETE → ShardsData |
22
+ | batchObjects | adapters/handlers/grpc/v1/service.go | UPDATE → ShardsData<br>CREATE → ShardsData |
23
+ | classGetterWithAuthzFunc | adapters/handlers/grpc/v1/service.go | READ → Collections |
24
+ | createRole | adapters/handlers/rest/authz/handlers_authz.go | CREATE → Roles |
25
+ | addPermissions | adapters/handlers/rest/authz/handlers_authz.go | UPDATE → Roles |
26
+ | removePermissions | adapters/handlers/rest/authz/handlers_authz.go | UPDATE → Roles |
27
+ | hasPermission | adapters/handlers/rest/authz/handlers_authz.go | READ → Roles |
28
+ | getRoles | adapters/handlers/rest/authz/handlers_authz.go | READ → Roles |
29
+ | getRole | adapters/handlers/rest/authz/handlers_authz.go | READ → Roles |
30
+ | deleteRole | adapters/handlers/rest/authz/handlers_authz.go | DELETE → Roles |
31
+ | assignRole | adapters/handlers/rest/authz/handlers_authz.go | UPDATE → Roles |
32
+ | getRolesForUser | adapters/handlers/rest/authz/handlers_authz.go | READ → Roles |
33
+ | getUsersForRole | adapters/handlers/rest/authz/handlers_authz.go | READ → Roles |
34
+ | revokeRole | adapters/handlers/rest/authz/handlers_authz.go | UPDATE → Roles |
35
+ | setupGraphQLHandlers | adapters/handlers/rest/handlers_graphql.go | READ → CollectionsMetadata, Collections |
36
+ | Backup | usecases/backup/scheduler.go | CREATE → Backups |
37
+ | Restore | usecases/backup/scheduler.go | CREATE → Backups |
38
+ | Cancel | usecases/backup/scheduler.go | DELETE → Backups |
39
+ | Schedule | usecases/classification/classifier.go | UPDATE → CollectionsMetadata |
40
+ | validateFilter | usecases/classification/classifier.go | READ → CollectionsMetadata |
41
+ | Get | usecases/classification/classifier.go | READ → CollectionsMetadata |
42
+ | GetNodeStatus | usecases/nodes/handler.go | READ → Nodes |
43
+ | GetNodeStatistics | usecases/nodes/handler.go | READ → Cluster |
44
+ | AddObject | usecases/objects/add.go | CREATE → ShardsData<br>READ → CollectionsMetadata |
45
+ | autoSchema | usecases/objects/auto_schema.go | CREATE → CollectionsMetadata<br>UPDATE → CollectionsMetadata |
46
+ | AddObjects | usecases/objects/batch_add.go | UPDATE → ShardsData<br>CREATE → ShardsData |
47
+ | DeleteObjects | usecases/objects/batch_delete.go | DELETE → ShardsData |
48
+ | classGetterFunc | usecases/objects/batch_delete.go | READ → Collections |
49
+ | AddReferences | usecases/objects/batch_references_add.go | UPDATE → pathsData<br>READ → pathsMetadata |
50
+ | addReferences | usecases/objects/batch_references_add.go | READ → shardsDataPaths |
51
+ | DeleteObject | usecases/objects/delete.go | READ → CollectionsMetadata<br>DELETE → Objects |
52
+ | GetObject | usecases/objects/get.go | READ → Objects |
53
+ | GetObjects | usecases/objects/get.go | READ → Objects |
54
+ | GetObjectsClass | usecases/objects/get.go | READ → Objects |
55
+ | HeadObject | usecases/objects/head.go | READ → Objects, CollectionsMetadata |
56
+ | MergeObject | usecases/objects/merge.go | UPDATE → Objects<br>READ → CollectionsMetadata |
57
+ | Query | usecases/objects/query.go | READ → CollectionsMetadata |
58
+ | AddObjectReference | usecases/objects/references_add.go | UPDATE → ShardsData<br>READ → CollectionsMetadata, Collections |
59
+ | DeleteObjectReference | usecases/objects/references_delete.go | UPDATE → ShardsData<br>READ → CollectionsMetadata, CollectionsData |
60
+ | UpdateObjectReferences | usecases/objects/references_update.go | UPDATE → ShardsData<br>READ → CollectionsMetadata, Collections |
61
+ | UpdateObject | usecases/objects/update.go | UPDATE → Objects<br>READ → CollectionsMetadata |
62
+ | ValidateObject | usecases/objects/validate.go | READ → Objects |
63
+ | GetClass | usecases/schema/class.go | READ → CollectionsMetadata |
64
+ | GetConsistentClass | usecases/schema/class.go | READ → CollectionsMetadata |
65
+ | GetCachedClass | usecases/schema/class.go | READ → CollectionsMetadata |
66
+ | AddClass | usecases/schema/class.go | CREATE → CollectionsMetadata<br>READ → CollectionsMetadata |
67
+ | DeleteClass | usecases/schema/class.go | DELETE → CollectionsMetadata<br>READ → CollectionsMetadata |
68
+ | UpdateClass | usecases/schema/class.go | UPDATE → CollectionsMetadata |
69
+ | GetSchema | usecases/schema/handler.go | READ → CollectionsMetadata |
70
+ | GetConsistentSchema | usecases/schema/handler.go | READ → CollectionsMetadata |
71
+ | UpdateShardStatus | usecases/schema/handler.go | UPDATE → ShardsMetadata |
72
+ | ShardsStatus | usecases/schema/handler.go | READ → ShardsMetadata |
73
+ | AddClassProperty | usecases/schema/property.go | UPDATE → CollectionsMetadata<br>READ → CollectionsMetadata |
74
+ | DeleteClassProperty | usecases/schema/property.go | UPDATE → CollectionsMetadata |
75
+ | AddTenants | usecases/schema/tenant.go | CREATE → ShardsMetadata |
76
+ | UpdateTenants | usecases/schema/tenant.go | UPDATE → ShardsMetadata |
77
+ | DeleteTenants | usecases/schema/tenant.go | DELETE → ShardsMetadata |
78
+ | GetConsistentTenants | usecases/schema/tenant.go | READ → ShardsMetadata |
79
+ | ConsistentTenantExists | usecases/schema/tenant.go | READ → ShardsMetadata |
80
+ | validateFilters | usecases/traverser/traverser_get.go | READ → CollectionsMetadata |
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/docs/generator.go ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ //go:build ignore
13
+ // +build ignore
14
+
15
+ package main
16
+
17
+ import (
18
+ "fmt"
19
+ "go/ast"
20
+ "go/parser"
21
+ "go/token"
22
+ "os"
23
+ "path/filepath"
24
+ "strings"
25
+ )
26
+
27
+ type authCall struct {
28
+ Function string
29
+ // Map verbs to their resources
30
+ VerbResourceMap map[string][]string // key: verb, value: slice of resources
31
+ FilePath string
32
+ }
33
+
34
+ const mainDirPath = "../../../../"
35
+
36
+ func main() {
37
+ var calls []authCall
38
+ var totalFiles, skippedFiles, processedFiles int
39
+
40
+ err := filepath.Walk(mainDirPath, func(path string, info os.FileInfo, err error) error {
41
+ totalFiles++
42
+
43
+ if err != nil {
44
+ fmt.Fprintf(os.Stderr, "Error accessing path %s: %v\n", path, err)
45
+ return nil
46
+ }
47
+
48
+ // Skip directories
49
+ if info.IsDir() {
50
+ if shouldSkipDir(path) {
51
+ fmt.Fprintf(os.Stderr, "Skipping directory: %s\n", path)
52
+ return filepath.SkipDir
53
+ }
54
+ return nil
55
+ }
56
+
57
+ // Skip non-go files, vendor, and test files
58
+ if !strings.HasSuffix(path, ".go") ||
59
+ strings.Contains(path, "/vendor/") ||
60
+ strings.HasSuffix(path, "_test.go") {
61
+ skippedFiles++
62
+ return nil
63
+ }
64
+
65
+ fmt.Fprintf(os.Stderr, "Processing file: %s\n", path)
66
+ processedFiles++
67
+
68
+ // Read and parse the file
69
+ fset := token.NewFileSet()
70
+ content, err := os.ReadFile(path)
71
+ if err != nil {
72
+ fmt.Fprintf(os.Stderr, "Error reading %s: %v\n", path, err)
73
+ return nil
74
+ }
75
+
76
+ node, err := parser.ParseFile(fset, path, content, 0)
77
+ if err != nil {
78
+ fmt.Fprintf(os.Stderr, "Error parsing %s: %v\n", path, err)
79
+ return nil
80
+ }
81
+
82
+ // Visit all nodes in the AST
83
+ ast.Inspect(node, func(n ast.Node) bool {
84
+ if call, ok := n.(*ast.CallExpr); ok {
85
+ if sel, ok := call.Fun.(*ast.SelectorExpr); ok {
86
+ if sel.Sel.Name == "Authorize" {
87
+ // Find the containing function
88
+ var funcName string
89
+ ast.Inspect(node, func(parent ast.Node) bool {
90
+ if fn, ok := parent.(*ast.FuncDecl); ok {
91
+ if fn.Pos() <= call.Pos() && call.End() <= fn.End() {
92
+ // Skip test functions
93
+ if !strings.HasPrefix(fn.Name.Name, "Test") {
94
+ funcName = fn.Name.Name
95
+ }
96
+ return false
97
+ }
98
+ }
99
+ return true
100
+ })
101
+
102
+ // Skip if no valid function name (e.g., test function)
103
+ if funcName == "" {
104
+ return true
105
+ }
106
+
107
+ if len(call.Args) >= 3 {
108
+ verb := formatArg(call.Args[1])
109
+ resource := formatArg(call.Args[2])
110
+
111
+ verb = strings.TrimPrefix(verb, "&")
112
+ verb = strings.TrimPrefix(verb, "authorization.")
113
+ resource = strings.TrimPrefix(resource, "authorization.")
114
+
115
+ // Check if we already have an entry for this function+file
116
+ if idx, found := findOrCreateCall(calls, funcName, path); found {
117
+ // Initialize map if needed
118
+ if calls[idx].VerbResourceMap == nil {
119
+ calls[idx].VerbResourceMap = make(map[string][]string)
120
+ }
121
+ // Add resource to verb's resource list if not already present
122
+ if !contains(calls[idx].VerbResourceMap[verb], resource) {
123
+ calls[idx].VerbResourceMap[verb] = append(calls[idx].VerbResourceMap[verb], resource)
124
+ }
125
+ } else {
126
+ verbMap := make(map[string][]string)
127
+ verbMap[verb] = []string{resource}
128
+ calls = append(calls, authCall{
129
+ Function: funcName,
130
+ VerbResourceMap: verbMap,
131
+ FilePath: path,
132
+ })
133
+ }
134
+ }
135
+ }
136
+ }
137
+ }
138
+ return true
139
+ })
140
+ return nil
141
+ })
142
+ if err != nil {
143
+ fmt.Fprintf(os.Stderr, "Error walking directory: %v\n", err)
144
+ os.Exit(1)
145
+ }
146
+
147
+ // Print statistics
148
+ fmt.Fprintf(os.Stderr, "\nStatistics:\n")
149
+ fmt.Fprintf(os.Stderr, "Total files found: %d\n", totalFiles)
150
+ fmt.Fprintf(os.Stderr, "Files skipped: %d\n", skippedFiles)
151
+ fmt.Fprintf(os.Stderr, "Files processed: %d\n", processedFiles)
152
+
153
+ // Count total auth calls by summing the length of VerbResourceMap for each function
154
+ totalCalls := 0
155
+ for _, call := range calls {
156
+ totalCalls += len(call.VerbResourceMap)
157
+ }
158
+ fmt.Fprintf(os.Stderr, "Total Authorize calls found: %d\n", totalCalls)
159
+
160
+ // Create and write to the markdown file
161
+ f, err := os.Create("auth_calls.md")
162
+ if err != nil {
163
+ fmt.Fprintf(os.Stderr, "Error creating file: %v\n", err)
164
+ os.Exit(1)
165
+ }
166
+ defer f.Close()
167
+
168
+ // Write the table header
169
+ fmt.Fprintln(f, "# Authorization Calls")
170
+ fmt.Fprintln(f, "This document lists all authorization calls in the codebase.")
171
+
172
+ // Add usage section
173
+ fmt.Fprintln(f, "## Usage")
174
+ fmt.Fprintln(f, "To regenerate this documentation, run the following commands from the repository root:")
175
+ fmt.Fprintln(f, "```bash")
176
+ fmt.Fprintln(f, "cd usecases/auth/authorization/docs")
177
+ fmt.Fprintln(f, "go run generator.go")
178
+ fmt.Fprintln(f, "```")
179
+
180
+ // Continue with statistics section
181
+ fmt.Fprintln(f, "## Statistics")
182
+ fmt.Fprintf(f, "- Total files found: %d\n", totalFiles)
183
+ fmt.Fprintf(f, "- Files processed: %d\n", processedFiles)
184
+ fmt.Fprintf(f, "- Total Authorize calls found: %d\n\n", totalCalls)
185
+
186
+ fmt.Fprintln(f, "| Function | File | Verb → Resources |")
187
+ fmt.Fprintln(f, "|----------|------|-----------------|")
188
+
189
+ // Write each call in table format
190
+ for _, call := range calls {
191
+ var mappings []string
192
+ for verb, resources := range call.VerbResourceMap {
193
+ mappings = append(mappings, fmt.Sprintf("%s → %s", verb, strings.Join(resources, ", ")))
194
+ }
195
+ fmt.Fprintf(f, "| %s | %s | %s |\n",
196
+ call.Function,
197
+ strings.TrimPrefix(call.FilePath, mainDirPath),
198
+ strings.Join(mappings, "<br>"),
199
+ )
200
+ }
201
+
202
+ fmt.Fprintf(os.Stderr, "Results written to auth_calls.md\n")
203
+ }
204
+
205
+ func shouldSkipDir(path string) bool {
206
+ skippedDirs := []string{
207
+ ".git",
208
+ "vendor",
209
+ "node_modules",
210
+ "dist",
211
+ "build",
212
+ }
213
+
214
+ base := filepath.Base(path)
215
+ for _, skip := range skippedDirs {
216
+ if base == skip {
217
+ return true
218
+ }
219
+ }
220
+ return false
221
+ }
222
+
223
+ func formatArg(expr ast.Expr) string {
224
+ switch v := expr.(type) {
225
+ case *ast.SelectorExpr:
226
+ if ident, ok := v.X.(*ast.Ident); ok {
227
+ return fmt.Sprintf("%s.%s", ident.Name, v.Sel.Name)
228
+ }
229
+ case *ast.Ident:
230
+ return v.Name
231
+ case *ast.CallExpr:
232
+ if sel, ok := v.Fun.(*ast.SelectorExpr); ok {
233
+ if ident, ok := sel.X.(*ast.Ident); ok {
234
+ return fmt.Sprintf("%s.%s", ident.Name, sel.Sel.Name)
235
+ }
236
+ }
237
+ }
238
+ return fmt.Sprintf("%v", expr)
239
+ }
240
+
241
+ func findOrCreateCall(calls []authCall, function, filePath string) (int, bool) {
242
+ for i, call := range calls {
243
+ if call.Function == function && call.FilePath == filePath {
244
+ return i, true
245
+ }
246
+ }
247
+ return 0, false
248
+ }
249
+
250
+ func contains(slice []string, item string) bool {
251
+ for _, s := range slice {
252
+ if s == item {
253
+ return true
254
+ }
255
+ }
256
+ return false
257
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/errors/errors.go ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package errors
13
+
14
+ import (
15
+ "fmt"
16
+ "strings"
17
+
18
+ "github.com/weaviate/weaviate/entities/models"
19
+ )
20
+
21
+ // Forbidden indicates a failed authorization
22
+ type Forbidden struct {
23
+ principal *models.Principal
24
+ verb string
25
+ resources []string
26
+ }
27
+
28
+ type Unauthenticated struct{}
29
+
30
+ func (u Unauthenticated) Error() string {
31
+ return "user is not authenticated"
32
+ }
33
+
34
+ // NewUnauthenticated creates an explicit Unauthenticated error
35
+ func NewUnauthenticated() Unauthenticated {
36
+ return Unauthenticated{}
37
+ }
38
+
39
+ // NewForbidden creates an explicit Forbidden error with details about the
40
+ // principal and the attempted access on a specific resource
41
+ func NewForbidden(principal *models.Principal, verb string, resources ...string) Forbidden {
42
+ return Forbidden{
43
+ principal: principal,
44
+ verb: verb,
45
+ resources: resources,
46
+ }
47
+ }
48
+
49
+ func (f Forbidden) Error() string {
50
+ optionalGroups := ""
51
+ if len(f.principal.Groups) == 1 {
52
+ optionalGroups = fmt.Sprintf(" (of group '%s')", f.principal.Groups[0])
53
+ } else if len(f.principal.Groups) > 1 {
54
+ groups := wrapInSingleQuotes(f.principal.Groups)
55
+ groupsList := strings.Join(groups, ", ")
56
+ optionalGroups = fmt.Sprintf(" (of groups %s)", groupsList)
57
+ }
58
+
59
+ return fmt.Sprintf("authorization, forbidden action: user '%s'%s has insufficient permissions to %s %s",
60
+ f.principal.Username, optionalGroups, f.verb, f.resources)
61
+ }
62
+
63
+ func wrapInSingleQuotes(input []string) []string {
64
+ for i, s := range input {
65
+ input[i] = fmt.Sprintf("'%s'", s)
66
+ }
67
+
68
+ return input
69
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/errors/errors_test.go ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package errors
13
+
14
+ import (
15
+ "testing"
16
+
17
+ "github.com/stretchr/testify/assert"
18
+ "github.com/weaviate/weaviate/entities/models"
19
+ )
20
+
21
+ func Test_ForbiddenError_NoGroups(t *testing.T) {
22
+ principal := &models.Principal{
23
+ Username: "john",
24
+ }
25
+
26
+ err := NewForbidden(principal, "delete", "schema/things")
27
+ expectedErrMsg := "authorization, forbidden action: user 'john' has insufficient permissions to delete [schema/things]"
28
+ assert.Equal(t, expectedErrMsg, err.Error())
29
+ }
30
+
31
+ func Test_ForbiddenError_SingleGroup(t *testing.T) {
32
+ principal := &models.Principal{
33
+ Username: "john",
34
+ Groups: []string{"worstusers"},
35
+ }
36
+
37
+ err := NewForbidden(principal, "delete", "schema/things")
38
+ expectedErrMsg := "authorization, forbidden action: user 'john' (of group 'worstusers') has insufficient permissions to delete [schema/things]"
39
+ assert.Equal(t, expectedErrMsg, err.Error())
40
+ }
41
+
42
+ func Test_ForbiddenError_MultipleGroups(t *testing.T) {
43
+ principal := &models.Principal{
44
+ Username: "john",
45
+ Groups: []string{"worstusers", "fraudsters", "evilpeople"},
46
+ }
47
+
48
+ err := NewForbidden(principal, "delete", "schema/things")
49
+ expectedErrMsg := "authorization, forbidden action: user 'john' (of groups 'worstusers', 'fraudsters', 'evilpeople') " +
50
+ "has insufficient permissions to delete [schema/things]"
51
+ assert.Equal(t, expectedErrMsg, err.Error())
52
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/filter/filter.go ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package filter
13
+
14
+ import (
15
+ "context"
16
+ "slices"
17
+
18
+ "github.com/weaviate/weaviate/usecases/auth/authorization/rbac/rbacconf"
19
+
20
+ "github.com/sirupsen/logrus"
21
+
22
+ "github.com/weaviate/weaviate/entities/models"
23
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
24
+ )
25
+
26
+ // ResourceFilter handles filtering resources based on authorization
27
+ type ResourceFilter[T any] struct {
28
+ authorizer authorization.Authorizer
29
+ config rbacconf.Config
30
+ }
31
+
32
+ func New[T any](authorizer authorization.Authorizer, config rbacconf.Config) *ResourceFilter[T] {
33
+ return &ResourceFilter[T]{
34
+ authorizer: authorizer,
35
+ config: config,
36
+ }
37
+ }
38
+
39
+ // FilterFn defines a function that generates authorization resources for an item
40
+ type FilterFn[T any] func(item T) string
41
+
42
+ // Filter filters a slice of items based on authorization
43
+ func (f *ResourceFilter[T]) Filter(
44
+ ctx context.Context,
45
+ logger logrus.FieldLogger,
46
+ principal *models.Principal,
47
+ items []T,
48
+ verb string,
49
+ resourceFn FilterFn[T],
50
+ ) []T {
51
+ if len(items) == 0 {
52
+ return items
53
+ }
54
+ if !f.config.Enabled {
55
+ // here it's either you have the permissions or not so 1 check is enough
56
+ if err := f.authorizer.Authorize(ctx, principal, verb, resourceFn(items[0])); err != nil {
57
+ logger.WithFields(logrus.Fields{
58
+ "username": principal.Username,
59
+ "verb": verb,
60
+ "resources": items,
61
+ }).Error(err)
62
+ return nil
63
+ }
64
+ return items
65
+ }
66
+
67
+ // For RBAC, first check if all items have the same parent resource
68
+ firstResource := resourceFn(items[0])
69
+ allSameParent := true
70
+
71
+ for i := 1; i < len(items); i++ {
72
+ if authorization.WildcardPath(resourceFn(items[i])) != authorization.WildcardPath(firstResource) {
73
+ allSameParent = false
74
+ }
75
+ }
76
+
77
+ // If all items have the same parent, we can do a single authorization check
78
+ if allSameParent {
79
+ err := f.authorizer.Authorize(ctx, principal, verb, authorization.WildcardPath(firstResource))
80
+ if err != nil {
81
+ logger.WithFields(logrus.Fields{
82
+ "username": principal.Username,
83
+ "verb": verb,
84
+ "resource": authorization.WildcardPath(firstResource),
85
+ }).Error(err)
86
+ }
87
+
88
+ if err == nil {
89
+ // user is authorized
90
+ return items
91
+ }
92
+ }
93
+
94
+ // For RBAC, filter based on per-item authorization
95
+ filtered := make([]T, 0, len(items))
96
+ resources := make([]string, 0, len(items))
97
+ for _, item := range items {
98
+ resources = append(resources, resourceFn(item))
99
+ }
100
+
101
+ allowedList, err := f.authorizer.FilterAuthorizedResources(ctx, principal, verb, resources...)
102
+ if err != nil {
103
+ logger.WithFields(logrus.Fields{
104
+ "username": principal.Username,
105
+ "verb": verb,
106
+ "resources": resources,
107
+ }).Error(err)
108
+ }
109
+
110
+ if len(allowedList) == len(resources) {
111
+ // has permissions to all
112
+ return items
113
+ }
114
+
115
+ for _, item := range items {
116
+ if slices.Contains(allowedList, resourceFn(item)) {
117
+ filtered = append(filtered, item)
118
+ }
119
+ }
120
+
121
+ return filtered
122
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/filter/filter_test.go ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package filter
13
+
14
+ import (
15
+ "context"
16
+ "testing"
17
+
18
+ "github.com/sirupsen/logrus/hooks/test"
19
+ "github.com/stretchr/testify/require"
20
+ "github.com/weaviate/weaviate/entities/models"
21
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
22
+ "github.com/weaviate/weaviate/usecases/auth/authorization/mocks"
23
+ "github.com/weaviate/weaviate/usecases/auth/authorization/rbac/rbacconf"
24
+ )
25
+
26
+ func TestFilter(t *testing.T) {
27
+ tests := []struct {
28
+ Name string
29
+ Config rbacconf.Config
30
+ Items []*models.Object
31
+ }{
32
+ {
33
+ Name: "rbac enabled, no objects",
34
+ Items: []*models.Object{},
35
+ Config: rbacconf.Config{Enabled: true},
36
+ },
37
+ {
38
+ Name: "rbac disenabled, no objects",
39
+ Items: []*models.Object{},
40
+ Config: rbacconf.Config{Enabled: false},
41
+ },
42
+ }
43
+
44
+ l, _ := test.NewNullLogger()
45
+
46
+ authorizer := mocks.NewMockAuthorizer()
47
+ for _, tt := range tests {
48
+ t.Run(tt.Name, func(t *testing.T) {
49
+ resourceFilter := New[*models.Object](authorizer, tt.Config)
50
+ filteredObjects := resourceFilter.Filter(
51
+ context.Background(),
52
+ l,
53
+ &models.Principal{Username: "user"},
54
+ tt.Items,
55
+ authorization.READ,
56
+ func(obj *models.Object) string {
57
+ return ""
58
+ },
59
+ )
60
+
61
+ require.Equal(t, len(tt.Items), len(filteredObjects))
62
+ })
63
+ }
64
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/mocks/authorizer.go ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package mocks
13
+
14
+ import (
15
+ "context"
16
+
17
+ models "github.com/weaviate/weaviate/entities/models"
18
+ )
19
+
20
+ type AuthZReq struct {
21
+ Principal *models.Principal
22
+ Verb string
23
+ Resources []string
24
+ }
25
+
26
+ type FakeAuthorizer struct {
27
+ err error
28
+ requests []AuthZReq
29
+ }
30
+
31
+ func NewMockAuthorizer() *FakeAuthorizer {
32
+ return &FakeAuthorizer{}
33
+ }
34
+
35
+ func (a *FakeAuthorizer) SetErr(err error) {
36
+ a.err = err
37
+ }
38
+
39
+ // Authorize provides a mock function with given fields: principal, verb, resource
40
+ func (a *FakeAuthorizer) Authorize(ctx context.Context, principal *models.Principal, verb string, resources ...string) error {
41
+ a.requests = append(a.requests, AuthZReq{principal, verb, resources})
42
+ if a.err != nil {
43
+ return a.err
44
+ }
45
+ return nil
46
+ }
47
+
48
+ func (a *FakeAuthorizer) AuthorizeSilent(ctx context.Context, principal *models.Principal, verb string, resources ...string) error {
49
+ return a.Authorize(ctx, principal, verb, resources...)
50
+ }
51
+
52
+ func (a *FakeAuthorizer) FilterAuthorizedResources(ctx context.Context, principal *models.Principal, verb string, resources ...string) ([]string, error) {
53
+ if err := a.Authorize(ctx, principal, verb, resources...); err != nil {
54
+ return nil, err
55
+ }
56
+ return resources, nil
57
+ }
58
+
59
+ func (a *FakeAuthorizer) Calls() []AuthZReq {
60
+ return a.requests
61
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/authorizer.go ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package rbac
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+
18
+ "github.com/sirupsen/logrus"
19
+
20
+ "github.com/weaviate/weaviate/entities/models"
21
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
22
+ "github.com/weaviate/weaviate/usecases/auth/authorization/conv"
23
+ "github.com/weaviate/weaviate/usecases/auth/authorization/errors"
24
+ )
25
+
26
+ const AuditLogVersion = 2
27
+
28
+ func (m *Manager) authorize(ctx context.Context, principal *models.Principal, verb string, skipAudit bool, resources ...string) error {
29
+ if principal == nil {
30
+ return fmt.Errorf("rbac: %w", errors.NewUnauthenticated())
31
+ }
32
+
33
+ if len(resources) == 0 {
34
+ return fmt.Errorf("at least 1 resource is required")
35
+ }
36
+
37
+ logger := m.logger.WithFields(logrus.Fields{
38
+ "action": "authorize",
39
+ "user": principal.Username,
40
+ "component": authorization.ComponentName,
41
+ "request_action": verb,
42
+ "rbac_log_version": AuditLogVersion,
43
+ })
44
+ if !m.rbacConf.IpInAuditDisabled {
45
+ sourceIp := ctx.Value("sourceIp")
46
+ logger = logger.WithField("source_ip", sourceIp)
47
+ }
48
+
49
+ if len(principal.Groups) > 0 {
50
+ logger = logger.WithField("groups", principal.Groups)
51
+ }
52
+
53
+ // Create a map to aggregate resources and their counts while preserving order
54
+ resourceCounts := make(map[string]int)
55
+ var uniqueResources []string
56
+ for _, resource := range resources {
57
+ if _, exists := resourceCounts[resource]; !exists {
58
+ uniqueResources = append(uniqueResources, resource)
59
+ }
60
+ resourceCounts[resource]++
61
+ }
62
+ permResults := make([]logrus.Fields, 0, len(uniqueResources))
63
+
64
+ for _, resource := range uniqueResources {
65
+ allowed, err := m.checkPermissions(principal, resource, verb)
66
+ if err != nil {
67
+ logger.WithFields(logrus.Fields{
68
+ "resource": resource,
69
+ }).WithError(err).Error("failed to enforce policy")
70
+ return err
71
+ }
72
+
73
+ perm, err := conv.PathToPermission(verb, resource)
74
+ if err != nil {
75
+ return fmt.Errorf("rbac: %w", err)
76
+ }
77
+
78
+ if allowed {
79
+ permResults = append(permResults, logrus.Fields{
80
+ "resource": prettyPermissionsResources(perm),
81
+ "results": prettyStatus(allowed),
82
+ })
83
+ }
84
+
85
+ if !allowed {
86
+ if !skipAudit {
87
+ logger.WithField("permissions", permResults).Error("authorization denied")
88
+ }
89
+ return fmt.Errorf("rbac: %w", errors.NewForbidden(principal, prettyPermissionsActions(perm), prettyPermissionsResources(perm)))
90
+ }
91
+ }
92
+
93
+ // Log all results at once if audit is enabled
94
+ if !skipAudit {
95
+ logger.WithField("permissions", permResults).Info()
96
+ }
97
+
98
+ return nil
99
+ }
100
+
101
+ // Authorize verify if the user has access to a resource to do specific action
102
+ func (m *Manager) Authorize(ctx context.Context, principal *models.Principal, verb string, resources ...string) error {
103
+ return m.authorize(ctx, principal, verb, false, resources...)
104
+ }
105
+
106
+ // AuthorizeSilent verify if the user has access to a resource to do specific action without audit logs
107
+ // to be used internally
108
+ func (m *Manager) AuthorizeSilent(ctx context.Context, principal *models.Principal, verb string, resources ...string) error {
109
+ return m.authorize(ctx, principal, verb, true, resources...)
110
+ }
111
+
112
+ // FilterAuthorizedResources authorize the passed resources with best effort approach, it will return
113
+ // list of allowed resources, if none, it will return an empty slice
114
+ func (m *Manager) FilterAuthorizedResources(ctx context.Context, principal *models.Principal, verb string, resources ...string) ([]string, error) {
115
+ if principal == nil {
116
+ return nil, errors.NewUnauthenticated()
117
+ }
118
+
119
+ if len(resources) == 0 {
120
+ return nil, fmt.Errorf("at least 1 resource is required")
121
+ }
122
+
123
+ logger := m.logger.WithFields(logrus.Fields{
124
+ "action": "authorize",
125
+ "user": principal.Username,
126
+ "component": authorization.ComponentName,
127
+ "request_action": verb,
128
+ })
129
+
130
+ if len(principal.Groups) > 0 {
131
+ logger = logger.WithField("groups", principal.Groups)
132
+ }
133
+
134
+ allowedResources := make([]string, 0, len(resources))
135
+
136
+ // Create a map to aggregate resources and their counts while preserving order
137
+ resourceCounts := make(map[string]int)
138
+ var uniqueResources []string
139
+ for _, resource := range resources {
140
+ if _, exists := resourceCounts[resource]; !exists {
141
+ uniqueResources = append(uniqueResources, resource)
142
+ }
143
+ resourceCounts[resource]++
144
+ }
145
+
146
+ permResults := make([]logrus.Fields, 0, len(uniqueResources))
147
+
148
+ for _, resource := range uniqueResources {
149
+ allowed, err := m.checkPermissions(principal, resource, verb)
150
+ if err != nil {
151
+ logger.WithError(err).WithField("resource", resource).Error("failed to enforce policy")
152
+ return nil, err
153
+ }
154
+
155
+ if allowed {
156
+ perm, err := conv.PathToPermission(verb, resource)
157
+ if err != nil {
158
+ return nil, err
159
+ }
160
+
161
+ permResults = append(permResults, logrus.Fields{
162
+ "resource": prettyPermissionsResources(perm),
163
+ "results": prettyStatus(allowed),
164
+ })
165
+ allowedResources = append(allowedResources, resource)
166
+ }
167
+ }
168
+
169
+ logger.WithField("permissions", permResults).Info()
170
+ return allowedResources, nil
171
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/authorizer_test.go ADDED
@@ -0,0 +1,640 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package rbac
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "os"
18
+ "path/filepath"
19
+ "testing"
20
+
21
+ "github.com/weaviate/weaviate/usecases/auth/authentication"
22
+
23
+ "github.com/sirupsen/logrus"
24
+ "github.com/sirupsen/logrus/hooks/test"
25
+ "github.com/stretchr/testify/assert"
26
+ "github.com/stretchr/testify/require"
27
+
28
+ "github.com/weaviate/weaviate/entities/models"
29
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
30
+ "github.com/weaviate/weaviate/usecases/auth/authorization/conv"
31
+ authzErrors "github.com/weaviate/weaviate/usecases/auth/authorization/errors"
32
+ "github.com/weaviate/weaviate/usecases/auth/authorization/rbac/rbacconf"
33
+ "github.com/weaviate/weaviate/usecases/config"
34
+ )
35
+
36
+ func TestAuthorize(t *testing.T) {
37
+ tests := []struct {
38
+ name string
39
+ principal *models.Principal
40
+ verb string
41
+ resources []string
42
+ skipAudit bool
43
+ setupPolicies func(*Manager) error
44
+ wantErr bool
45
+ errContains string
46
+ }{
47
+ {
48
+ name: "nil principal returns unauthenticated error",
49
+ principal: nil,
50
+ verb: authorization.READ,
51
+ resources: authorization.CollectionsMetadata("Test"),
52
+ wantErr: true,
53
+ },
54
+ {
55
+ name: "empty resources returns error",
56
+ principal: &models.Principal{
57
+ Username: "test-user",
58
+ Groups: []string{},
59
+ },
60
+ verb: authorization.READ,
61
+ resources: []string{},
62
+ wantErr: true,
63
+ errContains: "at least 1 resource is required",
64
+ },
65
+ {
66
+ name: "authorized user with correct permissions",
67
+ principal: &models.Principal{
68
+ Username: "admin-user",
69
+ Groups: []string{"admin-group"},
70
+ UserType: models.UserTypeInputDb,
71
+ },
72
+ verb: authorization.READ,
73
+ resources: authorization.CollectionsMetadata("Test1", "Test2"),
74
+ setupPolicies: func(m *Manager) error {
75
+ _, err := m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("admin"), "*", authorization.SchemaDomain, authorization.READ)
76
+ if err != nil {
77
+ return err
78
+ }
79
+ ok, err := m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("admin-user", authentication.AuthTypeDb),
80
+ conv.PrefixRoleName("admin"))
81
+ if err != nil {
82
+ return err
83
+ }
84
+ if !ok {
85
+ return fmt.Errorf("failed to add role for user")
86
+ }
87
+ return nil
88
+ },
89
+ },
90
+ {
91
+ name: "unauthorized user returns forbidden error",
92
+ principal: &models.Principal{
93
+ Username: "regular-user",
94
+ Groups: []string{},
95
+ },
96
+ verb: authorization.UPDATE,
97
+ resources: authorization.CollectionsMetadata("Test1"),
98
+ wantErr: true,
99
+ errContains: "forbidden",
100
+ },
101
+ {
102
+ name: "partial authorization fails completely",
103
+ principal: &models.Principal{
104
+ Username: "partial-user",
105
+ Groups: []string{},
106
+ UserType: models.UserTypeInputDb,
107
+ },
108
+ verb: authorization.READ,
109
+ resources: authorization.CollectionsMetadata("Test1", "Test2"),
110
+ setupPolicies: func(m *Manager) error {
111
+ _, err := m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("partial"), authorization.CollectionsMetadata("Test1")[0], authorization.READ, authorization.SchemaDomain)
112
+ if err != nil {
113
+ return err
114
+ }
115
+ ok, err := m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("partial-user", authentication.AuthTypeDb),
116
+ conv.PrefixRoleName("partial"))
117
+ if err != nil {
118
+ return err
119
+ }
120
+ if !ok {
121
+ return fmt.Errorf("failed to add role for user")
122
+ }
123
+ return nil
124
+ },
125
+ wantErr: true,
126
+ errContains: "Test2",
127
+ },
128
+ {
129
+ name: "group-based authorization",
130
+ principal: &models.Principal{
131
+ Username: "group-user",
132
+ Groups: []string{"authorized-group"},
133
+ },
134
+ verb: authorization.READ,
135
+ resources: authorization.CollectionsMetadata("Test1"),
136
+ setupPolicies: func(m *Manager) error {
137
+ _, err := m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("group-role"), authorization.CollectionsMetadata("Test1")[0], authorization.READ, authorization.SchemaDomain)
138
+ if err != nil {
139
+ return err
140
+ }
141
+ ok, err := m.casbin.AddRoleForUser(conv.PrefixGroupName("authorized-group"),
142
+ conv.PrefixRoleName("group-role"))
143
+ if err != nil {
144
+ return err
145
+ }
146
+ if !ok {
147
+ return fmt.Errorf("failed to add role for group")
148
+ }
149
+ return nil
150
+ },
151
+ },
152
+ {
153
+ name: "audit logging can be skipped",
154
+ principal: &models.Principal{
155
+ Username: "audit-test-user",
156
+ Groups: []string{},
157
+ UserType: models.UserTypeInputDb,
158
+ },
159
+ verb: authorization.READ,
160
+ resources: authorization.CollectionsMetadata("Test1"),
161
+ skipAudit: true,
162
+ setupPolicies: func(m *Manager) error {
163
+ _, err := m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("audit-role"), authorization.CollectionsMetadata("Test1")[0], authorization.READ, authorization.SchemaDomain)
164
+ if err != nil {
165
+ return err
166
+ }
167
+ ok, err := m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("audit-test-user", authentication.AuthTypeDb),
168
+ conv.PrefixRoleName("audit-role"))
169
+ if err != nil {
170
+ return err
171
+ }
172
+ if !ok {
173
+ return fmt.Errorf("failed to add role for user")
174
+ }
175
+ return nil
176
+ },
177
+ },
178
+ }
179
+
180
+ for _, tt := range tests {
181
+ t.Run(tt.name, func(t *testing.T) {
182
+ // Setup logger with hook for testing
183
+ logger, hook := test.NewNullLogger()
184
+ m, err := setupTestManager(t, logger)
185
+ require.NoError(t, err)
186
+
187
+ // Setup policies if needed
188
+ if tt.setupPolicies != nil {
189
+ err := tt.setupPolicies(m)
190
+ require.NoError(t, err)
191
+ }
192
+
193
+ // Execute
194
+ err = m.authorize(context.Background(), tt.principal, tt.verb, tt.skipAudit, tt.resources...)
195
+
196
+ // Assert error conditions
197
+ if tt.wantErr {
198
+ require.Error(t, err)
199
+ if tt.errContains != "" {
200
+ assert.Contains(t, err.Error(), tt.errContains)
201
+ }
202
+ return
203
+ }
204
+
205
+ require.NoError(t, err)
206
+
207
+ // Verify logging behavior
208
+ if !tt.skipAudit {
209
+ require.NotEmpty(t, hook.AllEntries())
210
+ lastEntry := hook.LastEntry()
211
+ require.NotNil(t, lastEntry)
212
+
213
+ // Verify log fields
214
+ assert.Equal(t, "authorize", lastEntry.Data["action"])
215
+ assert.Equal(t, tt.principal.Username, lastEntry.Data["user"])
216
+ assert.Equal(t, authorization.ComponentName, lastEntry.Data["component"])
217
+ assert.Equal(t, tt.verb, lastEntry.Data["request_action"])
218
+
219
+ if len(tt.principal.Groups) > 0 {
220
+ assert.Contains(t, lastEntry.Data, "groups")
221
+ assert.ElementsMatch(t, tt.principal.Groups, lastEntry.Data["groups"])
222
+ }
223
+ } else {
224
+ // Verify no info logs when audit is skipped
225
+ for _, entry := range hook.AllEntries() {
226
+ assert.NotEqual(t, logrus.InfoLevel, entry.Level)
227
+ }
228
+ }
229
+ })
230
+ }
231
+ }
232
+
233
+ func TestFilterAuthorizedResources(t *testing.T) {
234
+ tests := []struct {
235
+ name string
236
+ principal *models.Principal
237
+ verb string
238
+ resources []string
239
+ setupPolicies func(*Manager) error
240
+ wantResources []string
241
+ wantErr bool
242
+ errType error
243
+ }{
244
+ {
245
+ name: "nil principal returns unauthenticated error",
246
+ principal: nil,
247
+ verb: authorization.READ,
248
+ resources: authorization.CollectionsMetadata("Test"),
249
+ wantErr: true,
250
+ errType: authzErrors.Unauthenticated{},
251
+ },
252
+ {
253
+ name: "wildcard permission allows all resources",
254
+ principal: &models.Principal{
255
+ Username: "admin-user",
256
+ UserType: models.UserTypeInputDb,
257
+ },
258
+ verb: authorization.READ,
259
+ resources: authorization.CollectionsMetadata("Test1", "Test2"),
260
+ setupPolicies: func(m *Manager) error {
261
+ _, err := m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("admin"),
262
+ "*", authorization.READ, authorization.SchemaDomain)
263
+ if err != nil {
264
+ return err
265
+ }
266
+ ok, err := m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("admin-user", authentication.AuthTypeDb),
267
+ conv.PrefixRoleName("admin"))
268
+ if err != nil {
269
+ return err
270
+ }
271
+ if !ok {
272
+ return fmt.Errorf("failed to add role for user")
273
+ }
274
+ return nil
275
+ },
276
+ wantResources: authorization.CollectionsMetadata("Test1", "Test2"),
277
+ },
278
+ {
279
+ name: "specific permission allows only matching resource",
280
+ principal: &models.Principal{
281
+ Username: "limited-user",
282
+ UserType: models.UserTypeInputDb,
283
+ },
284
+ verb: authorization.READ,
285
+ resources: authorization.CollectionsMetadata("Test1", "Test2"),
286
+ setupPolicies: func(m *Manager) error {
287
+ _, err := m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("limited"),
288
+ authorization.CollectionsMetadata("Test1")[0], authorization.READ, authorization.SchemaDomain)
289
+ if err != nil {
290
+ return err
291
+ }
292
+ ok, err := m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("limited-user", authentication.AuthTypeDb),
293
+ conv.PrefixRoleName("limited"))
294
+ if err != nil {
295
+ return err
296
+ }
297
+ if !ok {
298
+ return fmt.Errorf("failed to add role for user")
299
+ }
300
+ return nil
301
+ },
302
+ wantResources: authorization.CollectionsMetadata("Test1"),
303
+ },
304
+ {
305
+ name: "no permissions returns empty list",
306
+ principal: &models.Principal{
307
+ Username: "no-perm-user",
308
+ },
309
+ verb: authorization.READ,
310
+ resources: authorization.CollectionsMetadata("Test1", "Test2"),
311
+ wantResources: []string{},
312
+ },
313
+ {
314
+ name: "wildcard collection permission allows all collections",
315
+ principal: &models.Principal{
316
+ Username: "collections-admin",
317
+ UserType: models.UserTypeInputDb,
318
+ },
319
+ verb: authorization.READ,
320
+ resources: authorization.CollectionsMetadata("Test1", "Test2"),
321
+ setupPolicies: func(m *Manager) error {
322
+ _, err := m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("collections-admin"),
323
+ authorization.CollectionsMetadata()[0], authorization.READ, authorization.SchemaDomain)
324
+ if err != nil {
325
+ return err
326
+ }
327
+ ok, err := m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("collections-admin", authentication.AuthTypeDb),
328
+ conv.PrefixRoleName("collections-admin"))
329
+ if err != nil {
330
+ return err
331
+ }
332
+ if !ok {
333
+ return fmt.Errorf("failed to add role for user")
334
+ }
335
+ return nil
336
+ },
337
+ wantResources: authorization.CollectionsMetadata("Test1", "Test2"),
338
+ },
339
+ {
340
+ name: "empty resources list returns empty result",
341
+ principal: &models.Principal{
342
+ Username: "test-user",
343
+ },
344
+ verb: authorization.READ,
345
+ resources: []string{},
346
+ wantResources: []string{},
347
+ wantErr: true,
348
+ errType: fmt.Errorf("at least 1 resource is required"),
349
+ },
350
+ {
351
+ name: "user with multiple roles",
352
+ principal: &models.Principal{
353
+ Username: "multi-role-user",
354
+ UserType: models.UserTypeInputDb,
355
+ },
356
+ verb: authorization.READ,
357
+ resources: authorization.CollectionsMetadata("Test1", "Test2", "Test3"),
358
+ setupPolicies: func(m *Manager) error {
359
+ if _, err := m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("role1"), authorization.CollectionsMetadata("Test1")[0], authorization.READ, authorization.SchemaDomain); err != nil {
360
+ return err
361
+ }
362
+ if _, err := m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("role2"), authorization.CollectionsMetadata("Test2")[0], authorization.READ, authorization.SchemaDomain); err != nil {
363
+ return err
364
+ }
365
+ if ok, err := m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("multi-role-user", authentication.AuthTypeDb), conv.PrefixRoleName("role1")); err != nil {
366
+ return err
367
+ } else if !ok {
368
+ return fmt.Errorf("failed to add role for user")
369
+ }
370
+ if ok, err := m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("multi-role-user", authentication.AuthTypeDb), conv.PrefixRoleName("role2")); err != nil {
371
+ return err
372
+ } else if !ok {
373
+ return fmt.Errorf("failed to add role for user")
374
+ }
375
+ return nil
376
+ },
377
+ wantResources: authorization.CollectionsMetadata("Test1", "Test2"),
378
+ },
379
+ }
380
+
381
+ for _, tt := range tests {
382
+ t.Run(tt.name, func(t *testing.T) {
383
+ // Setup
384
+ logger, _ := test.NewNullLogger()
385
+ m, err := setupTestManager(t, logger)
386
+ require.NoError(t, err)
387
+
388
+ // Setup policies if needed
389
+ if tt.setupPolicies != nil {
390
+ err := tt.setupPolicies(m)
391
+ require.NoError(t, err)
392
+ }
393
+
394
+ // Execute
395
+ got, err := m.FilterAuthorizedResources(context.Background(), tt.principal, tt.verb, tt.resources...)
396
+
397
+ // Assert
398
+ if tt.wantErr {
399
+ require.Error(t, err)
400
+ if tt.errType != nil {
401
+ assert.Contains(t, err.Error(), tt.errType.Error())
402
+ }
403
+ return
404
+ }
405
+
406
+ require.NoError(t, err)
407
+ assert.ElementsMatch(t, tt.wantResources, got)
408
+ })
409
+ }
410
+ }
411
+
412
+ func TestFilterAuthorizedResourcesLogging(t *testing.T) {
413
+ logger, hook := test.NewNullLogger()
414
+ m, err := setupTestManager(t, logger)
415
+ require.NoError(t, err)
416
+
417
+ principal := &models.Principal{
418
+ Username: "test-user",
419
+ Groups: []string{"group1"},
420
+ UserType: models.UserTypeInputDb,
421
+ }
422
+
423
+ testResources := authorization.CollectionsMetadata("Test1", "Test2")
424
+
425
+ // Setup a policy
426
+ _, err = m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("admin"), "*", "*", authorization.RolesDomain)
427
+ require.NoError(t, err)
428
+ _, err = m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("test-user", authentication.AuthTypeDb), conv.PrefixRoleName("admin"))
429
+ require.NoError(t, err)
430
+
431
+ // Call the function
432
+ allowedResources, err := m.FilterAuthorizedResources(context.Background(), principal, authorization.READ, testResources...)
433
+ require.NoError(t, err)
434
+
435
+ // Verify logging
436
+ require.NotEmpty(t, hook.AllEntries())
437
+ entry := hook.LastEntry()
438
+ require.NotNil(t, entry)
439
+
440
+ // Check the permissions array exists and has the correct structure
441
+ permissions, ok := entry.Data["permissions"].([]logrus.Fields)
442
+ require.True(t, ok, "permissions should be []logrus.Fields")
443
+ require.NotEmpty(t, permissions, "permissions should not be empty")
444
+
445
+ // Check that we have entries for both resources
446
+ require.Len(t, permissions, 2, "Should have permissions entries for both resources")
447
+
448
+ // Check the first permission entry
449
+ firstPerm := permissions[0]
450
+ assert.Contains(t, firstPerm, "resource", "First permission entry should contain resource field")
451
+ assert.Contains(t, firstPerm, "results", "First permission entry should contain results field")
452
+ assert.Equal(t, "[Domain: collections, Collection: Test1]", firstPerm["resource"])
453
+ assert.Equal(t, "success", firstPerm["results"])
454
+
455
+ // Check the second permission entry
456
+ secondPerm := permissions[1]
457
+ assert.Contains(t, secondPerm, "resource", "Second permission entry should contain resource field")
458
+ assert.Contains(t, secondPerm, "results", "Second permission entry should contain results field")
459
+ assert.Equal(t, "[Domain: collections, Collection: Test2]", secondPerm["resource"])
460
+ assert.Equal(t, "success", secondPerm["results"])
461
+
462
+ // Check other required fields
463
+ assert.Equal(t, "authorize", entry.Data["action"])
464
+ assert.Equal(t, principal.Username, entry.Data["user"])
465
+ assert.Equal(t, principal.Groups, entry.Data["groups"])
466
+ assert.Equal(t, authorization.ComponentName, entry.Data["component"])
467
+ assert.Equal(t, authorization.READ, entry.Data["request_action"])
468
+
469
+ // Verify the final result matches the logged permissions
470
+ assert.ElementsMatch(t, testResources, allowedResources,
471
+ "Allowed resources should match input resources")
472
+ }
473
+
474
+ func TestAuthorizeResourceAggregation(t *testing.T) {
475
+ // Setup proper logger with hook for testing
476
+ logger := logrus.New()
477
+ logger.SetLevel(logrus.InfoLevel)
478
+
479
+ // Create a hook to capture log entries
480
+ hook := &test.Hook{}
481
+ logger.AddHook(hook)
482
+
483
+ m, err := setupTestManager(t, logger)
484
+ require.NoError(t, err)
485
+
486
+ // Setup admin policy
487
+ _, err = m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("admin"), "*", authorization.READ, authorization.DataDomain)
488
+ require.NoError(t, err)
489
+ ok, err := m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("admin-user", authentication.AuthTypeDb),
490
+ conv.PrefixRoleName("admin"))
491
+ require.NoError(t, err)
492
+ require.True(t, ok)
493
+
494
+ principal := &models.Principal{
495
+ Username: "admin-user",
496
+ Groups: []string{"admin-group"},
497
+ UserType: models.UserTypeInputDb,
498
+ }
499
+
500
+ // Test with 1000 duplicate resources (simulating the original issue)
501
+ resources := make([]string, 1000)
502
+ for i := 0; i < 1000; i++ {
503
+ resources[i] = "data/collections/ContactRecommendations/shards/*/objects/*"
504
+ }
505
+
506
+ // Execute authorization
507
+ err = m.authorize(context.Background(), principal, authorization.READ, false, resources...)
508
+ require.NoError(t, err)
509
+
510
+ // Verify logging behavior
511
+ require.NotEmpty(t, hook.AllEntries())
512
+ lastEntry := hook.LastEntry()
513
+ require.NotNil(t, lastEntry)
514
+
515
+ // Verify log fields
516
+ assert.Equal(t, "authorize", lastEntry.Data["action"])
517
+ assert.Equal(t, "admin-user", lastEntry.Data["user"])
518
+ assert.Equal(t, authorization.ComponentName, lastEntry.Data["component"])
519
+ assert.Equal(t, authorization.READ, lastEntry.Data["request_action"])
520
+
521
+ // Verify permissions field exists
522
+ permissions, ok := lastEntry.Data["permissions"].([]logrus.Fields)
523
+ require.True(t, ok, "permissions field should be present")
524
+
525
+ // Verify aggregation - should only have 1 entry instead of 1000
526
+ assert.Len(t, permissions, 1, "should aggregate 1000 duplicate resources into 1 entry")
527
+
528
+ // Verify the single entry has the correct resource and count
529
+ require.Len(t, permissions, 1)
530
+ perm := permissions[0]
531
+
532
+ resource, ok := perm["resource"].(string)
533
+ require.True(t, ok, "resource should be a string")
534
+ assert.Equal(t, "[Domain: data, Collection: ContactRecommendations, Tenant: *, Object: *]", resource)
535
+
536
+ // Verify aggregation by checking that we have fewer log entries than resources
537
+ // This proves that 1000 identical resources were aggregated into 1 log entry
538
+ assert.Len(t, permissions, 1, "should aggregate 1000 duplicate resources into 1 log entry")
539
+
540
+ results, ok := perm["results"].(string)
541
+ require.True(t, ok, "results should be a string")
542
+ assert.Equal(t, "success", results)
543
+ }
544
+
545
+ func TestFilterAuthorizedResourcesAggregation(t *testing.T) {
546
+ // Setup proper logger with hook for testing
547
+ logger := logrus.New()
548
+ logger.SetLevel(logrus.InfoLevel)
549
+
550
+ // Create a hook to capture log entries
551
+ hook := &test.Hook{}
552
+ logger.AddHook(hook)
553
+
554
+ m, err := setupTestManager(t, logger)
555
+ require.NoError(t, err)
556
+
557
+ // Setup admin policy
558
+ _, err = m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("admin"), "*", authorization.READ, authorization.DataDomain)
559
+ require.NoError(t, err)
560
+ ok, err := m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("admin-user", authentication.AuthTypeDb),
561
+ conv.PrefixRoleName("admin"))
562
+ require.NoError(t, err)
563
+ require.True(t, ok)
564
+
565
+ principal := &models.Principal{
566
+ Username: "admin-user",
567
+ Groups: []string{"admin-group"},
568
+ UserType: models.UserTypeInputDb,
569
+ }
570
+
571
+ // Test with 1000 duplicate resources (simulating the original issue)
572
+ resources := make([]string, 1000)
573
+ for i := 0; i < 1000; i++ {
574
+ resources[i] = "data/collections/ContactRecommendations/shards/*/objects/*"
575
+ }
576
+
577
+ // Execute FilterAuthorizedResources
578
+ allowedResources, err := m.FilterAuthorizedResources(context.Background(), principal, authorization.READ, resources...)
579
+ require.NoError(t, err)
580
+
581
+ // Verify logging behavior
582
+ require.NotEmpty(t, hook.AllEntries())
583
+ lastEntry := hook.LastEntry()
584
+ require.NotNil(t, lastEntry)
585
+
586
+ // Verify log fields
587
+ assert.Equal(t, "authorize", lastEntry.Data["action"])
588
+ assert.Equal(t, "admin-user", lastEntry.Data["user"])
589
+ assert.Equal(t, authorization.ComponentName, lastEntry.Data["component"])
590
+ assert.Equal(t, authorization.READ, lastEntry.Data["request_action"])
591
+
592
+ // Verify permissions field exists
593
+ permissions, ok := lastEntry.Data["permissions"].([]logrus.Fields)
594
+ require.True(t, ok, "permissions field should be present")
595
+
596
+ // Verify aggregation - should only have 1 entry instead of 1000
597
+ assert.Len(t, permissions, 1, "should aggregate 1000 duplicate resources into 1 entry")
598
+
599
+ // Verify the single entry has the correct resource and count
600
+ require.Len(t, permissions, 1)
601
+ perm := permissions[0]
602
+
603
+ resource, ok := perm["resource"].(string)
604
+ require.True(t, ok, "resource should be a string")
605
+ assert.Equal(t, "[Domain: data, Collection: ContactRecommendations, Tenant: *, Object: *]", resource)
606
+
607
+ results, ok := perm["results"].(string)
608
+ require.True(t, ok, "results should be a string")
609
+ assert.Equal(t, "success", results)
610
+
611
+ // Verify that all 1000 resources are returned in allowedResources
612
+ assert.Len(t, allowedResources, 1, "should return 1 unique resource (duplicates are aggregated)")
613
+
614
+ // Verify the returned resource is correct
615
+ assert.Equal(t, "data/collections/ContactRecommendations/shards/*/objects/*", allowedResources[0], "returned resource should be the same as input")
616
+ }
617
+
618
+ func setupTestManager(t *testing.T, logger *logrus.Logger) (*Manager, error) {
619
+ tmpDir, err := os.MkdirTemp("", "rbac-test-*")
620
+ if err != nil {
621
+ return nil, err
622
+ }
623
+
624
+ t.Cleanup(func() {
625
+ os.RemoveAll(tmpDir)
626
+ })
627
+
628
+ rbacDir := filepath.Join(tmpDir, "rbac")
629
+ if err := os.MkdirAll(rbacDir, 0o755); err != nil {
630
+ return nil, err
631
+ }
632
+
633
+ policyPath := filepath.Join(rbacDir, "policy.csv")
634
+
635
+ conf := rbacconf.Config{
636
+ Enabled: true,
637
+ }
638
+
639
+ return New(policyPath, conf, config.Authentication{OIDC: config.OIDC{Enabled: true}, APIKey: config.StaticAPIKey{Enabled: true, Users: []string{"test-user"}}}, logger)
640
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/manager.go ADDED
@@ -0,0 +1,595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package rbac
13
+
14
+ import (
15
+ "bytes"
16
+ "encoding/json"
17
+ "errors"
18
+ "fmt"
19
+ "slices"
20
+ "strings"
21
+ "sync"
22
+
23
+ "github.com/weaviate/weaviate/usecases/auth/authentication"
24
+
25
+ "github.com/casbin/casbin/v2"
26
+ "github.com/sirupsen/logrus"
27
+
28
+ "github.com/weaviate/weaviate/entities/models"
29
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
30
+ "github.com/weaviate/weaviate/usecases/auth/authorization/conv"
31
+ "github.com/weaviate/weaviate/usecases/auth/authorization/rbac/rbacconf"
32
+ "github.com/weaviate/weaviate/usecases/config"
33
+ )
34
+
35
+ const (
36
+ SnapshotVersionV0 = iota
37
+ SnapshotVersionLatest
38
+ )
39
+
40
+ type Manager struct {
41
+ casbin *casbin.SyncedCachedEnforcer
42
+ logger logrus.FieldLogger
43
+ authNconf config.Authentication
44
+ rbacConf rbacconf.Config
45
+ backupLock sync.RWMutex
46
+ }
47
+
48
+ func New(rbacStoragePath string, rbacConf rbacconf.Config, authNconf config.Authentication, logger logrus.FieldLogger) (*Manager, error) {
49
+ csbin, err := Init(rbacConf, rbacStoragePath, authNconf)
50
+ if err != nil {
51
+ return nil, err
52
+ }
53
+
54
+ return &Manager{csbin, logger, authNconf, rbacConf, sync.RWMutex{}}, nil
55
+ }
56
+
57
+ // there is no different between UpdateRolesPermissions and CreateRolesPermissions, purely to satisfy an interface
58
+ func (m *Manager) UpdateRolesPermissions(roles map[string][]authorization.Policy) error {
59
+ m.backupLock.RLock()
60
+ defer m.backupLock.RUnlock()
61
+
62
+ return m.upsertRolesPermissions(roles)
63
+ }
64
+
65
+ func (m *Manager) CreateRolesPermissions(roles map[string][]authorization.Policy) error {
66
+ m.backupLock.RLock()
67
+ defer m.backupLock.RUnlock()
68
+
69
+ return m.upsertRolesPermissions(roles)
70
+ }
71
+
72
+ func (m *Manager) GetUsersOrGroupsWithRoles(isGroup bool, authType authentication.AuthType) ([]string, error) {
73
+ roles, err := m.casbin.GetAllSubjects()
74
+ if err != nil {
75
+ return nil, err
76
+ }
77
+ usersOrGroups := map[string]struct{}{}
78
+ for _, role := range roles {
79
+ users, err := m.casbin.GetUsersForRole(role)
80
+ if err != nil {
81
+ return nil, err
82
+ }
83
+ for _, userOrGroup := range users {
84
+ name, _ := conv.GetUserAndPrefix(userOrGroup)
85
+ if isGroup {
86
+ // groups are only supported for OIDC
87
+ if authType == authentication.AuthTypeOIDC && strings.HasPrefix(userOrGroup, conv.OIDC_GROUP_NAME_PREFIX) {
88
+ usersOrGroups[name] = struct{}{}
89
+ }
90
+ } else {
91
+ // groups are only supported for OIDC
92
+ if authType == authentication.AuthTypeOIDC && strings.HasPrefix(userOrGroup, string(authentication.AuthTypeOIDC)) {
93
+ usersOrGroups[name] = struct{}{}
94
+ }
95
+
96
+ if authType == authentication.AuthTypeDb && strings.HasPrefix(userOrGroup, string(authentication.AuthTypeDb)) {
97
+ usersOrGroups[name] = struct{}{}
98
+ }
99
+
100
+ }
101
+ }
102
+ }
103
+
104
+ usersOrGroupsList := make([]string, 0, len(usersOrGroups))
105
+ for user := range usersOrGroups {
106
+ usersOrGroupsList = append(usersOrGroupsList, user)
107
+ }
108
+
109
+ return usersOrGroupsList, nil
110
+ }
111
+
112
+ func (m *Manager) upsertRolesPermissions(roles map[string][]authorization.Policy) error {
113
+ for roleName, policies := range roles {
114
+ // assign role to internal user to make sure to catch empty roles
115
+ // e.g. : g, user:wv_internal_empty, role:roleName
116
+ if _, err := m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId(conv.InternalPlaceHolder, authentication.AuthTypeDb), conv.PrefixRoleName(roleName)); err != nil {
117
+ return fmt.Errorf("AddRoleForUser: %w", err)
118
+ }
119
+ for _, policy := range policies {
120
+ if _, err := m.casbin.AddNamedPolicy("p", conv.PrefixRoleName(roleName), policy.Resource, policy.Verb, policy.Domain); err != nil {
121
+ return fmt.Errorf("AddNamedPolicy: %w", err)
122
+ }
123
+ }
124
+ }
125
+ if err := m.casbin.SavePolicy(); err != nil {
126
+ return fmt.Errorf("SavePolicy: %w", err)
127
+ }
128
+ if err := m.casbin.InvalidateCache(); err != nil {
129
+ return fmt.Errorf("InvalidateCache: %w", err)
130
+ }
131
+ return nil
132
+ }
133
+
134
+ func (m *Manager) GetRoles(names ...string) (map[string][]authorization.Policy, error) {
135
+ m.backupLock.RLock()
136
+ defer m.backupLock.RUnlock()
137
+
138
+ var (
139
+ casbinStoragePolicies [][][]string
140
+ casbinStoragePoliciesMap = make(map[string]struct{})
141
+ )
142
+
143
+ if len(names) == 0 {
144
+ // get all roles
145
+ polices, err := m.casbin.GetNamedPolicy("p")
146
+ if err != nil {
147
+ return nil, fmt.Errorf("GetNamedPolicy: %w", err)
148
+ }
149
+ casbinStoragePolicies = append(casbinStoragePolicies, polices)
150
+
151
+ for _, p := range polices {
152
+ // e.g. policy line in casbin -> role:roleName resource verb domain, that's why p[0]
153
+ casbinStoragePoliciesMap[p[0]] = struct{}{}
154
+ }
155
+
156
+ polices, err = m.casbin.GetNamedGroupingPolicy("g")
157
+ if err != nil {
158
+ return nil, fmt.Errorf("GetNamedGroupingPolicy: %w", err)
159
+ }
160
+ casbinStoragePolicies = collectStaleRoles(polices, casbinStoragePoliciesMap, casbinStoragePolicies)
161
+ } else {
162
+ for _, name := range names {
163
+ polices, err := m.casbin.GetFilteredNamedPolicy("p", 0, conv.PrefixRoleName(name))
164
+ if err != nil {
165
+ return nil, fmt.Errorf("GetFilteredNamedPolicy: %w", err)
166
+ }
167
+ casbinStoragePolicies = append(casbinStoragePolicies, polices)
168
+
169
+ for _, p := range polices {
170
+ // e.g. policy line in casbin -> role:roleName resource verb domain, that's why p[0]
171
+ casbinStoragePoliciesMap[p[0]] = struct{}{}
172
+ }
173
+
174
+ polices, err = m.casbin.GetFilteredNamedGroupingPolicy("g", 1, conv.PrefixRoleName(name))
175
+ if err != nil {
176
+ return nil, fmt.Errorf("GetFilteredNamedGroupingPolicy: %w", err)
177
+ }
178
+ casbinStoragePolicies = collectStaleRoles(polices, casbinStoragePoliciesMap, casbinStoragePolicies)
179
+ }
180
+ }
181
+ policies, err := conv.CasbinPolicies(casbinStoragePolicies...)
182
+ if err != nil {
183
+ return nil, fmt.Errorf("CasbinPolicies: %w", err)
184
+ }
185
+ return policies, nil
186
+ }
187
+
188
+ func (m *Manager) RemovePermissions(roleName string, permissions []*authorization.Policy) error {
189
+ m.backupLock.RLock()
190
+ defer m.backupLock.RUnlock()
191
+
192
+ for _, permission := range permissions {
193
+ ok, err := m.casbin.RemoveNamedPolicy("p", conv.PrefixRoleName(roleName), permission.Resource, permission.Verb, permission.Domain)
194
+ if err != nil {
195
+ return fmt.Errorf("RemoveNamedPolicy: %w", err)
196
+ }
197
+ if !ok {
198
+ return nil // deletes are idempotent
199
+ }
200
+ }
201
+ if err := m.casbin.SavePolicy(); err != nil {
202
+ return fmt.Errorf("SavePolicy: %w", err)
203
+ }
204
+ if err := m.casbin.InvalidateCache(); err != nil {
205
+ return fmt.Errorf("InvalidateCache: %w", err)
206
+ }
207
+ return nil
208
+ }
209
+
210
+ func (m *Manager) HasPermission(roleName string, permission *authorization.Policy) (bool, error) {
211
+ m.backupLock.RLock()
212
+ defer m.backupLock.RUnlock()
213
+
214
+ policy, err := m.casbin.HasNamedPolicy("p", conv.PrefixRoleName(roleName), permission.Resource, permission.Verb, permission.Domain)
215
+ if err != nil {
216
+ return false, fmt.Errorf("HasNamedPolicy: %w", err)
217
+ }
218
+ return policy, nil
219
+ }
220
+
221
+ func (m *Manager) DeleteRoles(roles ...string) error {
222
+ m.backupLock.RLock()
223
+ defer m.backupLock.RUnlock()
224
+
225
+ for _, roleName := range roles {
226
+ // remove role
227
+ roleRemoved, err := m.casbin.RemoveFilteredNamedPolicy("p", 0, conv.PrefixRoleName(roleName))
228
+ if err != nil {
229
+ return fmt.Errorf("RemoveFilteredNamedPolicy: %w", err)
230
+ }
231
+ // remove role assignment
232
+ roleAssignmentsRemoved, err := m.casbin.RemoveFilteredGroupingPolicy(1, conv.PrefixRoleName(roleName))
233
+ if err != nil {
234
+ return fmt.Errorf("RemoveFilteredGroupingPolicy: %w", err)
235
+ }
236
+
237
+ if !roleRemoved && !roleAssignmentsRemoved {
238
+ return nil // deletes are idempotent
239
+ }
240
+ }
241
+ if err := m.casbin.SavePolicy(); err != nil {
242
+ return fmt.Errorf("SavePolicy: %w", err)
243
+ }
244
+ if err := m.casbin.InvalidateCache(); err != nil {
245
+ return fmt.Errorf("InvalidateCache: %w", err)
246
+ }
247
+ return nil
248
+ }
249
+
250
+ // AddRolesFroUser NOTE: user has to be prefixed by user:, group:, key: etc.
251
+ // see func PrefixUserName(user) it will prefix username and nop-op if already prefixed
252
+ func (m *Manager) AddRolesForUser(user string, roles []string) error {
253
+ m.backupLock.RLock()
254
+ defer m.backupLock.RUnlock()
255
+
256
+ if !conv.NameHasPrefix(user) {
257
+ return errors.New("user does not contain a prefix")
258
+ }
259
+
260
+ for _, role := range roles {
261
+ if _, err := m.casbin.AddRoleForUser(user, conv.PrefixRoleName(role)); err != nil {
262
+ return fmt.Errorf("AddRoleForUser: %w", err)
263
+ }
264
+ }
265
+ if err := m.casbin.SavePolicy(); err != nil {
266
+ return fmt.Errorf("SavePolicy: %w", err)
267
+ }
268
+ if err := m.casbin.InvalidateCache(); err != nil {
269
+ return fmt.Errorf("InvalidateCache: %w", err)
270
+ }
271
+ return nil
272
+ }
273
+
274
+ func (m *Manager) GetRolesForUserOrGroup(userName string, authType authentication.AuthType, isGroup bool) (map[string][]authorization.Policy, error) {
275
+ m.backupLock.RLock()
276
+ defer m.backupLock.RUnlock()
277
+
278
+ var rolesNames []string
279
+ var err error
280
+ if isGroup {
281
+ rolesNames, err = m.casbin.GetRolesForUser(conv.PrefixGroupName(userName))
282
+ if err != nil {
283
+ return nil, fmt.Errorf("GetRolesForUserOrGroup: %w", err)
284
+ }
285
+ } else {
286
+ rolesNames, err = m.casbin.GetRolesForUser(conv.UserNameWithTypeFromId(userName, authType))
287
+ if err != nil {
288
+ return nil, fmt.Errorf("GetRolesForUserOrGroup: %w", err)
289
+ }
290
+ }
291
+ if len(rolesNames) == 0 {
292
+ return map[string][]authorization.Policy{}, err
293
+ }
294
+ roles, err := m.GetRoles(rolesNames...)
295
+ if err != nil {
296
+ return nil, fmt.Errorf("GetRoles: %w", err)
297
+ }
298
+ return roles, err
299
+ }
300
+
301
+ func (m *Manager) GetUsersOrGroupForRole(roleName string, authType authentication.AuthType, isGroup bool) ([]string, error) {
302
+ m.backupLock.RLock()
303
+ defer m.backupLock.RUnlock()
304
+
305
+ pusers, err := m.casbin.GetUsersForRole(conv.PrefixRoleName(roleName))
306
+ if err != nil {
307
+ return nil, fmt.Errorf("GetUsersOrGroupForRole: %w", err)
308
+ }
309
+ users := make([]string, 0, len(pusers))
310
+ for idx := range pusers {
311
+ userOrGroup, prefix := conv.GetUserAndPrefix(pusers[idx])
312
+ if userOrGroup == conv.InternalPlaceHolder {
313
+ continue
314
+ }
315
+ if isGroup {
316
+ if authType == authentication.AuthTypeOIDC && strings.HasPrefix(conv.OIDC_GROUP_NAME_PREFIX, prefix) {
317
+ users = append(users, userOrGroup)
318
+ }
319
+ } else {
320
+ if prefix == string(authType) {
321
+ users = append(users, userOrGroup)
322
+ }
323
+ }
324
+ }
325
+ return users, nil
326
+ }
327
+
328
+ func (m *Manager) RevokeRolesForUser(userName string, roles ...string) error {
329
+ m.backupLock.RLock()
330
+ defer m.backupLock.RUnlock()
331
+
332
+ if !conv.NameHasPrefix(userName) {
333
+ return errors.New("user does not contain a prefix")
334
+ }
335
+
336
+ for _, roleName := range roles {
337
+ if _, err := m.casbin.DeleteRoleForUser(userName, conv.PrefixRoleName(roleName)); err != nil {
338
+ return fmt.Errorf("DeleteRoleForUser: %w", err)
339
+ }
340
+ }
341
+ if err := m.casbin.SavePolicy(); err != nil {
342
+ return fmt.Errorf("SavePolicy: %w", err)
343
+ }
344
+ if err := m.casbin.InvalidateCache(); err != nil {
345
+ return fmt.Errorf("InvalidateCache: %w", err)
346
+ }
347
+ return nil
348
+ }
349
+
350
+ // Snapshot is the RBAC state to be used for RAFT snapshots
351
+ type snapshot struct {
352
+ Policy [][]string `json:"roles_policies"`
353
+ GroupingPolicy [][]string `json:"grouping_policies"`
354
+ Version int `json:"version"`
355
+ }
356
+
357
+ func (m *Manager) Snapshot() ([]byte, error) {
358
+ // snapshot isn't always initialized, e.g. when RBAC is disabled
359
+ if m == nil {
360
+ return []byte{}, nil
361
+ }
362
+ if m.casbin == nil {
363
+ return nil, nil
364
+ }
365
+
366
+ policy, err := m.casbin.GetPolicy()
367
+ if err != nil {
368
+ return nil, err
369
+ }
370
+ groupingPolicy, err := m.casbin.GetGroupingPolicy()
371
+ if err != nil {
372
+ return nil, err
373
+ }
374
+
375
+ // Use a buffer to stream the JSON encoding
376
+ var buf bytes.Buffer
377
+ if err := json.NewEncoder(&buf).Encode(snapshot{Policy: policy, GroupingPolicy: groupingPolicy, Version: SnapshotVersionLatest}); err != nil {
378
+ return nil, err
379
+ }
380
+ return buf.Bytes(), nil
381
+ }
382
+
383
+ func (m *Manager) Restore(b []byte) error {
384
+ // don't overwrite with empty snapshot to avoid overwriting recovery from file
385
+ // with a non-existent RBAC snapshot when coming from old versions
386
+ if m == nil || len(b) == 0 {
387
+ return nil
388
+ }
389
+ if m.casbin == nil {
390
+ return nil
391
+ }
392
+
393
+ snapshot := snapshot{}
394
+ if err := json.Unmarshal(b, &snapshot); err != nil {
395
+ return fmt.Errorf("restore snapshot: decode json: %w", err)
396
+ }
397
+
398
+ // we need to clear the policies before adding the new ones
399
+ m.casbin.ClearPolicy()
400
+
401
+ _, err := m.casbin.AddPolicies(snapshot.Policy)
402
+ if err != nil {
403
+ return fmt.Errorf("add policies: %w", err)
404
+ }
405
+
406
+ _, err = m.casbin.AddGroupingPolicies(snapshot.GroupingPolicy)
407
+ if err != nil {
408
+ return fmt.Errorf("add grouping policies: %w", err)
409
+ }
410
+
411
+ if snapshot.Version == SnapshotVersionV0 {
412
+ if err := upgradePoliciesFrom129(m.casbin, true); err != nil {
413
+ return fmt.Errorf("upgrade policies: %w", err)
414
+ }
415
+
416
+ if err := upgradeGroupingsFrom129(m.casbin, m.authNconf); err != nil {
417
+ return fmt.Errorf("upgrade groupings: %w", err)
418
+ }
419
+ }
420
+
421
+ // environment config needs to be applied again in case there were changes since the last snapshot
422
+ if err := applyPredefinedRoles(m.casbin, m.rbacConf, m.authNconf); err != nil {
423
+ return fmt.Errorf("apply env config: %w", err)
424
+ }
425
+
426
+ // Load the policies to ensure they are in memory
427
+ if err := m.casbin.LoadPolicy(); err != nil {
428
+ return fmt.Errorf("load policies: %w", err)
429
+ }
430
+
431
+ return nil
432
+ }
433
+
434
+ // BatchEnforcers is not needed after some digging they just loop over requests,
435
+ // w.r.t.
436
+ // source code https://github.com/casbin/casbin/blob/master/enforcer.go#L872
437
+ // issue https://github.com/casbin/casbin/issues/710
438
+ func (m *Manager) checkPermissions(principal *models.Principal, resource, verb string) (bool, error) {
439
+ // first check group permissions
440
+ for _, group := range principal.Groups {
441
+ allowed, err := m.casbin.Enforce(conv.PrefixGroupName(group), resource, verb)
442
+ if err != nil {
443
+ return false, err
444
+ }
445
+ if allowed {
446
+ return true, nil
447
+ }
448
+ }
449
+
450
+ // If no group permissions, check user permissions
451
+ return m.casbin.Enforce(conv.UserNameWithTypeFromPrincipal(principal), resource, verb)
452
+ }
453
+
454
+ func prettyPermissionsActions(perm *models.Permission) string {
455
+ if perm == nil || perm.Action == nil {
456
+ return ""
457
+ }
458
+ return *perm.Action
459
+ }
460
+
461
+ func prettyPermissionsResources(perm *models.Permission) string {
462
+ res := ""
463
+ if perm == nil {
464
+ return ""
465
+ }
466
+
467
+ if perm.Backups != nil {
468
+ s := fmt.Sprintf("Domain: %s,", authorization.BackupsDomain)
469
+ if perm.Backups.Collection != nil && *perm.Backups.Collection != "" {
470
+ s += fmt.Sprintf("Collection: %s", *perm.Backups.Collection)
471
+ }
472
+ s = strings.TrimSuffix(s, ",")
473
+ res += fmt.Sprintf("[%s]", s)
474
+ }
475
+
476
+ if perm.Data != nil {
477
+ s := fmt.Sprintf("Domain: %s,", authorization.DataDomain)
478
+ if perm.Data.Collection != nil && *perm.Data.Collection != "" {
479
+ s += fmt.Sprintf(" Collection: %s,", *perm.Data.Collection)
480
+ }
481
+ if perm.Data.Tenant != nil && *perm.Data.Tenant != "" {
482
+ s += fmt.Sprintf(" Tenant: %s,", *perm.Data.Tenant)
483
+ }
484
+ if perm.Data.Object != nil && *perm.Data.Object != "" {
485
+ s += fmt.Sprintf(" Object: %s", *perm.Data.Object)
486
+ }
487
+ s = strings.TrimSuffix(s, ",")
488
+ res += fmt.Sprintf("[%s]", s)
489
+ }
490
+
491
+ if perm.Nodes != nil {
492
+ s := fmt.Sprintf("Domain: %s,", authorization.NodesDomain)
493
+
494
+ if perm.Nodes.Verbosity != nil && *perm.Nodes.Verbosity != "" {
495
+ s += fmt.Sprintf(" Verbosity: %s,", *perm.Nodes.Verbosity)
496
+ }
497
+ if perm.Nodes.Collection != nil && *perm.Nodes.Collection != "" {
498
+ s += fmt.Sprintf(" Collection: %s", *perm.Nodes.Collection)
499
+ }
500
+ s = strings.TrimSuffix(s, ",")
501
+ res += fmt.Sprintf("[%s]", s)
502
+ }
503
+
504
+ if perm.Roles != nil {
505
+ s := fmt.Sprintf("Domain: %s,", authorization.RolesDomain)
506
+ if perm.Roles.Role != nil && *perm.Roles.Role != "" {
507
+ s += fmt.Sprintf(" Role: %s,", *perm.Roles.Role)
508
+ }
509
+ s = strings.TrimSuffix(s, ",")
510
+ res += fmt.Sprintf("[%s]", s)
511
+ }
512
+
513
+ if perm.Collections != nil {
514
+ s := fmt.Sprintf("Domain: %s,", authorization.CollectionsDomain)
515
+
516
+ if perm.Collections.Collection != nil && *perm.Collections.Collection != "" {
517
+ s += fmt.Sprintf(" Collection: %s,", *perm.Collections.Collection)
518
+ }
519
+ s = strings.TrimSuffix(s, ",")
520
+ res += fmt.Sprintf("[%s]", s)
521
+ }
522
+
523
+ if perm.Tenants != nil {
524
+ s := fmt.Sprintf("Domain: %s,", authorization.TenantsDomain)
525
+
526
+ if perm.Tenants.Tenant != nil && *perm.Tenants.Tenant != "" {
527
+ s += fmt.Sprintf(" Collection: %s,", *perm.Tenants.Collection)
528
+ s += fmt.Sprintf(" Tenant: %s", *perm.Tenants.Tenant)
529
+ }
530
+ s = strings.TrimSuffix(s, ",")
531
+ res += fmt.Sprintf("[%s]", s)
532
+ }
533
+
534
+ if perm.Users != nil {
535
+ s := fmt.Sprintf("Domain: %s,", authorization.UsersDomain)
536
+
537
+ if perm.Users.Users != nil {
538
+ s += fmt.Sprintf(" User: %s,", *perm.Users.Users)
539
+ }
540
+ s = strings.TrimSuffix(s, ",")
541
+ res += fmt.Sprintf("[%s]", s)
542
+ }
543
+
544
+ if perm.Replicate != nil {
545
+ s := fmt.Sprintf("Domain: %s,", authorization.ReplicateDomain)
546
+
547
+ if perm.Replicate.Collection != nil && *perm.Replicate.Collection != "" {
548
+ s += fmt.Sprintf(" Collection: %s,", *perm.Replicate.Collection)
549
+ }
550
+ if perm.Replicate.Shard != nil && *perm.Replicate.Shard != "" {
551
+ s += fmt.Sprintf(" Shard: %s,", *perm.Replicate.Shard)
552
+ }
553
+ s = strings.TrimSuffix(s, ",")
554
+ res += fmt.Sprintf("[%s]", s)
555
+ }
556
+
557
+ if perm.Aliases != nil {
558
+ s := fmt.Sprintf("Domain: %s,", authorization.AliasesDomain)
559
+
560
+ if perm.Aliases.Collection != nil && *perm.Aliases.Collection != "" {
561
+ s += fmt.Sprintf(" Collection: %s,", *perm.Aliases.Collection)
562
+ }
563
+ if perm.Aliases.Alias != nil && *perm.Aliases.Alias != "" {
564
+ s += fmt.Sprintf(" Alias: %s,", *perm.Aliases.Alias)
565
+ }
566
+ s = strings.TrimSuffix(s, ",")
567
+ res += fmt.Sprintf("[%s]", s)
568
+ }
569
+
570
+ return res
571
+ }
572
+
573
+ func prettyStatus(value bool) string {
574
+ if value {
575
+ return "success"
576
+ }
577
+ return "failed"
578
+ }
579
+
580
+ func collectStaleRoles(polices [][]string, casbinStoragePoliciesMap map[string]struct{}, casbinStoragePolicies [][][]string) [][][]string {
581
+ for _, p := range polices {
582
+ // ignore builtin roles
583
+ if slices.Contains(authorization.BuiltInRoles, conv.TrimRoleNamePrefix(p[1])) {
584
+ continue
585
+ }
586
+ // collect stale or empty roles
587
+ if _, ok := casbinStoragePoliciesMap[p[1]]; !ok {
588
+ // e.g. policy line in casbin -> g, user:wv_internal_empty, role:roleName, that's why p[1]
589
+ casbinStoragePolicies = append(casbinStoragePolicies, [][]string{{
590
+ p[1], conv.InternalPlaceHolder, conv.InternalPlaceHolder, "*",
591
+ }})
592
+ }
593
+ }
594
+ return casbinStoragePolicies
595
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/manager_test.go ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package rbac
13
+
14
+ import (
15
+ "encoding/json"
16
+ "testing"
17
+
18
+ "github.com/weaviate/weaviate/usecases/auth/authentication"
19
+
20
+ "github.com/sirupsen/logrus/hooks/test"
21
+ "github.com/stretchr/testify/assert"
22
+ "github.com/stretchr/testify/require"
23
+
24
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
25
+ "github.com/weaviate/weaviate/usecases/auth/authorization/conv"
26
+ )
27
+
28
+ func TestSnapshotAndRestore(t *testing.T) {
29
+ tests := []struct {
30
+ name string
31
+ setupPolicies func(*Manager) error
32
+ wantErr bool
33
+ }{
34
+ {
35
+ name: "empty policies",
36
+ setupPolicies: func(m *Manager) error {
37
+ return nil
38
+ },
39
+ },
40
+ {
41
+ name: "with role and policy",
42
+ setupPolicies: func(m *Manager) error {
43
+ // Add a role and policy
44
+ _, err := m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("admin"), "*", authorization.READ, authorization.SchemaDomain)
45
+ if err != nil {
46
+ return err
47
+ }
48
+ _, err = m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("test-user", authentication.AuthTypeDb), conv.PrefixRoleName("admin"))
49
+ return err
50
+ },
51
+ },
52
+ {
53
+ name: "multiple roles and policies",
54
+ setupPolicies: func(m *Manager) error {
55
+ // Add multiple roles and policies
56
+ _, err := m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("admin"), "*", authorization.READ, authorization.SchemaDomain)
57
+ if err != nil {
58
+ return err
59
+ }
60
+ _, err = m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("editor"), "collections/*", authorization.UPDATE, authorization.SchemaDomain)
61
+ if err != nil {
62
+ return err
63
+ }
64
+ _, err = m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("test-user", authentication.AuthTypeDb), conv.PrefixRoleName("admin"))
65
+ if err != nil {
66
+ return err
67
+ }
68
+ _, err = m.casbin.AddRoleForUser(conv.UserNameWithTypeFromId("test-user", authentication.AuthTypeDb), conv.PrefixRoleName("editor"))
69
+ return err
70
+ },
71
+ },
72
+ }
73
+
74
+ for _, tt := range tests {
75
+ t.Run(tt.name, func(t *testing.T) {
76
+ // Setup logger with hook for testing
77
+ logger, _ := test.NewNullLogger()
78
+ m, err := setupTestManager(t, logger)
79
+ require.NoError(t, err)
80
+
81
+ // Get initial policies before our test setup
82
+ initialPolicies, err := m.casbin.GetPolicy()
83
+ require.NoError(t, err)
84
+ initialGroupingPolicies, err := m.casbin.GetGroupingPolicy()
85
+ require.NoError(t, err)
86
+
87
+ // Setup policies if needed
88
+ if tt.setupPolicies != nil {
89
+ err := tt.setupPolicies(m)
90
+ require.NoError(t, err)
91
+ }
92
+
93
+ // Take snapshot
94
+ snapshotData, err := m.Snapshot()
95
+ require.NoError(t, err)
96
+ require.NotNil(t, snapshotData)
97
+
98
+ // Create a new manager for restore
99
+ m2, err := setupTestManager(t, logger)
100
+ require.NoError(t, err)
101
+
102
+ // Restore from snapshot
103
+ err = m2.Restore(snapshotData)
104
+ if tt.wantErr {
105
+ require.Error(t, err)
106
+ return
107
+ }
108
+ require.NoError(t, err)
109
+
110
+ // Get final policies after our test setup
111
+ finalPolicies, err := m.casbin.GetPolicy()
112
+ require.NoError(t, err)
113
+ finalGroupingPolicies, err := m.casbin.GetGroupingPolicy()
114
+ require.NoError(t, err)
115
+
116
+ // Get restored policies
117
+ restoredPolicies, err := m2.casbin.GetPolicy()
118
+ require.NoError(t, err)
119
+ restoredGroupingPolicies, err := m2.casbin.GetGroupingPolicy()
120
+ require.NoError(t, err)
121
+
122
+ // Compare only the delta of policies we added
123
+ addedPolicies := getPolicyDelta(initialPolicies, finalPolicies)
124
+ restoredAddedPolicies := getPolicyDelta(initialPolicies, restoredPolicies)
125
+ assert.ElementsMatch(t, addedPolicies, restoredAddedPolicies)
126
+
127
+ // Compare only the delta of grouping policies we added
128
+ addedGroupingPolicies := getPolicyDelta(initialGroupingPolicies, finalGroupingPolicies)
129
+ restoredAddedGroupingPolicies := getPolicyDelta(initialGroupingPolicies, restoredGroupingPolicies)
130
+ assert.ElementsMatch(t, addedGroupingPolicies, restoredAddedGroupingPolicies)
131
+ })
132
+ }
133
+ }
134
+
135
+ // getPolicyDelta returns the policies that are in b but not in a
136
+ func getPolicyDelta(a, b [][]string) [][]string {
137
+ delta := make([][]string, 0)
138
+ for _, policyB := range b {
139
+ found := false
140
+ for _, policyA := range a {
141
+ if equalPolicies(policyA, policyB) {
142
+ found = true
143
+ break
144
+ }
145
+ }
146
+ if !found {
147
+ delta = append(delta, policyB)
148
+ }
149
+ }
150
+ return delta
151
+ }
152
+
153
+ // equalPolicies compares two policies for equality
154
+ func equalPolicies(a, b []string) bool {
155
+ if len(a) != len(b) {
156
+ return false
157
+ }
158
+ for i := range a {
159
+ if a[i] != b[i] {
160
+ return false
161
+ }
162
+ }
163
+ return true
164
+ }
165
+
166
+ func TestSnapshotNilCasbin(t *testing.T) {
167
+ logger, _ := test.NewNullLogger()
168
+ m := &Manager{
169
+ casbin: nil,
170
+ logger: logger,
171
+ }
172
+
173
+ snapshotData, err := m.Snapshot()
174
+ require.NoError(t, err)
175
+ assert.Nil(t, snapshotData)
176
+ }
177
+
178
+ func TestRestoreNilCasbin(t *testing.T) {
179
+ logger, _ := test.NewNullLogger()
180
+ m := &Manager{
181
+ casbin: nil,
182
+ logger: logger,
183
+ }
184
+
185
+ err := m.Restore([]byte("{}"))
186
+ require.NoError(t, err)
187
+ }
188
+
189
+ func TestRestoreInvalidData(t *testing.T) {
190
+ logger, _ := test.NewNullLogger()
191
+ m, err := setupTestManager(t, logger)
192
+ require.NoError(t, err)
193
+
194
+ // Test with invalid JSON
195
+ err = m.Restore([]byte("invalid json"))
196
+ require.Error(t, err)
197
+ assert.Contains(t, err.Error(), "decode json")
198
+
199
+ // Test with empty data
200
+ err = m.Restore([]byte("{}"))
201
+ require.NoError(t, err)
202
+ }
203
+
204
+ func TestRestoreEmptyData(t *testing.T) {
205
+ logger, _ := test.NewNullLogger()
206
+ m, err := setupTestManager(t, logger)
207
+ require.NoError(t, err)
208
+
209
+ _, err = m.casbin.AddNamedPolicy("p", conv.PrefixRoleName("admin"), "*", authorization.READ, authorization.SchemaDomain)
210
+ require.NoError(t, err)
211
+
212
+ policies, err := m.casbin.GetPolicy()
213
+ require.NoError(t, err)
214
+ require.Len(t, policies, 5)
215
+
216
+ err = m.Restore([]byte{})
217
+ require.NoError(t, err)
218
+
219
+ // nothing overwritten
220
+ policies, err = m.casbin.GetPolicy()
221
+ require.NoError(t, err)
222
+ require.Len(t, policies, 5)
223
+ }
224
+
225
+ func TestSnapshotAndRestoreUpgrade(t *testing.T) {
226
+ tests := []struct {
227
+ name string
228
+ policiesInput [][]string
229
+ policiesExpected [][]string
230
+ groupingsInput [][]string
231
+ groupingsExpected [][]string
232
+ }{
233
+ {
234
+ name: "assign users",
235
+ policiesInput: [][]string{
236
+ {"role:some_role", "users/.*", "U", "users"},
237
+ },
238
+ policiesExpected: [][]string{
239
+ {"role:some_role", "users/.*", "A", "users"},
240
+ // build-in roles are added after restore
241
+ {"role:viewer", "*", authorization.READ, "*"},
242
+ {"role:read-only", "*", authorization.READ, "*"},
243
+ {"role:admin", "*", conv.VALID_VERBS, "*"},
244
+ {"role:root", "*", conv.VALID_VERBS, "*"},
245
+ },
246
+ },
247
+ {
248
+ name: "build-in",
249
+ policiesInput: [][]string{
250
+ {"role:viewer", "*", "R", "*"},
251
+ {"role:admin", "*", "(C)|(R)|(U)|(D)", "*"},
252
+ },
253
+ policiesExpected: [][]string{
254
+ {"role:viewer", "*", "R", "*"},
255
+ {"role:read-only", "*", "R", "*"},
256
+ {"role:admin", "*", conv.VALID_VERBS, "*"},
257
+ // build-in roles are added after restore
258
+ {"role:root", "*", conv.VALID_VERBS, "*"},
259
+ },
260
+ },
261
+ {
262
+ name: "users",
263
+ policiesInput: [][]string{
264
+ {"role:admin", "*", "(C)|(R)|(U)|(D)", "*"}, // present to iterate over all roles in downgrade
265
+ },
266
+ policiesExpected: [][]string{
267
+ {"role:admin", "*", "(C)|(R)|(U)|(D)|(A)", "*"},
268
+ // build-in roles are added after restore
269
+ {"role:viewer", "*", authorization.READ, "*"},
270
+ {"role:read-only", "*", authorization.READ, "*"},
271
+ {"role:root", "*", conv.VALID_VERBS, "*"},
272
+ },
273
+ groupingsInput: [][]string{
274
+ {"user:test-user", "role:admin"},
275
+ },
276
+ groupingsExpected: [][]string{
277
+ {"db:test-user", "role:admin"},
278
+ {"oidc:test-user", "role:admin"},
279
+ },
280
+ },
281
+ }
282
+
283
+ for _, tt := range tests {
284
+ t.Run(tt.name, func(t *testing.T) {
285
+ logger, _ := test.NewNullLogger()
286
+ m, err := setupTestManager(t, logger)
287
+ require.NoError(t, err)
288
+
289
+ sh := snapshot{Version: 0, GroupingPolicy: tt.groupingsInput, Policy: tt.policiesInput}
290
+
291
+ bytes, err := json.Marshal(sh)
292
+ require.NoError(t, err)
293
+
294
+ err = m.Restore(bytes)
295
+ require.NoError(t, err)
296
+
297
+ finalPolicies, err := m.casbin.GetPolicy()
298
+ require.NoError(t, err)
299
+ assert.ElementsMatch(t, finalPolicies, tt.policiesExpected)
300
+
301
+ finalGroupingPolicies, err := m.casbin.GetGroupingPolicy()
302
+ require.NoError(t, err)
303
+ assert.Equal(t, finalGroupingPolicies, tt.groupingsExpected)
304
+ })
305
+ }
306
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/model.go ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package rbac
13
+
14
+ import (
15
+ "bufio"
16
+ "fmt"
17
+ "os"
18
+ "path/filepath"
19
+ "slices"
20
+ "strconv"
21
+ "strings"
22
+
23
+ "github.com/weaviate/weaviate/usecases/auth/authentication"
24
+
25
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
26
+ "github.com/weaviate/weaviate/usecases/auth/authorization/conv"
27
+
28
+ "github.com/casbin/casbin/v2"
29
+ "github.com/casbin/casbin/v2/model"
30
+ fileadapter "github.com/casbin/casbin/v2/persist/file-adapter"
31
+ casbinutil "github.com/casbin/casbin/v2/util"
32
+ "github.com/pkg/errors"
33
+
34
+ "github.com/weaviate/weaviate/usecases/auth/authorization/rbac/rbacconf"
35
+ "github.com/weaviate/weaviate/usecases/build"
36
+ "github.com/weaviate/weaviate/usecases/config"
37
+ )
38
+
39
+ const DEFAULT_POLICY_VERSION = "1.29.0"
40
+
41
+ const (
42
+ // MODEL is the used model for casbin to store roles, permissions, users and comparisons patterns
43
+ // docs: https://casbin.org/docs/syntax-for-models
44
+ MODEL = `
45
+ [request_definition]
46
+ r = sub, obj, act
47
+
48
+ [policy_definition]
49
+ p = sub, obj, act, dom
50
+
51
+ [role_definition]
52
+ g = _, _
53
+
54
+ [policy_effect]
55
+ e = some(where (p.eft == allow))
56
+
57
+ [matchers]
58
+ m = g(r.sub, p.sub) && weaviateMatcher(r.obj, p.obj) && regexMatch(r.act, p.act)
59
+ `
60
+ )
61
+
62
+ func createStorage(filePath string) error {
63
+ if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
64
+ return fmt.Errorf("failed to create directories: %w", err)
65
+ }
66
+
67
+ _, err := os.Stat(filePath)
68
+ if err == nil { // file exists
69
+ return nil
70
+ }
71
+
72
+ if os.IsNotExist(err) {
73
+ file, err := os.Create(filePath)
74
+ if err != nil {
75
+ return fmt.Errorf("failed to create file: %w", err)
76
+ }
77
+ defer file.Close()
78
+ return nil
79
+ }
80
+
81
+ return err
82
+ }
83
+
84
+ func Init(conf rbacconf.Config, policyPath string, authNconf config.Authentication) (*casbin.SyncedCachedEnforcer, error) {
85
+ if !conf.Enabled {
86
+ return nil, nil
87
+ }
88
+
89
+ m, err := model.NewModelFromString(MODEL)
90
+ if err != nil {
91
+ return nil, fmt.Errorf("load rbac model: %w", err)
92
+ }
93
+
94
+ enforcer, err := casbin.NewSyncedCachedEnforcer(m)
95
+ if err != nil {
96
+ return nil, fmt.Errorf("failed to create enforcer: %w", err)
97
+ }
98
+ enforcer.EnableCache(true)
99
+
100
+ rbacStoragePath := fmt.Sprintf("%s/rbac", policyPath)
101
+ rbacStorageFilePath := fmt.Sprintf("%s/rbac/policy.csv", policyPath)
102
+
103
+ if err := createStorage(rbacStorageFilePath); err != nil {
104
+ return nil, errors.Wrapf(err, "create storage path: %v", rbacStorageFilePath)
105
+ }
106
+
107
+ enforcer.SetAdapter(fileadapter.NewAdapter(rbacStorageFilePath))
108
+
109
+ if err := enforcer.LoadPolicy(); err != nil {
110
+ return nil, err
111
+ }
112
+ // parse version string to check if upgrade is needed
113
+ policyVersion, err := getVersion(rbacStoragePath)
114
+ if err != nil {
115
+ return nil, err
116
+ }
117
+ versionParts := strings.Split(policyVersion, ".")
118
+ minorVersion, err := strconv.Atoi(versionParts[1])
119
+ if err != nil {
120
+ return nil, err
121
+ }
122
+
123
+ if versionParts[0] == "1" && minorVersion < 30 {
124
+ if err := upgradePoliciesFrom129(enforcer, false); err != nil {
125
+ return nil, err
126
+ }
127
+
128
+ if err := upgradeGroupingsFrom129(enforcer, authNconf); err != nil {
129
+ return nil, err
130
+ }
131
+ }
132
+ // docs: https://casbin.org/docs/function/
133
+ enforcer.AddFunction("weaviateMatcher", WeaviateMatcherFunc)
134
+
135
+ if err := applyPredefinedRoles(enforcer, conf, authNconf); err != nil {
136
+ return nil, errors.Wrapf(err, "apply env config")
137
+ }
138
+
139
+ // update version after casbin policy has been written
140
+ if err := writeVersion(rbacStoragePath, build.Version); err != nil {
141
+ return nil, err
142
+ }
143
+
144
+ return enforcer, nil
145
+ }
146
+
147
+ // applyPredefinedRoles adds pre-defined roles (admin/viewer/root) and assigns them to the users provided in the
148
+ // local config
149
+ func applyPredefinedRoles(enforcer *casbin.SyncedCachedEnforcer, conf rbacconf.Config, authNconf config.Authentication) error {
150
+ // remove preexisting root role including assignments
151
+ _, err := enforcer.RemoveFilteredNamedPolicy("p", 0, conv.PrefixRoleName(authorization.Root))
152
+ if err != nil {
153
+ return err
154
+ }
155
+ _, err = enforcer.RemoveFilteredGroupingPolicy(1, conv.PrefixRoleName(authorization.Root))
156
+ if err != nil {
157
+ return err
158
+ }
159
+
160
+ _, err = enforcer.RemoveFilteredNamedPolicy("p", 0, conv.PrefixRoleName(authorization.ReadOnly))
161
+ if err != nil {
162
+ return err
163
+ }
164
+ _, err = enforcer.RemoveFilteredGroupingPolicy(1, conv.PrefixRoleName(authorization.ReadOnly))
165
+ if err != nil {
166
+ return err
167
+ }
168
+
169
+ // add pre existing roles
170
+ for name, verb := range conv.BuiltInPolicies {
171
+ if verb == "" {
172
+ continue
173
+ }
174
+ if _, err := enforcer.AddNamedPolicy("p", conv.PrefixRoleName(name), "*", verb, "*"); err != nil {
175
+ return fmt.Errorf("add policy: %w", err)
176
+ }
177
+ }
178
+
179
+ for i := range conf.RootUsers {
180
+ if strings.TrimSpace(conf.RootUsers[i]) == "" {
181
+ continue
182
+ }
183
+
184
+ if authNconf.APIKey.Enabled && slices.Contains(authNconf.APIKey.Users, conf.RootUsers[i]) {
185
+ if _, err := enforcer.AddRoleForUser(conv.UserNameWithTypeFromId(conf.RootUsers[i], authentication.AuthTypeDb), conv.PrefixRoleName(authorization.Root)); err != nil {
186
+ return fmt.Errorf("add role for user: %w", err)
187
+ }
188
+ }
189
+
190
+ if authNconf.OIDC.Enabled {
191
+ if _, err := enforcer.AddRoleForUser(conv.UserNameWithTypeFromId(conf.RootUsers[i], authentication.AuthTypeOIDC), conv.PrefixRoleName(authorization.Root)); err != nil {
192
+ return fmt.Errorf("add role for user: %w", err)
193
+ }
194
+ }
195
+ }
196
+
197
+ // temporary to enable import of existing keys to WCD (Admin + readonly)
198
+ for i := range conf.AdminUsers {
199
+ if strings.TrimSpace(conf.AdminUsers[i]) == "" {
200
+ continue
201
+ }
202
+
203
+ if authNconf.APIKey.Enabled && slices.Contains(authNconf.APIKey.Users, conf.AdminUsers[i]) {
204
+ if _, err := enforcer.AddRoleForUser(conv.UserNameWithTypeFromId(conf.AdminUsers[i], authentication.AuthTypeDb), conv.PrefixRoleName(authorization.Admin)); err != nil {
205
+ return fmt.Errorf("add role for user: %w", err)
206
+ }
207
+ }
208
+
209
+ if authNconf.OIDC.Enabled {
210
+ if _, err := enforcer.AddRoleForUser(conv.UserNameWithTypeFromId(conf.AdminUsers[i], authentication.AuthTypeOIDC), conv.PrefixRoleName(authorization.Admin)); err != nil {
211
+ return fmt.Errorf("add role for user: %w", err)
212
+ }
213
+ }
214
+ }
215
+
216
+ for i := range conf.ViewerUsers {
217
+ if strings.TrimSpace(conf.ViewerUsers[i]) == "" {
218
+ continue
219
+ }
220
+
221
+ if authNconf.APIKey.Enabled && slices.Contains(authNconf.APIKey.Users, conf.ViewerUsers[i]) {
222
+ if _, err := enforcer.AddRoleForUser(conv.UserNameWithTypeFromId(conf.ViewerUsers[i], authentication.AuthTypeDb), conv.PrefixRoleName(authorization.Viewer)); err != nil {
223
+ return fmt.Errorf("add role for user: %w", err)
224
+ }
225
+ }
226
+
227
+ if authNconf.OIDC.Enabled {
228
+ if _, err := enforcer.AddRoleForUser(conv.UserNameWithTypeFromId(conf.ViewerUsers[i], authentication.AuthTypeOIDC), conv.PrefixRoleName(authorization.Viewer)); err != nil {
229
+ return fmt.Errorf("add role for user: %w", err)
230
+ }
231
+ }
232
+ }
233
+
234
+ for _, group := range conf.RootGroups {
235
+ if strings.TrimSpace(group) == "" {
236
+ continue
237
+ }
238
+ if _, err := enforcer.AddRoleForUser(conv.PrefixGroupName(group), conv.PrefixRoleName(authorization.Root)); err != nil {
239
+ return fmt.Errorf("add role for group %s: %w", group, err)
240
+ }
241
+ }
242
+
243
+ for _, viewerGroup := range conf.ReadOnlyGroups {
244
+ if strings.TrimSpace(viewerGroup) == "" {
245
+ continue
246
+ }
247
+ if _, err := enforcer.AddRoleForUser(conv.PrefixGroupName(viewerGroup), conv.PrefixRoleName(authorization.ReadOnly)); err != nil {
248
+ return fmt.Errorf("add viewer role for group %s: %w", viewerGroup, err)
249
+ }
250
+ }
251
+
252
+ if err := enforcer.SavePolicy(); err != nil {
253
+ return errors.Wrapf(err, "save policy")
254
+ }
255
+
256
+ return nil
257
+ }
258
+
259
+ func WeaviateMatcher(key1 string, key2 string) bool {
260
+ // If we're dealing with a tenant-specific path (matches /shards/#$)
261
+ if strings.HasSuffix(key1, "/shards/#") {
262
+ // Don't allow matching with wildcard patterns
263
+ if strings.HasSuffix(key2, "/shards/.*") {
264
+ return false
265
+ }
266
+ }
267
+ // For all other cases, use standard KeyMatch5
268
+ return casbinutil.KeyMatch5(key1, key2)
269
+ }
270
+
271
+ func WeaviateMatcherFunc(args ...interface{}) (interface{}, error) {
272
+ name1 := args[0].(string)
273
+ name2 := args[1].(string)
274
+
275
+ return (bool)(WeaviateMatcher(name1, name2)), nil
276
+ }
277
+
278
+ func getVersion(path string) (string, error) {
279
+ filePath := path + "/version"
280
+ _, err := os.Stat(filePath)
281
+ if err != nil { // file exists
282
+ return DEFAULT_POLICY_VERSION, nil
283
+ }
284
+ b, err := os.ReadFile(filePath)
285
+ if err != nil {
286
+ return "", err
287
+ }
288
+ return string(b), nil
289
+ }
290
+
291
+ func writeVersion(path, version string) error {
292
+ tmpFile, err := os.CreateTemp(path, "policy-temp-*.tmp")
293
+ if err != nil {
294
+ return err
295
+ }
296
+ tempFilename := tmpFile.Name()
297
+
298
+ defer func() {
299
+ tmpFile.Close()
300
+ os.Remove(tempFilename) // Remove temp file if it still exists
301
+ }()
302
+
303
+ writer := bufio.NewWriter(tmpFile)
304
+ if _, err := fmt.Fprint(writer, version); err != nil {
305
+ return err
306
+ }
307
+
308
+ // Flush the writer to ensure all data is written, then sync and flush tmpfile and atomically rename afterwards
309
+ if err := writer.Flush(); err != nil {
310
+ return err
311
+ }
312
+ if err := tmpFile.Sync(); err != nil {
313
+ return err
314
+ }
315
+ if err := tmpFile.Close(); err != nil {
316
+ return err
317
+ }
318
+
319
+ return os.Rename(tempFilename, path+"/version")
320
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/model_test.go ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package rbac
13
+
14
+ import (
15
+ "testing"
16
+
17
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
18
+ "github.com/weaviate/weaviate/usecases/auth/authorization/conv"
19
+ )
20
+
21
+ func testKeyMatch5(t *testing.T, key1, key2 string, expected bool) {
22
+ t.Helper()
23
+ if result := WeaviateMatcher(key1, key2); result != expected {
24
+ t.Errorf("WeaviateMatcher(%q, %q) = %v; want %v", key1, key2, result, expected)
25
+ }
26
+ }
27
+
28
+ func TestKeyMatch5AuthZ(t *testing.T) {
29
+ tests := []struct {
30
+ name string
31
+ key1 string
32
+ key2 string
33
+ expected bool
34
+ }{
35
+ // Allow all
36
+ {"Allow all roles", authorization.Roles()[0], "*", true},
37
+ {"Allow all collections", authorization.CollectionsMetadata()[0], "*", true},
38
+ {"Allow all collections with ABC", authorization.CollectionsMetadata("ABC")[0], "*", true},
39
+ {"Allow all shards", authorization.ShardsMetadata("")[0], "*", true},
40
+ {"Allow all shards with ABC", authorization.ShardsMetadata("ABC", "ABC")[0], "*", true},
41
+ {"Allow all objects", authorization.Objects("", "", ""), "*", true},
42
+ {"Allow all objects with Tenant1", authorization.Objects("", "Tenant1", ""), "*", true},
43
+ {"Allow all tenants", authorization.ShardsMetadata("")[0], "*", true},
44
+ {"Allow all tenants with ABC", authorization.ShardsMetadata("ABC", "ABC")[0], "*", true},
45
+
46
+ // Class level
47
+ {"Class level collections ABC", authorization.CollectionsMetadata("ABC")[0], conv.CasbinSchema("*", "#"), true},
48
+ {"Class level shards ABC", authorization.ShardsMetadata("ABC")[0], conv.CasbinSchema("*", "*"), true},
49
+ {"Class level collections ABC exact", authorization.CollectionsMetadata("ABC")[0], conv.CasbinSchema("ABC", "#"), true},
50
+ {"Class level collections Class1 exact", authorization.CollectionsMetadata("Class1")[0], conv.CasbinSchema("Class1", "#"), true},
51
+ {"Class level collections Class2 mismatch", authorization.CollectionsMetadata("Class2")[0], conv.CasbinSchema("Class1", "#"), false},
52
+ {"Class level shards ABC TenantX", authorization.ShardsMetadata("ABC", "TenantX")[0], conv.CasbinSchema("ABC", ""), true},
53
+ {"Class level objects ABC TenantX objectY", authorization.Objects("ABC", "TenantX", "objectY"), conv.CasbinData("ABC", "*", "*"), true},
54
+ {"Class level tenant ABC TenantX", authorization.ShardsMetadata("ABC", "TenantX")[0], conv.CasbinSchema("ABC", ""), true},
55
+
56
+ // Tenants level
57
+ {"Tenants level shards", authorization.ShardsMetadata("")[0], conv.CasbinSchema("*", "*"), true},
58
+ {"Tenants level shards ABC Tenant1", authorization.ShardsMetadata("ABC", "Tenant1")[0], conv.CasbinSchema("*", "*"), true},
59
+ {"Tenants level shards Class1 Tenant1", authorization.ShardsMetadata("Class1", "Tenant1")[0], conv.CasbinSchema("*", "Tenant1"), true},
60
+ {"Tenants level objects Class1 Tenant1 ObjectY", authorization.Objects("Class1", "Tenant1", "ObjectY"), conv.CasbinData("*", "Tenant1", ""), true},
61
+ {"Tenants level shards Class1 Tenant2 mismatch", authorization.ShardsMetadata("Class1", "Tenant2")[0], conv.CasbinSchema("*", "Tenant1"), false},
62
+ {"Tenants level shards Class1 Tenant2 mismatch 2", authorization.ShardsMetadata("Class1", "Tenant2")[0], conv.CasbinSchema("Class2", "Tenant1"), false},
63
+ {"Tenants level shards mismatch", authorization.ShardsMetadata("")[0], conv.CasbinSchema("Class1", ""), false},
64
+ {"Tenants level collections Class1", authorization.CollectionsMetadata("Class1")[0], conv.CasbinSchema("Class1", "#"), true},
65
+ {"Tenants level shards Class1 tenant1", authorization.ShardsMetadata("Class1", "tenant1")[0], conv.CasbinSchema("Class1", ""), true},
66
+
67
+ // Objects level
68
+ {"Objects level all", authorization.Objects("", "", ""), conv.CasbinData(".*", ".*", ".*"), true},
69
+ {"Objects level ABC Tenant1", authorization.Objects("ABC", "Tenant1", ""), conv.CasbinData("*", "*", "*"), true},
70
+ {"Objects level ABC Tenant1 exact", authorization.Objects("ABC", "Tenant1", ""), conv.CasbinData("*", "Tenant1", "*"), true},
71
+ {"Objects level ABC Tenant1 abc", authorization.Objects("ABC", "Tenant1", "abc"), conv.CasbinData("*", "Tenant1", "*"), true},
72
+ {"Objects level ABC Tenant1 abc exact", authorization.Objects("ABC", "Tenant1", "abc"), conv.CasbinData("*", "Tenant1", "*"), true},
73
+ {"Objects level ABC Tenant1 abc exact 2", authorization.Objects("ABC", "Tenant1", "abc"), conv.CasbinData("*", "*", "abc"), true},
74
+ {"Objects level ABC Tenant1 abc exact 3", authorization.Objects("ABC", "Tenant1", "abc"), conv.CasbinData("ABC", "Tenant1", "abc"), true},
75
+ {"Objects level ABCD Tenant1 abc mismatch", authorization.Objects("ABCD", "Tenant1", "abc"), conv.CasbinData("ABC", "Tenant1", "abc"), false},
76
+ {"Objects level ABC Tenant1 abcd mismatch", authorization.Objects("ABC", "Tenant1", "abcd"), conv.CasbinData("ABC", "Tenant1", "abc"), false},
77
+ {"Objects level ABC bar abcd", authorization.Objects("ABC", "bar", "abcd"), conv.CasbinData("*", "bar", ""), true},
78
+
79
+ // Tenants
80
+ {"Tenants level tenant", authorization.ShardsMetadata("")[0], conv.CasbinSchema("*", "*"), true},
81
+ {"Tenants level tenant ABC Tenant1", authorization.ShardsMetadata("ABC", "Tenant1")[0], conv.CasbinSchema("*", "*"), true},
82
+ {"Tenants level tenant Class1 Tenant1", authorization.ShardsMetadata("Class1", "Tenant1")[0], conv.CasbinSchema("*", "Tenant1"), true},
83
+ {"Tenants level objects Class1 Tenant1 ObjectY", authorization.Objects("Class1", "Tenant1", "ObjectY"), conv.CasbinData("*", "Tenant1", ""), true},
84
+ {"Tenants level tenant Class1 Tenant2 mismatch", authorization.ShardsMetadata("Class1", "Tenant2")[0], conv.CasbinSchema("*", "Tenant1"), false},
85
+ {"Tenants level tenant Class1 Tenant2 mismatch 2", authorization.ShardsMetadata("Class1", "Tenant2")[0], conv.CasbinSchema("Class2", "Tenant1"), false},
86
+ {"Tenants level tenant mismatch", authorization.ShardsMetadata("")[0], conv.CasbinSchema("Class1", ""), false},
87
+ {"Tenants level collections Class1", authorization.ShardsMetadata("Class1")[0], conv.CasbinSchema("Class1", ""), true},
88
+ {"Tenants level tenant Class1 tenant1", authorization.ShardsMetadata("Class1", "tenant1")[0], conv.CasbinSchema("Class1", ""), true},
89
+
90
+ // Regex
91
+ {"Regex collections ABCD", authorization.CollectionsMetadata("ABCD")[0], conv.CasbinSchema("ABC", "#"), false},
92
+ {"Regex shards ABC", authorization.ShardsMetadata("ABC", "")[0], conv.CasbinSchema("ABC", ""), true},
93
+ {"Regex objects ABC", authorization.Objects("ABC", "", ""), conv.CasbinData("ABC", "*", "*"), true},
94
+ {"Regex objects ABCD mismatch", authorization.Objects("ABCD", "", ""), conv.CasbinData("ABC", "*", "*"), false},
95
+ {"Regex objects ABCD wildcard", authorization.Objects("ABCD", "", ""), conv.CasbinData("ABC.*", "*", "*"), true},
96
+ {"Regex objects BCD mismatch", authorization.Objects("BCD", "", ""), conv.CasbinData("ABC", "*", "*"), false},
97
+ {"Regex tenant ABC", authorization.ShardsMetadata("ABC", "")[0], conv.CasbinSchema("ABC", ""), true},
98
+
99
+ {"Regex collections ABC wildcard", authorization.CollectionsMetadata("ABC")[0], conv.CasbinSchema("ABC*", "#"), true},
100
+ {"Regex collections ABC wildcard 2", authorization.CollectionsMetadata("ABC")[0], conv.CasbinSchema("ABC*", "#"), true},
101
+ {"Regex collections ABCD wildcard", authorization.CollectionsMetadata("ABCD")[0], conv.CasbinSchema("ABC*", "#"), true},
102
+
103
+ // ShardsMetadata read on collections level permissions
104
+ {"ShardsMetadata read on collections level ABC", authorization.ShardsMetadata("ABC")[0], conv.CasbinSchema("ABC", ""), true},
105
+
106
+ // some other cases
107
+ {"Mismatched collection", authorization.CollectionsMetadata("Class1")[0], conv.CasbinSchema("Class2", "#"), false},
108
+ {"Mismatched shard", authorization.ShardsMetadata("Class1", "Shard1")[0], conv.CasbinSchema("Class1", "Shard2"), false},
109
+ {"Partial match role", authorization.Roles("anotherRole")[0], conv.CasbinRoles("ro*"), false},
110
+ {"Partial match role", authorization.Roles("role")[0], conv.CasbinRoles("ro*"), true},
111
+ {"Partial match collection", authorization.CollectionsMetadata("Class1")[0], conv.CasbinSchema("Cla*", "#"), true},
112
+ {"Partial match shard", authorization.ShardsMetadata("Class1", "Shard1")[0], conv.CasbinSchema("Class1", "Sha*"), true},
113
+ {"Partial match object", authorization.Objects("Class1", "Shard1", "Object1"), conv.CasbinData("Class1", "Shard1", "Obj*"), true},
114
+ {"Special character mismatch", authorization.Objects("Class1", "Shard1", "Object1"), "data/collections/Class1/shards/Shard1/objects/Object1!", false},
115
+ {"Mismatched object", authorization.Objects("Class1", "Shard1", "Object1"), conv.CasbinData("Class1", "Shard1", "Object2"), false},
116
+ {"Mismatched tenant", authorization.ShardsMetadata("Class1", "Tenant1")[0], conv.CasbinSchema("Class1", "Tenant2"), false},
117
+
118
+ {"Collection check vs all shards", authorization.CollectionsMetadata("Class1")[0], conv.CasbinSchema("Class1", "*"), false},
119
+ }
120
+
121
+ for _, tt := range tests {
122
+ t.Run(tt.name, func(t *testing.T) {
123
+ testKeyMatch5(t, tt.key1, tt.key2, tt.expected)
124
+ })
125
+ }
126
+ }
127
+
128
+ func TestKeyMatchTenant(t *testing.T) {
129
+ tests := []struct {
130
+ name string
131
+ key1 string
132
+ key2 string
133
+ expected bool
134
+ }{
135
+ // Tenant specific patterns
136
+ {
137
+ "Tenant specific path should not match wildcard",
138
+ "schema/collections/Class1/shards/#",
139
+ "schema/collections/Class1/shards/.*",
140
+ false,
141
+ },
142
+ {
143
+ "Tenant specific path should match exact #",
144
+ "schema/collections/Class1/shards/#",
145
+ "schema/collections/Class1/shards/#",
146
+ true,
147
+ },
148
+ {
149
+ "Regular shard should match wildcard",
150
+ "schema/collections/Class1/shards/shard-1",
151
+ "schema/collections/Class1/shards/.*",
152
+ true,
153
+ },
154
+ {
155
+ "Regular shard should not match tenant specific",
156
+ "schema/collections/Class1/shards/shard-1",
157
+ "schema/collections/Class1/shards/#",
158
+ false,
159
+ },
160
+ }
161
+
162
+ for _, tt := range tests {
163
+ t.Run(tt.name, func(t *testing.T) {
164
+ result := WeaviateMatcher(tt.key1, tt.key2)
165
+ if result != tt.expected {
166
+ t.Errorf("WeaviateMatcher(%s, %s) = %v; want %v", tt.key1, tt.key2, result, tt.expected)
167
+ }
168
+ })
169
+ }
170
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/rbacconf/config.go ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package rbacconf
13
+
14
+ // Config makes every subject on the list an admin, whereas everyone else
15
+ // has no rights whatsoever
16
+ type Config struct {
17
+ Enabled bool `json:"enabled" yaml:"enabled"`
18
+ RootUsers []string `json:"root_users" yaml:"root_users"`
19
+ RootGroups []string `json:"root_groups" yaml:"root_groups"`
20
+ ReadOnlyGroups []string `json:"readonly_groups" yaml:"readonly_groups"`
21
+ ViewerUsers []string `json:"viewer_users" yaml:"viewer_users"`
22
+ AdminUsers []string `json:"admin_users" yaml:"admin_users"`
23
+ IpInAuditDisabled bool `json:"ip_in_audit" yaml:"ip_in_audit"`
24
+ }
25
+
26
+ // Validate admin list config for viability, can be called from the central
27
+ // config package
28
+ func (c Config) Validate() error {
29
+ return nil
30
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/up_down_grades.go ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package rbac
13
+
14
+ import (
15
+ "fmt"
16
+ "slices"
17
+ "strings"
18
+
19
+ "github.com/weaviate/weaviate/usecases/auth/authentication"
20
+
21
+ "github.com/casbin/casbin/v2"
22
+ "github.com/weaviate/weaviate/usecases/auth/authorization"
23
+ "github.com/weaviate/weaviate/usecases/auth/authorization/conv"
24
+ "github.com/weaviate/weaviate/usecases/config"
25
+ )
26
+
27
+ func upgradeGroupingsFrom129(enforcer *casbin.SyncedCachedEnforcer, authNconf config.Authentication) error {
28
+ // clear out assignments without namespaces and re-add them with namespaces
29
+ roles, _ := enforcer.GetAllSubjects()
30
+ for _, role := range roles {
31
+ users, err := enforcer.GetUsersForRole(role)
32
+ if err != nil {
33
+ return err
34
+ }
35
+
36
+ for _, user := range users {
37
+ // internal user assignments (for empty roles) need to be converted from namespaced assignment to db-user only
38
+ // other assignments need to be converted to both namespaces
39
+ if strings.Contains(user, conv.InternalPlaceHolder) {
40
+ if _, err := enforcer.DeleteRoleForUser(user, role); err != nil {
41
+ return err
42
+ }
43
+
44
+ if _, err := enforcer.AddRoleForUser(conv.UserNameWithTypeFromId(conv.InternalPlaceHolder, authentication.AuthTypeDb), role); err != nil {
45
+ return err
46
+ }
47
+ } else if strings.HasPrefix(user, "user:") {
48
+ userNoPrefix := strings.TrimPrefix(user, "user:")
49
+ if _, err := enforcer.DeleteRoleForUser(user, role); err != nil {
50
+ return err
51
+ }
52
+ if authNconf.APIKey.Enabled && slices.Contains(authNconf.APIKey.Users, userNoPrefix) {
53
+ if _, err := enforcer.AddRoleForUser(conv.UserNameWithTypeFromId(userNoPrefix, authentication.AuthTypeDb), role); err != nil {
54
+ return err
55
+ }
56
+ }
57
+ if authNconf.OIDC.Enabled {
58
+ if _, err := enforcer.AddRoleForUser(conv.UserNameWithTypeFromId(userNoPrefix, authentication.AuthTypeOIDC), role); err != nil {
59
+ return err
60
+ }
61
+ }
62
+ }
63
+ }
64
+
65
+ }
66
+ return nil
67
+ }
68
+
69
+ func upgradePoliciesFrom129(enforcer *casbin.SyncedCachedEnforcer, keepBuildInRoles bool) error {
70
+ policies, err := enforcer.GetPolicy()
71
+ if err != nil {
72
+ return err
73
+ }
74
+
75
+ // a role can have multiple policies, so first all old role need to be removed and then re-added
76
+ policiesToAdd := make([][]string, 0, len(policies))
77
+ for _, policy := range policies {
78
+ if _, err := enforcer.RemoveFilteredNamedPolicy("p", 0, policy[0]); err != nil {
79
+ return err
80
+ }
81
+
82
+ if policy[3] == authorization.UsersDomain && policy[2] == authorization.UPDATE {
83
+ policy[2] = authorization.USER_AND_GROUP_ASSIGN_AND_REVOKE
84
+ }
85
+
86
+ policiesToAdd = append(policiesToAdd, policy)
87
+ }
88
+
89
+ for _, policy := range policiesToAdd {
90
+ roleName := conv.TrimRoleNamePrefix(policy[0])
91
+ if _, ok := conv.BuiltInPolicies[roleName]; ok {
92
+ if !keepBuildInRoles {
93
+ continue
94
+ } else if policy[2] == conv.CRUD {
95
+ policy[2] = conv.VALID_VERBS
96
+ }
97
+ }
98
+
99
+ if _, err := enforcer.AddNamedPolicy("p", policy[0], policy[1], policy[2], policy[3]); err != nil {
100
+ return fmt.Errorf("readd policy: %w", err)
101
+ }
102
+ }
103
+
104
+ return nil
105
+ }
platform/dbops/binaries/weaviate-src/usecases/auth/authorization/rbac/up_down_grades_test.go ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // _ _
2
+ // __ _____ __ ___ ___ __ _| |_ ___
3
+ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
4
+ // \ V V / __/ (_| |\ V /| | (_| | || __/
5
+ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
6
+ //
7
+ // Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
8
+ //
9
+ // CONTACT: hello@weaviate.io
10
+ //
11
+
12
+ package rbac
13
+
14
+ import (
15
+ "bufio"
16
+ "fmt"
17
+ "os"
18
+ "slices"
19
+ "testing"
20
+
21
+ "github.com/casbin/casbin/v2"
22
+ "github.com/casbin/casbin/v2/model"
23
+ fileadapter "github.com/casbin/casbin/v2/persist/file-adapter"
24
+ "github.com/stretchr/testify/require"
25
+
26
+ "github.com/weaviate/weaviate/usecases/auth/authorization/conv"
27
+ "github.com/weaviate/weaviate/usecases/config"
28
+ )
29
+
30
+ func TestUpdateGroupings(t *testing.T) {
31
+ tests := []struct {
32
+ name string
33
+ rolesToAdd []string
34
+ assignments map[string]string
35
+ expectedAfterWards map[string]string
36
+ authNconf config.Authentication
37
+ }{
38
+ {
39
+ name: "only internal - will only be added as db",
40
+ rolesToAdd: []string{"role:test"},
41
+ assignments: map[string]string{"user:" + conv.InternalPlaceHolder: "role:test"},
42
+ expectedAfterWards: map[string]string{"db:" + conv.InternalPlaceHolder: "role:test"},
43
+ authNconf: config.Authentication{OIDC: config.OIDC{Enabled: true}},
44
+ },
45
+ {
46
+ name: "only oidc enabled - normal user will only be added as oidc",
47
+ rolesToAdd: []string{"role:test"},
48
+ assignments: map[string]string{"user:something": "role:test"},
49
+ expectedAfterWards: map[string]string{"oidc:something": "role:test"},
50
+ authNconf: config.Authentication{OIDC: config.OIDC{Enabled: true}},
51
+ },
52
+ {
53
+ name: "only db enabled - normal user will only be added as db",
54
+ rolesToAdd: []string{"role:test"},
55
+ assignments: map[string]string{"user:something": "role:test"},
56
+ expectedAfterWards: map[string]string{"db:something": "role:test"},
57
+ authNconf: config.Authentication{APIKey: config.StaticAPIKey{Enabled: true, Users: []string{"something"}}},
58
+ },
59
+ {
60
+ name: "both enabled - normal user will be added for both",
61
+ rolesToAdd: []string{"role:test"},
62
+ assignments: map[string]string{"user:something": "role:test"},
63
+ expectedAfterWards: map[string]string{"db:something": "role:test", "oidc:something": "role:test"},
64
+ authNconf: config.Authentication{APIKey: config.StaticAPIKey{Enabled: true, Users: []string{"something"}}, OIDC: config.OIDC{Enabled: true}},
65
+ },
66
+ {
67
+ name: "both enabled but user is not added to api key list- normal user will be added for both",
68
+ rolesToAdd: []string{"role:test"},
69
+ assignments: map[string]string{"user:something": "role:test"},
70
+ expectedAfterWards: map[string]string{"oidc:something": "role:test"},
71
+ authNconf: config.Authentication{APIKey: config.StaticAPIKey{Enabled: true}, OIDC: config.OIDC{Enabled: true}},
72
+ },
73
+ }
74
+
75
+ for _, tt := range tests {
76
+ t.Run(tt.name, func(t *testing.T) {
77
+ m, err := model.NewModelFromString(MODEL)
78
+ require.NoError(t, err)
79
+
80
+ enforcer, err := casbin.NewSyncedCachedEnforcer(m)
81
+ require.NoError(t, err)
82
+
83
+ for _, role := range tt.rolesToAdd {
84
+ _, err := enforcer.AddNamedPolicy("p", role, "*", "R", "*")
85
+ require.NoError(t, err)
86
+
87
+ }
88
+
89
+ for user, role := range tt.assignments {
90
+ _, err := enforcer.AddRoleForUser(user, role)
91
+ require.NoError(t, err)
92
+ }
93
+
94
+ require.NoError(t, upgradeGroupingsFrom129(enforcer, tt.authNconf))
95
+ roles, _ := enforcer.GetAllSubjects()
96
+ require.Len(t, roles, len(tt.rolesToAdd))
97
+ for user, role := range tt.expectedAfterWards {
98
+ users, err := enforcer.GetUsersForRole(role)
99
+ require.NoError(t, err)
100
+ require.True(t, slices.Contains(users, user))
101
+ }
102
+ })
103
+ }
104
+ }
105
+
106
+ func TestUpgradeRoles(t *testing.T) {
107
+ tests := []struct {
108
+ name string
109
+ lines []string
110
+ expectedPolicies [][]string
111
+ version string
112
+ }{
113
+ {
114
+ name: "skip build in roles",
115
+ lines: []string{
116
+ "p, role:other_role, data/collections/.*/shards/.*/objects/.*, R, data",
117
+ "p, role:viewer, *, R, *",
118
+ },
119
+ expectedPolicies: [][]string{
120
+ {"role:other_role", "data/collections/.*/shards/.*/objects/.*", " R", "data"},
121
+ },
122
+ },
123
+ {
124
+ name: "upgrade update user if coming from old version",
125
+ lines: []string{
126
+ "p, role:some_role, users/.*, U, users",
127
+ },
128
+ expectedPolicies: [][]string{
129
+ {"p, role:some_role, users/.*, A, users"},
130
+ },
131
+ },
132
+ {
133
+ name: "mixed upgrade and not upgrade and skip",
134
+ lines: []string{
135
+ "p, role:some_role, users/.*, U, users",
136
+ "p, role:other_role, data/collections/.*/shards/.*/objects/.*, R, data",
137
+ "p, role:viewer, *, R, *",
138
+ },
139
+ expectedPolicies: [][]string{
140
+ {"p, role:some_role, users/.*, A, users, "},
141
+ {"role:other_role", "data/collections/.*/shards/.*/objects/.*", " R", "data"},
142
+ },
143
+ },
144
+ }
145
+ for _, tt := range tests {
146
+ t.Run(tt.name, func(t *testing.T) {
147
+ path := t.TempDir()
148
+ tmpFile, err := os.CreateTemp(path, "upgrade-temp-*.tmp")
149
+ require.NoError(t, err)
150
+
151
+ writer := bufio.NewWriter(tmpFile)
152
+ for _, line := range tt.lines {
153
+ _, err := fmt.Fprintln(writer, line)
154
+ require.NoError(t, err)
155
+ }
156
+ require.NoError(t, writer.Flush())
157
+ require.NoError(t, tmpFile.Sync())
158
+ require.NoError(t, tmpFile.Close())
159
+
160
+ m, err := model.NewModelFromString(MODEL)
161
+ require.NoError(t, err)
162
+
163
+ enforcer, err := casbin.NewSyncedCachedEnforcer(m)
164
+ require.NoError(t, err)
165
+ enforcer.SetAdapter(fileadapter.NewAdapter(tmpFile.Name()))
166
+ require.NoError(t, enforcer.LoadPolicy())
167
+
168
+ require.NoError(t, upgradePoliciesFrom129(enforcer, false))
169
+ policies, _ := enforcer.GetPolicy()
170
+ require.Len(t, policies, len(tt.expectedPolicies))
171
+ for i, policy := range tt.expectedPolicies {
172
+ require.Equal(t, tt.expectedPolicies[i], policy)
173
+ }
174
+ })
175
+ }
176
+ }
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/chunk-1.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c9c7916275093514a2ff0552f86b7bf975ad8e5a13ad27aece239a28dcc7fac
3
+ size 404
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX.hnsw.commitlog.d/1689867524 ADDED
Binary file (73 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX.indexcount ADDED
Binary file (8 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX.proplengths ADDED
@@ -0,0 +1 @@
 
 
1
+ {"BucketedData":{"title":{"7":2},"title2":{"7":2}},"SumData":{"title":16,"title2":16},"CountData":{"title":2,"title2":2}}
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX.version ADDED
Binary file (2 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/dimensions/segment-1689867627555054000.bloom ADDED
Binary file (36 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/dimensions/segment-1689867627555054000.db ADDED
Binary file (114 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/objects/segment-1689867627551445000.bloom ADDED
Binary file (36 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/objects/segment-1689867627551445000.cna ADDED
Binary file (12 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/objects/segment-1689867627551445000.db ADDED
Binary file (6.87 kB). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/objects/segment-1689867627551445000.secondary.0.bloom ADDED
Binary file (36 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property__id/segment-1689867627561328000.bloom ADDED
Binary file (36 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property__id/segment-1689867627561328000.db ADDED
Binary file (290 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title/segment-1689867627559163000.bloom ADDED
Binary file (52 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title/segment-1689867627559163000.db ADDED
Binary file (2.99 kB). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title2/segment-1689867627557281000.bloom ADDED
Binary file (52 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title2/segment-1689867627557281000.db ADDED
Binary file (2.99 kB). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title2_searchable/segment-1689867627564376000.bloom ADDED
Binary file (52 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title2_searchable/segment-1689867627564376000.db ADDED
Binary file (1.15 kB). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title_searchable/segment-1689867627563072000.bloom ADDED
Binary file (52 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_cT9eTErXgmTX_lsm/property_title_searchable/segment-1689867627563072000.db ADDED
Binary file (1.15 kB). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO.hnsw.commitlog.d/1689867524 ADDED
Binary file (22 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO.indexcount ADDED
Binary file (8 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO.proplengths ADDED
@@ -0,0 +1 @@
 
 
1
+ {"BucketedData":{"title":{"7":1},"title2":{"7":1}},"SumData":{"title":8,"title2":8},"CountData":{"title":1,"title2":1}}
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO.version ADDED
Binary file (2 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/dimensions/segment-1689867537919947000.bloom ADDED
Binary file (36 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/dimensions/segment-1689867537919947000.db ADDED
Binary file (93 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/objects/segment-1689867537919476000.bloom ADDED
Binary file (36 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/objects/segment-1689867537919476000.cna ADDED
Binary file (12 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/objects/segment-1689867537919476000.db ADDED
Binary file (3.44 kB). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/objects/segment-1689867537919476000.secondary.0.bloom ADDED
Binary file (36 Bytes). View file
 
platform/dbops/binaries/weaviate-src/usecases/backup/test_data/node1/article_uq5WKfRlq2mO_lsm/property__id/segment-1689867537919986000.bloom ADDED
Binary file (36 Bytes). View file