Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: entity access management crate (#2465)

Will Hutchinson3d7c80703d0f
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index f3bd2fb91b..aca9999c7a 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3861,6 +3861,26 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "entity_access_management"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "cool_asserts",
+ "macro_db_migrator",
+ "macro_user_id",
+ "mockall",
+ "model-entity",
+ "models_permissions",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.17",
+ "tokio",
+ "tracing",
+ "uuid",
+]
+
[[package]]
name = "enum-as-inner"
version = "0.6.1"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 7bc9421811..52e1920d7c 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -24,8 +24,8 @@ members = [
"contacts_service",
"convert_service",
"cowlike",
- "decode_jwt",
"dataloss_prevention_handler",
+ "decode_jwt",
"delete_chat_handler",
"deleted_item_poller",
"document_cognition_service",
@@ -48,6 +48,7 @@ members = [
"email_utils",
"email_validator",
"entity_access",
+ "entity_access_management",
"frecency",
"fusionauth",
"github",
diff --git a/rust/cloud-storage/entity_access_management/.sqlx/query-279926d74db34fd618a6b507e2ec60160ef8399af5cfa11393a2e1e8d9762d65.json b/rust/cloud-storage/entity_access_management/.sqlx/query-279926d74db34fd618a6b507e2ec60160ef8399af5cfa11393a2e1e8d9762d65.json
new file mode 100644
index 0000000000..0216da5e97
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/.sqlx/query-279926d74db34fd618a6b507e2ec60160ef8399af5cfa11393a2e1e8d9762d65.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM entity_access\n WHERE entity_id = ANY($1)\n AND granted_from_project_id = ANY($2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "279926d74db34fd618a6b507e2ec60160ef8399af5cfa11393a2e1e8d9762d65"
+}
diff --git a/rust/cloud-storage/entity_access_management/.sqlx/query-5b17a30f841372cce9989af409baf993e24bfe90d3a3553f6851b3e92c8540eb.json b/rust/cloud-storage/entity_access_management/.sqlx/query-5b17a30f841372cce9989af409baf993e24bfe90d3a3553f6851b3e92c8540eb.json
new file mode 100644
index 0000000000..113b9e269a
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/.sqlx/query-5b17a30f841372cce9989af409baf993e24bfe90d3a3553f6851b3e92c8540eb.json
@@ -0,0 +1,63 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n entity_id,\n source_id,\n source_type as \"source_type:EntityAccessSourceType\",\n access_level as \"access_level:AccessLevel\"\n FROM entity_access\n WHERE entity_id = ANY($1) AND entity_type = 'project' AND granted_from_project_id IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "source_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "source_type:EntityAccessSourceType",
+ "type_info": {
+ "Custom": {
+ "name": "entity_access_source_type",
+ "kind": {
+ "Enum": [
+ "channel",
+ "team",
+ "user"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "access_level:AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "5b17a30f841372cce9989af409baf993e24bfe90d3a3553f6851b3e92c8540eb"
+}
diff --git a/rust/cloud-storage/entity_access_management/.sqlx/query-cd2ae30f38c8fd4467fafbf57d515e303d2c5bed1c53a5c1cf255a172defa46c.json b/rust/cloud-storage/entity_access_management/.sqlx/query-cd2ae30f38c8fd4467fafbf57d515e303d2c5bed1c53a5c1cf255a172defa46c.json
new file mode 100644
index 0000000000..a42c11b623
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/.sqlx/query-cd2ae30f38c8fd4467fafbf57d515e303d2c5bed1c53a5c1cf255a172defa46c.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM entity_access\n WHERE entity_id = $1\n AND entity_type = $2\n AND granted_from_project_id = ANY($3)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "cd2ae30f38c8fd4467fafbf57d515e303d2c5bed1c53a5c1cf255a172defa46c"
+}
diff --git a/rust/cloud-storage/entity_access_management/.sqlx/query-e08bcee71072e0e693b1b3f2df39a2b9574f45847919251446878f32b9febbc2.json b/rust/cloud-storage/entity_access_management/.sqlx/query-e08bcee71072e0e693b1b3f2df39a2b9574f45847919251446878f32b9febbc2.json
new file mode 100644
index 0000000000..f47413e3dc
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/.sqlx/query-e08bcee71072e0e693b1b3f2df39a2b9574f45847919251446878f32b9febbc2.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE parent_projects AS (\n -- Base case: the project itself\n SELECT id, name, \"parentId\"\n FROM \"Project\"\n WHERE id = $1\n\n UNION ALL\n\n -- Recursive case: walk up to the parent\n SELECT p.id, p.name, p.\"parentId\"\n FROM \"Project\" p\n INNER JOIN parent_projects pp ON p.id = pp.\"parentId\"\n )\n SELECT id as \"id!\"\n FROM parent_projects\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "e08bcee71072e0e693b1b3f2df39a2b9574f45847919251446878f32b9febbc2"
+}
diff --git a/rust/cloud-storage/entity_access_management/.sqlx/query-f6a7499d3079d346afe5d866734ffc5d4ac3f9f1a8c2a5714ef130e53d11145f.json b/rust/cloud-storage/entity_access_management/.sqlx/query-f6a7499d3079d346afe5d866734ffc5d4ac3f9f1a8c2a5714ef130e53d11145f.json
new file mode 100644
index 0000000000..c718076a09
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/.sqlx/query-f6a7499d3079d346afe5d866734ffc5d4ac3f9f1a8c2a5714ef130e53d11145f.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE child_projects AS (\n SELECT id FROM \"Project\" WHERE id = $1\n\n UNION ALL\n\n SELECT p.id FROM \"Project\" p\n INNER JOIN child_projects cp ON p.\"parentId\" = cp.id\n )\n SELECT id as \"entity_id!\", 'project' as \"entity_type!\" FROM child_projects\n\n UNION ALL\n\n SELECT d.id as \"entity_id!\", 'document' as \"entity_type!\" FROM \"Document\" d\n WHERE d.\"projectId\" IN (SELECT id FROM child_projects)\n\n UNION ALL\n\n SELECT c.id as \"entity_id!\", 'chat' as \"entity_type!\" FROM \"Chat\" c\n WHERE c.\"projectId\" IN (SELECT id FROM child_projects)\n\n UNION ALL\n\n SELECT et.id::text as \"entity_id!\", 'email_thread' as \"entity_type!\" FROM email_threads et\n WHERE et.project_id IN (SELECT id FROM child_projects)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_type!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null,
+ null
+ ]
+ },
+ "hash": "f6a7499d3079d346afe5d866734ffc5d4ac3f9f1a8c2a5714ef130e53d11145f"
+}
diff --git a/rust/cloud-storage/entity_access_management/Cargo.toml b/rust/cloud-storage/entity_access_management/Cargo.toml
new file mode 100644
index 0000000000..9a41d279fe
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/Cargo.toml
@@ -0,0 +1,37 @@
+[package]
+edition = "2024"
+name = "entity_access_management"
+publish = false
+version = "0.1.0"
+
+[features]
+default = ["outbound", "ports"]
+outbound = ["dep:sqlx", "ports"]
+ports = ["dep:tokio"]
+
+[dependencies]
+# Core
+anyhow = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+thiserror = { workspace = true }
+tracing = { workspace = true }
+uuid = { workspace = true }
+
+# Domain models (always included)
+macro_user_id = { path = "../macro_user_id" }
+model-entity = { path = "../model-entity" }
+models_permissions = { path = "../models_permissions" }
+
+# Async runtime (for ports)
+tokio = { workspace = true, optional = true }
+
+# Database
+sqlx = { workspace = true, optional = true }
+
+[dev-dependencies]
+cool_asserts = "2"
+macro_db_migrator = { path = "../macro_db_migrator" }
+mockall = { workspace = true }
+sqlx = { workspace = true, features = ["postgres", "runtime-tokio-rustls"] }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/rust/cloud-storage/entity_access_management/fixtures/complex_project_tree_test_data.sql b/rust/cloud-storage/entity_access_management/fixtures/complex_project_tree_test_data.sql
new file mode 100644
index 0000000000..60b572d958
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/fixtures/complex_project_tree_test_data.sql
@@ -0,0 +1,67 @@
+INSERT INTO public."Organization" ("id", "name")
+ VALUES (1, 'test-org');
+
+-- Three users (UA, UB, UC)
+INSERT INTO public."macro_user" ("id", "username", "email", "stripe_customer_id") VALUES
+ ('a1111111-1111-1111-1111-111111111111', 'user_a', '[email protected]', 'stripe_a'),
+ ('a2222222-2222-2222-2222-222222222222', 'user_b', '[email protected]', 'stripe_b'),
+ ('a3333333-3333-3333-3333-333333333333', 'user_c', '[email protected]', 'stripe_c');
+
+INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id") VALUES
+ ('macro|[email protected]', '[email protected]', 'stripe_a', 1, 'a1111111-1111-1111-1111-111111111111'),
+ ('macro|[email protected]', '[email protected]', 'stripe_b', 1, 'a2222222-2222-2222-2222-222222222222'),
+ ('macro|[email protected]', '[email protected]', 'stripe_c', 1, 'a3333333-3333-3333-3333-333333333333');
+
+-- PROJECT_A (root, owner UA)
+INSERT INTO public."Project" ("id", "name", "userId")
+ VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'project-a', 'macro|[email protected]');
+
+-- PROJECT_B (child of A, owner UB)
+INSERT INTO public."Project" ("id", "name", "userId", "parentId")
+ VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'project-b', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+
+-- PROJECT_C (child of B, owner UC)
+INSERT INTO public."Project" ("id", "name", "userId", "parentId")
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project-c', 'macro|[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
+
+-- Documents: one in project_a, one in project_c
+INSERT INTO public."Document" ("id", "name", "owner", "projectId")
+ VALUES ('doc-in-a', 'doc-a', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+INSERT INTO public."Document" ("id", "name", "owner", "projectId")
+ VALUES ('doc-in-c', 'doc-c', 'macro|[email protected]', 'cccccccc-cccc-cccc-cccc-cccccccccccc');
+
+-- Chats: one in project_b
+INSERT INTO public."Chat" ("id", "name", "userId", "projectId")
+ VALUES ('chat-in-b', 'chat-b', 'macro|[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
+
+-- Direct owner records (granted_from_project_id IS NULL)
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'project', 'macro|[email protected]', 'user', 'owner');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'project', 'macro|[email protected]', 'user', 'owner');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project', 'macro|[email protected]', 'user', 'owner');
+
+-- Inherited owner records (should be excluded by query)
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'project', 'macro|[email protected]', 'user', 'owner', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project', 'macro|[email protected]', 'user', 'owner', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project', 'macro|[email protected]', 'user', 'owner', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
+
+-- Direct channel/team shares (granted_from_project_id IS NULL)
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'project', 'channel-1', 'channel', 'view');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'project', 'team-1', 'team', 'edit');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project', 'channel-2', 'channel', 'comment');
+
+-- Inherited channel/team shares (should be excluded by query)
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'project', 'channel-1', 'channel', 'view', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project', 'channel-1', 'channel', 'view', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project', 'team-1', 'team', 'edit', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
diff --git a/rust/cloud-storage/entity_access_management/fixtures/move_project_test_data.sql b/rust/cloud-storage/entity_access_management/fixtures/move_project_test_data.sql
new file mode 100644
index 0000000000..970e30b7f5
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/fixtures/move_project_test_data.sql
@@ -0,0 +1,113 @@
+INSERT INTO public."Organization" ("id", "name")
+ VALUES (1, 'test-org');
+
+-- Four users
+INSERT INTO public."macro_user" ("id", "username", "email", "stripe_customer_id") VALUES
+ ('a1111111-1111-1111-1111-111111111111', 'user_a', '[email protected]', 'stripe_a'),
+ ('a2222222-2222-2222-2222-222222222222', 'user_b', '[email protected]', 'stripe_b'),
+ ('a3333333-3333-3333-3333-333333333333', 'user_c', '[email protected]', 'stripe_c'),
+ ('a4444444-4444-4444-4444-444444444444', 'user_d', '[email protected]', 'stripe_d');
+
+INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id") VALUES
+ ('macro|[email protected]', '[email protected]', 'stripe_a', 1, 'a1111111-1111-1111-1111-111111111111'),
+ ('macro|[email protected]', '[email protected]', 'stripe_b', 1, 'a2222222-2222-2222-2222-222222222222'),
+ ('macro|[email protected]', '[email protected]', 'stripe_c', 1, 'a3333333-3333-3333-3333-333333333333'),
+ ('macro|[email protected]', '[email protected]', 'stripe_d', 1, 'a4444444-4444-4444-4444-444444444444');
+
+-- PROJECT_A (root, owner UA) — source parent
+INSERT INTO public."Project" ("id", "name", "userId")
+ VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'project-a', 'macro|[email protected]');
+
+-- PROJECT_B (child of A, owner UB) — the project being moved
+INSERT INTO public."Project" ("id", "name", "userId", "parentId")
+ VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'project-b', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+
+-- PROJECT_C (child of B, owner UC) — nested under B
+INSERT INTO public."Project" ("id", "name", "userId", "parentId")
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project-c', 'macro|[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
+
+-- PROJECT_D (root, owner UD) — destination parent
+INSERT INTO public."Project" ("id", "name", "userId")
+ VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'project-d', 'macro|[email protected]');
+
+-- Documents with UUID ids (required for move_project's Uuid::parse_str)
+INSERT INTO public."Document" ("id", "name", "owner", "projectId")
+ VALUES ('d1111111-1111-1111-1111-111111111111', 'doc-in-b', 'macro|[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
+INSERT INTO public."Document" ("id", "name", "owner", "projectId")
+ VALUES ('d2222222-2222-2222-2222-222222222222', 'doc-in-c', 'macro|[email protected]', 'cccccccc-cccc-cccc-cccc-cccccccccccc');
+
+---------------------------------------------------------------------------
+-- entity_access: direct project shares (granted_from_project_id IS NULL)
+---------------------------------------------------------------------------
+
+-- project_a: user_a/owner, channel-1/view
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'project', 'macro|[email protected]', 'user', 'owner');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'project', 'channel-1', 'channel', 'view');
+
+-- project_b: user_b/owner, team-1/edit
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'project', 'macro|[email protected]', 'user', 'owner');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'project', 'team-1', 'team', 'edit');
+
+-- project_c: user_c/owner
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project', 'macro|[email protected]', 'user', 'owner');
+
+-- project_d: user_d/owner, team-2/comment
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'project', 'macro|[email protected]', 'user', 'owner');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'project', 'team-2', 'team', 'comment');
+
+---------------------------------------------------------------------------
+-- entity_access: inherited project shares
+---------------------------------------------------------------------------
+
+-- project_b inherited from project_a
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'project', 'macro|[email protected]', 'user', 'owner', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'project', 'channel-1', 'channel', 'view', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+
+-- project_c inherited from project_a
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project', 'macro|[email protected]', 'user', 'owner', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project', 'channel-1', 'channel', 'view', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+
+-- project_c inherited from project_b
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project', 'macro|[email protected]', 'user', 'owner', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'project', 'team-1', 'team', 'edit', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
+
+---------------------------------------------------------------------------
+-- entity_access: doc_in_b access (as if add_entity_to_project was called for project_b)
+-- walk_up(B) = [B, A] → sources: user_a/owner(A), channel-1/view(A), user_b/owner(B), team-1/edit(B)
+---------------------------------------------------------------------------
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('d1111111-1111-1111-1111-111111111111', 'document', 'macro|[email protected]', 'user', 'owner', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('d1111111-1111-1111-1111-111111111111', 'document', 'channel-1', 'channel', 'view', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('d1111111-1111-1111-1111-111111111111', 'document', 'macro|[email protected]', 'user', 'owner', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('d1111111-1111-1111-1111-111111111111', 'document', 'team-1', 'team', 'edit', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
+
+---------------------------------------------------------------------------
+-- entity_access: doc_in_c access (as if add_entity_to_project was called for project_c)
+-- walk_up(C) = [C, B, A] → sources: user_a/owner(A), channel-1/view(A), user_b/owner(B), team-1/edit(B), user_c/owner(C)
+---------------------------------------------------------------------------
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('d2222222-2222-2222-2222-222222222222', 'document', 'macro|[email protected]', 'user', 'owner', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('d2222222-2222-2222-2222-222222222222', 'document', 'channel-1', 'channel', 'view', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('d2222222-2222-2222-2222-222222222222', 'document', 'macro|[email protected]', 'user', 'owner', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('d2222222-2222-2222-2222-222222222222', 'document', 'team-1', 'team', 'edit', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('d2222222-2222-2222-2222-222222222222', 'document', 'macro|[email protected]', 'user', 'owner', 'cccccccc-cccc-cccc-cccc-cccccccccccc');
diff --git a/rust/cloud-storage/entity_access_management/fixtures/project_tree_test_data.sql b/rust/cloud-storage/entity_access_management/fixtures/project_tree_test_data.sql
new file mode 100644
index 0000000000..915b719bd5
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/fixtures/project_tree_test_data.sql
@@ -0,0 +1,40 @@
+INSERT INTO public."Organization" ("id", "name")
+ VALUES (1, 'test-org');
+
+INSERT INTO public."macro_user" ("id", "username", "email", "stripe_customer_id")
+ VALUES ('a1111111-1111-1111-1111-111111111111', 'testuser', '[email protected]', 'stripe_test');
+
+INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id")
+ VALUES ('macro|[email protected]', '[email protected]', 'stripe_test', 1, 'a1111111-1111-1111-1111-111111111111');
+
+-- Root project (no parent)
+INSERT INTO public."Project" ("id", "name", "userId")
+ VALUES ('11111111-1111-1111-1111-111111111111', 'root-project', 'macro|[email protected]');
+
+-- Child project (parent = root)
+INSERT INTO public."Project" ("id", "name", "userId", "parentId")
+ VALUES ('22222222-2222-2222-2222-222222222222', 'child-project', 'macro|[email protected]', '11111111-1111-1111-1111-111111111111');
+
+-- Grandchild project (parent = child)
+INSERT INTO public."Project" ("id", "name", "userId", "parentId")
+ VALUES ('33333333-3333-3333-3333-333333333333', 'grandchild-project', 'macro|[email protected]', '22222222-2222-2222-2222-222222222222');
+
+-- entity_access: direct share — user has edit on root project
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('11111111-1111-1111-1111-111111111111', 'project', 'macro|[email protected]', 'user', 'edit');
+
+-- entity_access: direct share — team has view on root project
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('11111111-1111-1111-1111-111111111111', 'project', 'team-one', 'team', 'view');
+
+-- entity_access: direct share — channel has comment on child project
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('22222222-2222-2222-2222-222222222222', 'project', 'channel-one', 'channel', 'comment');
+
+-- entity_access: inherited access (has granted_from_project_id) — should be excluded by query
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ('22222222-2222-2222-2222-222222222222', 'project', 'macro|[email protected]', 'user', 'view', '11111111-1111-1111-1111-111111111111');
+
+-- entity_access: wrong entity_type (document, not project) — should be excluded by query
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ('11111111-1111-1111-1111-111111111111', 'document', 'macro|[email protected]', 'user', 'view');
diff --git a/rust/cloud-storage/entity_access_management/justfile b/rust/cloud-storage/entity_access_management/justfile
new file mode 100644
index 0000000000..d5a52bc432
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/justfile
@@ -0,0 +1,6 @@
+DATABASE_URL := "postgres://user:password@localhost:5432/macrodb"
+
+mod sqlx '../sqlx.just'
+
+prepare_db:
+ just sqlx::prepare_db {{ DATABASE_URL }}
diff --git a/rust/cloud-storage/entity_access_management/src/domain.rs b/rust/cloud-storage/entity_access_management/src/domain.rs
new file mode 100644
index 0000000000..0d1ee442b5
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/src/domain.rs
@@ -0,0 +1,11 @@
+//! Domain layer for entity access management.
+//!
+//! Contains models, ports (traits), and the service implementation.
+
+pub mod models;
+
+#[cfg(feature = "ports")]
+pub mod ports;
+
+#[cfg(feature = "ports")]
+pub mod service;
diff --git a/rust/cloud-storage/entity_access_management/src/domain/models.rs b/rust/cloud-storage/entity_access_management/src/domain/models.rs
new file mode 100644
index 0000000000..2ecbbcedc6
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/src/domain/models.rs
@@ -0,0 +1,33 @@
+//! Domain models for entity access management.
+
+use model_entity::EntityType;
+
+/// Errors that can occur in entity_access_management crate.
+#[derive(Debug, thiserror::Error)]
+pub enum EntityAccessManagementError {
+ /// Unsupported entity type provided
+ #[error("unsupported entity type provided {0}")]
+ UnsupportedEntityType(EntityType),
+ /// Database error occured
+ #[error(transparent)]
+ DatabaseError(#[from] anyhow::Error),
+ /// Invalid project move configuration
+ #[error("invalid project move configuration")]
+ InvalidProjectMove,
+}
+
+/// Entity access source type
+#[derive(Debug, Clone, Copy)]
+#[cfg_attr(feature = "outbound", derive(sqlx::Type))]
+#[cfg_attr(
+ feature = "outbound",
+ sqlx(type_name = "entity_access_source_type", rename_all = "lowercase")
+)]
+pub enum EntityAccessSourceType {
+ /// Channel source
+ Channel,
+ /// Team source
+ Team,
+ /// User source
+ User,
+}
diff --git a/rust/cloud-storage/entity_access_management/src/domain/ports.rs b/rust/cloud-storage/entity_access_management/src/domain/ports.rs
new file mode 100644
index 0000000000..61370839ed
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/src/domain/ports.rs
@@ -0,0 +1,64 @@
+//! Port definitions for entity access management.
+//!
+//! These traits define the contracts that adapters must implement.
+
+use model_entity::EntityType;
+
+use crate::domain::models::EntityAccessManagementError;
+
+/// Repository for persisting entity_access in the database.
+pub trait EntityAccessManagementRepository: Clone + Send + Sync + 'static {
+ /// The error type returned by repository operations
+ type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
+
+ /// Updates entity access when an entity is **added** to a project
+ fn add_entity_to_project(
+ &self,
+ entity_id: &uuid::Uuid,
+ entity_type: EntityType,
+ project_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Updates entity access when an entity is **removed** from a project
+ fn remove_entity_from_project(
+ &self,
+ entity_id: &uuid::Uuid,
+ entity_type: EntityType,
+ old_project_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Updates entity access when a project is moved from one location to another
+ fn move_project(
+ &self,
+ project_id: &uuid::Uuid,
+ old_project_id: Option<&uuid::Uuid>,
+ new_project_id: Option<&uuid::Uuid>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Service for managing entity access.
+pub trait EntityAccessManagementService: Clone + Send + Sync + 'static {
+ /// Updates entity access when an entity is **added** to a project
+ fn add_entity_to_project(
+ &self,
+ entity_id: &uuid::Uuid,
+ entity_type: EntityType,
+ project_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<(), EntityAccessManagementError>> + Send;
+
+ /// Updates entity access when an entity is **removed** from a project
+ fn remove_entity_from_project(
+ &self,
+ entity_id: &uuid::Uuid,
+ entity_type: EntityType,
+ old_project_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<(), EntityAccessManagementError>> + Send;
+
+ /// Updates entity access when a project is moved from one location to another
+ fn move_project(
+ &self,
+ project_id: &uuid::Uuid,
+ old_project_id: Option<&uuid::Uuid>,
+ new_project_id: Option<&uuid::Uuid>,
+ ) -> impl Future<Output = Result<(), EntityAccessManagementError>> + Send;
+}
diff --git a/rust/cloud-storage/entity_access_management/src/domain/service.rs b/rust/cloud-storage/entity_access_management/src/domain/service.rs
new file mode 100644
index 0000000000..ef4a7f4811
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/src/domain/service.rs
@@ -0,0 +1,90 @@
+//! Entity access management service implementation.
+
+use model_entity::EntityType;
+
+use crate::domain::{
+ models::EntityAccessManagementError,
+ ports::{EntityAccessManagementRepository, EntityAccessManagementService},
+};
+
+/// Implementation of the [`EntityAccessManagementService`]
+#[derive(Clone)]
+pub struct EntityAccessManagementServiceImpl<R> {
+ repo: R,
+}
+
+impl<R: EntityAccessManagementRepository> EntityAccessManagementServiceImpl<R> {
+ /// Create a new entity access management service.
+ pub fn new(repo: R) -> Self {
+ Self { repo }
+ }
+}
+
+impl<R: EntityAccessManagementRepository> EntityAccessManagementService
+ for EntityAccessManagementServiceImpl<R>
+{
+ #[tracing::instrument(skip(self), err)]
+ async fn add_entity_to_project(
+ &self,
+ entity_id: &uuid::Uuid,
+ entity_type: EntityType,
+ project_id: &uuid::Uuid,
+ ) -> Result<(), EntityAccessManagementError> {
+ if !entity_type.is_valid_entity_access_entity() {
+ return Err(EntityAccessManagementError::UnsupportedEntityType(
+ entity_type,
+ ));
+ }
+
+ self.repo
+ .add_entity_to_project(entity_id, entity_type, project_id)
+ .await
+ .map_err(|e| EntityAccessManagementError::DatabaseError(e.into()))
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn remove_entity_from_project(
+ &self,
+ entity_id: &uuid::Uuid,
+ entity_type: EntityType,
+ old_project_id: &uuid::Uuid,
+ ) -> Result<(), EntityAccessManagementError> {
+ if !entity_type.is_valid_entity_access_entity() {
+ return Err(EntityAccessManagementError::UnsupportedEntityType(
+ entity_type,
+ ));
+ }
+
+ self.repo
+ .remove_entity_from_project(entity_id, entity_type, old_project_id)
+ .await
+ .map_err(|e| EntityAccessManagementError::DatabaseError(e.into()))
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn move_project(
+ &self,
+ project_id: &uuid::Uuid,
+ old_project_id: Option<&uuid::Uuid>,
+ new_project_id: Option<&uuid::Uuid>,
+ ) -> Result<(), EntityAccessManagementError> {
+ match (old_project_id, new_project_id) {
+ // cannot both be the same
+ (Some(old_project_id), Some(new_project_id)) => {
+ if old_project_id.eq(new_project_id) {
+ return Err(EntityAccessManagementError::InvalidProjectMove);
+ }
+ }
+ // cannot both be empty
+ (None, None) => {
+ return Err(EntityAccessManagementError::InvalidProjectMove);
+ }
+ _ => {}
+ }
+
+ self.repo
+ .move_project(project_id, old_project_id, new_project_id)
+ .await
+ .map_err(|e| EntityAccessManagementError::DatabaseError(e.into()))
+ }
+}
diff --git a/rust/cloud-storage/entity_access_management/src/lib.rs b/rust/cloud-storage/entity_access_management/src/lib.rs
new file mode 100644
index 0000000000..51480117c1
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/src/lib.rs
@@ -0,0 +1,16 @@
+//! Entity access management for cloud storage.
+//!
+//! This crate provides a hexagonal architecture implementation for managing
+//! CRUD operations on entity access.
+//!
+//! # Architecture
+//!
+//! - **domain**: Contains domain models, ports (traits), and the service implementation
+//! - **outbound**: Contains adapters for external dependencies (PostgreSQL)
+
+#![deny(missing_docs)]
+
+pub mod domain;
+
+#[cfg(feature = "outbound")]
+pub mod outbound;
diff --git a/rust/cloud-storage/entity_access_management/src/outbound.rs b/rust/cloud-storage/entity_access_management/src/outbound.rs
new file mode 100644
index 0000000000..40b67c1a05
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/src/outbound.rs
@@ -0,0 +1,7 @@
+//! Outbound adapters for entity access management.
+//!
+//! These modules contain concrete implementations of the domain ports.
+
+mod pg_repo;
+
+pub use pg_repo::PgRepository;
diff --git a/rust/cloud-storage/entity_access_management/src/outbound/pg_repo.rs b/rust/cloud-storage/entity_access_management/src/outbound/pg_repo.rs
new file mode 100644
index 0000000000..3d1275f5d4
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/src/outbound/pg_repo.rs
@@ -0,0 +1,339 @@
+//! PostgreSQL implementation of the EntityAccessManagementRepository trait.
+
+#[cfg(test)]
+mod test;
+
+use model_entity::EntityType;
+use models_permissions::share_permission::access_level::AccessLevel;
+use sqlx::{PgPool, Postgres, QueryBuilder, Transaction};
+use uuid::Uuid;
+
+use crate::domain::{models::EntityAccessSourceType, ports::EntityAccessManagementRepository};
+
+/// A source entity we need to update permissions for
+#[derive(Clone, Debug)]
+struct ProjectSourceEntity {
+ /// The project entity that was shared
+ pub project_id: uuid::Uuid,
+ /// This could be a user, channel or a team
+ pub source_id: String,
+ /// The source type
+ pub source_type: EntityAccessSourceType,
+ /// The access level for the source entity
+ pub access_level: AccessLevel,
+}
+
+/// Simple entity wrapper
+#[derive(Clone, Debug)]
+struct SimpleEntity {
+ /// The entity id
+ pub entity_id: String,
+ /// The entity type
+ pub entity_type: String,
+}
+
+/// PostgreSQL-backed implementation of [`EntityAccessManagementRepository`]
+#[derive(Clone)]
+pub struct PgRepository {
+ pool: PgPool,
+}
+
+impl PgRepository {
+ /// Create a new PgRepository
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl PgRepository {
+ /// Gets all nested entities for a given project
+ /// Includes the project itself
+ #[tracing::instrument(skip(self, transaction), err)]
+ async fn get_nested_project_entities(
+ &self,
+ transaction: &mut Transaction<'_, Postgres>,
+ project_id: &uuid::Uuid,
+ ) -> Result<Vec<SimpleEntity>, sqlx::Error> {
+ let results = sqlx::query!(
+ r#"
+ WITH RECURSIVE child_projects AS (
+ SELECT id FROM "Project" WHERE id = $1
+
+ UNION ALL
+
+ SELECT p.id FROM "Project" p
+ INNER JOIN child_projects cp ON p."parentId" = cp.id
+ )
+ SELECT id as "entity_id!", 'project' as "entity_type!" FROM child_projects
+
+ UNION ALL
+
+ SELECT d.id as "entity_id!", 'document' as "entity_type!" FROM "Document" d
+ WHERE d."projectId" IN (SELECT id FROM child_projects)
+
+ UNION ALL
+
+ SELECT c.id as "entity_id!", 'chat' as "entity_type!" FROM "Chat" c
+ WHERE c."projectId" IN (SELECT id FROM child_projects)
+
+ UNION ALL
+
+ SELECT et.id::text as "entity_id!", 'email_thread' as "entity_type!" FROM email_threads et
+ WHERE et.project_id IN (SELECT id FROM child_projects)
+ "#,
+ &project_id.to_string()
+ )
+ .map(|r| SimpleEntity {
+ entity_id: r.entity_id,
+ entity_type: r.entity_type,
+ })
+ .fetch_all(transaction.as_mut())
+ .await?;
+
+ Ok(results)
+ }
+
+ /// Walks up the project tree and grabs all projects including the project provided id
+ #[tracing::instrument(skip(self, transaction), err)]
+ async fn walk_up_project_tree(
+ &self,
+ transaction: &mut Transaction<'_, Postgres>,
+ project_id: &uuid::Uuid,
+ ) -> Result<Vec<uuid::Uuid>, sqlx::Error> {
+ let results = sqlx::query!(
+ r#"
+ WITH RECURSIVE parent_projects AS (
+ -- Base case: the project itself
+ SELECT id, name, "parentId"
+ FROM "Project"
+ WHERE id = $1
+
+ UNION ALL
+
+ -- Recursive case: walk up to the parent
+ SELECT p.id, p.name, p."parentId"
+ FROM "Project" p
+ INNER JOIN parent_projects pp ON p.id = pp."parentId"
+ )
+ SELECT id as "id!"
+ FROM parent_projects
+ "#,
+ &project_id.to_string()
+ )
+ .map(|p| Uuid::parse_str(&p.id).unwrap()) // SAFETY: the project_id is always a uuid, we just haven't migrated the type to be that in the db schema
+ .fetch_all(transaction.as_mut())
+ .await?;
+
+ Ok(results)
+ }
+
+ /// Given a list of project ids, this will return a list of all source entities (source_id/source_type/access_level) entries that we need to insert rows for the new entity
+ #[tracing::instrument(skip(self, transaction), err)]
+ async fn get_all_source_entities_for_projects(
+ &self,
+ transaction: &mut Transaction<'_, Postgres>,
+ project_ids: &[uuid::Uuid],
+ ) -> Result<Vec<ProjectSourceEntity>, sqlx::Error> {
+ // Grab every instance of any project_ids being shared
+ // This will allow us to insert records for all these source entities for the new id
+ let result = sqlx::query!(
+ r#"
+ SELECT
+ entity_id,
+ source_id,
+ source_type as "source_type:EntityAccessSourceType",
+ access_level as "access_level:AccessLevel"
+ FROM entity_access
+ WHERE entity_id = ANY($1) AND entity_type = 'project' AND granted_from_project_id IS NULL
+ "#,
+ project_ids,
+ )
+ .map(|r| ProjectSourceEntity {
+ project_id: r.entity_id,
+ source_id: r.source_id,
+ source_type: r.source_type,
+ access_level: r.access_level,
+ })
+ .fetch_all(transaction.as_mut())
+ .await?;
+
+ Ok(result)
+ }
+}
+
+impl EntityAccessManagementRepository for PgRepository {
+ type Err = sqlx::Error;
+
+ #[tracing::instrument(skip(self), err)]
+ async fn add_entity_to_project(
+ &self,
+ entity_id: &uuid::Uuid,
+ entity_type: EntityType,
+ project_id: &uuid::Uuid,
+ ) -> Result<(), Self::Err> {
+ let mut transaction = self.pool.begin().await?;
+
+ let walked_up_project_ids = self
+ .walk_up_project_tree(&mut transaction, project_id)
+ .await?;
+
+ let source_entities = self
+ .get_all_source_entities_for_projects(&mut transaction, &walked_up_project_ids)
+ .await?;
+
+ if !source_entities.is_empty() {
+ let entity_type_str: &str = entity_type.into();
+
+ let mut qb: QueryBuilder<Postgres> = QueryBuilder::new(
+ "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id) ",
+ );
+
+ qb.push_values(&source_entities, |mut b, source| {
+ b.push_bind(entity_id)
+ .push_bind(entity_type_str)
+ .push_bind(&source.source_id)
+ .push_bind(source.source_type)
+ .push_bind(source.access_level)
+ .push_bind(source.project_id.to_string());
+ });
+
+ qb.push(" ON CONFLICT DO NOTHING");
+ qb.build().execute(transaction.as_mut()).await?;
+ }
+
+ transaction.commit().await?;
+
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn remove_entity_from_project(
+ &self,
+ entity_id: &uuid::Uuid,
+ entity_type: EntityType,
+ old_project_id: &uuid::Uuid,
+ ) -> Result<(), Self::Err> {
+ let mut transaction = self.pool.begin().await?;
+
+ let walked_up_project_ids = self
+ .walk_up_project_tree(&mut transaction, old_project_id)
+ .await?;
+
+ if !walked_up_project_ids.is_empty() {
+ let entity_type_str: &str = entity_type.into();
+ sqlx::query!(
+ r#"
+ DELETE FROM entity_access
+ WHERE entity_id = $1
+ AND entity_type = $2
+ AND granted_from_project_id = ANY($3)
+ "#,
+ entity_id,
+ entity_type_str,
+ &walked_up_project_ids
+ .into_iter()
+ .map(|s| s.to_string())
+ .collect::<Vec<String>>(),
+ )
+ .execute(transaction.as_mut())
+ .await?;
+
+ transaction.commit().await?;
+ }
+
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn move_project(
+ &self,
+ project_id: &uuid::Uuid,
+ old_project_id: Option<&uuid::Uuid>,
+ new_project_id: Option<&uuid::Uuid>,
+ ) -> Result<(), Self::Err> {
+ let mut transaction = self.pool.begin().await?;
+
+ // The project entities we will need to update (including the project itself)
+ let project_entities = self
+ .get_nested_project_entities(&mut transaction, project_id)
+ .await?;
+
+ // Get all project items including the project itself
+ // If there is an old_project_id we need to remove all project item shares for the old_project_id and above
+ if let Some(old_project_id) = old_project_id {
+ // Walk project tree
+ let old_walked_up_project_ids = self
+ .walk_up_project_tree(&mut transaction, old_project_id)
+ .await?;
+
+ // Delete all entities in the project for projects shared
+ if !old_walked_up_project_ids.is_empty() {
+ sqlx::query!(
+ r#"
+ DELETE FROM entity_access
+ WHERE entity_id = ANY($1)
+ AND granted_from_project_id = ANY($2)
+ "#,
+ &project_entities
+ .iter()
+ .filter_map(|s| Uuid::parse_str(&s.entity_id).ok())
+ .collect::<Vec<uuid::Uuid>>(),
+ &old_walked_up_project_ids
+ .into_iter()
+ .map(|s| s.to_string())
+ .collect::<Vec<String>>(),
+ )
+ .execute(transaction.as_mut())
+ .await?;
+ }
+ }
+
+ // If there is a new_project_id we need to add all project item shares for new_project_id and above
+ if let Some(new_project_id) = new_project_id {
+ let new_walked_up_project_ids = self
+ .walk_up_project_tree(&mut transaction, new_project_id)
+ .await?;
+
+ // get all source entities for the new walked up projects
+ let source_entities = self
+ .get_all_source_entities_for_projects(&mut transaction, &new_walked_up_project_ids)
+ .await?;
+
+ if !source_entities.is_empty() {
+ let mut qb: QueryBuilder<Postgres> = QueryBuilder::new(
+ "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id) ",
+ );
+
+ let rows: Vec<_> = project_entities
+ .iter()
+ .filter_map(|entity| {
+ Uuid::parse_str(&entity.entity_id)
+ .ok()
+ .map(|id| (id, &entity.entity_type))
+ })
+ .flat_map(|(entity_id, entity_type)| {
+ source_entities
+ .iter()
+ .map(move |source| (entity_id, entity_type, source))
+ })
+ .collect();
+
+ qb.push_values(&rows, |mut b, (entity_id, entity_type, source)| {
+ b.push_bind(entity_id)
+ .push_bind(entity_type)
+ .push_bind(&source.source_id)
+ .push_bind(source.source_type)
+ .push_bind(source.access_level)
+ .push_bind(source.project_id.to_string());
+ });
+
+ qb.push(" ON CONFLICT DO NOTHING");
+ qb.build().execute(transaction.as_mut()).await?;
+ }
+ }
+
+ transaction.commit().await?;
+
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/entity_access_management/src/outbound/pg_repo/test.rs b/rust/cloud-storage/entity_access_management/src/outbound/pg_repo/test.rs
new file mode 100644
index 0000000000..ae5219118d
--- /dev/null
+++ b/rust/cloud-storage/entity_access_management/src/outbound/pg_repo/test.rs
@@ -0,0 +1,749 @@
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use model_entity::EntityType;
+use models_permissions::share_permission::access_level::AccessLevel;
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+use super::PgRepository;
+use crate::domain::models::EntityAccessSourceType;
+use crate::domain::ports::EntityAccessManagementRepository;
+
+const ROOT_PROJECT_ID: Uuid = Uuid::from_u128(0x11111111_1111_1111_1111_111111111111);
+const CHILD_PROJECT_ID: Uuid = Uuid::from_u128(0x22222222_2222_2222_2222_222222222222);
+const GRANDCHILD_PROJECT_ID: Uuid = Uuid::from_u128(0x33333333_3333_3333_3333_333333333333);
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
+)]
+async fn walk_up_from_grandchild_returns_all_ancestors(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+
+ let result = repo
+ .walk_up_project_tree(&mut tx, &GRANDCHILD_PROJECT_ID)
+ .await
+ .unwrap();
+
+ assert_eq!(result.len(), 3);
+ assert!(result.contains(&GRANDCHILD_PROJECT_ID));
+ assert!(result.contains(&CHILD_PROJECT_ID));
+ assert!(result.contains(&ROOT_PROJECT_ID));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
+)]
+async fn walk_up_from_root_returns_only_self(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+
+ let result = repo
+ .walk_up_project_tree(&mut tx, &ROOT_PROJECT_ID)
+ .await
+ .unwrap();
+
+ assert_eq!(result.len(), 1);
+ assert_eq!(result[0], ROOT_PROJECT_ID);
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
+)]
+async fn walk_up_nonexistent_project_returns_empty(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+ let nonexistent = Uuid::new_v4();
+
+ let result = repo
+ .walk_up_project_tree(&mut tx, &nonexistent)
+ .await
+ .unwrap();
+
+ assert!(result.is_empty());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
+)]
+async fn source_entities_returns_direct_shares_across_projects(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+
+ let result = repo
+ .get_all_source_entities_for_projects(&mut tx, &[ROOT_PROJECT_ID, CHILD_PROJECT_ID])
+ .await
+ .unwrap();
+
+ // 3 direct shares: user/edit on root, team/view on root, channel/comment on child
+ assert_eq!(result.len(), 3);
+
+ let user_entry = result
+ .iter()
+ .find(|e| e.source_id == "macro|[email protected]")
+ .unwrap();
+ assert!(matches!(
+ user_entry.source_type,
+ EntityAccessSourceType::User
+ ));
+ assert_eq!(user_entry.access_level, AccessLevel::Edit);
+
+ let team_entry = result.iter().find(|e| e.source_id == "team-one").unwrap();
+ assert!(matches!(
+ team_entry.source_type,
+ EntityAccessSourceType::Team
+ ));
+ assert_eq!(team_entry.access_level, AccessLevel::View);
+
+ let channel_entry = result
+ .iter()
+ .find(|e| e.source_id == "channel-one")
+ .unwrap();
+ assert!(matches!(
+ channel_entry.source_type,
+ EntityAccessSourceType::Channel
+ ));
+ assert_eq!(channel_entry.access_level, AccessLevel::Comment);
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
+)]
+async fn source_entities_excludes_inherited_access(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+
+ // Child project has one direct share (channel/comment) and one inherited (user/view with granted_from_project_id)
+ let result = repo
+ .get_all_source_entities_for_projects(&mut tx, &[CHILD_PROJECT_ID])
+ .await
+ .unwrap();
+
+ assert_eq!(result.len(), 1);
+ assert_eq!(result[0].source_id, "channel-one");
+ assert!(matches!(
+ result[0].source_type,
+ EntityAccessSourceType::Channel
+ ));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
+)]
+async fn source_entities_excludes_non_project_entity_type(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+
+ // Root project has 2 direct project shares + 1 document row (should be excluded)
+ let result = repo
+ .get_all_source_entities_for_projects(&mut tx, &[ROOT_PROJECT_ID])
+ .await
+ .unwrap();
+
+ assert_eq!(result.len(), 2);
+ assert!(
+ result
+ .iter()
+ .all(|e| e.source_id != "macro|[email protected]"
+ || matches!(e.source_type, EntityAccessSourceType::User))
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
+)]
+async fn source_entities_empty_for_project_without_access(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+
+ let result = repo
+ .get_all_source_entities_for_projects(&mut tx, &[GRANDCHILD_PROJECT_ID])
+ .await
+ .unwrap();
+
+ assert!(result.is_empty());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
+)]
+async fn source_entities_empty_for_nonexistent_project(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+ let nonexistent = Uuid::new_v4();
+
+ let result = repo
+ .get_all_source_entities_for_projects(&mut tx, &[nonexistent])
+ .await
+ .unwrap();
+
+ assert!(result.is_empty());
+}
+
+/// Simulates adding an entity to PROJECT_C in a 3-level hierarchy with
+/// different owners at each level.
+///
+/// Project tree:
+/// PROJECT_A (owner: user_a)
+/// PROJECT_B (owner: user_b)
+/// PROJECT_C (owner: user_c)
+///
+/// The `entity_access` table contains 12 rows total:
+///
+/// | entity_id | source_id | source_type | access_level | granted_from_project_id |
+/// |-----------|-----------|-------------|--------------|-------------------------|
+/// | project_a | user_a | user | owner | NULL |
+/// | project_b | user_b | user | owner | NULL |
+/// | project_c | user_c | user | owner | NULL |
+/// | project_a | channel_1 | channel | view | NULL |
+/// | project_b | team_1 | team | edit | NULL |
+/// | project_c | channel_2 | channel | comment | NULL |
+/// | project_b | user_a | user | owner | project_a |
+/// | project_c | user_a | user | owner | project_a |
+/// | project_c | user_b | user | owner | project_b |
+/// | project_b | channel_1 | channel | view | project_a |
+/// | project_c | channel_1 | channel | view | project_a |
+/// | project_c | team_1 | team | edit | project_b |
+///
+/// Walking up from PROJECT_C gives [A, B, C]. The query should return only the
+/// 6 direct shares (where `granted_from_project_id IS NULL`), excluding the 6
+/// inherited rows.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("complex_project_tree_test_data"))
+)]
+async fn source_entities_for_full_tree_walk_returns_only_direct_shares(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+
+ let project_a = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
+ let project_b = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb").unwrap();
+ let project_c = Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc").unwrap();
+
+ // Simulates walk_up_project_tree from PROJECT_C → [A, B, C]
+ let result = repo
+ .get_all_source_entities_for_projects(&mut tx, &[project_a, project_b, project_c])
+ .await
+ .unwrap();
+
+ // 6 direct shares total: 3 users + 1 team + 2 channels
+ // All 6 inherited rows (granted_from_project_id IS NOT NULL) should be excluded
+ assert_eq!(result.len(), 6);
+
+ // 3 user owner records
+ let users: Vec<_> = result
+ .iter()
+ .filter(|e| matches!(e.source_type, EntityAccessSourceType::User))
+ .collect();
+ assert_eq!(users.len(), 3);
+ assert!(users.iter().any(|e| e.source_id == "macro|[email protected]" && e.access_level == AccessLevel::Owner));
+ assert!(users.iter().any(|e| e.source_id == "macro|[email protected]" && e.access_level == AccessLevel::Owner));
+ assert!(users.iter().any(|e| e.source_id == "macro|[email protected]" && e.access_level == AccessLevel::Owner));
+
+ // 2 channel shares
+ let channels: Vec<_> = result
+ .iter()
+ .filter(|e| matches!(e.source_type, EntityAccessSourceType::Channel))
+ .collect();
+ assert_eq!(channels.len(), 2);
+ assert!(
+ channels
+ .iter()
+ .any(|e| e.source_id == "channel-1" && e.access_level == AccessLevel::View)
+ );
+ assert!(
+ channels
+ .iter()
+ .any(|e| e.source_id == "channel-2" && e.access_level == AccessLevel::Comment)
+ );
+
+ // 1 team share
+ let teams: Vec<_> = result
+ .iter()
+ .filter(|e| matches!(e.source_type, EntityAccessSourceType::Team))
+ .collect();
+ assert_eq!(teams.len(), 1);
+ assert_eq!(teams[0].source_id, "team-1");
+ assert_eq!(teams[0].access_level, AccessLevel::Edit);
+}
+
+/// Adds a document to PROJECT_C and verifies that `add_entity_to_project`
+/// inserts 6 entity_access rows — one for each direct share found across
+/// the full ancestor chain [A, B, C].
+///
+/// Expected inserted rows (all with granted_from_project_id set):
+///
+/// | source_id | source_type | access_level | granted_from_project_id |
+/// |-----------|-------------|--------------|-------------------------|
+/// | user_a | user | owner | project_a |
+/// | user_b | user | owner | project_b |
+/// | user_c | user | owner | project_c |
+/// | channel_1 | channel | view | project_a |
+/// | team_1 | team | edit | project_b |
+/// | channel_2 | channel | comment | project_c |
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("complex_project_tree_test_data"))
+)]
+async fn add_entity_to_project_inserts_access_for_all_ancestor_shares(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+
+ let document_id = Uuid::new_v4();
+ let project_c = Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc").unwrap();
+
+ repo.add_entity_to_project(&document_id, EntityType::Document, &project_c)
+ .await
+ .unwrap();
+
+ // Query the inserted rows for this document
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ source_id,
+ source_type as "source_type:EntityAccessSourceType",
+ access_level as "access_level:AccessLevel",
+ granted_from_project_id,
+ entity_type
+ FROM entity_access
+ WHERE entity_id = $1
+ ORDER BY source_id
+ "#,
+ &document_id,
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(rows.len(), 6);
+
+ // All rows should be entity_type = 'document'
+ assert!(rows.iter().all(|r| r.entity_type == "document"));
+
+ // All rows should have granted_from_project_id set (none are direct shares on the document)
+ assert!(rows.iter().all(|r| r.granted_from_project_id.is_some()));
+
+ // channel-1: view, granted from project_a
+ let ch1 = rows.iter().find(|r| r.source_id == "channel-1").unwrap();
+ assert_eq!(ch1.access_level, AccessLevel::View);
+ assert_eq!(
+ ch1.granted_from_project_id.as_deref(),
+ Some("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
+ );
+
+ // channel-2: comment, granted from project_c
+ let ch2 = rows.iter().find(|r| r.source_id == "channel-2").unwrap();
+ assert_eq!(ch2.access_level, AccessLevel::Comment);
+ assert_eq!(
+ ch2.granted_from_project_id.as_deref(),
+ Some("cccccccc-cccc-cccc-cccc-cccccccccccc")
+ );
+
+ // team-1: edit, granted from project_b
+ let t1 = rows.iter().find(|r| r.source_id == "team-1").unwrap();
+ assert_eq!(t1.access_level, AccessLevel::Edit);
+ assert_eq!(
+ t1.granted_from_project_id.as_deref(),
+ Some("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")
+ );
+
+ // user_a: owner, granted from project_a
+ let ua = rows
+ .iter()
+ .find(|r| r.source_id == "macro|[email protected]")
+ .unwrap();
+ assert_eq!(ua.access_level, AccessLevel::Owner);
+ assert_eq!(
+ ua.granted_from_project_id.as_deref(),
+ Some("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
+ );
+
+ // user_b: owner, granted from project_b
+ let ub = rows
+ .iter()
+ .find(|r| r.source_id == "macro|[email protected]")
+ .unwrap();
+ assert_eq!(ub.access_level, AccessLevel::Owner);
+ assert_eq!(
+ ub.granted_from_project_id.as_deref(),
+ Some("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")
+ );
+
+ // user_c: owner, granted from project_c
+ let uc = rows
+ .iter()
+ .find(|r| r.source_id == "macro|[email protected]")
+ .unwrap();
+ assert_eq!(uc.access_level, AccessLevel::Owner);
+ assert_eq!(
+ uc.granted_from_project_id.as_deref(),
+ Some("cccccccc-cccc-cccc-cccc-cccccccccccc")
+ );
+}
+
+/// Adds a document to PROJECT_C then removes it, verifying that all 6
+/// inherited access rows are deleted while the pre-existing project
+/// access rows remain untouched.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("complex_project_tree_test_data"))
+)]
+async fn remove_entity_from_project_deletes_inherited_access(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+
+ let document_id = Uuid::new_v4();
+ let project_c = Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc").unwrap();
+
+ // Add entity to project — creates 6 inherited access rows
+ repo.add_entity_to_project(&document_id, EntityType::Document, &project_c)
+ .await
+ .unwrap();
+
+ // Verify 6 rows exist before removal
+ let before_count = sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM entity_access WHERE entity_id = $1",
+ &document_id,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(before_count, Some(6));
+
+ // Remove entity from project
+ repo.remove_entity_from_project(&document_id, EntityType::Document, &project_c)
+ .await
+ .unwrap();
+
+ // All 6 document rows should be gone
+ let after_count = sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM entity_access WHERE entity_id = $1",
+ &document_id,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(after_count, Some(0));
+
+ // Pre-existing project access rows should be untouched (12 rows from fixture)
+ let project_rows =
+ sqlx::query_scalar!("SELECT COUNT(*) FROM entity_access WHERE entity_type = 'project'",)
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(project_rows, Some(12));
+}
+
+/// Calling from PROJECT_A (root) should return the full tree:
+/// 3 projects (A, B, C) + 1 document in A + 1 chat in B + 1 document in C = 6 entities
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("complex_project_tree_test_data"))
+)]
+async fn nested_entities_from_root_returns_full_tree(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+ let project_a = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
+
+ let result = repo
+ .get_nested_project_entities(&mut tx, &project_a)
+ .await
+ .unwrap();
+
+ assert_eq!(result.len(), 6);
+
+ let projects: Vec<_> = result
+ .iter()
+ .filter(|e| e.entity_type == "project")
+ .collect();
+ assert_eq!(projects.len(), 3);
+
+ let documents: Vec<_> = result
+ .iter()
+ .filter(|e| e.entity_type == "document")
+ .collect();
+ assert_eq!(documents.len(), 2);
+ assert!(documents.iter().any(|e| e.entity_id == "doc-in-a"));
+ assert!(documents.iter().any(|e| e.entity_id == "doc-in-c"));
+
+ let chats: Vec<_> = result.iter().filter(|e| e.entity_type == "chat").collect();
+ assert_eq!(chats.len(), 1);
+ assert_eq!(chats[0].entity_id, "chat-in-b");
+}
+
+/// Calling from PROJECT_B should return B's subtree:
+/// 2 projects (B, C) + 1 chat in B + 1 document in C = 4 entities
+/// Should NOT include project_a or doc-in-a.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("complex_project_tree_test_data"))
+)]
+async fn nested_entities_from_mid_returns_subtree_only(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+ let project_b = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb").unwrap();
+
+ let result = repo
+ .get_nested_project_entities(&mut tx, &project_b)
+ .await
+ .unwrap();
+
+ assert_eq!(result.len(), 4);
+
+ let projects: Vec<_> = result
+ .iter()
+ .filter(|e| e.entity_type == "project")
+ .collect();
+ assert_eq!(projects.len(), 2);
+ assert!(
+ !projects
+ .iter()
+ .any(|e| e.entity_id == "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
+ );
+
+ assert!(result.iter().any(|e| e.entity_id == "chat-in-b"));
+ assert!(result.iter().any(|e| e.entity_id == "doc-in-c"));
+ assert!(!result.iter().any(|e| e.entity_id == "doc-in-a"));
+}
+
+/// Calling from PROJECT_C (leaf) should return:
+/// 1 project (C) + 1 document in C = 2 entities
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("complex_project_tree_test_data"))
+)]
+async fn nested_entities_from_leaf_returns_self_and_children(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+ let project_c = Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc").unwrap();
+
+ let result = repo
+ .get_nested_project_entities(&mut tx, &project_c)
+ .await
+ .unwrap();
+
+ assert_eq!(result.len(), 2);
+ assert!(result.iter().any(
+ |e| e.entity_type == "project" && e.entity_id == "cccccccc-cccc-cccc-cccc-cccccccccccc"
+ ));
+ assert!(
+ result
+ .iter()
+ .any(|e| e.entity_type == "document" && e.entity_id == "doc-in-c")
+ );
+}
+
+/// Non-existent project returns empty.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("complex_project_tree_test_data"))
+)]
+async fn nested_entities_nonexistent_project_returns_empty(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let mut tx = pool.begin().await.unwrap();
+ let nonexistent = Uuid::new_v4();
+
+ let result = repo
+ .get_nested_project_entities(&mut tx, &nonexistent)
+ .await
+ .unwrap();
+
+ assert!(result.is_empty());
+}
+
+/// Move PROJECT_B from under PROJECT_A to under PROJECT_D.
+///
+/// Project tree before:
+/// PROJECT_A (user_a/owner, channel-1/view)
+/// PROJECT_B (user_b/owner, team-1/edit)
+/// PROJECT_C (user_c/owner)
+/// doc_in_c
+/// doc_in_b
+/// PROJECT_D (user_d/owner, team-2/comment)
+///
+/// Project tree after:
+/// PROJECT_A (unchanged)
+/// PROJECT_D
+/// PROJECT_B
+/// PROJECT_C
+/// doc_in_c
+/// doc_in_b
+///
+/// The move should:
+/// - Remove all inherited access from project_a for B's nested entities (8 rows)
+/// - Add inherited access from project_d for B's nested entities (8 rows)
+/// - Leave project_a's own access and project_d's own access untouched
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("move_project_test_data"))
+)]
+async fn move_project_from_a_to_d_updates_inherited_access(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+
+ let project_a = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
+ let project_b = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb").unwrap();
+ let project_c = Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc").unwrap();
+ let project_d = Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap();
+ let doc_in_b = Uuid::parse_str("d1111111-1111-1111-1111-111111111111").unwrap();
+ let doc_in_c = Uuid::parse_str("d2222222-2222-2222-2222-222222222222").unwrap();
+
+ repo.move_project(&project_b, Some(&project_a), Some(&project_d))
+ .await
+ .unwrap();
+
+ // Helper to count entity_access rows for a given entity
+ let count_for = |pool: Pool<Postgres>, entity_id: Uuid| async move {
+ sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM entity_access WHERE entity_id = $1",
+ &entity_id,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap()
+ .unwrap_or(0)
+ };
+
+ // Helper to check grants from a specific project
+ let grants_from = |pool: Pool<Postgres>, entity_id: Uuid, project: &'static str| async move {
+ sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM entity_access WHERE entity_id = $1 AND granted_from_project_id = $2",
+ &entity_id,
+ project,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap()
+ .unwrap_or(0)
+ };
+
+ // -- project_a: unchanged (2 direct shares, no inherited)
+ assert_eq!(count_for(pool.clone(), project_a).await, 2);
+
+ // -- project_d: unchanged (2 direct shares, no inherited)
+ assert_eq!(count_for(pool.clone(), project_d).await, 2);
+
+ // -- project_b: 2 direct + 2 from D (lost 2 from A)
+ assert_eq!(count_for(pool.clone(), project_b).await, 4);
+ assert_eq!(
+ grants_from(
+ pool.clone(),
+ project_b,
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
+ )
+ .await,
+ 0
+ );
+ assert_eq!(
+ grants_from(
+ pool.clone(),
+ project_b,
+ "dddddddd-dddd-dddd-dddd-dddddddddddd"
+ )
+ .await,
+ 2
+ );
+
+ // -- project_c: 1 direct + 2 from B + 2 from D (lost 2 from A)
+ assert_eq!(count_for(pool.clone(), project_c).await, 5);
+ assert_eq!(
+ grants_from(
+ pool.clone(),
+ project_c,
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
+ )
+ .await,
+ 0
+ );
+ assert_eq!(
+ grants_from(
+ pool.clone(),
+ project_c,
+ "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
+ )
+ .await,
+ 2
+ );
+ assert_eq!(
+ grants_from(
+ pool.clone(),
+ project_c,
+ "dddddddd-dddd-dddd-dddd-dddddddddddd"
+ )
+ .await,
+ 2
+ );
+
+ // -- doc_in_b: 2 from B + 2 from D (lost 2 from A)
+ assert_eq!(count_for(pool.clone(), doc_in_b).await, 4);
+ assert_eq!(
+ grants_from(
+ pool.clone(),
+ doc_in_b,
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
+ )
+ .await,
+ 0
+ );
+ assert_eq!(
+ grants_from(
+ pool.clone(),
+ doc_in_b,
+ "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
+ )
+ .await,
+ 2
+ );
+ assert_eq!(
+ grants_from(
+ pool.clone(),
+ doc_in_b,
+ "dddddddd-dddd-dddd-dddd-dddddddddddd"
+ )
+ .await,
+ 2
+ );
+
+ // -- doc_in_c: 2 from B + 1 from C + 2 from D (lost 2 from A)
+ assert_eq!(count_for(pool.clone(), doc_in_c).await, 5);
+ assert_eq!(
+ grants_from(
+ pool.clone(),
+ doc_in_c,
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
+ )
+ .await,
+ 0
+ );
+ assert_eq!(
+ grants_from(
+ pool.clone(),
+ doc_in_c,
+ "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
+ )
+ .await,
+ 2
+ );
+ assert_eq!(
+ grants_from(
+ pool.clone(),
+ doc_in_c,
+ "cccccccc-cccc-cccc-cccc-cccccccccccc"
+ )
+ .await,
+ 1
+ );
+ assert_eq!(
+ grants_from(
+ pool.clone(),
+ doc_in_c,
+ "dddddddd-dddd-dddd-dddd-dddddddddddd"
+ )
+ .await,
+ 2
+ );
+}
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index 8170c97364..bcc3274b31 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -90,6 +90,7 @@ setup_test_envs:
echo "DATABASE_URL={{ MACRODB }}" >> ./memory/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./call/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./backfill_entity_access/.env
+ echo "DATABASE_URL={{ MACRODB }}" >> ./entity_access_management/.env
setup_macrodb:
just macro_db_client/create_db
diff --git a/rust/cloud-storage/model-entity/src/lib.rs b/rust/cloud-storage/model-entity/src/lib.rs
index c20fbefd74..dedf36311b 100644
--- a/rust/cloud-storage/model-entity/src/lib.rs
+++ b/rust/cloud-storage/model-entity/src/lib.rs
@@ -48,6 +48,19 @@ pub enum EntityType {
}
impl EntityType {
+ /// Returns if the given entity type is a valid entity that is stored in
+ /// entity_access
+ pub fn is_valid_entity_access_entity(&self) -> bool {
+ match self {
+ EntityType::User => false,
+ EntityType::Team => false,
+ EntityType::Channel => false,
+ EntityType::Chat => true,
+ EntityType::Document => true,
+ EntityType::Project => true,
+ EntityType::EmailThread => true,
+ }
+ }
/// provide an entity string slice to upgrade this type into an [Entity]
pub fn with_entity_str<'a>(self, entity_id: &'a str) -> Entity<'a> {
Entity {