ADAPT-Chase commited on
Commit
713a83b
·
verified ·
1 Parent(s): c7d8ce7

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/conftest.py +93 -0
  2. platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_batch_grpc.py +49 -0
  3. platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_casing.py +61 -0
  4. platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_db_users.py +157 -0
  5. platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_object_endpoint.py +353 -0
  6. platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_rbac_refs.py +425 -0
  7. platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_rbac_search_grpc.py +68 -0
  8. platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_roles.py +33 -0
  9. platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_schema.py +210 -0
  10. platform/dbops/binaries/weaviate-src/test/benchmark/remote/README.md +52 -0
  11. platform/dbops/binaries/weaviate-src/test/benchmark/remote/run.sh +156 -0
  12. platform/dbops/binaries/weaviate-src/test/benchmark/remote/terraform/.gitignore +9 -0
  13. platform/dbops/binaries/weaviate-src/test/benchmark/remote/terraform/main.tf +3 -0
  14. platform/dbops/binaries/weaviate-src/test/benchmark/remote/terraform/variables.tf +4 -0
  15. platform/dbops/binaries/weaviate-src/test/benchmark/remote/terraform/vm.tf +23 -0
  16. platform/dbops/binaries/weaviate-src/test/benchmark_bm25/cmd/import.go +247 -0
  17. platform/dbops/binaries/weaviate-src/test/benchmark_bm25/cmd/query.go +288 -0
  18. platform/dbops/binaries/weaviate-src/test/benchmark_bm25/cmd/root.go +72 -0
  19. platform/dbops/binaries/weaviate-src/test/benchmark_bm25/lib/batch.go +43 -0
  20. platform/dbops/binaries/weaviate-src/test/benchmark_bm25/lib/client.go +34 -0
platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/conftest.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import (
2
+ Union,
3
+ Sequence,
4
+ Any,
5
+ ContextManager,
6
+ Protocol,
7
+ Iterator,
8
+ )
9
+
10
+ import pytest
11
+ import weaviate
12
+ import weaviate.classes as wvc
13
+ from _pytest.fixtures import SubRequest
14
+ from contextlib import contextmanager
15
+
16
+ from weaviate import WeaviateClient
17
+ from weaviate.rbac.models import PermissionsCreateType
18
+
19
+
20
+ def _sanitize_role_name(name: str) -> str:
21
+ return (
22
+ name.replace("[", "")
23
+ .replace("]", "")
24
+ .replace("-", "")
25
+ .replace(" ", "")
26
+ .replace(".", "")
27
+ .replace("{", "")
28
+ .replace("}", "")
29
+ )
30
+
31
+
32
+ def generate_missing_permissions(permissions: list):
33
+ result = []
34
+ for i in range(len(permissions)):
35
+ result.append(permissions[:i] + permissions[i + 1 :])
36
+ return result
37
+
38
+
39
+ class RoleWrapperProtocol(Protocol):
40
+ def __call__(
41
+ self,
42
+ admin_client: WeaviateClient,
43
+ request: SubRequest,
44
+ permissions: PermissionsCreateType,
45
+ user: str = "custom-user",
46
+ ) -> ContextManager[Any]: ...
47
+
48
+
49
+ @pytest.fixture
50
+ def role_wrapper() -> RoleWrapperProtocol:
51
+ def wrapper(
52
+ admin_client: WeaviateClient,
53
+ request: SubRequest,
54
+ permissions: PermissionsCreateType,
55
+ user: str = "custom-user",
56
+ ) -> Iterator[None]:
57
+ name = _sanitize_role_name(request.node.name) + "role"
58
+ admin_client.roles.delete(name)
59
+ if not isinstance(permissions, list) or len(permissions) > 0:
60
+ admin_client.roles.create(role_name=name, permissions=permissions)
61
+ admin_client.users.assign_roles(user_id=user, role_names=name)
62
+
63
+ yield
64
+
65
+ if not isinstance(permissions, list) or len(permissions) > 0:
66
+ admin_client.users.revoke_roles(user_id=user, role_names=name)
67
+ admin_client.roles.delete(name)
68
+
69
+ return contextmanager(wrapper)
70
+
71
+
72
+ @pytest.fixture
73
+ def admin_client():
74
+ with weaviate.connect_to_local(
75
+ port=8081, grpc_port=50052, auth_credentials=wvc.init.Auth.api_key("admin-key")
76
+ ) as client:
77
+ yield client
78
+
79
+
80
+ @pytest.fixture
81
+ def custom_client():
82
+ with weaviate.connect_to_local(
83
+ port=8081, grpc_port=50052, auth_credentials=wvc.init.Auth.api_key("custom-key")
84
+ ) as client:
85
+ yield client
86
+
87
+
88
+ @pytest.fixture
89
+ def viewer_client():
90
+ with weaviate.connect_to_local(
91
+ port=8081, grpc_port=50052, auth_credentials=wvc.init.Auth.api_key("viewer-key")
92
+ ) as client:
93
+ yield client
platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_batch_grpc.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import weaviate
3
+ import weaviate.classes as wvc
4
+ from typing_extensions import Optional
5
+ from weaviate.rbac.models import Permissions
6
+ from _pytest.fixtures import SubRequest
7
+ from .conftest import _sanitize_role_name, generate_missing_permissions, RoleWrapperProtocol
8
+
9
+ pytestmark = pytest.mark.xdist_group(name="rbac")
10
+
11
+
12
+ @pytest.mark.parametrize("mt", [True, False])
13
+ def test_batch_grpc(
14
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
15
+ ):
16
+ name = _sanitize_role_name(request.node.name)
17
+ admin_client.collections.delete([name + "1", name + "2"])
18
+
19
+ col1 = admin_client.collections.create(
20
+ name=name + "1", multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
21
+ )
22
+ col2 = admin_client.collections.create(
23
+ name=name + "2", multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
24
+ )
25
+ tenant: Optional[str] = None
26
+ if mt:
27
+ tenant = "tenant1"
28
+ col1.tenants.create(tenant)
29
+ col2.tenants.create(tenant)
30
+ admin_client.roles.delete(name)
31
+
32
+ required_permissions = [
33
+ Permissions.data(collection=col1.name, create=True, update=True),
34
+ Permissions.data(collection=col2.name, create=True, update=True),
35
+ ]
36
+ with role_wrapper(admin_client, request, required_permissions):
37
+ with custom_client.batch.fixed_size() as batch:
38
+ batch.add_object(collection=col1.name, properties={}, tenant=tenant)
39
+ batch.add_object(collection=col2.name, properties={}, tenant=tenant)
40
+ assert len(custom_client.batch.failed_objects) == 0
41
+
42
+ for permission in generate_missing_permissions(required_permissions):
43
+ with role_wrapper(admin_client, request, permission):
44
+ with custom_client.batch.fixed_size() as batch:
45
+ batch.add_object(collection=col1.name, properties={}, tenant=tenant)
46
+ batch.add_object(collection=col2.name, properties={}, tenant=tenant)
47
+ # only one permission is missing, so one object will fail
48
+ assert len(custom_client.batch.failed_objects) == 1
49
+ admin_client.collections.delete([name + "1", name + "2"])
platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_casing.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import weaviate
3
+ import weaviate.classes as wvc
4
+ from weaviate.rbac.models import Permissions
5
+
6
+ from .conftest import _sanitize_role_name
7
+ from _pytest.fixtures import SubRequest
8
+
9
+ pytestmark = pytest.mark.xdist_group(name="rbac")
10
+
11
+
12
+ @pytest.mark.parametrize("to_upper", [True, False])
13
+ def test_rbac_refs(request: SubRequest, admin_client, custom_client, to_upper: bool):
14
+ name = _sanitize_role_name(request.node.name)
15
+ if to_upper:
16
+ name = name[0].upper() + name[1:]
17
+ admin_client.collections.delete(name)
18
+ admin_client.roles.delete(name)
19
+ collection = admin_client.collections.create(name=name)
20
+
21
+ admin_client.roles.create(
22
+ role_name=name,
23
+ permissions=[
24
+ Permissions.collections(collection=name, read_config=True),
25
+ Permissions.data(collection=name, read=True),
26
+ ],
27
+ )
28
+ admin_client.users.assign_roles(user_id="custom-user", role_names=name)
29
+ collection_no_rights = custom_client.collections.get(collection.name)
30
+ collection_no_rights.query.fetch_objects()
31
+
32
+ admin_client.users.revoke_roles(user_id="custom-user", role_names=name)
33
+ admin_client.roles.delete(name)
34
+
35
+ admin_client.collections.delete(name)
36
+
37
+
38
+ def test_role_name_case_sensitivity(request: SubRequest, admin_client):
39
+ col_name = _sanitize_role_name(request.node.name)
40
+ l_name = _sanitize_role_name(request.node.name)
41
+ u_name = l_name[0].upper() + l_name[1:]
42
+
43
+ admin_client.collections.delete(col_name)
44
+ admin_client.roles.delete(l_name)
45
+ admin_client.roles.delete(u_name)
46
+
47
+ admin_client.roles.create(
48
+ role_name=l_name, permissions=Permissions.collections(collection="lower", read_config=True)
49
+ )
50
+
51
+ admin_client.roles.create(
52
+ role_name=u_name, permissions=Permissions.collections(collection="upper", read_config=True)
53
+ )
54
+
55
+ admin_client.users.assign_roles(user_id="custom-user", role_names=[l_name, u_name])
56
+
57
+ roles = admin_client.users.get_assigned_roles("custom-user")
58
+ assert sorted(roles.keys()) == sorted([l_name, u_name])
59
+
60
+ admin_client.roles.delete(l_name)
61
+ admin_client.roles.delete(u_name)
platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_db_users.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import weaviate
3
+ import weaviate.classes as wvc
4
+ from weaviate.exceptions import UnexpectedStatusCodeError
5
+ from weaviate.rbac.models import Permissions
6
+ from _pytest.fixtures import SubRequest
7
+ from .conftest import _sanitize_role_name
8
+
9
+ pytestmark = pytest.mark.xdist_group(name="rbac")
10
+
11
+
12
+ def test_db_user_create_collection(request: SubRequest, admin_client):
13
+ admin_client.users.db.delete(user_id="test-user")
14
+ api_key = admin_client.users.db.create(user_id="test-user")
15
+
16
+ admin_client.users.db.assign_roles(user_id="test-user", role_names="admin")
17
+
18
+ collection_name = _sanitize_role_name(request.node.name) + "col"
19
+
20
+ # normal collection
21
+ with weaviate.connect_to_local(
22
+ port=8081, grpc_port=50052, auth_credentials=wvc.init.Auth.api_key(api_key)
23
+ ) as custom_client:
24
+ admin_client.collections.delete(collection_name)
25
+
26
+ collection = custom_client.collections.create(
27
+ collection_name,
28
+ properties=[wvc.config.Property(name="name", data_type=wvc.config.DataType.TEXT)],
29
+ )
30
+ uuid1 = collection.data.insert({"name": "testing"})
31
+
32
+ obj = collection.query.fetch_object_by_id(uuid1)
33
+ assert obj.properties["name"] == "testing"
34
+
35
+ assert collection.data.delete_by_id(uuid1)
36
+ assert collection.query.fetch_object_by_id(uuid1) is None
37
+
38
+ custom_client.collections.delete(collection_name)
39
+ assert not custom_client.collections.exists(collection_name)
40
+ admin_client.users.db.delete(user_id="test-user")
41
+
42
+
43
+ def test_db_user_multi_tenant(request: SubRequest, admin_client):
44
+ admin_client.users.db.delete(user_id="test-user")
45
+ api_key = admin_client.users.db.create(user_id="test-user")
46
+
47
+ admin_client.users.db.assign_roles(user_id="test-user", role_names="admin")
48
+
49
+ collection_name = _sanitize_role_name(request.node.name) + "col"
50
+ with weaviate.connect_to_local(
51
+ port=8081, grpc_port=50052, auth_credentials=wvc.init.Auth.api_key(api_key)
52
+ ) as custom_client:
53
+ admin_client.collections.delete(collection_name)
54
+
55
+ collection = custom_client.collections.create(
56
+ collection_name,
57
+ properties=[wvc.config.Property(name="name", data_type=wvc.config.DataType.TEXT)],
58
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=True),
59
+ )
60
+
61
+ collection.tenants.create(["tenant1", "tenant2", "tenant3"])
62
+ collection = collection.with_tenant("tenant1")
63
+
64
+ uuid1 = collection.data.insert({"name": "testing"})
65
+
66
+ obj = collection.query.fetch_object_by_id(uuid1)
67
+ assert obj.properties["name"] == "testing"
68
+
69
+ assert collection.data.delete_by_id(uuid1)
70
+ assert collection.query.fetch_object_by_id(uuid1) is None
71
+
72
+ # update tenant status to inactive and fail
73
+ collection.tenants.update(
74
+ wvc.tenants.TenantUpdate(
75
+ name="tenant2", activity_status=wvc.tenants.TenantUpdateActivityStatus.INACTIVE
76
+ )
77
+ )
78
+ collection = collection.with_tenant("tenant2")
79
+ with pytest.raises(UnexpectedStatusCodeError):
80
+ collection.data.insert({"name": "testing"})
81
+
82
+ custom_client.collections.delete(collection_name)
83
+ assert not custom_client.collections.exists(collection_name)
84
+ admin_client.users.db.delete(user_id="test-user")
85
+
86
+
87
+ def test_db_user_role_and_users(request: SubRequest, admin_client):
88
+ admin_client.users.db.delete(user_id="test-user")
89
+ admin_client.users.db.delete(user_id="second-user")
90
+ api_key = admin_client.users.db.create(user_id="test-user")
91
+
92
+ admin_client.users.db.assign_roles(user_id="test-user", role_names="admin")
93
+
94
+ collection_name = _sanitize_role_name(request.node.name) + "col"
95
+ role_name = _sanitize_role_name(request.node.name) + "role"
96
+ with weaviate.connect_to_local(
97
+ port=8081, grpc_port=50052, auth_credentials=wvc.init.Auth.api_key(api_key)
98
+ ) as custom_client:
99
+ admin_client.collections.delete(collection_name)
100
+ admin_client.roles.delete(role_name)
101
+ custom_client.roles.create(
102
+ role_name=role_name,
103
+ permissions=[
104
+ Permissions.data(collection=collection_name, read=True, create=True),
105
+ Permissions.collections(collection=collection_name, create_collection=True),
106
+ ],
107
+ )
108
+
109
+ second_api_key = custom_client.users.db.create(user_id="second-user")
110
+ with weaviate.connect_to_local(
111
+ port=8081, grpc_port=50052, auth_credentials=wvc.init.Auth.api_key(second_api_key)
112
+ ) as second_client:
113
+ # cannot create collection without permissions
114
+ with pytest.raises(UnexpectedStatusCodeError):
115
+ second_client.collections.create(collection_name)
116
+
117
+ custom_client.users.db.assign_roles(user_id="second-user", role_names=role_name)
118
+ second_client.collections.create(collection_name)
119
+ admin_client.users.db.delete(user_id="test-user")
120
+ admin_client.users.db.delete(user_id="second-user")
121
+ admin_client.collections.delete(collection_name)
122
+
123
+
124
+ def test_db_user_batch_import(request: SubRequest, admin_client):
125
+ admin_client.users.db.delete(user_id="test-user")
126
+ api_key = admin_client.users.db.create(user_id="test-user")
127
+
128
+ admin_client.users.db.assign_roles(user_id="test-user", role_names="admin")
129
+
130
+ collection_name = _sanitize_role_name(request.node.name) + "col"
131
+ with weaviate.connect_to_local(
132
+ port=8081, grpc_port=50052, auth_credentials=wvc.init.Auth.api_key(api_key)
133
+ ) as custom_client:
134
+ admin_client.collections.delete(collection_name)
135
+ collection = custom_client.collections.create(
136
+ collection_name,
137
+ properties=[
138
+ wvc.config.Property(name="name", data_type=wvc.config.DataType.TEXT),
139
+ wvc.config.Property(name="counter", data_type=wvc.config.DataType.INT),
140
+ ],
141
+ )
142
+ num_objects = 100
143
+ ret = collection.data.insert_many(
144
+ [{"name": "test" + str(i), "counter": i} for i in range(num_objects)]
145
+ )
146
+ assert len(collection) == num_objects
147
+ uuid_to_check = ret.uuids[25]
148
+ obj = collection.query.fetch_object_by_id(uuid_to_check)
149
+ assert obj.properties["name"] == "test" + str(25)
150
+
151
+ assert collection.data.delete_by_id(uuid_to_check)
152
+ assert collection.query.fetch_object_by_id(uuid_to_check) is None
153
+ assert len(collection) == num_objects - 1
154
+
155
+ custom_client.collections.delete(collection_name)
156
+ assert not custom_client.collections.exists(collection_name)
157
+ admin_client.users.db.delete(user_id="test-user")
platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_object_endpoint.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import weaviate
3
+ import weaviate.classes as wvc
4
+ from weaviate.rbac.models import Permissions
5
+ from _pytest.fixtures import SubRequest
6
+ from .conftest import _sanitize_role_name, RoleWrapperProtocol, generate_missing_permissions
7
+
8
+ pytestmark = pytest.mark.xdist_group(name="rbac")
9
+
10
+
11
+ @pytest.mark.parametrize("mt", [True, False])
12
+ def test_obj_insert(
13
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
14
+ ):
15
+ name = _sanitize_role_name(request.node.name)
16
+ admin_client.collections.delete(name)
17
+ admin_client.roles.delete(name)
18
+ col = admin_client.collections.create(
19
+ name=name, multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
20
+ )
21
+ if mt:
22
+ col.tenants.create("tenant1")
23
+
24
+ required_permissions = [
25
+ Permissions.data(collection=col.name, create=True),
26
+ ]
27
+ with role_wrapper(admin_client, request, required_permissions):
28
+ source_no_rights = custom_client.collections.get(name) # no network call => no RBAC check
29
+ if mt:
30
+ source_no_rights = source_no_rights.with_tenant("tenant1")
31
+ source_no_rights.data.insert({})
32
+
33
+ for permission in generate_missing_permissions(required_permissions):
34
+ with role_wrapper(admin_client, request, permission):
35
+ source_no_rights = custom_client.collections.get(
36
+ name
37
+ ) # no network call => no RBAC check
38
+ if mt:
39
+ source_no_rights = source_no_rights.with_tenant("tenant1")
40
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
41
+ source_no_rights.data.insert({})
42
+ assert e.value.status_code == 403
43
+ admin_client.collections.delete(name)
44
+
45
+
46
+ @pytest.mark.parametrize("mt", [True, False])
47
+ def test_obj_insert_ref(
48
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
49
+ ):
50
+ name = _sanitize_role_name(request.node.name)
51
+ admin_client.collections.delete([name + "source", name + "target"])
52
+ admin_client.roles.delete(name)
53
+ target = admin_client.collections.create(
54
+ name=name + "target", multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
55
+ )
56
+ source = admin_client.collections.create(
57
+ name=name + "source",
58
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
59
+ references=[wvc.config.ReferenceProperty(name="ref", target_collection=target.name)],
60
+ )
61
+
62
+ if mt:
63
+ source.tenants.create("tenant1")
64
+ target.tenants.create("tenant1")
65
+ target = target.with_tenant("tenant1")
66
+
67
+ uuid_target = target.data.insert({})
68
+
69
+ required_permissions = [
70
+ Permissions.data(collection=source.name, create=True),
71
+ ]
72
+ with role_wrapper(admin_client, request, required_permissions):
73
+ source_no_rights = custom_client.collections.get(
74
+ source.name
75
+ ) # no network call => no RBAC check
76
+ if mt:
77
+ source_no_rights = source_no_rights.with_tenant("tenant1")
78
+ source_no_rights.data.insert(properties={}, references={"ref": uuid_target})
79
+
80
+ for permission in generate_missing_permissions(required_permissions):
81
+ with role_wrapper(admin_client, request, permission):
82
+ source_no_rights = custom_client.collections.get(
83
+ source.name
84
+ ) # no network call => no RBAC check
85
+ if mt:
86
+ source_no_rights = source_no_rights.with_tenant("tenant1")
87
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
88
+ source_no_rights.data.insert(properties={}, references={"ref": uuid_target})
89
+ assert e.value.status_code == 403
90
+ admin_client.collections.delete(name)
91
+
92
+
93
+ @pytest.mark.parametrize("mt", [True, False])
94
+ def test_obj_replace(
95
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
96
+ ):
97
+ name = _sanitize_role_name(request.node.name)
98
+ admin_client.collections.delete(name)
99
+ admin_client.roles.delete(name)
100
+ col = admin_client.collections.create(
101
+ name=name, multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
102
+ )
103
+ if mt:
104
+ col.tenants.create("tenant1")
105
+ col = col.with_tenant("tenant1")
106
+
107
+ uuid_to_replace = col.data.insert({})
108
+
109
+ required_permissions = [
110
+ Permissions.data(collection=col.name, update=True),
111
+ ]
112
+ with role_wrapper(admin_client, request, required_permissions):
113
+ source_no_rights = custom_client.collections.get(name) # no network call => no RBAC check
114
+ if mt:
115
+ source_no_rights = source_no_rights.with_tenant("tenant1")
116
+ source_no_rights.data.replace(uuid=uuid_to_replace, properties={})
117
+
118
+ for permission in generate_missing_permissions(required_permissions):
119
+ with role_wrapper(admin_client, request, permission):
120
+ source_no_rights = custom_client.collections.get(
121
+ name
122
+ ) # no network call => no RBAC check
123
+ if mt:
124
+ source_no_rights = source_no_rights.with_tenant("tenant1")
125
+
126
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
127
+ source_no_rights.data.replace(uuid=uuid_to_replace, properties={})
128
+ assert e.value.status_code == 403
129
+ admin_client.collections.delete(name)
130
+
131
+
132
+ @pytest.mark.parametrize("mt", [True, False])
133
+ def test_obj_replace_ref(
134
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
135
+ ):
136
+ name = _sanitize_role_name(request.node.name)
137
+ admin_client.collections.delete([name + "source", name + "target"])
138
+ admin_client.roles.delete(name)
139
+ target = admin_client.collections.create(
140
+ name=name + "target", multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
141
+ )
142
+ source = admin_client.collections.create(
143
+ name=name + "source",
144
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
145
+ references=[wvc.config.ReferenceProperty(name="ref", target_collection=target.name)],
146
+ )
147
+
148
+ if mt:
149
+ source.tenants.create("tenant1")
150
+ target.tenants.create("tenant1")
151
+ source = source.with_tenant("tenant1")
152
+ target = target.with_tenant("tenant1")
153
+
154
+ uuid_target = target.data.insert({})
155
+ uuid_to_replace = source.data.insert({})
156
+
157
+ required_permissions = [
158
+ Permissions.data(collection=source.name, update=True),
159
+ ]
160
+ with role_wrapper(admin_client, request, required_permissions):
161
+ source_no_rights = custom_client.collections.get(
162
+ source.name
163
+ ) # no network call => no RBAC check
164
+ if mt:
165
+ source_no_rights = source_no_rights.with_tenant("tenant1")
166
+ source_no_rights.data.replace(
167
+ uuid=uuid_to_replace, properties={}, references={"ref": uuid_target}
168
+ )
169
+
170
+ for permission in generate_missing_permissions(required_permissions):
171
+ with role_wrapper(admin_client, request, permission):
172
+ source_no_rights = custom_client.collections.get(
173
+ source.name
174
+ ) # no network call => no RBAC check
175
+ if mt:
176
+ source_no_rights = source_no_rights.with_tenant("tenant1")
177
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
178
+ source_no_rights.data.replace(
179
+ uuid=uuid_to_replace, properties={}, references={"ref": uuid_target}
180
+ )
181
+ assert e.value.status_code == 403
182
+ admin_client.collections.delete(name)
183
+
184
+
185
+ @pytest.mark.parametrize("mt", [True, False])
186
+ def test_obj_update(
187
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
188
+ ):
189
+ name = _sanitize_role_name(request.node.name)
190
+ admin_client.collections.delete(name)
191
+ admin_client.roles.delete(name)
192
+ col = admin_client.collections.create(
193
+ name=name, multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
194
+ )
195
+ if mt:
196
+ col.tenants.create("tenant1")
197
+ col = col.with_tenant("tenant1")
198
+
199
+ uuid_to_replace = col.data.insert({})
200
+
201
+ required_permissions = [
202
+ Permissions.data(collection=col.name, update=True),
203
+ ]
204
+ with role_wrapper(admin_client, request, required_permissions):
205
+ source_no_rights = custom_client.collections.get(name) # no network call => no RBAC check
206
+ if mt:
207
+ source_no_rights = source_no_rights.with_tenant("tenant1")
208
+ source_no_rights.data.update(uuid=uuid_to_replace, properties={})
209
+
210
+ for permission in generate_missing_permissions(required_permissions):
211
+ with role_wrapper(admin_client, request, permission):
212
+ source_no_rights = custom_client.collections.get(
213
+ name
214
+ ) # no network call => no RBAC check
215
+ if mt:
216
+ source_no_rights = source_no_rights.with_tenant("tenant1")
217
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
218
+ source_no_rights.data.update(uuid=uuid_to_replace, properties={})
219
+ assert e.value.status_code == 403
220
+ admin_client.collections.delete(name)
221
+
222
+
223
+ @pytest.mark.parametrize("mt", [True, False])
224
+ def test_obj_update_ref(
225
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
226
+ ):
227
+ name = _sanitize_role_name(request.node.name)
228
+ admin_client.collections.delete([name + "source", name + "target"])
229
+ admin_client.roles.delete(name)
230
+ target = admin_client.collections.create(
231
+ name=name + "target", multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
232
+ )
233
+ source = admin_client.collections.create(
234
+ name=name + "source",
235
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
236
+ references=[wvc.config.ReferenceProperty(name="ref", target_collection=target.name)],
237
+ )
238
+
239
+ if mt:
240
+ source.tenants.create("tenant1")
241
+ target.tenants.create("tenant1")
242
+ source = source.with_tenant("tenant1")
243
+ target = target.with_tenant("tenant1")
244
+
245
+ uuid_target = target.data.insert({})
246
+ uuid_to_replace = source.data.insert({})
247
+
248
+ required_permissions = [
249
+ Permissions.data(collection=source.name, update=True),
250
+ ]
251
+ with role_wrapper(admin_client, request, required_permissions):
252
+ source_no_rights = custom_client.collections.get(
253
+ source.name
254
+ ) # no network call => no RBAC check
255
+ if mt:
256
+ source_no_rights = source_no_rights.with_tenant("tenant1")
257
+ source_no_rights.data.update(
258
+ uuid=uuid_to_replace, properties={}, references={"ref": uuid_target}
259
+ )
260
+
261
+ for permission in generate_missing_permissions(required_permissions):
262
+ with role_wrapper(admin_client, request, permission):
263
+ source_no_rights = custom_client.collections.get(
264
+ source.name
265
+ ) # no network call => no RBAC check
266
+ if mt:
267
+ source_no_rights = source_no_rights.with_tenant("tenant1")
268
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
269
+ source_no_rights.data.update(
270
+ uuid=uuid_to_replace, properties={}, references={"ref": uuid_target}
271
+ )
272
+ assert e.value.status_code == 403
273
+ admin_client.collections.delete(name)
274
+
275
+
276
+ @pytest.mark.parametrize("mt", [True, False])
277
+ def test_obj_delete(
278
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
279
+ ):
280
+ name = _sanitize_role_name(request.node.name)
281
+ admin_client.collections.delete(name)
282
+ admin_client.roles.delete(name)
283
+ col = admin_client.collections.create(
284
+ name=name, multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
285
+ )
286
+ if mt:
287
+ col.tenants.create("tenant1")
288
+ col = col.with_tenant("tenant1")
289
+
290
+ uuid_to_delete = col.data.insert({})
291
+
292
+ required_permissions = [
293
+ Permissions.data(collection=col.name, delete=True),
294
+ ]
295
+ with role_wrapper(admin_client, request, required_permissions):
296
+ col_no_rights = custom_client.collections.get(name) # no network call => no RBAC check
297
+ if mt:
298
+ col_no_rights = col_no_rights.with_tenant("tenant1")
299
+ assert len(col) == 1
300
+ col_no_rights.data.delete_by_id(uuid=uuid_to_delete)
301
+ assert len(col) == 0
302
+
303
+ uuid_to_delete = col.data.insert({})
304
+ for permission in generate_missing_permissions(required_permissions):
305
+ with role_wrapper(admin_client, request, permission):
306
+ col_no_rights = custom_client.collections.get(name) # no network call => no RBAC check
307
+ if mt:
308
+ col_no_rights = col_no_rights.with_tenant("tenant1")
309
+
310
+ assert len(col) == 1
311
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
312
+ col_no_rights.data.delete_by_id(uuid=uuid_to_delete)
313
+ assert e.value.status_code == 403
314
+ assert len(col) == 1
315
+ admin_client.collections.delete(name)
316
+
317
+
318
+ @pytest.mark.parametrize("mt", [True, False])
319
+ def test_obj_exists(
320
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
321
+ ):
322
+ name = _sanitize_role_name(request.node.name)
323
+ admin_client.collections.delete(name)
324
+ admin_client.roles.delete(name)
325
+ col = admin_client.collections.create(
326
+ name=name, multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
327
+ )
328
+ if mt:
329
+ col.tenants.create("tenant1")
330
+ col = col.with_tenant("tenant1")
331
+
332
+ uuid_to_check = col.data.insert({})
333
+
334
+ required_permissions = [
335
+ Permissions.data(collection=col.name, read=True),
336
+ ]
337
+ with role_wrapper(admin_client, request, required_permissions):
338
+ col_no_rights = custom_client.collections.get(name) # no network call => no RBAC check
339
+ if mt:
340
+ col_no_rights = col_no_rights.with_tenant("tenant1")
341
+ assert col_no_rights.data.exists(uuid=uuid_to_check)
342
+
343
+ for permission in generate_missing_permissions(required_permissions):
344
+ with role_wrapper(admin_client, request, permission):
345
+
346
+ col_no_rights = custom_client.collections.get(name) # no network call => no RBAC check
347
+ if mt:
348
+ col_no_rights = col_no_rights.with_tenant("tenant1")
349
+
350
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
351
+ col_no_rights.data.exists(uuid=uuid_to_check)
352
+ assert e.value.status_code == 403
353
+ admin_client.collections.delete(name)
platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_rbac_refs.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+
3
+ import pytest
4
+ import weaviate
5
+ import weaviate.classes as wvc
6
+ from _pytest.fixtures import SubRequest
7
+ from weaviate.collections.classes.data import DataReference
8
+ from weaviate.rbac.models import Permissions
9
+ from weaviate.rbac.roles import _flatten_permissions
10
+
11
+ from .conftest import _sanitize_role_name, generate_missing_permissions, RoleWrapperProtocol
12
+
13
+ pytestmark = pytest.mark.xdist_group(name="rbac")
14
+
15
+
16
+ @pytest.mark.parametrize("mt", [True, False])
17
+ def test_rbac_refs(
18
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
19
+ ):
20
+ col_name = _sanitize_role_name(request.node.name)
21
+ admin_client.collections.delete([col_name + "target", col_name + "source"])
22
+ # create two collections with some objects to test refs
23
+ target = admin_client.collections.create(
24
+ name=col_name + "target",
25
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
26
+ )
27
+ source = admin_client.collections.create(
28
+ name=col_name + "source",
29
+ references=[wvc.config.ReferenceProperty(name="ref", target_collection=target.name)],
30
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
31
+ )
32
+ if mt:
33
+ target.tenants.create("tenant1")
34
+ source.tenants.create("tenant1")
35
+ target = target.with_tenant("tenant1")
36
+ source = source.with_tenant("tenant1")
37
+
38
+ uuid_target1 = target.data.insert({})
39
+ uuid_target2 = target.data.insert({})
40
+ uuid_source = source.data.insert(properties={})
41
+ role_name = _sanitize_role_name(request.node.name)
42
+ admin_client.roles.delete(role_name)
43
+
44
+ required_permissions = [
45
+ Permissions.collections(collection=[source.name, target.name], read_config=True),
46
+ Permissions.data(collection=[source.name, target.name], update=True, read=True),
47
+ ]
48
+ with role_wrapper(admin_client, request, required_permissions):
49
+ source_no_rights = custom_client.collections.get(
50
+ source.name
51
+ ) # no network call => no RBAC check
52
+ if mt:
53
+ source_no_rights = source_no_rights.with_tenant("tenant1")
54
+
55
+ source_no_rights.data.reference_add(
56
+ from_uuid=uuid_source,
57
+ from_property="ref",
58
+ to=uuid_target1,
59
+ )
60
+
61
+ source_no_rights.data.reference_replace(
62
+ from_uuid=uuid_source,
63
+ from_property="ref",
64
+ to=uuid_target2,
65
+ )
66
+
67
+ source_no_rights.data.reference_delete(
68
+ from_uuid=uuid_source,
69
+ from_property="ref",
70
+ to=uuid_target2,
71
+ )
72
+
73
+ for permission in generate_missing_permissions(required_permissions):
74
+ with role_wrapper(admin_client, request, permission):
75
+ source_no_rights = custom_client.collections.get(
76
+ source.name
77
+ ) # no network call => no RBAC check
78
+ if mt:
79
+ source_no_rights = source_no_rights.with_tenant("tenant1")
80
+
81
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
82
+ source_no_rights.data.reference_add(
83
+ from_uuid=uuid_source,
84
+ from_property="ref",
85
+ to=uuid_target1,
86
+ )
87
+ assert e.value.status_code == 403
88
+
89
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
90
+ source_no_rights.data.reference_replace(
91
+ from_uuid=uuid_source,
92
+ from_property="ref",
93
+ to=uuid_target2,
94
+ )
95
+ assert e.value.status_code == 403
96
+
97
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
98
+ source_no_rights.data.reference_delete(
99
+ from_uuid=uuid_source,
100
+ from_property="ref",
101
+ to=uuid_target1,
102
+ )
103
+ assert e.value.status_code == 403
104
+
105
+ admin_client.collections.delete([target.name, source.name])
106
+
107
+
108
+ @pytest.mark.parametrize("mt", [True, False])
109
+ def test_batch_delete_with_filter(
110
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
111
+ ) -> None:
112
+ col_name = _sanitize_role_name(request.node.name)
113
+
114
+ admin_client.collections.delete([col_name + "target", col_name + "source"])
115
+ # create two collections with some objects to test refs
116
+ target = admin_client.collections.create(
117
+ name=col_name + "target",
118
+ properties=[wvc.config.Property(name="prop", data_type=wvc.config.DataType.TEXT)],
119
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
120
+ )
121
+ source = admin_client.collections.create(
122
+ name=col_name + "source",
123
+ references=[wvc.config.ReferenceProperty(name="ref", target_collection=target.name)],
124
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
125
+ )
126
+ if mt:
127
+ target.tenants.create("tenant1")
128
+ source.tenants.create("tenant1")
129
+ target = target.with_tenant("tenant1")
130
+ source = source.with_tenant("tenant1")
131
+
132
+ uuid_target1 = target.data.insert({})
133
+
134
+ role_name = _sanitize_role_name(request.node.name)
135
+ admin_client.roles.delete(role_name)
136
+
137
+ uuid_source = source.data.insert(properties={}, references={"ref": uuid_target1})
138
+ source.data.reference_add(
139
+ from_uuid=uuid_source,
140
+ from_property="ref",
141
+ to=uuid_target1,
142
+ )
143
+
144
+ required_permissions = [
145
+ Permissions.data(collection=source.name, delete=True, read=True),
146
+ Permissions.data(collection=target.name, read=True),
147
+ ]
148
+
149
+ # failing permissions first, so the object isn't actually deleted
150
+ for permission in generate_missing_permissions(required_permissions):
151
+ with role_wrapper(admin_client, request, permission):
152
+ assert (
153
+ len(source) == 1
154
+ ) # uses aggregate in background, cannot do that with restricted user
155
+
156
+ source_no_rights = custom_client.collections.get(
157
+ source.name
158
+ ) # no network call => no RBAC check
159
+ if mt:
160
+ source_no_rights = source_no_rights.with_tenant("tenant1")
161
+
162
+ # deletion does not work
163
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
164
+ source_no_rights.data.delete_many(
165
+ where=wvc.query.Filter.by_ref("ref").by_id().equal(uuid_target1)
166
+ )
167
+ assert "forbidden" in e.value.args[0]
168
+ assert (
169
+ len(source) == 1
170
+ ) # uses aggregate in background, cannot do that with restricted user
171
+
172
+ with role_wrapper(admin_client, request, required_permissions):
173
+ assert len(source) == 1 # uses aggregate in background, cannot do that with restricted user
174
+
175
+ source_no_rights = custom_client.collections.get(
176
+ source.name
177
+ ) # no network call => no RBAC check
178
+ if mt:
179
+ source_no_rights = source_no_rights.with_tenant("tenant1")
180
+
181
+ ret = source_no_rights.data.delete_many(
182
+ where=wvc.query.Filter.by_ref("ref").by_id().equal(uuid_target1)
183
+ )
184
+ assert ret.successful == 1
185
+ assert len(source) == 0 # uses aggregate in background, cannot do that with restricted user
186
+
187
+ admin_client.collections.delete([target.name, source.name])
188
+
189
+
190
+ @pytest.mark.parametrize("mt", [True, False])
191
+ def test_search_with_filter_and_return(
192
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
193
+ ) -> None:
194
+ col_name = _sanitize_role_name(request.node.name)
195
+
196
+ admin_client.collections.delete([col_name + "target", col_name + "source"])
197
+ # create two collections with some objects to test refs
198
+ target = admin_client.collections.create(
199
+ name=col_name + "target",
200
+ properties=[wvc.config.Property(name="prop", data_type=wvc.config.DataType.TEXT)],
201
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
202
+ )
203
+ source = admin_client.collections.create(
204
+ name=col_name + "source",
205
+ references=[wvc.config.ReferenceProperty(name="ref", target_collection=target.name)],
206
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
207
+ )
208
+ if mt:
209
+ target.tenants.create("tenant1")
210
+ source.tenants.create("tenant1")
211
+ target = target.with_tenant("tenant1")
212
+ source = source.with_tenant("tenant1")
213
+
214
+ uuid_target1 = target.data.insert({"prop": "word"})
215
+ source.data.insert(properties={}, references={"ref": uuid_target1})
216
+
217
+ role_name = _sanitize_role_name(request.node.name)
218
+ admin_client.roles.delete(role_name)
219
+
220
+ required_permissions = [
221
+ Permissions.data(collection=[source.name], read=True),
222
+ Permissions.data(collection=[target.name], read=True),
223
+ ]
224
+ with role_wrapper(admin_client, request, required_permissions):
225
+ source_no_rights = custom_client.collections.get(
226
+ source.name
227
+ ) # no network call => no RBAC check
228
+ if mt:
229
+ source_no_rights = source_no_rights.with_tenant("tenant1")
230
+
231
+ ret_filter = source_no_rights.query.fetch_objects(
232
+ filters=wvc.query.Filter.by_ref("ref").by_id().equal(uuid_target1),
233
+ )
234
+ assert len(ret_filter.objects) == 1
235
+
236
+ ret_return = source_no_rights.query.fetch_objects(
237
+ return_references=wvc.query.QueryReference(
238
+ link_on="ref",
239
+ return_properties=["prop"],
240
+ ),
241
+ )
242
+ assert len(ret_return.objects[0].references["ref"].objects) == 1
243
+
244
+ for permission in generate_missing_permissions(required_permissions):
245
+ with role_wrapper(admin_client, request, permission):
246
+ source_no_rights = custom_client.collections.get(
247
+ source.name
248
+ ) # no network call => no RBAC check
249
+ if mt:
250
+ source_no_rights = source_no_rights.with_tenant("tenant1")
251
+
252
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
253
+ source_no_rights.query.fetch_objects(
254
+ filters=wvc.query.Filter.by_ref("ref").by_id().equal(uuid_target1)
255
+ )
256
+ assert "forbidden" in e.value.args[0]
257
+
258
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
259
+ source_no_rights.query.fetch_objects(
260
+ return_references=wvc.query.QueryReference(
261
+ link_on="ref",
262
+ return_properties=["prop"],
263
+ ),
264
+ )
265
+ assert "forbidden" in e.value.args[0]
266
+
267
+ admin_client.collections.delete([target.name, source.name])
268
+
269
+
270
+ @pytest.mark.parametrize("mt", [True, False])
271
+ def test_batch_ref(
272
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
273
+ ):
274
+ col_name = _sanitize_role_name(request.node.name)
275
+ admin_client.collections.delete(
276
+ [col_name + "target1", col_name + "target2", col_name + "source"]
277
+ )
278
+ # create two collections with some objects to test refs
279
+ target1 = admin_client.collections.create(
280
+ name=col_name + "target1",
281
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
282
+ )
283
+ target2 = admin_client.collections.create(
284
+ name=col_name + "target2",
285
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
286
+ )
287
+ source = admin_client.collections.create(
288
+ name=col_name + "source",
289
+ references=[
290
+ wvc.config.ReferenceProperty(name="ref1", target_collection=target1.name),
291
+ wvc.config.ReferenceProperty(name="ref2", target_collection=target2.name),
292
+ ],
293
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
294
+ )
295
+ if mt:
296
+ target1.tenants.create("tenant1")
297
+ target2.tenants.create("tenant1")
298
+ source.tenants.create("tenant1")
299
+ target1 = target1.with_tenant("tenant1")
300
+ target2 = target2.with_tenant("tenant1")
301
+ source = source.with_tenant("tenant1")
302
+
303
+ source.config.add_reference(
304
+ wvc.config.ReferenceProperty(name="self", target_collection=source.name)
305
+ )
306
+
307
+ uuid_target1 = target1.data.insert({})
308
+ uuid_target2 = target2.data.insert({})
309
+ uuid_source = source.data.insert(properties={})
310
+ role_name = _sanitize_role_name(request.node.name)
311
+ admin_client.roles.delete(role_name)
312
+
313
+ # self reference
314
+ required_permissions = [
315
+ Permissions.collections(collection=source.name, read_config=True),
316
+ Permissions.data(collection=source.name, read=True, update=True),
317
+ ]
318
+ with role_wrapper(admin_client, request, required_permissions):
319
+ source_no_rights = custom_client.collections.get(
320
+ source.name
321
+ ) # no network call => no RBAC check
322
+ if mt:
323
+ source_no_rights = source_no_rights.with_tenant("tenant1")
324
+
325
+ ret = source_no_rights.data.reference_add_many(
326
+ [DataReference(from_property="self", from_uuid=uuid_source, to_uuid=uuid_source)]
327
+ )
328
+ assert len(ret.errors) == 0
329
+
330
+ for permission in generate_missing_permissions(required_permissions):
331
+ with role_wrapper(admin_client, request, permission):
332
+ source_no_rights = custom_client.collections.get(
333
+ source.name
334
+ ) # no network call => no RBAC check
335
+ if mt:
336
+ source_no_rights = source_no_rights.with_tenant("tenant1")
337
+
338
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
339
+ source_no_rights.data.reference_add_many(
340
+ [
341
+ DataReference(
342
+ from_property="self", from_uuid=uuid_source, to_uuid=uuid_source
343
+ )
344
+ ]
345
+ )
346
+ assert e.value.status_code == 403
347
+
348
+ # ref to one target
349
+ required_permissions = [
350
+ Permissions.collections(collection=source.name, read_config=True),
351
+ Permissions.data(collection=[source.name, target1.name], read=True),
352
+ Permissions.data(collection=source.name, update=True),
353
+ Permissions.collections(collection=target1.name, read_config=True),
354
+ ]
355
+
356
+ with role_wrapper(admin_client, request, required_permissions):
357
+ source_no_rights = custom_client.collections.get(source.name)
358
+ if mt:
359
+ source_no_rights = source_no_rights.with_tenant("tenant1")
360
+
361
+ ret = source_no_rights.data.reference_add_many(
362
+ [
363
+ DataReference(from_property="self", from_uuid=uuid_source, to_uuid=uuid_source),
364
+ DataReference(from_property="ref1", from_uuid=uuid_source, to_uuid=uuid_target1),
365
+ ]
366
+ )
367
+ assert len(ret.errors) == 0
368
+
369
+ # without read permission for target that one reference fails
370
+ # no rights to read target class
371
+ with role_wrapper(admin_client, request, required_permissions[:-1]):
372
+ source_no_rights = custom_client.collections.get(source.name)
373
+ if mt:
374
+ source_no_rights = source_no_rights.with_tenant("tenant1")
375
+ ret = source_no_rights.data.reference_add_many(
376
+ [
377
+ DataReference(from_property="self", from_uuid=uuid_source, to_uuid=uuid_source),
378
+ DataReference(from_property="ref1", from_uuid=uuid_source, to_uuid=uuid_target1),
379
+ ]
380
+ )
381
+
382
+ assert len(ret.errors) == 1
383
+ assert "forbidden" in ret.errors[1].message
384
+
385
+ # ref to two targets
386
+ ref2_required_permissions = [
387
+ Permissions.collections(collection=[source.name, target1.name], read_config=True),
388
+ Permissions.data(collection=source.name, update=True),
389
+ Permissions.data(collection=[source.name, target1.name, target2.name], read=True),
390
+ Permissions.collections(collection=target2.name, read_config=True),
391
+ ]
392
+
393
+ with role_wrapper(admin_client, request, ref2_required_permissions):
394
+ source_no_rights = custom_client.collections.get(source.name)
395
+ if mt:
396
+ source_no_rights = source_no_rights.with_tenant("tenant1")
397
+ ret = source_no_rights.data.reference_add_many(
398
+ [
399
+ DataReference(from_property="self", from_uuid=uuid_source, to_uuid=uuid_source),
400
+ DataReference(from_property="ref1", from_uuid=uuid_source, to_uuid=uuid_target1),
401
+ DataReference(from_property="ref2", from_uuid=uuid_source, to_uuid=uuid_target2),
402
+ ]
403
+ )
404
+ assert len(ret.errors) == 0
405
+
406
+ # without read permission for target collection config, references TO that collection fail
407
+ with role_wrapper(admin_client, request, ref2_required_permissions[:-1]):
408
+ source_no_rights = custom_client.collections.get(source.name)
409
+ if mt:
410
+ source_no_rights = source_no_rights.with_tenant("tenant1")
411
+ ret = source_no_rights.data.reference_add_many(
412
+ [
413
+ DataReference(from_property="self", from_uuid=uuid_source, to_uuid=uuid_source),
414
+ DataReference(from_property="ref1", from_uuid=uuid_source, to_uuid=uuid_target1),
415
+ DataReference(from_property="ref2", from_uuid=uuid_source, to_uuid=uuid_target2),
416
+ ]
417
+ )
418
+
419
+ # only target where we miss permissions is failing
420
+ assert len(ret.errors) == 1
421
+ assert "forbidden" in ret.errors[2].message
422
+
423
+ admin_client.collections.delete(
424
+ [col_name + "target1", col_name + "target2", col_name + "source"]
425
+ )
platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_rbac_search_grpc.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import weaviate
3
+ import weaviate.classes as wvc
4
+ from weaviate.rbac.models import Permissions
5
+ from _pytest.fixtures import SubRequest
6
+ from .conftest import _sanitize_role_name, RoleWrapperProtocol, generate_missing_permissions
7
+
8
+ pytestmark = pytest.mark.xdist_group(name="rbac")
9
+
10
+
11
+ @pytest.mark.parametrize("mt", [True, False])
12
+ def test_rbac_search(
13
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol, mt: bool
14
+ ):
15
+ name_collection1 = _sanitize_role_name(request.node.name) + "col1"
16
+ name_collection2 = _sanitize_role_name(request.node.name) + "col2"
17
+ admin_client.collections.delete([name_collection1, name_collection2])
18
+ name_role = _sanitize_role_name(request.node.name) + "role"
19
+ admin_client.roles.delete(name_role)
20
+
21
+ col1 = admin_client.collections.create(
22
+ name=name_collection1, multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
23
+ )
24
+ col2 = admin_client.collections.create(
25
+ name=name_collection2, multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
26
+ )
27
+
28
+ if mt:
29
+ col1.tenants.create("tenant1")
30
+ col2.tenants.create("tenant1")
31
+ col1 = col1.with_tenant("tenant1")
32
+ col2 = col2.with_tenant("tenant1")
33
+
34
+ col1.data.insert({})
35
+ col2.data.insert({})
36
+
37
+ # with correct rights
38
+ required_permissions = [
39
+ Permissions.data(collection=col1.name, read=True),
40
+ ]
41
+ with role_wrapper(admin_client, request, required_permissions):
42
+ col_no_rights = custom_client.collections.get(col1.name) # no network call => no RBAC check
43
+ if mt:
44
+ col_no_rights = col_no_rights.with_tenant("tenant1")
45
+ res = col_no_rights.query.fetch_objects()
46
+ assert len(res.objects) == 1
47
+
48
+ for permission in generate_missing_permissions(required_permissions):
49
+ with role_wrapper(admin_client, request, permission):
50
+ col_no_rights = custom_client.collections.get(
51
+ col1.name
52
+ ) # no network call => no RBAC check
53
+ if mt:
54
+ col_no_rights = col_no_rights.with_tenant("tenant1")
55
+
56
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
57
+ col_no_rights.query.fetch_objects()
58
+ assert e.value.status_code == 7
59
+
60
+ # rights for wrong collection
61
+ wrong_collection = Permissions.collections(collection=col2.name, read_config=True)
62
+ with role_wrapper(admin_client, request, wrong_collection):
63
+ col_no_rights = custom_client.collections.get(col1.name) # no network call => no RBAC check
64
+ if mt:
65
+ col_no_rights = col_no_rights.with_tenant("tenant1")
66
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
67
+ col_no_rights.query.fetch_objects()
68
+ assert e.value.status_code == 7
platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_roles.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import weaviate
3
+ from _pytest.fixtures import SubRequest
4
+ from weaviate.rbac.models import Permissions
5
+
6
+ from .conftest import _sanitize_role_name, role_wrapper, RoleWrapperProtocol
7
+
8
+ pytestmark = pytest.mark.xdist_group(name="rbac")
9
+
10
+
11
+ def test_rbac_with_regexp(
12
+ request: SubRequest, admin_client, custom_client, role_wrapper: RoleWrapperProtocol
13
+ ):
14
+ name = _sanitize_role_name(request.node.name)
15
+ base = "python_"
16
+ python_name = base + name
17
+ admin_client.collections.delete([name, python_name])
18
+ admin_client.collections.create(name=name)
19
+ admin_client.collections.create(name=python_name)
20
+
21
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
22
+ custom_client.collections.delete(python_name)
23
+
24
+ # can delete everything starting with "python_" but nothing else
25
+ required_permissions = [
26
+ Permissions.collections(collection="*", read_config=True),
27
+ Permissions.collections(collection=base + "*", delete_collection=True),
28
+ ]
29
+ with role_wrapper(admin_client, request, required_permissions):
30
+ custom_client.collections.delete(python_name)
31
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
32
+ custom_client.collections.delete(name)
33
+ admin_client.collections.delete([name, python_name])
platform/dbops/binaries/weaviate-src/test/acceptance_with_python/rbac/test_schema.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import weaviate
3
+ import weaviate.classes as wvc
4
+ from weaviate.rbac.models import Permissions
5
+ from _pytest.fixtures import SubRequest
6
+ from .conftest import _sanitize_role_name, RoleWrapperProtocol, generate_missing_permissions
7
+
8
+ pytestmark = pytest.mark.xdist_group(name="rbac")
9
+
10
+
11
+ def test_rbac_collection_create(
12
+ admin_client, custom_client, role_wrapper: RoleWrapperProtocol, request: SubRequest
13
+ ):
14
+ name = _sanitize_role_name(request.node.name) + "col"
15
+ admin_client.collections.delete(name)
16
+ required_permissions = [
17
+ Permissions.collections(collection=name, read_config=True, create_collection=True),
18
+ ]
19
+ with role_wrapper(admin_client, request, required_permissions):
20
+ custom_client.collections.create(name=name)
21
+ admin_client.collections.delete(name)
22
+
23
+ for permission in generate_missing_permissions(required_permissions):
24
+ with role_wrapper(admin_client, request, permission):
25
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
26
+ custom_client.collections.create(name=name)
27
+ assert e.value.status_code == 403
28
+ assert "forbidden" in e.value.args[0]
29
+ admin_client.collections.delete(name)
30
+
31
+
32
+ @pytest.mark.parametrize("mt", [True, False])
33
+ def test_rbac_collection_create_with_ref(
34
+ admin_client, custom_client, role_wrapper: RoleWrapperProtocol, request: SubRequest, mt: bool
35
+ ):
36
+ name_target = _sanitize_role_name(request.node.name) + "target"
37
+ name_source = _sanitize_role_name(request.node.name) + "source"
38
+ admin_client.collections.delete([name_target, name_source])
39
+ target = admin_client.collections.create(
40
+ name=name_target, multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt)
41
+ )
42
+
43
+ required_permissions = [
44
+ Permissions.collections(collection=[name_source, target.name], read_config=True),
45
+ Permissions.collections(collection=name_source, create_collection=True),
46
+ ]
47
+ with role_wrapper(admin_client, request, required_permissions):
48
+ custom_client.collections.create(
49
+ name=name_source,
50
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
51
+ references=[wvc.config.ReferenceProperty(name="ref", target_collection=target.name)],
52
+ )
53
+
54
+ for permission in generate_missing_permissions(required_permissions):
55
+ with role_wrapper(admin_client, request, permission):
56
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
57
+ custom_client.collections.create(
58
+ name=name_source,
59
+ multi_tenancy_config=wvc.config.Configure.multi_tenancy(enabled=mt),
60
+ references=[
61
+ wvc.config.ReferenceProperty(name="ref", target_collection=target.name)
62
+ ],
63
+ )
64
+ assert e.value.status_code == 403
65
+ assert "forbidden" in e.value.args[0]
66
+
67
+ admin_client.collections.delete([name_target, name_source])
68
+
69
+
70
+ def test_rbac_collection_read(
71
+ admin_client, custom_client, role_wrapper: RoleWrapperProtocol, request: SubRequest
72
+ ):
73
+ name = _sanitize_role_name(request.node.name) + "col"
74
+ admin_client.collections.delete(name)
75
+ admin_client.collections.create(name=name)
76
+
77
+ required_permissions = Permissions.collections(collection=name, read_config=True)
78
+ with role_wrapper(admin_client, request, required_permissions):
79
+ col = custom_client.collections.get(name=name)
80
+ assert col.config.get() is not None
81
+
82
+ with role_wrapper(admin_client, request, []):
83
+ col = custom_client.collections.get(name=name)
84
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
85
+ col.config.get()
86
+ assert e.value.status_code == 403
87
+ assert "forbidden" in e.value.args[0]
88
+
89
+ admin_client.collections.delete(name)
90
+
91
+
92
+ def test_rbac_schema_read(
93
+ admin_client, custom_client, role_wrapper: RoleWrapperProtocol, request: SubRequest
94
+ ):
95
+ name = _sanitize_role_name(request.node.name) + "col"
96
+ admin_client.collections.delete(name)
97
+ admin_client.collections.create(name=name)
98
+
99
+ required_permission = Permissions.collections(collection="*", read_config=True)
100
+ with role_wrapper(admin_client, request, required_permission):
101
+ custom_client.collections.list_all()
102
+
103
+ with role_wrapper(admin_client, request, []):
104
+ collections = custom_client.collections.list_all()
105
+ assert len(collections) == 0
106
+
107
+ admin_client.collections.delete(name)
108
+
109
+ def test_rbac_schema_read_filtered_collections(
110
+ admin_client, custom_client, role_wrapper: RoleWrapperProtocol, request: SubRequest
111
+ ):
112
+ base_name = _sanitize_role_name(request.node.name)
113
+ allowed_collection = f"{base_name}_allowed"
114
+ restricted_collection = f"{base_name}_restricted"
115
+
116
+ for name in [allowed_collection, restricted_collection]:
117
+ admin_client.collections.delete(name)
118
+ admin_client.collections.create(name=name)
119
+
120
+
121
+ required_permission = Permissions.collections(collection=allowed_collection, read_config=True)
122
+ with role_wrapper(admin_client, request, required_permission):
123
+ collections = custom_client.collections.list_all()
124
+ collection_names = {name.lower() for name in collections.keys()}
125
+ assert len(collection_names) == 1
126
+ assert allowed_collection.lower() in collection_names
127
+ assert restricted_collection.lower() not in collection_names
128
+
129
+ admin_client.collections.delete(allowed_collection)
130
+ admin_client.collections.delete(restricted_collection)
131
+
132
+ def test_rbac_collection_update(
133
+ admin_client, custom_client, role_wrapper: RoleWrapperProtocol, request: SubRequest
134
+ ):
135
+ name = _sanitize_role_name(request.node.name) + "col"
136
+ admin_client.collections.delete(name)
137
+ admin_client.collections.create(name=name)
138
+
139
+ required_permissions = [
140
+ Permissions.collections(collection=name, read_config=True, update_config=True),
141
+ ]
142
+ with role_wrapper(admin_client, request, required_permissions):
143
+ col_custom = custom_client.collections.get(name)
144
+ col_custom.config.update(description="test")
145
+
146
+ for permission in generate_missing_permissions(required_permissions):
147
+ with role_wrapper(admin_client, request, permission):
148
+ col_custom = custom_client.collections.get(name)
149
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
150
+ col_custom.config.update(description="test")
151
+ assert e.value.status_code == 403
152
+ assert "forbidden" in e.value.args[0]
153
+
154
+ admin_client.collections.delete(name)
155
+
156
+
157
+ def test_rbac_collection_update_with_ref(
158
+ admin_client, custom_client, role_wrapper: RoleWrapperProtocol, request: SubRequest
159
+ ):
160
+ name_target = _sanitize_role_name(request.node.name) + "target"
161
+ name_source = _sanitize_role_name(request.node.name) + "source"
162
+ admin_client.collections.delete([name_target, name_source])
163
+ admin_client.collections.create(name=name_target)
164
+ admin_client.collections.create(name=name_source)
165
+
166
+ required_permissions = [
167
+ Permissions.collections(collection=[name_target, name_source], read_config=True),
168
+ Permissions.collections(collection=name_source, update_config=True),
169
+ ]
170
+ with role_wrapper(admin_client, request, required_permissions):
171
+ col_custom = custom_client.collections.get(name_source)
172
+ col_custom.config.add_reference(
173
+ wvc.config.ReferenceProperty(name="self1", target_collection=name_target)
174
+ )
175
+
176
+ for permission in generate_missing_permissions(required_permissions):
177
+ with role_wrapper(admin_client, request, permission):
178
+ col_custom = custom_client.collections.get(name_source)
179
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
180
+ col_custom.config.add_reference(
181
+ wvc.config.ReferenceProperty(name="self2", target_collection=name_target)
182
+ )
183
+ assert e.value.status_code == 403
184
+ assert "forbidden" in e.value.args[0]
185
+
186
+ admin_client.collections.delete([name_target, name_source])
187
+
188
+
189
+ def test_rbac_collection_delete(
190
+ admin_client, custom_client, role_wrapper: RoleWrapperProtocol, request: SubRequest
191
+ ):
192
+ name = _sanitize_role_name(request.node.name) + "col"
193
+ admin_client.collections.delete(name)
194
+
195
+ required_permissions = [
196
+ Permissions.collections(collection=name, delete_collection=True, read_config=True),
197
+ ]
198
+ for permission in generate_missing_permissions(required_permissions):
199
+ with role_wrapper(admin_client, request, permission):
200
+ with pytest.raises(weaviate.exceptions.InsufficientPermissionsError) as e:
201
+ custom_client.collections.delete(name)
202
+ assert e.value.status_code == 403
203
+ assert "forbidden" in e.value.args[0]
204
+ assert admin_client.collections.get(name) is not None
205
+
206
+ with role_wrapper(admin_client, request, required_permissions):
207
+ custom_client.collections.delete(name)
208
+ assert not admin_client.collections.exists(name)
209
+
210
+ admin_client.collections.delete(name)
platform/dbops/binaries/weaviate-src/test/benchmark/remote/README.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This folder contains scripts to help execute the benchmark remotely on a GCP
2
+ VM.
3
+
4
+ ## Requirements
5
+
6
+ - Bash
7
+ - gcloud (logged in and permissions to `semi-automated-benchmarking` project
8
+ - terraform
9
+
10
+ ## Usage
11
+
12
+ From the root folder run
13
+
14
+ ```
15
+ test/benchmark/remote/run.sh --all
16
+ ```
17
+
18
+ To run the whole benchmark suite. The `--all` command will:
19
+
20
+ - Check that `gcloud` and `terraform` are installed locally
21
+ - Spin up a machine in GCP
22
+ - Install the dependencies on this machine
23
+ - Clone Weaviate
24
+ - Check out the same commit that is check out locally
25
+ - Run the benchmarks script
26
+ - Copy the results file to the local machine
27
+ - Destroy the machine
28
+
29
+ If any of the command fails the machine will be destroyed.
30
+
31
+ ## Debugging
32
+
33
+ You can also run all commands individually, simply run the command without
34
+ parameters to list all possible options.
35
+
36
+ To do all steps (including spinning up a machine) that happen _before_ running
37
+ the benchmarks you can invoke it with the `--prepare` option. To get an
38
+ interactive ssh session into the machine, use `--ssh`. To destroy the machine
39
+ at an arbitrary point run `--delete_machine`.
40
+
41
+ ## Run on arbitrary branch
42
+
43
+ *Note: Checking out a branch that does not yet have the scripts from this
44
+ folder, will fail. You need a branch created after this script was initially
45
+ built or has been rebased on top of it.*
46
+
47
+ ```
48
+ test/benchmark/remote/run.sh --prepare
49
+ test/benchmark/remote/run.sh --checkout <name-of-your-branch-or-commit>
50
+ test/benchmark/remote/run.sh --benchmark
51
+ test/benchmark/remote/run.sh --delete_machine
52
+ ```
platform/dbops/binaries/weaviate-src/test/benchmark/remote/run.sh ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ PROJECT=semi-automated-benchmarking
4
+ ZONE=us-central1-a
5
+ INSTANCE=automated-loadtest
6
+ GOVERSION=https://go.dev/dl/go1.18.4.linux-amd64.tar.gz
7
+ FILE_PREFIX=${FILE_PREFIX:-""}
8
+
9
+ set -eou pipefail
10
+
11
+ # change to script directory
12
+ cd "${0%/*}" || exit
13
+
14
+ function main() {
15
+ while [[ "$#" -gt 0 ]]; do
16
+ case $1 in
17
+ --all) run_all; exit 0 ;;
18
+ --create_machine) create_machine; exit 0 ;;
19
+ --clone_repository) clone_repository; exit 0;;
20
+ --delete_machine) delete_machine; exit 0;;
21
+ --install_dependencies) install_dependencies; exit 0;;
22
+ --benchmark) benchmark; exit 0;;
23
+ --prepare) prepare; exit 0;;
24
+ --checkout) checkout "$2" ; exit 0;;
25
+ --ssh) interactive_ssh; exit 0;;
26
+ *) echo "Unknown parameter passed: $1"; exit 1 ;;
27
+ esac
28
+ shift
29
+ done
30
+
31
+ print_help
32
+ }
33
+
34
+ function print_help() {
35
+ echo "Valid arguments include:"
36
+ echo ""
37
+ echo " --all Run everything, including machine creation & destruction"
38
+ echo " --prepare Create Machine & run all the steps prior to benchmark execution"
39
+ echo " --create_machine Only create machine"
40
+ echo " --delete_machine Stop & Delete running machine"
41
+ echo " --clone_repository Clone and checkout Weaviate repo at specified commit"
42
+ echo " --checkout Checkout arbitrary branch or commit"
43
+ echo " --ssh Interactive SSH session"
44
+ }
45
+
46
+ function run_all() {
47
+ trap delete_machine EXIT
48
+
49
+ prepare
50
+ benchmark
51
+ }
52
+
53
+ function prepare() {
54
+ check
55
+ create_machine
56
+ install_dependencies
57
+ clone_repository
58
+ }
59
+
60
+ function check() {
61
+ echo_green "Checking required dependencies"
62
+ if ! command -v gcloud &> /dev/null
63
+ then
64
+ echo_red "Missing gcloud binary"
65
+ return 1
66
+ fi
67
+
68
+ if ! command -v terraform &> /dev/null
69
+ then
70
+ echo_red "Missing terraform binary"
71
+ return 1
72
+ fi
73
+
74
+ echo "Ready to go!"
75
+ }
76
+
77
+ function create_machine() {
78
+ (cd terraform && terraform init)
79
+ (cd terraform && terraform apply -auto-approve)
80
+ echo "Sleeping for 10s, so first ssh doesn't fail. This should be improved through polling"
81
+ sleep 10
82
+ }
83
+
84
+ function delete_machine() {
85
+ (cd terraform && terraform destroy -auto-approve)
86
+ }
87
+
88
+ function install_dependencies() {
89
+ ssh_command "sudo apt-get update && sudo apt-get install -y git git-lfs curl"
90
+ ssh_command "ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts"
91
+ install_go
92
+ install_docker
93
+ }
94
+
95
+ function install_go {
96
+ ssh_command "curl -Lo go.tar.gz $GOVERSION"
97
+ ssh_command "sudo rm -rf /usr/local/go && sudo tar -C /usr/local -xzf go.tar.gz"
98
+ ssh_command 'echo '"'"'PATH=$PATH:/usr/local/go/bin'"'"' >> ~/.profile'
99
+ ssh_command "go version"
100
+ }
101
+
102
+ function install_docker() {
103
+ ssh_command "if ! command -v docker &> /dev/null; then curl -fsSL https://get.docker.com -o get-docker.sh && sh ./get-docker.sh; fi"
104
+ ssh_command "sudo groupadd docker || true"
105
+ ssh_command "sudo usermod -aG docker $USER"
106
+ }
107
+
108
+ function clone_repository() {
109
+ ref=$(git rev-parse --abbrev-ref HEAD)
110
+ echo_green "Cloning weaviate repo to branch $ref"
111
+ ssh_command "cd; [ ! -d weaviate ] && git clone --depth 1 --branch $ref https://github.com/weaviate/weaviate.git weaviate || true"
112
+ ssh_command "cd weaviate; git-lfs install; git-lfs pull"
113
+ }
114
+
115
+ function checkout() {
116
+ ref="$1"
117
+ ssh_command "cd weaviate; git checkout $ref"
118
+ }
119
+
120
+ function benchmark() {
121
+ echo_green "Run benchmarks on remote machine"
122
+ ssh_command "echo "stop all running docker containers"; docker rm -f $(docker ps -q) || true"
123
+ ssh_command "cd ~/weaviate; rm test/benchmark/benchmark_results.json || true"
124
+ ssh_command "cd ~/weaviate; test/benchmark/run_performance_tracker.sh"
125
+ echo_green "Copy results file to local machine"
126
+ filename="${FILE_PREFIX}benchmark_results_$(date +%s).json"
127
+ scp_command "$INSTANCE:~/weaviate/test/benchmark/benchmark_results.json" "$filename"
128
+ echo "Results file succesfully copied to ${PWD}/$filename"
129
+ }
130
+
131
+
132
+ function echo_green() {
133
+ green='\033[0;32m'
134
+ nc='\033[0m'
135
+ echo -e "${green}${*}${nc}"
136
+ }
137
+
138
+ function echo_red() {
139
+ red='\033[0;31m'
140
+ nc='\033[0m'
141
+ echo -e "${red}${*}${nc}"
142
+ }
143
+
144
+ function ssh_command() {
145
+ gcloud beta compute ssh --project=$PROJECT --zone=$ZONE "$INSTANCE" --command="source ~/.profile; $1"
146
+ }
147
+
148
+ function scp_command() {
149
+ gcloud beta compute scp --project=$PROJECT --zone=$ZONE "$@"
150
+ }
151
+
152
+ function interactive_ssh() {
153
+ gcloud beta compute ssh --project=$PROJECT --zone=$ZONE "$INSTANCE"
154
+ }
155
+
156
+ main "$@"
platform/dbops/binaries/weaviate-src/test/benchmark/remote/terraform/.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Local .terraform directories
2
+ **/.terraform/*
3
+
4
+ .terraform.lock.hcl
5
+
6
+
7
+ # .tfstate files
8
+ *.tfstate
9
+ *.tfstate.*
platform/dbops/binaries/weaviate-src/test/benchmark/remote/terraform/main.tf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ provider "google" {
2
+ project = "semi-automated-benchmarking"
3
+ }
platform/dbops/binaries/weaviate-src/test/benchmark/remote/terraform/variables.tf ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ variable "machine_type" {
2
+ type = string
3
+ default = "c2-standard-16"
4
+ }
platform/dbops/binaries/weaviate-src/test/benchmark/remote/terraform/vm.tf ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ resource "google_compute_instance" "default" {
2
+ name = "automated-loadtest"
3
+ machine_type = var.machine_type
4
+ zone = "us-central1-a"
5
+
6
+ tags = ["automated-loadtest"]
7
+
8
+ boot_disk {
9
+ initialize_params {
10
+ image = "debian-cloud/debian-11"
11
+ size = 100
12
+ type = "pd-ssd"
13
+ }
14
+ }
15
+
16
+ network_interface {
17
+ network = "default"
18
+
19
+ access_config {
20
+ // Ephemeral public IP
21
+ }
22
+ }
23
+ }
platform/dbops/binaries/weaviate-src/test/benchmark_bm25/cmd/import.go ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 cmd
13
+
14
+ import (
15
+ "context"
16
+ "fmt"
17
+ "log"
18
+ "strconv"
19
+ "time"
20
+
21
+ "github.com/go-openapi/strfmt"
22
+ "github.com/google/uuid"
23
+ "github.com/spf13/cobra"
24
+ "github.com/weaviate/weaviate-go-client/v5/weaviate/batch"
25
+ "github.com/weaviate/weaviate/entities/models"
26
+ "github.com/weaviate/weaviate/test/benchmark_bm25/lib"
27
+ )
28
+
29
+ func init() {
30
+ rootCmd.AddCommand(importCmd)
31
+ importCmd.PersistentFlags().IntVarP(&BatchSize, "batch-size", "b", DefaultBatchSize, "number of objects in a single import batch")
32
+ importCmd.PersistentFlags().IntVarP(&MultiplyProperties, "multiply-properties", "m", DefaultMultiplyProperties, "create artifical copies of real properties by setting a value larger than 1. The properties have identical contents, so it won't alter results, but leads to many more calculations.")
33
+ importCmd.PersistentFlags().BoolVarP(&Vectorizer, "vectorizer", "v", DefaultVectorizer, "Vectorize import data with default vectorizer")
34
+ importCmd.PersistentFlags().IntVarP(&QueriesCount, "count", "c", DefaultQueriesCount, "run only the specified amount of queries, negative numbers mean unlimited")
35
+ importCmd.PersistentFlags().IntVarP(&FilterObjectPercentage, "filter", "f", DefaultFilterObjectPercentage, "The given percentage of objects are filtered out. Off by default, use <=0 to disable")
36
+ importCmd.PersistentFlags().Float32VarP(&Alpha, "alpha", "a", DefaultAlpha, "Weighting for keyword vs vector search. Alpha = 0 (Default) is pure BM25 search.")
37
+ importCmd.PersistentFlags().StringVarP(&Ranking, "ranking", "r", DefaultRanking, "Which ranking algorithm should be used for hybrid search, rankedFusion (default) and relativeScoreFusion.")
38
+ importCmd.PersistentFlags().IntVarP(&QueriesInterval, "query-interval", "i", DefaultQueriesInterval, "run queries every this number of inserts")
39
+ importCmd.PersistentFlags().IntVarP(&Limit, "limit", "l", DefaultLimit, "Limit the number of results returned by the query")
40
+ importCmd.PersistentFlags().BoolVarP(&AdditionalExplanations, "additional-explanations", "e", DefaultAdditionalExplanations, "Request additional explanations for the query results")
41
+ importCmd.PersistentFlags().BoolVarP(&PrintDetailedResults, "print-detailed-results", "p", DefaultPrintDetailedResults, "Print detailed results")
42
+ }
43
+
44
+ func parseData(data []lib.Corpus, datasetId string, batch *batch.ObjectsBatcher, i int) int {
45
+ total := 0
46
+ for _, corp := range data {
47
+ index := i + total
48
+ id := uuid.MustParse(fmt.Sprintf("%032x", index)).String()
49
+ props := map[string]interface{}{
50
+ "modulo_10": index % 10,
51
+ "modulo_100": index % 100,
52
+ "modulo_1000": index % 1000,
53
+ }
54
+
55
+ for key, value := range corp {
56
+ props[key] = value
57
+ }
58
+
59
+ batch.WithObjects(&models.Object{
60
+ ID: strfmt.UUID(id),
61
+ Class: lib.ClassNameFromDatasetID(datasetId),
62
+ Properties: props,
63
+ })
64
+
65
+ total++
66
+ }
67
+ return total
68
+ }
69
+
70
+ type IndexingExperimentResult struct {
71
+ // The name of the dataset
72
+ Dataset string
73
+ // The number of objects in the dataset
74
+ Objects int
75
+ // The batch size used for importing
76
+ MultiplyProperties int
77
+ // Docs where vectorized
78
+ Vectorize bool
79
+ // The time it took to import the dataset
80
+ ImportTime float64
81
+ // Average time to import 1000 objects
82
+ ImportTimePer1000 float64
83
+ // Objects per second
84
+ ObjectsPerSecond float64
85
+ }
86
+
87
+ var importCmd = &cobra.Command{
88
+ Use: "import",
89
+ Short: "Import a dataset (or multiple datasets) into Weaviate",
90
+
91
+ RunE: func(cmd *cobra.Command, args []string) error {
92
+ client, err := lib.ClientFromOrigin(Origin)
93
+ if err != nil {
94
+ return err
95
+ }
96
+
97
+ ok, err := client.Misc().LiveChecker().Do(context.Background())
98
+ if err != nil {
99
+ return fmt.Errorf("weaviate is not ready at %v: %w", Origin, err)
100
+ }
101
+
102
+ if !ok {
103
+ return fmt.Errorf("weaviate is not ready")
104
+ }
105
+
106
+ datasets, err := lib.ParseDatasetConfig(DatasetConfigPath)
107
+ if err != nil {
108
+ return fmt.Errorf("parse dataset cfg file: %w", err)
109
+ }
110
+
111
+ //if err := client.Schema().AllDeleter().Do(context.Background()); err != nil {
112
+ // return fmt.Errorf("clear schema prior to import: %w", err)
113
+ //}
114
+
115
+ experimentResults := make([]IndexingExperimentResult, len(datasets.Datasets))
116
+ queryResults := make([]*QueryExperimentResult, 0)
117
+
118
+ for di, dataset := range datasets.Datasets {
119
+
120
+ // delete the class if it exists
121
+ if err := client.Schema().ClassDeleter().WithClassName(lib.ClassNameFromDatasetID(dataset.ID)).Do(context.Background()); err != nil {
122
+ return fmt.Errorf("delete class for %s: %w", dataset, err)
123
+ }
124
+
125
+ if err := client.Schema().ClassCreator().
126
+ WithClass(lib.SchemaFromDataset(dataset, Vectorizer)).
127
+ Do(context.Background()); err != nil {
128
+ return fmt.Errorf("create schema for %s: %w", dataset, err)
129
+ }
130
+ log.Print("importing dataset " + dataset.ID)
131
+ queries := make([]lib.Query, 0)
132
+ if QueriesInterval != -1 {
133
+ log.Print("parse queries")
134
+ queries, err = lib.ParseQueries(dataset, QueriesCount)
135
+ if err != nil {
136
+ return err
137
+ }
138
+ log.Print("queries parsed")
139
+ }
140
+
141
+ start := time.Now()
142
+ startBatch := time.Now()
143
+ batch := client.Batch().ObjectsBatcher()
144
+
145
+ indexCount := 0
146
+
147
+ c, err := lib.ParseCorpi(dataset, MultiplyProperties)
148
+ if err != nil {
149
+ return err
150
+ }
151
+
152
+ i := 0
153
+ for c.Next(BatchSize) == nil {
154
+ data := c.Data
155
+
156
+ if len(data) == 0 {
157
+ break
158
+ }
159
+ parsedCount := parseData(data, dataset.ID, batch, i)
160
+ i += parsedCount
161
+ indexCount += parsedCount
162
+
163
+ if indexCount%BatchSize == 0 {
164
+ br, err := batch.Do(context.Background())
165
+ if err != nil {
166
+ return fmt.Errorf("batch %d: %w", indexCount, err)
167
+ }
168
+
169
+ if err := lib.HandleBatchResponse(br); err != nil {
170
+ return err
171
+ }
172
+ }
173
+
174
+ if indexCount%BatchSize == 0 {
175
+ totalTimeBatch := time.Since(startBatch).Seconds()
176
+ totalTime := time.Since(start).Seconds()
177
+ startBatch = time.Now()
178
+ log.Printf("imported %d objects in %.3f, time per 1k objects: %.3f, objects per second: %.0f", indexCount, totalTimeBatch, totalTime/float64(indexCount)*1000, float64(indexCount)/totalTime)
179
+ }
180
+
181
+ if QueriesInterval > 0 && indexCount%QueriesInterval == 0 {
182
+ result, err := query(client, queries, dataset, indexCount)
183
+ if err != nil {
184
+ return fmt.Errorf("query: %w", err)
185
+ }
186
+ queryResults = append(queryResults, result)
187
+
188
+ }
189
+ }
190
+
191
+ if len(c.Data) != 0 {
192
+ data := c.Data
193
+ parsedCount := parseData(data, dataset.ID, batch, i)
194
+ i += parsedCount
195
+ indexCount += parsedCount
196
+ // we need to send one final batch
197
+ br, err := batch.Do(context.Background())
198
+ if err != nil {
199
+ return fmt.Errorf("final batch: %w", err)
200
+ }
201
+ if err := lib.HandleBatchResponse(br); err != nil {
202
+ return err
203
+ }
204
+ totalTimeBatch := time.Since(startBatch).Seconds()
205
+ totalTime := time.Since(start).Seconds()
206
+ log.Printf("imported %d objects in %.3f, time per 1k objects: %.3f, objects per second: %.0f", indexCount, totalTimeBatch, totalTime/float64(indexCount)*1000, float64(indexCount)/totalTime)
207
+ }
208
+
209
+ totalTime := time.Since(start).Seconds()
210
+ log.Printf("importing finished %d objects in %.3f, time per 1k objects: %.3f, objects per second: %.0f", indexCount, totalTime, totalTime/float64(indexCount)*1000, float64(indexCount)/totalTime)
211
+
212
+ if QueriesInterval != -1 && indexCount%QueriesInterval != 0 {
213
+ // run queries after full import
214
+ result, err := query(client, queries, dataset, indexCount)
215
+ if err != nil {
216
+ return fmt.Errorf("query: %w", err)
217
+ }
218
+ queryResults = append(queryResults, result)
219
+ }
220
+
221
+ experimentResults[di] = IndexingExperimentResult{
222
+ Dataset: dataset.ID,
223
+ Objects: indexCount,
224
+ MultiplyProperties: MultiplyProperties,
225
+ Vectorize: Vectorizer,
226
+ ImportTime: time.Since(start).Seconds(),
227
+ ImportTimePer1000: time.Since(start).Seconds() / float64(indexCount) * 1000,
228
+ ObjectsPerSecond: float64(indexCount) / time.Since(start).Seconds(),
229
+ }
230
+ }
231
+ // pretty print results fas TSV
232
+ fmt.Printf("\nIndexing Results:\n")
233
+ fmt.Printf("Dataset\tObjects\tMultiplyProperties\tVectorizer\tImportTime\tImportTimePer1000\tObjectsPerSecond\n")
234
+ for _, result := range experimentResults {
235
+ fmt.Printf("%s\t%d\t%d\t%t\t%.3f\t%.3f\t%.0f\n", result.Dataset, result.Objects, result.MultiplyProperties, result.Vectorize, result.ImportTime, result.ImportTimePer1000, result.ObjectsPerSecond)
236
+ }
237
+
238
+ fmt.Printf("\nQuery Results:\n")
239
+ fmt.Printf("Dataset\tObjects\tQueries\tFilterObjectPercentage\tAlpha\tRanking\tQueryTime\tQueryTimePer1000\tQueriesPerSecond\tQueryTimePer1000000Documents\tMin\tMax\tP50\tP90\tP99\tnDCG\tP@1\tP@5\n")
240
+ for _, result := range queryResults {
241
+ ranking, _ := strconv.ParseFloat(result.Ranking, 64) // Convert result.Ranking to float64
242
+ fmt.Printf("%s\t%d\t%d\t%d\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n", result.Dataset, result.Objects, result.Queries, result.FilterObjectPercentage, result.Alpha, ranking, result.TotalQueryTime, result.AvgQueryTime.Seconds(), result.QueriesPerSecond, result.QueryTimePer1000000Documents, float32(result.Min.Milliseconds())/1000.0, float32(result.Max.Milliseconds())/1000.0, float32(result.P50.Milliseconds())/1000.0, float32(result.P90.Milliseconds())/1000.0, float32(result.P99.Milliseconds())/1000.0, result.Scores.CurrentNDCG(), result.Scores.CurrentPrecisionAt1(), result.Scores.CurrentPrecisionAt5())
243
+ }
244
+
245
+ return nil
246
+ },
247
+ }
platform/dbops/binaries/weaviate-src/test/benchmark_bm25/cmd/query.go ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 cmd
13
+
14
+ import (
15
+ "context"
16
+ "encoding/csv"
17
+ "errors"
18
+ "fmt"
19
+ "log"
20
+ "os"
21
+ "strconv"
22
+ "strings"
23
+ "time"
24
+
25
+ "github.com/spf13/cobra"
26
+
27
+ "github.com/weaviate/weaviate-go-client/v5/weaviate"
28
+ "github.com/weaviate/weaviate-go-client/v5/weaviate/filters"
29
+ "github.com/weaviate/weaviate-go-client/v5/weaviate/graphql"
30
+ "github.com/weaviate/weaviate/entities/models"
31
+ "github.com/weaviate/weaviate/test/benchmark_bm25/lib"
32
+ )
33
+
34
+ type QueryExperimentResult struct {
35
+ // The name of the dataset
36
+ Dataset string
37
+ // Dataset size
38
+ Objects int
39
+ // Query count
40
+ Queries int
41
+ // Filter object percentage
42
+ FilterObjectPercentage int
43
+ // Alpha
44
+ Alpha float32
45
+ // Ranking
46
+ Ranking string
47
+ // The time it took to query the dataset
48
+ TotalQueryTime float64
49
+ // Average query time
50
+ AvgQueryTime time.Duration
51
+ // Average time to query per 1000 indexed objects
52
+ QueryTimePer1000000Documents float64
53
+ // Objects per second
54
+ QueriesPerSecond float64
55
+ // Min query time
56
+ Min time.Duration
57
+ // Max query time
58
+ Max time.Duration
59
+ // P50 query time
60
+ P50 time.Duration
61
+ // P90 query time
62
+ P90 time.Duration
63
+ // P95 query time
64
+ P99 time.Duration
65
+ // Scores
66
+ Scores lib.Scores
67
+ }
68
+
69
+ func init() {
70
+ rootCmd.AddCommand(queryCmd)
71
+ queryCmd.PersistentFlags().IntVarP(&QueriesCount, "count", "c", DefaultQueriesCount, "run only the specified amount of queries, negative numbers mean unlimited")
72
+ queryCmd.PersistentFlags().IntVarP(&FilterObjectPercentage, "filter", "f", DefaultFilterObjectPercentage, "The given percentage of objects are filtered out. Off by default, use <=0 to disable")
73
+ queryCmd.PersistentFlags().Float32VarP(&Alpha, "alpha", "a", DefaultAlpha, "Weighting for keyword vs vector search. Alpha = 0 (Default) is pure BM25 search.")
74
+ queryCmd.PersistentFlags().StringVarP(&Ranking, "ranking", "r", DefaultRanking, "Which ranking algorithm should be used for hybrid search, rankedFusion (default) and relativeScoreFusion.")
75
+ queryCmd.PersistentFlags().IntVarP(&Limit, "limit", "l", DefaultLimit, "Limit the number of results returned by the query")
76
+ queryCmd.PersistentFlags().BoolVarP(&AdditionalExplanations, "additional-explanations", "e", DefaultAdditionalExplanations, "Request additional explanations for the query results")
77
+ queryCmd.PersistentFlags().BoolVarP(&PrintDetailedResults, "print-detailed-results", "p", DefaultPrintDetailedResults, "Print detailed results")
78
+ }
79
+
80
+ func writeQueryResultsToFile(results *models.GraphQLResponse, filename, collection, queryId string, additionalExplanations bool) {
81
+ file, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
82
+ if err != nil {
83
+ log.Fatal(err)
84
+ }
85
+ defer file.Close()
86
+
87
+ writer := csv.NewWriter(file)
88
+ defer writer.Flush()
89
+
90
+ header := []string{"queryId", "id", "score"}
91
+ if additionalExplanations {
92
+ header = append(header, "explainScore")
93
+ }
94
+
95
+ // Write the header
96
+ writer.Write(header)
97
+ for _, obj := range results.Data["Get"].(map[string]interface{})[collection].([]interface{}) {
98
+ id := obj.(map[string]interface{})["_additional"].(map[string]interface{})["id"].(string)
99
+ score := obj.(map[string]interface{})["_additional"].(map[string]interface{})["score"].(string)
100
+
101
+ // round score to 2 decimal places
102
+ scoreFloat, err := strconv.ParseFloat(score, 64)
103
+ if err != nil {
104
+ log.Fatal(err)
105
+ }
106
+ score = fmt.Sprintf("%.2f", scoreFloat)
107
+
108
+ line := []string{queryId, id, score}
109
+ if additionalExplanations {
110
+ line = append(line, obj.(map[string]interface{})["_additional"].(map[string]interface{})["explainScore"].(string))
111
+ }
112
+
113
+ writer.Write(line)
114
+ }
115
+ }
116
+
117
+ func query(client *weaviate.Client, q lib.Queries, ds lib.Dataset, index int) (*QueryExperimentResult, error) {
118
+ propNameWithId := lib.SanitizePropName(ds.Queries.PropertyWithId)
119
+ propertiesToMatch := ds.Queries.PropertiesToMatch
120
+ for i := 0; i < len(propertiesToMatch); i++ {
121
+ propertiesToMatch[i] = lib.SanitizePropName(propertiesToMatch[i])
122
+ }
123
+ className := lib.ClassNameFromDatasetID(ds.ID)
124
+ times := []time.Duration{}
125
+ scores := lib.Scores{}
126
+
127
+ // unix timestamp as string
128
+ t := strconv.FormatInt(time.Now().Unix(), 10)
129
+ propName := strings.Join(propertiesToMatch, "_")
130
+ if len(propertiesToMatch) == 0 {
131
+ propName = "all"
132
+ }
133
+ if index >= 0 {
134
+ propName = propName + "_" + strconv.Itoa(index)
135
+ }
136
+ filename := t + "_" + className + "_" + propName + ".csv"
137
+
138
+ additionalFlags := "id"
139
+ if PrintDetailedResults {
140
+ additionalFlags = "id score explainScore"
141
+ }
142
+ for i, query := range q {
143
+ before := time.Now()
144
+ var queryBuilder *graphql.GetBuilder
145
+
146
+ queryBuilder = client.GraphQL().Get().WithClassName(className).WithLimit(Limit).WithFields(graphql.Field{Name: "_additional { " + additionalFlags + " }"}, graphql.Field{Name: propNameWithId})
147
+ if Alpha == 0 {
148
+ bm25 := &graphql.BM25ArgumentBuilder{}
149
+ bm25.WithQuery(query.Query)
150
+ bm25.WithProperties(propertiesToMatch...)
151
+ queryBuilder.WithBM25(bm25)
152
+ } else {
153
+ hybrid := &graphql.HybridArgumentBuilder{}
154
+ ranking := graphql.FusionType(Ranking)
155
+ hybrid.WithQuery(query.Query).WithAlpha(Alpha).WithFusionType(ranking)
156
+ hybrid.WithProperties(propertiesToMatch)
157
+ queryBuilder.WithHybrid(hybrid)
158
+ }
159
+ if FilterObjectPercentage > 0 {
160
+ filter := filters.Where()
161
+ filter.WithPath([]string{"modulo_100"})
162
+ filter.WithOperator(filters.GreaterThan)
163
+ filter.WithValueInt(int64(FilterObjectPercentage))
164
+ queryBuilder = queryBuilder.WithWhere(filter)
165
+ }
166
+ result, err := queryBuilder.Do(context.Background())
167
+ if err != nil {
168
+ return nil, err
169
+ }
170
+
171
+ if result.Errors != nil {
172
+ return nil, errors.New(result.Errors[0].Message)
173
+ }
174
+ times = append(times, time.Since(before))
175
+
176
+ // print result scores and ids to a csv file
177
+ if PrintDetailedResults {
178
+ queryId := strconv.Itoa(i)
179
+ writeQueryResultsToFile(result, filename, className, queryId, AdditionalExplanations)
180
+ }
181
+
182
+ logMsg := fmt.Sprintf("completed %d/%d queries.", i, len(q))
183
+
184
+ if len(query.MatchingIds) > 0 && len(ds.Queries.PropertyWithId) > 0 {
185
+ resultIds := result.Data["Get"].(map[string]interface{})[className].([]interface{})
186
+ if err := scores.AddResult(query.MatchingIds, resultIds, propNameWithId); err != nil {
187
+ return nil, err
188
+ }
189
+ logMsg += fmt.Sprintf("nDCG score: %.04f", scores.CurrentNDCG())
190
+ }
191
+ if i%1000 == 0 && i > 0 {
192
+ log.Print(logMsg)
193
+ }
194
+ }
195
+
196
+ meta, err := client.GraphQL().Aggregate().WithClassName(lib.ClassNameFromDatasetID(ds.ID)).
197
+ WithFields(graphql.Field{Name: "meta", Fields: []graphql.Field{{Name: "count"}}}).
198
+ Do(context.Background())
199
+ if err != nil {
200
+ return nil, err
201
+ }
202
+
203
+ objCount := int(meta.Data["Aggregate"].(map[string]interface{})[lib.ClassNameFromDatasetID(ds.ID)].([]interface{})[0].(map[string]interface{})["meta"].(map[string]interface{})["count"].(float64))
204
+
205
+ stat := lib.AnalyzeLatencies(times)
206
+ stat.PrettyPrint()
207
+ scores.PrettyPrint()
208
+ totalTime := 0.0
209
+ for _, t := range times {
210
+ totalTime += t.Seconds()
211
+ }
212
+
213
+ result := QueryExperimentResult{
214
+ Dataset: ds.ID,
215
+ Objects: objCount,
216
+ Queries: len(q),
217
+ FilterObjectPercentage: FilterObjectPercentage,
218
+ Alpha: Alpha,
219
+ Ranking: Ranking,
220
+ TotalQueryTime: totalTime,
221
+ AvgQueryTime: stat.Mean,
222
+ QueriesPerSecond: 1 / stat.Mean.Seconds(),
223
+ QueryTimePer1000000Documents: float64(stat.Mean.Milliseconds()) * 1000000 / float64(objCount),
224
+ Min: stat.Min,
225
+ Max: stat.Max,
226
+ P50: stat.P50,
227
+ P90: stat.P90,
228
+ P99: stat.P99,
229
+ Scores: scores,
230
+ }
231
+
232
+ return &result, nil
233
+ }
234
+
235
+ var queryCmd = &cobra.Command{
236
+ Use: "query",
237
+ Short: "Send queries for a dataset",
238
+ RunE: func(cmd *cobra.Command, args []string) error {
239
+ client, err := lib.ClientFromOrigin(Origin)
240
+ if err != nil {
241
+ return err
242
+ }
243
+
244
+ ok, err := client.Misc().LiveChecker().Do(context.Background())
245
+ if err != nil {
246
+ return fmt.Errorf("weaviate is not ready: %w", err)
247
+ }
248
+
249
+ if !ok {
250
+ return fmt.Errorf("weaviate is not ready")
251
+ }
252
+ log.Print("weaviate is ready")
253
+
254
+ datasets, err := lib.ParseDatasetConfig(DatasetConfigPath)
255
+ if err != nil {
256
+ return fmt.Errorf("parse dataset cfg file: %w", err)
257
+ }
258
+
259
+ results := make([]*QueryExperimentResult, len(datasets.Datasets))
260
+ for di, ds := range datasets.Datasets {
261
+ log.Print("querying dataset " + ds.ID)
262
+ log.Print("parse queries")
263
+ q, err := lib.ParseQueries(ds, QueriesCount)
264
+ if err != nil {
265
+ return err
266
+ }
267
+ log.Print("queries parsed")
268
+ log.Print("start querying")
269
+
270
+ result, err := query(client, q, ds, -1)
271
+ if err != nil {
272
+ return err
273
+ }
274
+
275
+ results[di] = result
276
+
277
+ }
278
+
279
+ fmt.Printf("\nQuery Results:\n")
280
+ fmt.Printf("Dataset\tObjects\tQueries\tFilterObjectPercentage\tAlpha\tRanking\tQueryTime\tAvgQueryTime\tQueriesPerSecond\tQueryTimePer1000000Documents\tMin\tMax\tP50\tP90\tP99\tnDCG\tP@1\tP@5\n")
281
+ for _, result := range results {
282
+ ranking, _ := strconv.ParseFloat(result.Ranking, 64) // Convert result.Ranking to float64
283
+ fmt.Printf("%s\t%d\t%d\t%d\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n", result.Dataset, result.Objects, result.Queries, result.FilterObjectPercentage, result.Alpha, ranking, result.TotalQueryTime, result.AvgQueryTime.Seconds(), result.QueriesPerSecond, result.QueryTimePer1000000Documents, result.Min.Seconds(), result.Max.Seconds(), result.P50.Seconds(), result.P90.Seconds(), result.P99.Seconds(), result.Scores.CurrentNDCG(), result.Scores.CurrentPrecisionAt1(), result.Scores.CurrentPrecisionAt5())
284
+ }
285
+
286
+ return nil
287
+ },
288
+ }
platform/dbops/binaries/weaviate-src/test/benchmark_bm25/cmd/root.go ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 cmd
13
+
14
+ import (
15
+ "fmt"
16
+ "os"
17
+
18
+ "github.com/spf13/cobra"
19
+ )
20
+
21
+ var (
22
+ Origin string
23
+ DatasetConfigPath string
24
+ BatchSize int
25
+ QueriesCount int
26
+ MultiplyProperties int
27
+ FilterObjectPercentage int
28
+ QueriesInterval int
29
+ Alpha float32
30
+ Ranking string
31
+ Vectorizer bool
32
+ Limit int
33
+ AdditionalExplanations bool
34
+ PrintDetailedResults bool
35
+ )
36
+
37
+ const (
38
+ DefaultOrigin = "http://localhost:8080"
39
+ DefaultDatasetConfigPath = "datasets.yml"
40
+ DefaultBatchSize = 100
41
+ DefaultQueriesCount = -1
42
+ DefaultQueriesInterval = -1
43
+ DefaultMultiplyProperties = 1
44
+ DefaultFilterObjectPercentage = 0
45
+ DefaultAlpha = 0
46
+ DefaultRanking = "ranked_fusion"
47
+ DefaultVectorizer = false
48
+ DefaultLimit = 100
49
+ DefaultAdditionalExplanations = false
50
+ DefaultPrintDetailedResults = false
51
+ )
52
+
53
+ var rootCmd = &cobra.Command{
54
+ Use: "benchmarker",
55
+ Short: "benchmarker is a simple tool to obtain bm25 speed benchmarks",
56
+ RunE: func(cmd *cobra.Command, args []string) error {
57
+ fmt.Printf("Run --help to see usage instructions.\n")
58
+ return nil
59
+ },
60
+ }
61
+
62
+ func Execute() {
63
+ if err := rootCmd.Execute(); err != nil {
64
+ fmt.Fprintln(os.Stderr, err)
65
+ os.Exit(1)
66
+ }
67
+ }
68
+
69
+ func init() {
70
+ rootCmd.PersistentFlags().StringVarP(&Origin, "origin", "o", DefaultOrigin, "origin (schema + host + port) where weaviate is running")
71
+ rootCmd.PersistentFlags().StringVar(&DatasetConfigPath, "dataset-config", DefaultDatasetConfigPath, "path to dataset config file")
72
+ }
platform/dbops/binaries/weaviate-src/test/benchmark_bm25/lib/batch.go ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 lib
13
+
14
+ import (
15
+ "fmt"
16
+ "strings"
17
+
18
+ "github.com/weaviate/weaviate/entities/models"
19
+ )
20
+
21
+ func HandleBatchResponse(res []models.ObjectsGetResponse) error {
22
+ msgs := []string{}
23
+
24
+ for i, obj := range res {
25
+ if obj.Result.Errors == nil {
26
+ continue
27
+ }
28
+
29
+ if len(obj.Result.Errors.Error) == 0 {
30
+ continue
31
+ }
32
+
33
+ msg := fmt.Sprintf("at pos %d: %s", i, obj.Result.Errors.Error[0].Message)
34
+ msgs = append(msgs, msg)
35
+ }
36
+
37
+ if len(msgs) == 0 {
38
+ return nil
39
+ }
40
+
41
+ msg := strings.Join(msgs, ", ")
42
+ return fmt.Errorf("%s", msg)
43
+ }
platform/dbops/binaries/weaviate-src/test/benchmark_bm25/lib/client.go ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 lib
13
+
14
+ import (
15
+ "net/url"
16
+
17
+ client "github.com/weaviate/weaviate-go-client/v5/weaviate"
18
+ )
19
+
20
+ func ClientFromOrigin(origin string) (*client.Client, error) {
21
+ parsed, err := url.Parse(origin)
22
+ if err != nil {
23
+ return nil, err
24
+ }
25
+
26
+ config := client.Config{
27
+ Scheme: parsed.Scheme,
28
+ Host: parsed.Host,
29
+ }
30
+
31
+ client := client.New(config)
32
+
33
+ return client, nil
34
+ }