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(sharing): team based document sharing (#6294)

Will Hutchinson4d102c45b7ff
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 562e88453b..9c3c202132 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -5763,6 +5763,9 @@
"crates/workspace-hack"
],
"models_permissions": [
+ "crates/cowlike",
+ "crates/macro_user_id",
+ "crates/model-entity",
"crates/model_file_type",
"crates/models_permissions",
"crates/workspace-hack"
diff --git a/.sqlx/query-08830ba66af17ab6460014274ac62949771a4176fb94d501d7608bd79122be83.json b/.sqlx/query-08830ba66af17ab6460014274ac62949771a4176fb94d501d7608bd79122be83.json
new file mode 100644
index 0000000000..1772637cf8
--- /dev/null
+++ b/.sqlx/query-08830ba66af17ab6460014274ac62949771a4176fb94d501d7608bd79122be83.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n VALUES ($1, $2, $3, 'user', 'owner')\n ON CONFLICT (entity_id, entity_type, source_id, source_type)\n WHERE granted_from_project_id IS NULL\n DO UPDATE SET access_level = EXCLUDED.access_level\n WHERE entity_access.access_level = 'owner'\n RETURNING id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "08830ba66af17ab6460014274ac62949771a4176fb94d501d7608bd79122be83"
+}
diff --git a/.sqlx/query-261f2488ff9657bf310fc23517f87f99d08a5e8a433b1742ca116114e0f914c7.json b/.sqlx/query-261f2488ff9657bf310fc23517f87f99d08a5e8a433b1742ca116114e0f914c7.json
new file mode 100644
index 0000000000..52467b582a
--- /dev/null
+++ b/.sqlx/query-261f2488ff9657bf310fc23517f87f99d08a5e8a433b1742ca116114e0f914c7.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT pg_advisory_xact_lock(1413824845, 1)",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "pg_advisory_xact_lock",
+ "type_info": "Void"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "261f2488ff9657bf310fc23517f87f99d08a5e8a433b1742ca116114e0f914c7"
+}
diff --git a/.sqlx/query-2b51093ef799db343575cce3aead5f7db7aed774cb8d6fd74645f5e09b2215c6.json b/.sqlx/query-2b51093ef799db343575cce3aead5f7db7aed774cb8d6fd74645f5e09b2215c6.json
deleted file mode 100644
index 08b8cc2ff7..0000000000
--- a/.sqlx/query-2b51093ef799db343575cce3aead5f7db7aed774cb8d6fd74645f5e09b2215c6.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'document'\n AND source_id = $2\n AND source_type = 'team'\n AND granted_from_project_id IS NULL\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "2b51093ef799db343575cce3aead5f7db7aed774cb8d6fd74645f5e09b2215c6"
-}
diff --git a/.sqlx/query-2e0d56c9e8fecdbbd5ca1853876f9bf94f8980710a99f36274ab20bd75514a52.json b/.sqlx/query-2e0d56c9e8fecdbbd5ca1853876f9bf94f8980710a99f36274ab20bd75514a52.json
deleted file mode 100644
index e08e9ad42e..0000000000
--- a/.sqlx/query-2e0d56c9e8fecdbbd5ca1853876f9bf94f8980710a99f36274ab20bd75514a52.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n VALUES ($1, 'document', $2, 'team', $3)\n ON CONFLICT (entity_id, entity_type, source_id, source_type)\n WHERE granted_from_project_id IS NULL\n DO UPDATE SET access_level = EXCLUDED.access_level, updated_at = NOW()\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- ]
- },
- "nullable": []
- },
- "hash": "2e0d56c9e8fecdbbd5ca1853876f9bf94f8980710a99f36274ab20bd75514a52"
-}
diff --git a/.sqlx/query-2ee350d02ebbe557a37fe8043f07e273a12029b93eae4ac40b6cf4aeb449b1bb.json b/.sqlx/query-2ee350d02ebbe557a37fe8043f07e273a12029b93eae4ac40b6cf4aeb449b1bb.json
new file mode 100644
index 0000000000..1ec92adec5
--- /dev/null
+++ b/.sqlx/query-2ee350d02ebbe557a37fe8043f07e273a12029b93eae4ac40b6cf4aeb449b1bb.json
@@ -0,0 +1,36 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT access_level AS \"access_level: AccessLevel\" FROM entity_access\n WHERE entity_id = $1 AND entity_type = $2 AND source_type = 'team'\n AND source_id = $3 AND granted_from_project_id IS NULL",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "2ee350d02ebbe557a37fe8043f07e273a12029b93eae4ac40b6cf4aeb449b1bb"
+}
diff --git a/.sqlx/query-3d1a9b0be46b179bb49c528164c06da76897575d69f08613c01b6fc09f9b3a66.json b/.sqlx/query-3d1a9b0be46b179bb49c528164c06da76897575d69f08613c01b6fc09f9b3a66.json
deleted file mode 100644
index 5b63ce00be..0000000000
--- a/.sqlx/query-3d1a9b0be46b179bb49c528164c06da76897575d69f08613c01b6fc09f9b3a66.json
+++ /dev/null
@@ -1,58 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n sp.id as id,\n sp.\"linkShare\" as \"link_share?\",\n sp.\"linkShareAccessLevel\" as \"link_share_access_level?: AccessLevel\",\n m.\"user_id\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"MacroPromptPermission\" mpp\n JOIN \"SharePermission\" sp ON mpp.\"share_permission_id\" = sp.id\n JOIN \"MacroPrompt\" m ON mpp.\"macro_prompt_id\" = m.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n mpp.\"macro_prompt_id\" = $1\n GROUP BY\n sp.id, m.\"user_id\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "link_share?",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "link_share_access_level?: AccessLevel",
- "type_info": {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- },
- {
- "ordinal": 3,
- "name": "owner",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "channel_share_permissions?",
- "type_info": "Json"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- true,
- false,
- null
- ]
- },
- "hash": "3d1a9b0be46b179bb49c528164c06da76897575d69f08613c01b6fc09f9b3a66"
-}
diff --git a/.sqlx/query-45b2c2170f17a9efc5f4b6fe9c00d480c3dcb6d3c45c60d99b6fcec98e88a1a0.json b/.sqlx/query-45b2c2170f17a9efc5f4b6fe9c00d480c3dcb6d3c45c60d99b6fcec98e88a1a0.json
new file mode 100644
index 0000000000..c457203b67
--- /dev/null
+++ b/.sqlx/query-45b2c2170f17a9efc5f4b6fe9c00d480c3dcb6d3c45c60d99b6fcec98e88a1a0.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE \"SharePermission\" SET team_share_access_level = $2,\n team_share_team_id = $3, team_share_revision = $4, \"updatedAt\" = NOW()\n WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ },
+ "Uuid",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "45b2c2170f17a9efc5f4b6fe9c00d480c3dcb6d3c45c60d99b6fcec98e88a1a0"
+}
diff --git a/.sqlx/query-581f7f1d0b0bdaf637c1ec9557bae1df7fead693e3f32fca43af8374abdb27c7.json b/.sqlx/query-581f7f1d0b0bdaf637c1ec9557bae1df7fead693e3f32fca43af8374abdb27c7.json
deleted file mode 100644
index 20022dc309..0000000000
--- a/.sqlx/query-581f7f1d0b0bdaf637c1ec9557bae1df7fead693e3f32fca43af8374abdb27c7.json
+++ /dev/null
@@ -1,58 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n sp.id as id,\n sp.\"linkShare\" as \"link_share?\",\n sp.\"linkShareAccessLevel\" as \"link_share_access_level?: AccessLevel\",\n d.\"owner\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"DocumentPermission\" dp\n JOIN \"SharePermission\" sp ON dp.\"sharePermissionId\" = sp.id\n JOIN \"Document\" d ON dp.\"documentId\" = d.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n dp.\"documentId\" = $1\n GROUP BY\n sp.id, d.\"owner\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "link_share?",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "link_share_access_level?: AccessLevel",
- "type_info": {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- },
- {
- "ordinal": 3,
- "name": "owner",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "channel_share_permissions?",
- "type_info": "Json"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- true,
- false,
- null
- ]
- },
- "hash": "581f7f1d0b0bdaf637c1ec9557bae1df7fead693e3f32fca43af8374abdb27c7"
-}
diff --git a/.sqlx/query-81f5ce2ce0be7f1460be990c23288fd34664ebdd528c147bf5e045879b4bb5a5.json b/.sqlx/query-81f5ce2ce0be7f1460be990c23288fd34664ebdd528c147bf5e045879b4bb5a5.json
new file mode 100644
index 0000000000..e71c23cf01
--- /dev/null
+++ b/.sqlx/query-81f5ce2ce0be7f1460be990c23288fd34664ebdd528c147bf5e045879b4bb5a5.json
@@ -0,0 +1,76 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n sp.id as id,\n sp.\"linkShare\" as \"link_share?\",\n sp.\"linkShareAccessLevel\" as \"link_share_access_level?: AccessLevel\",\n sp.team_share_access_level as \"team_share_access_level?: AccessLevel\",\n m.\"user_id\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"MacroPromptPermission\" mpp\n JOIN \"SharePermission\" sp ON mpp.\"share_permission_id\" = sp.id\n JOIN \"MacroPrompt\" m ON mpp.\"macro_prompt_id\" = m.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n mpp.\"macro_prompt_id\" = $1\n GROUP BY\n sp.id, m.\"user_id\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "link_share?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "link_share_access_level?: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "team_share_access_level?: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 4,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "channel_share_permissions?",
+ "type_info": "Json"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ true,
+ true,
+ false,
+ null
+ ]
+ },
+ "hash": "81f5ce2ce0be7f1460be990c23288fd34664ebdd528c147bf5e045879b4bb5a5"
+}
diff --git a/.sqlx/query-a1233219aac966d8b6d0d68a02fcb705dd6e9b02375d09185c2cb47c8a70a973.json b/.sqlx/query-a1233219aac966d8b6d0d68a02fcb705dd6e9b02375d09185c2cb47c8a70a973.json
new file mode 100644
index 0000000000..c45f320d6f
--- /dev/null
+++ b/.sqlx/query-a1233219aac966d8b6d0d68a02fcb705dd6e9b02375d09185c2cb47c8a70a973.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n VALUES ($1, $2, $3, 'team', $4)\n ON CONFLICT (entity_id, entity_type, source_id, source_type)\n WHERE granted_from_project_id IS NULL\n DO UPDATE SET access_level = EXCLUDED.access_level, updated_at = NOW()",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "a1233219aac966d8b6d0d68a02fcb705dd6e9b02375d09185c2cb47c8a70a973"
+}
diff --git a/.sqlx/query-a7832517d221d29aa99d08a22e78322e3df103c95a29a3809f65713ab99bb58b.json b/.sqlx/query-a7832517d221d29aa99d08a22e78322e3df103c95a29a3809f65713ab99bb58b.json
new file mode 100644
index 0000000000..c47ed13b8b
--- /dev/null
+++ b/.sqlx/query-a7832517d221d29aa99d08a22e78322e3df103c95a29a3809f65713ab99bb58b.json
@@ -0,0 +1,76 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n sp.id as id,\n sp.\"linkShare\" as \"link_share?\",\n sp.\"linkShareAccessLevel\" as \"link_share_access_level?: AccessLevel\",\n sp.team_share_access_level as \"team_share_access_level?: AccessLevel\",\n d.\"owner\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"DocumentPermission\" dp\n JOIN \"SharePermission\" sp ON dp.\"sharePermissionId\" = sp.id\n JOIN \"Document\" d ON dp.\"documentId\" = d.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n dp.\"documentId\" = $1\n GROUP BY\n sp.id, d.\"owner\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "link_share?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "link_share_access_level?: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "team_share_access_level?: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 4,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "channel_share_permissions?",
+ "type_info": "Json"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ true,
+ true,
+ false,
+ null
+ ]
+ },
+ "hash": "a7832517d221d29aa99d08a22e78322e3df103c95a29a3809f65713ab99bb58b"
+}
diff --git a/.sqlx/query-a9ba876cdea3984f33b7d2a26583ef081da92d7c68b27e9057f9a8a4504820af.json b/.sqlx/query-a9ba876cdea3984f33b7d2a26583ef081da92d7c68b27e9057f9a8a4504820af.json
new file mode 100644
index 0000000000..0f102500f8
--- /dev/null
+++ b/.sqlx/query-a9ba876cdea3984f33b7d2a26583ef081da92d7c68b27e9057f9a8a4504820af.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM entity_access\n WHERE entity_id = $1 AND entity_type = $2 AND source_type = 'team'\n AND source_id = $3 AND granted_from_project_id IS NULL",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "a9ba876cdea3984f33b7d2a26583ef081da92d7c68b27e9057f9a8a4504820af"
+}
diff --git a/.sqlx/query-aaa2d6b9fffae680da9e50bc699ccb6d9102f4bffb0aa4948036bd7c81af600c.json b/.sqlx/query-aaa2d6b9fffae680da9e50bc699ccb6d9102f4bffb0aa4948036bd7c81af600c.json
new file mode 100644
index 0000000000..3ef9576d92
--- /dev/null
+++ b/.sqlx/query-aaa2d6b9fffae680da9e50bc699ccb6d9102f4bffb0aa4948036bd7c81af600c.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT current_setting('transaction_isolation')",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "current_setting",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "aaa2d6b9fffae680da9e50bc699ccb6d9102f4bffb0aa4948036bd7c81af600c"
+}
diff --git a/.sqlx/query-aab0a1bf68d63f534ec4c3014d3abee18bd3f454d90a890c03b1d686f9b84a26.json b/.sqlx/query-aab0a1bf68d63f534ec4c3014d3abee18bd3f454d90a890c03b1d686f9b84a26.json
new file mode 100644
index 0000000000..bdc8676526
--- /dev/null
+++ b/.sqlx/query-aab0a1bf68d63f534ec4c3014d3abee18bd3f454d90a890c03b1d686f9b84a26.json
@@ -0,0 +1,72 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "WITH entity AS (\n SELECT d.owner, dp.\"sharePermissionId\" AS permission_id\n FROM \"Document\" d LEFT JOIN \"DocumentPermission\" dp ON dp.\"documentId\" = d.id\n WHERE $2 = 'document' AND d.id = $1\n UNION ALL\n SELECT p.\"userId\", pp.\"sharePermissionId\"\n FROM \"Project\" p LEFT JOIN \"ProjectPermission\" pp ON pp.\"projectId\" = p.id\n WHERE $2 = 'project' AND p.id = $1\n UNION ALL\n SELECT c.\"userId\", cp.\"sharePermissionId\"\n FROM \"Chat\" c LEFT JOIN \"ChatPermission\" cp ON cp.\"chatId\" = c.id\n WHERE $2 = 'chat' AND c.id = $1\n UNION ALL\n SELECT l.macro_id, tp.\"sharePermissionId\"\n FROM email_threads t JOIN email_links l ON l.id = t.link_id\n LEFT JOIN \"EmailThreadPermission\" tp ON tp.\"threadId\" = t.id::text\n WHERE $2 = 'email_thread' AND t.id = $3\n UNION ALL\n SELECT c.created_by, c.share_permission_id FROM calls c\n WHERE $2 = 'call' AND c.id = $3\n UNION ALL\n SELECT c.created_by, c.share_permission_id FROM call_records c\n WHERE $2 = 'call' AND c.id = $3 AND NOT EXISTS (SELECT 1 FROM calls WHERE id = $3)\n )\n SELECT e.owner AS \"owner!\", e.permission_id,\n sp.id AS \"stored_permission_id?\",\n sp.team_share_access_level AS \"level: AccessLevel\",\n sp.team_share_team_id AS team_id, sp.team_share_revision AS \"revision?\",\n (SELECT tu.team_id FROM team_user tu WHERE tu.user_id = e.owner\n ORDER BY tu.team_role DESC LIMIT 1) AS owner_team_id\n FROM entity e LEFT JOIN \"SharePermission\" sp ON sp.id = e.permission_id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "owner!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "permission_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "stored_permission_id?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "level: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 4,
+ "name": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 5,
+ "name": "revision?",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 6,
+ "name": "owner_team_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ false,
+ true,
+ true,
+ false,
+ null
+ ]
+ },
+ "hash": "aab0a1bf68d63f534ec4c3014d3abee18bd3f454d90a890c03b1d686f9b84a26"
+}
diff --git a/.sqlx/query-bd3617e099b8f193c51f33d2bae4ef7cad029be4002f44f6a7de23b0ce50f5f8.json b/.sqlx/query-bd3617e099b8f193c51f33d2bae4ef7cad029be4002f44f6a7de23b0ce50f5f8.json
deleted file mode 100644
index 4634d1485a..0000000000
--- a/.sqlx/query-bd3617e099b8f193c51f33d2bae4ef7cad029be4002f44f6a7de23b0ce50f5f8.json
+++ /dev/null
@@ -1,58 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n sp.id as id,\n sp.\"linkShare\" as \"link_share?\",\n sp.\"linkShareAccessLevel\" as \"link_share_access_level?: AccessLevel\",\n c.\"userId\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"ChatPermission\" cp\n JOIN \"SharePermission\" sp ON cp.\"sharePermissionId\" = sp.id\n JOIN \"Chat\" c ON cp.\"chatId\" = c.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n cp.\"chatId\" = $1\n GROUP BY\n sp.id, c.\"userId\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "link_share?",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "link_share_access_level?: AccessLevel",
- "type_info": {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- },
- {
- "ordinal": 3,
- "name": "owner",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "channel_share_permissions?",
- "type_info": "Json"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- true,
- false,
- null
- ]
- },
- "hash": "bd3617e099b8f193c51f33d2bae4ef7cad029be4002f44f6a7de23b0ce50f5f8"
-}
diff --git a/.sqlx/query-de888f70b426374eb436dfab5e58cab5a5d5423325a7834515c9c6a327f25f50.json b/.sqlx/query-de888f70b426374eb436dfab5e58cab5a5d5423325a7834515c9c6a327f25f50.json
deleted file mode 100644
index 4f08d6fc9f..0000000000
--- a/.sqlx/query-de888f70b426374eb436dfab5e58cab5a5d5423325a7834515c9c6a327f25f50.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT tu.team_id\n FROM \"Document\" d\n JOIN team_user tu ON tu.user_id = d.owner\n WHERE d.id = $1\n LIMIT 1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "team_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "de888f70b426374eb436dfab5e58cab5a5d5423325a7834515c9c6a327f25f50"
-}
diff --git a/.sqlx/query-f0a958d1d92f196a2b6b7d5d75ce322ad79745abe807537a2d8c6c703fd6c7a6.json b/.sqlx/query-f0a958d1d92f196a2b6b7d5d75ce322ad79745abe807537a2d8c6c703fd6c7a6.json
new file mode 100644
index 0000000000..99f8bd08df
--- /dev/null
+++ b/.sqlx/query-f0a958d1d92f196a2b6b7d5d75ce322ad79745abe807537a2d8c6c703fd6c7a6.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (\n SELECT 1 FROM \"Document\" WHERE $2 = 'document' AND id = $1 AND \"deletedAt\" IS NOT NULL\n UNION ALL\n SELECT 1 FROM \"Project\" WHERE $2 = 'project' AND id = $1 AND \"deletedAt\" IS NOT NULL\n UNION ALL\n SELECT 1 FROM \"Chat\" WHERE $2 = 'chat' AND id = $1 AND \"deletedAt\" IS NOT NULL\n ) AS \"deleted!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "deleted!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "f0a958d1d92f196a2b6b7d5d75ce322ad79745abe807537a2d8c6c703fd6c7a6"
+}
diff --git a/.sqlx/query-f53db7386c5bcacad71c665b79d14921d77330e127ed9083235078bc0d8ee970.json b/.sqlx/query-f53db7386c5bcacad71c665b79d14921d77330e127ed9083235078bc0d8ee970.json
deleted file mode 100644
index 2dcc350139..0000000000
--- a/.sqlx/query-f53db7386c5bcacad71c665b79d14921d77330e127ed9083235078bc0d8ee970.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT EXISTS (\n SELECT 1 FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'document'\n AND source_id = $2\n AND source_type = 'team'\n ) as \"exists!\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "exists!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "f53db7386c5bcacad71c665b79d14921d77330e127ed9083235078bc0d8ee970"
-}
diff --git a/.sqlx/query-f9abab5e52a9153a3d2ab6a5f49ed5420dae15f12391281bf489e9d150e6185e.json b/.sqlx/query-f9abab5e52a9153a3d2ab6a5f49ed5420dae15f12391281bf489e9d150e6185e.json
new file mode 100644
index 0000000000..aed3408d00
--- /dev/null
+++ b/.sqlx/query-f9abab5e52a9153a3d2ab6a5f49ed5420dae15f12391281bf489e9d150e6185e.json
@@ -0,0 +1,76 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n sp.id as id,\n sp.\"linkShare\" as \"link_share?\",\n sp.\"linkShareAccessLevel\" as \"link_share_access_level?: AccessLevel\",\n sp.team_share_access_level as \"team_share_access_level?: AccessLevel\",\n c.\"userId\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"ChatPermission\" cp\n JOIN \"SharePermission\" sp ON cp.\"sharePermissionId\" = sp.id\n JOIN \"Chat\" c ON cp.\"chatId\" = c.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n cp.\"chatId\" = $1\n GROUP BY\n sp.id, c.\"userId\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "link_share?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "link_share_access_level?: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "team_share_access_level?: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 4,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "channel_share_permissions?",
+ "type_info": "Json"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ true,
+ true,
+ false,
+ null
+ ]
+ },
+ "hash": "f9abab5e52a9153a3d2ab6a5f49ed5420dae15f12391281bf489e9d150e6185e"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 34704c48ce..f2913e6cf6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -10878,13 +10878,17 @@ dependencies = [
name = "models_permissions"
version = "0.1.0"
dependencies = [
+ "macro_user_id",
+ "model-entity",
"model_file_type",
"schemars 1.2.1",
"serde",
"serde_json",
"sqlx",
"strum 0.27.2",
+ "thiserror 2.0.18",
"utoipa",
+ "uuid",
"workspace-hack",
]
@@ -15201,8 +15205,11 @@ dependencies = [
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
+ "model-entity",
"models_permissions",
+ "rootcause",
"sqlx",
+ "thiserror 2.0.18",
"tokio",
"workspace-hack",
]
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
index 5ad44db886..33887ff358 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
@@ -119,6 +119,9 @@ vi.mock('@core/util/url', () => ({
vi.mock('@service-cognition/client', () => ({
cognitionApiServiceClient: { getChatPermissions: mocks.getChatPermissions },
}));
+vi.mock('@queries/team/teams', () => ({
+ useCurrentTeamQuery: () => ({ isSuccess: false, data: undefined }),
+}));
vi.mock('@solidjs/router', () => ({ useNavigate: () => vi.fn() }));
vi.mock('./LoginButton', () => ({ openLoginModal: vi.fn() }));
vi.mock('@kobalte/core/dialog', () => {
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
index 7e9b39e56b..8943a9223b 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
@@ -46,6 +46,7 @@ import IconLink from '@phosphor/link.svg';
import IconEdit from '@phosphor/pencil.svg';
import IconShared from '@phosphor/share.svg';
import IconX from '@phosphor/x.svg';
+import { useCurrentTeamQuery } from '@queries/team/teams';
import { cognitionApiServiceClient } from '@service-cognition/client';
import {
blockNameToItemType,
@@ -92,12 +93,18 @@ import { openLoginModal } from './LoginButton';
import {
buildLinkSharePayload,
buildLinkShareScopePayload,
+ buildTeamSharePayload,
getLinkShareScope,
getLinkShareScopeCopy,
getShareStatus,
+ getTeamShareScope,
+ getTeamShareScopeCopy,
LINK_SHARE_SCOPE_OPTIONS,
type LinkSharePayload,
type LinkShareScope,
+ TEAM_SHARE_SCOPE_OPTIONS,
+ type TeamSharePayload,
+ type TeamShareScope,
} from './linkShare';
false && clickOutside;
@@ -281,6 +288,10 @@ interface LinkSharingControlsProps {
setLinkShareScope: (scope: LinkShareScope) => void;
setLinkShareAccessLevel: (accessLevel: AccessLevel | null) => void;
copyLink: () => void;
+ teamShare?: {
+ accessLevel: AccessLevel | null | undefined;
+ setAccessLevel: (scope: TeamShareScope) => void;
+ };
}
function LinkSharingControls(props: LinkSharingControlsProps) {
@@ -288,6 +299,7 @@ function LinkSharingControls(props: LinkSharingControlsProps) {
const scopeCopy = () => getLinkShareScopeCopy(scope());
const shareStatus = () =>
getShareStatus(props.linkShare, props.hasExplicitShares);
+ const teamShareScope = () => getTeamShareScope(props.teamShare?.accessLevel);
return (
<div class="flex flex-col gap-3 p-4 text-sm text-ink">
@@ -334,6 +346,45 @@ function LinkSharingControls(props: LinkSharingControlsProps) {
</Button>
</div>
</Show>
+ <Show when={props.teamShare}>
+ <div class="flex flex-wrap items-center justify-between gap-3 border-t border-edge-muted pt-3">
+ <div class="flex flex-col gap-1">
+ <span class="font-medium">Team access</span>
+ <p class="text-sm text-ink-muted">
+ Share this document directly with the owner's team.
+ </p>
+ </div>
+ <Dropdown>
+ <Dropdown.Trigger
+ variant="outline"
+ aria-label="Team access"
+ class="min-w-16.75 py-1 pl-2 pr-1 rounded-md flex items-center gap-1"
+ >
+ {getTeamShareScopeCopy(teamShareScope())}
+ <ChevronDownIcon class="size-4 text-ink-extra-muted" />
+ </Dropdown.Trigger>
+ <Dropdown.Content portalScope="local">
+ <Dropdown.RadioGroup
+ value={teamShareScope()}
+ onChange={(value) =>
+ props.teamShare?.setAccessLevel(value as TeamShareScope)
+ }
+ >
+ <For each={TEAM_SHARE_SCOPE_OPTIONS}>
+ {(option) => (
+ <Dropdown.RadioItem value={option.value}>
+ <span class="flex-1 truncate">{option.label}</span>
+ <Dropdown.ItemIndicator>
+ <CheckIcon class="size-3.5 text-accent" />
+ </Dropdown.ItemIndicator>
+ </Dropdown.RadioItem>
+ )}
+ </For>
+ </Dropdown.RadioGroup>
+ </Dropdown.Content>
+ </Dropdown>
+ </div>
+ </Show>
</div>
);
}
@@ -353,6 +404,8 @@ interface MobileShareDrawerProps {
formattedOwner: string;
linkShare: LinkShare | null | undefined;
linkShareAccessLevel: AccessLevel | null | undefined;
+ teamShareAccessLevel: AccessLevel | null | undefined;
+ setTeamShareAccessLevel?: (scope: TeamShareScope) => void;
refetch: () => void;
navigateToChannel: (channelId: string) => void;
removeChannelAccess: (channelId: string) => void;
@@ -581,6 +634,14 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {
setLinkShareScope={props.setLinkShareScope}
setLinkShareAccessLevel={props.setLinkShareAccessLevel}
copyLink={props.copyLink}
+ teamShare={
+ props.setTeamShareAccessLevel
+ ? {
+ accessLevel: props.teamShareAccessLevel,
+ setAccessLevel: props.setTeamShareAccessLevel,
+ }
+ : undefined
+ }
/>
</Show>
</MobileDrawer.Content>
@@ -592,6 +653,7 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {
export function ShareModal(props: ShareModalProps) {
const navigate = useNavigate();
const analytics = useAnalytics();
+ const currentTeamQuery = useCurrentTeamQuery();
const isBlockContext = isInBlock() && props.itemType !== 'agent_session';
const [fallbackPermissionsResource, { refetch: refetchFallback }] =
createResource(
@@ -888,6 +950,65 @@ export function ShareModal(props: ShareModalProps) {
return currentPermissions.value.linkShareAccessLevel;
});
+ const teamShareAccessLevel = createMemo(() => {
+ const currentPermissions = permissionsResource.latest;
+ if (!currentPermissions || currentPermissions.isErr()) return;
+
+ return currentPermissions.value.teamShareAccessLevel;
+ });
+
+ const updateTeamSharePermissions = createCallback(
+ async (sharePermission: TeamSharePayload) => {
+ if (props.itemType !== 'document') {
+ return;
+ }
+
+ const result = await storageServiceClient.editDocument({
+ sharePermission,
+ documentId: props.id,
+ });
+ if (result.isErr()) {
+ toast.alert('Failed to change team access', {
+ subtext: 'Please try again',
+ });
+ console.error(result);
+ return;
+ }
+
+ refetch();
+ const scope = getTeamShareScope(sharePermission.teamShareAccessLevel);
+ if (scope === 'NONE') {
+ toast.success('Removed team access for this document');
+ return;
+ }
+
+ toast.success('Updated team access', {
+ subtext: `The owner's team can ${getTeamShareScopeCopy(scope).toLowerCase()} this document`,
+ });
+ analytics.track('share_entity', {
+ entityType: props.itemType,
+ entityId: props.id,
+ shareMethod: 'team',
+ accessLevel: scope,
+ });
+ }
+ );
+
+ const setTeamShareAccessLevel = createCallback((scope: TeamShareScope) => {
+ return updateTeamSharePermissions(buildTeamSharePayload(scope));
+ });
+
+ const teamShareControls = () =>
+ props.itemType === 'document' &&
+ props.userPermissions === Permissions.OWNER &&
+ currentTeamQuery.isSuccess &&
+ currentTeamQuery.data
+ ? {
+ accessLevel: teamShareAccessLevel(),
+ setAccessLevel: setTeamShareAccessLevel,
+ }
+ : undefined;
+
const updateLinkSharePermissions = createCallback(
async (sharePermission: LinkSharePayload) => {
const scope = getLinkShareScope(sharePermission.linkShare);
@@ -922,8 +1043,8 @@ export function ShareModal(props: ShareModalProps) {
refetch();
if (scope === 'NONE') {
- toast.success(`Made ${entityLabel} private`, {
- subtext: `Only shared users can access this ${entityLabel}`,
+ toast.success(`Disabled link sharing for this ${entityLabel}`, {
+ subtext: getLinkShareScopeCopy('NONE').description,
});
return;
}
@@ -996,6 +1117,8 @@ export function ShareModal(props: ShareModalProps) {
formattedOwner={formattedOwner()}
linkShare={linkShare()}
linkShareAccessLevel={linkShareAccessLevel()}
+ teamShareAccessLevel={teamShareAccessLevel()}
+ setTeamShareAccessLevel={teamShareControls()?.setAccessLevel}
refetch={refetch}
navigateToChannel={navigateToChannel}
removeChannelAccess={removeChannelAccess}
@@ -1224,6 +1347,7 @@ export function ShareModal(props: ShareModalProps) {
setLinkShareScope={setLinkShareScope}
setLinkShareAccessLevel={setLinkShareAccessLevel}
copyLink={copyLink}
+ teamShare={teamShareControls()}
/>
</Panel.Body>
</Panel>
diff --git a/apps/web/src/lib/core/component/TopBar/linkShare.test.ts b/apps/web/src/lib/core/component/TopBar/linkShare.test.ts
index fd72531afd..4d62697b96 100644
--- a/apps/web/src/lib/core/component/TopBar/linkShare.test.ts
+++ b/apps/web/src/lib/core/component/TopBar/linkShare.test.ts
@@ -2,10 +2,13 @@ import { describe, expect, it } from 'vitest';
import {
buildLinkSharePayload,
buildLinkShareScopePayload,
+ buildTeamSharePayload,
getLinkShareScope,
getLinkShareScopeCopy,
getShareStatus,
+ getTeamShareScope,
LINK_SHARE_SCOPE_OPTIONS,
+ TEAM_SHARE_SCOPE_OPTIONS,
} from './linkShare';
describe('getLinkShareScope', () => {
@@ -88,6 +91,40 @@ describe('link share copy', () => {
});
});
+describe('team share payload', () => {
+ it('lists None plus the allowed team levels', () => {
+ expect(TEAM_SHARE_SCOPE_OPTIONS).toEqual([
+ { value: 'NONE', label: 'None' },
+ { value: 'view', label: 'View' },
+ { value: 'comment', label: 'Comment' },
+ { value: 'edit', label: 'Edit' },
+ ]);
+ });
+
+ it.each([undefined, null, 'owner'] as const)(
+ 'treats %s as no explicit team share',
+ (level) => {
+ expect(getTeamShareScope(level)).toBe('NONE');
+ }
+ );
+
+ it.each(['view', 'comment', 'edit'] as const)(
+ 'preserves explicit %s team access',
+ (level) => {
+ expect(getTeamShareScope(level)).toBe(level);
+ expect(buildTeamSharePayload(level)).toEqual({
+ teamShareAccessLevel: level,
+ });
+ }
+ );
+
+ it('clears team sharing with an explicit null', () => {
+ expect(buildTeamSharePayload('NONE')).toEqual({
+ teamShareAccessLevel: null,
+ });
+ });
+});
+
describe('getShareStatus', () => {
it.each([
['PUBLIC', true, 'Public'],
diff --git a/apps/web/src/lib/core/component/TopBar/linkShare.ts b/apps/web/src/lib/core/component/TopBar/linkShare.ts
index 20d0c40e79..a975403d71 100644
--- a/apps/web/src/lib/core/component/TopBar/linkShare.ts
+++ b/apps/web/src/lib/core/component/TopBar/linkShare.ts
@@ -10,6 +10,16 @@ export type LinkSharePayload = Required<
Pick<UpdateSharePermissionRequestV2, 'linkShare' | 'linkShareAccessLevel'>
>;
+export const NO_TEAM_SHARE = 'NONE' as const;
+
+export type TeamShareLevel = Exclude<AccessLevel, 'owner'>;
+
+export type TeamShareScope = TeamShareLevel | typeof NO_TEAM_SHARE;
+
+export type TeamSharePayload = Required<
+ Pick<UpdateSharePermissionRequestV2, 'teamShareAccessLevel'>
+>;
+
type LinkShareScopeCopy = {
label: string;
title: string;
@@ -41,6 +51,13 @@ const LINK_SHARE_SCOPE_COPY: Record<LinkShareScope, LinkShareScopeCopy> = {
},
};
+const TEAM_SHARE_COPY: Record<TeamShareScope, string> = {
+ NONE: 'None',
+ view: 'View',
+ comment: 'Comment',
+ edit: 'Edit',
+};
+
export const LINK_SHARE_SCOPE_OPTIONS = (
['NONE', 'PUBLIC', 'TEAM'] as const
).map((scope) => ({
@@ -48,6 +65,13 @@ export const LINK_SHARE_SCOPE_OPTIONS = (
label: LINK_SHARE_SCOPE_COPY[scope].label,
}));
+export const TEAM_SHARE_SCOPE_OPTIONS = (
+ ['NONE', 'view', 'comment', 'edit'] as const
+).map((scope) => ({
+ value: scope,
+ label: TEAM_SHARE_COPY[scope],
+}));
+
export function getLinkShareScope(
linkShare: LinkShare | null | undefined
): LinkShareScope {
@@ -87,6 +111,29 @@ export function getLinkShareScopeCopy(
return LINK_SHARE_SCOPE_COPY[scope];
}
+export function getTeamShareScope(
+ teamShareAccessLevel: AccessLevel | null | undefined
+): TeamShareScope {
+ if (
+ teamShareAccessLevel === 'view' ||
+ teamShareAccessLevel === 'comment' ||
+ teamShareAccessLevel === 'edit'
+ ) {
+ return teamShareAccessLevel;
+ }
+ return NO_TEAM_SHARE;
+}
+
+export function buildTeamSharePayload(scope: TeamShareScope): TeamSharePayload {
+ return {
+ teamShareAccessLevel: scope === NO_TEAM_SHARE ? null : scope,
+ };
+}
+
+export function getTeamShareScopeCopy(scope: TeamShareScope): string {
+ return TEAM_SHARE_COPY[scope];
+}
+
export function getShareStatus(
linkShare: LinkShare | null | undefined,
hasExplicitShares: boolean
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
index 03b7aa10b6..56cafc7a47 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
@@ -200,6 +200,7 @@ export * from './sharePermissionV2';
export * from './sharePermissionV2ChannelSharePermissions';
export * from './sharePermissionV2LinkShare';
export * from './sharePermissionV2LinkShareAccessLevel';
+export * from './sharePermissionV2TeamShareAccessLevel';
export * from './slackChannelMeta';
export * from './slackChannelMetaChannelId';
export * from './slackChannelMetaPurpose';
@@ -238,6 +239,7 @@ export * from './updateSharePermissionRequestV2';
export * from './updateSharePermissionRequestV2ChannelSharePermissions';
export * from './updateSharePermissionRequestV2LinkShare';
export * from './updateSharePermissionRequestV2LinkShareAccessLevel';
+export * from './updateSharePermissionRequestV2TeamShareAccessLevel';
export * from './updateToolCallRequest';
export * from './updateToolResponseRequest';
export * from './upsertProjectionRequest';
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2.ts
index cdcc07caa1..cda206dee7 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2.ts
@@ -7,6 +7,7 @@
import type { SharePermissionV2ChannelSharePermissions } from './sharePermissionV2ChannelSharePermissions';
import type { SharePermissionV2LinkShare } from './sharePermissionV2LinkShare';
import type { SharePermissionV2LinkShareAccessLevel } from './sharePermissionV2LinkShareAccessLevel';
+import type { SharePermissionV2TeamShareAccessLevel } from './sharePermissionV2TeamShareAccessLevel';
export interface SharePermissionV2 {
/** The channel share permissions for the item */
@@ -17,4 +18,5 @@ export interface SharePermissionV2 {
linkShareAccessLevel?: SharePermissionV2LinkShareAccessLevel;
/** The owner of the item */
owner: string;
+ teamShareAccessLevel?: SharePermissionV2TeamShareAccessLevel;
}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2TeamShareAccessLevel.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2TeamShareAccessLevel.ts
new file mode 100644
index 0000000000..e88d6833d5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2TeamShareAccessLevel.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+import type { AccessLevel } from './accessLevel';
+
+export type SharePermissionV2TeamShareAccessLevel = null | AccessLevel;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2.ts
index 2bf6c0533d..73e0e2548a 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2.ts
@@ -7,10 +7,12 @@
import type { UpdateSharePermissionRequestV2ChannelSharePermissions } from './updateSharePermissionRequestV2ChannelSharePermissions';
import type { UpdateSharePermissionRequestV2LinkShare } from './updateSharePermissionRequestV2LinkShare';
import type { UpdateSharePermissionRequestV2LinkShareAccessLevel } from './updateSharePermissionRequestV2LinkShareAccessLevel';
+import type { UpdateSharePermissionRequestV2TeamShareAccessLevel } from './updateSharePermissionRequestV2TeamShareAccessLevel';
export interface UpdateSharePermissionRequestV2 {
/** Any channel share permissions to be created/updated/removed */
channelSharePermissions?: UpdateSharePermissionRequestV2ChannelSharePermissions;
linkShare?: UpdateSharePermissionRequestV2LinkShare;
linkShareAccessLevel?: UpdateSharePermissionRequestV2LinkShareAccessLevel;
+ teamShareAccessLevel?: UpdateSharePermissionRequestV2TeamShareAccessLevel;
}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2TeamShareAccessLevel.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2TeamShareAccessLevel.ts
new file mode 100644
index 0000000000..14293e504a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2TeamShareAccessLevel.ts
@@ -0,0 +1,10 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+import type { AccessLevel } from './accessLevel';
+
+export type UpdateSharePermissionRequestV2TeamShareAccessLevel =
+ null | AccessLevel;
diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.json
index 32d7dae9f2..ddae0a28ef 100644
--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json
+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json
@@ -4366,6 +4366,17 @@
"owner": {
"type": "string",
"description": "The owner of the item"
+ },
+ "teamShareAccessLevel": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "The explicit access level granted to the owner's team, or `null` when disabled."
+ }
+ ]
}
}
},
@@ -4673,6 +4684,17 @@
"description": "The link access level. Omit to leave unchanged or pass `null` to reset it to the default\nlevel when a link share exists."
}
]
+ },
+ "teamShareAccessLevel": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "The explicit team access level. Omit to leave unchanged or pass `null` to disable team\nsharing. Only the actual owner may change this setting; `owner` is not an allowed level."
+ }
+ ]
}
}
},
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentTeamShareResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentTeamShareResponse.ts
index 9be8681f45..00d879058e 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentTeamShareResponse.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentTeamShareResponse.ts
@@ -11,7 +11,7 @@ import type { DocumentTeamShareResponseTeamId } from './documentTeamShareRespons
owner's team membership.
*/
export interface DocumentTeamShareResponse {
- /** Whether the document is currently shared with the owner's team. */
+ /** Whether explicit team sharing is enabled; inherited team access does not count. */
sharedWithTeam: boolean;
/** The owner's team the document is (or would be) shared with. `None` when
the owner does not belong to a team. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 9484874c0e..25d81f77d2 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -1085,6 +1085,7 @@ export * from './sharePermissionV2';
export * from './sharePermissionV2ChannelSharePermissions';
export * from './sharePermissionV2LinkShare';
export * from './sharePermissionV2LinkShareAccessLevel';
+export * from './sharePermissionV2TeamShareAccessLevel';
export * from './shortIdResponse';
export * from './simpleMention';
export * from './soupAgentSessionSoupPropertiesField';
@@ -1316,6 +1317,7 @@ export * from './updateSharePermissionRequestV2';
export * from './updateSharePermissionRequestV2ChannelSharePermissions';
export * from './updateSharePermissionRequestV2LinkShare';
export * from './updateSharePermissionRequestV2LinkShareAccessLevel';
+export * from './updateSharePermissionRequestV2TeamShareAccessLevel';
export * from './uploadDocumentStatus';
export * from './uploadExtractFolderHandler200';
export * from './uploadExtractFolderHandler200DataOneOf';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2.ts
index 743eb74c47..5b9321ea6e 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2.ts
@@ -7,6 +7,7 @@
import type { SharePermissionV2ChannelSharePermissions } from './sharePermissionV2ChannelSharePermissions';
import type { SharePermissionV2LinkShare } from './sharePermissionV2LinkShare';
import type { SharePermissionV2LinkShareAccessLevel } from './sharePermissionV2LinkShareAccessLevel';
+import type { SharePermissionV2TeamShareAccessLevel } from './sharePermissionV2TeamShareAccessLevel';
export interface SharePermissionV2 {
/** The channel share permissions for the item */
@@ -17,4 +18,5 @@ export interface SharePermissionV2 {
linkShareAccessLevel?: SharePermissionV2LinkShareAccessLevel;
/** The owner of the item */
owner: string;
+ teamShareAccessLevel?: SharePermissionV2TeamShareAccessLevel;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2TeamShareAccessLevel.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2TeamShareAccessLevel.ts
new file mode 100644
index 0000000000..ec19bec375
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2TeamShareAccessLevel.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AccessLevel } from './accessLevel';
+
+export type SharePermissionV2TeamShareAccessLevel = null | AccessLevel;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2.ts
index 5c2dfa70b6..1bcb34b443 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2.ts
@@ -7,10 +7,12 @@
import type { UpdateSharePermissionRequestV2ChannelSharePermissions } from './updateSharePermissionRequestV2ChannelSharePermissions';
import type { UpdateSharePermissionRequestV2LinkShare } from './updateSharePermissionRequestV2LinkShare';
import type { UpdateSharePermissionRequestV2LinkShareAccessLevel } from './updateSharePermissionRequestV2LinkShareAccessLevel';
+import type { UpdateSharePermissionRequestV2TeamShareAccessLevel } from './updateSharePermissionRequestV2TeamShareAccessLevel';
export interface UpdateSharePermissionRequestV2 {
/** Any channel share permissions to be created/updated/removed */
channelSharePermissions?: UpdateSharePermissionRequestV2ChannelSharePermissions;
linkShare?: UpdateSharePermissionRequestV2LinkShare;
linkShareAccessLevel?: UpdateSharePermissionRequestV2LinkShareAccessLevel;
+ teamShareAccessLevel?: UpdateSharePermissionRequestV2TeamShareAccessLevel;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2TeamShareAccessLevel.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2TeamShareAccessLevel.ts
new file mode 100644
index 0000000000..c0d796e312
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2TeamShareAccessLevel.ts
@@ -0,0 +1,10 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AccessLevel } from './accessLevel';
+
+export type UpdateSharePermissionRequestV2TeamShareAccessLevel =
+ null | AccessLevel;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index a46f681fd9..10d294c32b 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -2067,6 +2067,14 @@ export const editCallRecordBody = zod
.describe('Ordered from least to most access top -> bottom'),
])
.optional(),
+ teamShareAccessLevel: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['view', 'comment', 'edit', 'owner'])
+ .describe('Ordered from least to most access top -> bottom'),
+ ])
+ .optional(),
}),
])
.optional(),
@@ -7380,6 +7388,14 @@ export const editDocumentBody = zod
.describe('Ordered from least to most access top -> bottom'),
])
.optional(),
+ teamShareAccessLevel: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['view', 'comment', 'edit', 'owner'])
+ .describe('Ordered from least to most access top -> bottom'),
+ ])
+ .optional(),
}),
])
.optional(),
@@ -8282,7 +8298,7 @@ export const getDocumentTeamShareResponse = zod
sharedWithTeam: zod
.boolean()
.describe(
- "Whether the document is currently shared with the owner's team."
+ 'Whether explicit team sharing is enabled; inherited team access does not count.'
),
teamId: zod
.uuid()
@@ -8296,9 +8312,10 @@ export const getDocumentTeamShareResponse = zod
);
/**
- * @summary Sets the team-share state of a document. Sharing grants the document
-owner's team Edit access; unsharing removes the team's access. Requires
-Edit access on the document.
+ * @summary Sets explicit team sharing. Requires a verified acting identity matching
+the persisted document owner, not merely effective Edit or Owner access.
+Initial enable defaults to Edit; repeated enable preserves the chosen level.
+Clear removes only the managed direct grant, not inherited team access.
*/
export const setDocumentTeamShareParams = zod.object({
document_id: zod.string().describe('Document ID'),
@@ -8317,7 +8334,7 @@ export const setDocumentTeamShareResponse = zod
sharedWithTeam: zod
.boolean()
.describe(
- "Whether the document is currently shared with the owner's team."
+ 'Whether explicit team sharing is enabled; inherited team access does not count.'
),
teamId: zod
.uuid()
@@ -28965,6 +28982,14 @@ export const getProjectPermissionsV2Response = zod.object({
])
.optional(),
owner: zod.string().describe('The owner of the item'),
+ teamShareAccessLevel: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['view', 'comment', 'edit', 'owner'])
+ .describe('Ordered from least to most access top -> bottom'),
+ ])
+ .optional(),
});
/**
@@ -29725,6 +29750,14 @@ export const editThreadV2Body = zod.object({
.describe('Ordered from least to most access top -> bottom'),
])
.optional(),
+ teamShareAccessLevel: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['view', 'comment', 'edit', 'owner'])
+ .describe('Ordered from least to most access top -> bottom'),
+ ])
+ .optional(),
}),
])
.optional(),
@@ -29856,6 +29889,14 @@ export const getDocumentPermissionsV2Response = zod.object({
])
.optional(),
owner: zod.string().describe('The owner of the item'),
+ teamShareAccessLevel: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['view', 'comment', 'edit', 'owner'])
+ .describe('Ordered from least to most access top -> bottom'),
+ ])
+ .optional(),
}),
});
@@ -29915,6 +29956,14 @@ export const editProjectV2Body = zod.object({
.describe('Ordered from least to most access top -> bottom'),
])
.optional(),
+ teamShareAccessLevel: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['view', 'comment', 'edit', 'owner'])
+ .describe('Ordered from least to most access top -> bottom'),
+ ])
+ .optional(),
}),
])
.optional(),
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
index ffd469096c..4d5269eebe 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
@@ -63,7 +63,7 @@ export type EntityRefInput = {
type: GraphqlEntityType;
};
-/** Shared link/channel share-policy update. */
+/** Shared link, explicit team, and channel share-policy update. */
export type EntitySharePolicyInput = {
/** Channel access entries to add, remove, or replace. */
channelSharePermissions?: Array<ChannelSharePolicyInput> | null | undefined;
@@ -74,6 +74,12 @@ export type EntitySharePolicyInput = {
* when a link share exists.
*/
linkShareAccessLevel?: GraphqlEntityAccessLevel | null | undefined;
+ /**
+ * Explicit team access level. Omit to leave unchanged or pass null to disable team sharing,
+ * independently of link sharing. Only the actual owner may change this setting;
+ * enabling it requires the owner to belong to a team. OWNER is not an allowed level.
+ */
+ teamShareAccessLevel?: GraphqlEntityAccessLevel | null | undefined;
};
/** The two operands of a recursive `AgentSessionFilterExpr` binary expression. */
@@ -1163,7 +1169,7 @@ export type UpdateEntityPropertyOptionsInput = {
export type UpdateEntitySharePolicyInput = {
/** Entity whose share policy should change. */
entity: EntityRefInput;
- /** New link/channel policy values. */
+ /** New link, explicit team, and channel policy values. */
policy: EntitySharePolicyInput;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index f3010810da..4d03acf883 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -8341,7 +8341,7 @@
},
"put": {
"tags": ["document"],
- "summary": "Sets the team-share state of a document. Sharing grants the document\nowner's team Edit access; unsharing removes the team's access. Requires\nEdit access on the document.",
+ "summary": "Sets explicit team sharing. Requires a verified acting identity matching\nthe persisted document owner, not merely effective Edit or Owner access.\nInitial enable defaults to Edit; repeated enable preserves the chosen level.\nClear removes only the managed direct grant, not inherited team access.",
"operationId": "set_document_team_share",
"parameters": [
{
@@ -8376,7 +8376,7 @@
}
},
"400": {
- "description": "",
+ "description": "Owner has no team",
"content": {
"application/json": {
"schema": {
@@ -8386,7 +8386,7 @@
}
},
"401": {
- "description": "",
+ "description": "Acting identity is absent or is not the actual owner",
"content": {
"application/json": {
"schema": {
@@ -8405,6 +8405,16 @@
}
}
},
+ "409": {
+ "description": "Sharing facts changed or an untracked grant conflicts",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -19621,7 +19631,7 @@
"properties": {
"sharedWithTeam": {
"type": "boolean",
- "description": "Whether the document is currently shared with the owner's team."
+ "description": "Whether explicit team sharing is enabled; inherited team access does not count."
},
"teamId": {
"type": ["string", "null"],
@@ -25034,6 +25044,17 @@
"owner": {
"type": "string",
"description": "The owner of the item"
+ },
+ "teamShareAccessLevel": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "The explicit access level granted to the owner's team, or `null` when disabled."
+ }
+ ]
}
}
},
@@ -27558,6 +27579,17 @@
"description": "The link access level. Omit to leave unchanged or pass `null` to reset it to the default\nlevel when a link share exists."
}
]
+ },
+ "teamShareAccessLevel": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "The explicit team access level. Omit to leave unchanged or pass `null` to disable team\nsharing. Only the actual owner may change this setting; `owner` is not an allowed level."
+ }
+ ]
}
}
},
diff --git a/crates/call/src/domain/service/test.rs b/crates/call/src/domain/service/test.rs
index 117a3ba8ae..5c83227ddd 100644
--- a/crates/call/src/domain/service/test.rs
+++ b/crates/call/src/domain/service/test.rs
@@ -1494,6 +1494,7 @@ async fn edit_call_record_publishes_updated_event_for_share_permission_only() {
models_permissions::share_permission::LinkShare::Public,
)),
link_share_access_level: None,
+ team_share_access_level: None,
channel_share_permissions: None,
},
),
diff --git a/crates/call/src/outbound/pg_call_repo.rs b/crates/call/src/outbound/pg_call_repo.rs
index 07b6bddfef..b944e7b415 100644
--- a/crates/call/src/outbound/pg_call_repo.rs
+++ b/crates/call/src/outbound/pg_call_repo.rs
@@ -315,6 +315,7 @@ impl CallRepository for PgCallRepo {
id: share_permission_id.to_string(),
link_share: None,
link_share_access_level: None,
+ team_share_access_level: None,
owner: created_by.to_string(),
channel_share_permissions: Some(vec![ChannelSharePermission {
channel_id: channel_id.to_string(),
diff --git a/crates/call/src/outbound/pg_call_repo/test.rs b/crates/call/src/outbound/pg_call_repo/test.rs
index 364b2eb953..5db322b9f4 100644
--- a/crates/call/src/outbound/pg_call_repo/test.rs
+++ b/crates/call/src/outbound/pg_call_repo/test.rs
@@ -2227,6 +2227,7 @@ async fn patch_call_record_sets_public_link_and_defaults_level_to_view(
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: Some(Some(LinkShare::Public)),
link_share_access_level: None,
+ team_share_access_level: None,
channel_share_permissions: None,
}),
share_with_team: None,
@@ -2256,6 +2257,7 @@ async fn patch_call_record_sets_team_link_and_explicit_level(
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: Some(Some(LinkShare::Team)),
link_share_access_level: Some(Some(AccessLevel::Edit)),
+ team_share_access_level: None,
channel_share_permissions: None,
}),
share_with_team: None,
@@ -2286,6 +2288,7 @@ async fn patch_call_record_explicit_null_disables_link_sharing(
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: Some(None),
link_share_access_level: Some(Some(AccessLevel::Edit)),
+ team_share_access_level: None,
channel_share_permissions: None,
}),
share_with_team: None,
@@ -2321,6 +2324,7 @@ async fn patch_call_record_level_only_update_updates_link_share_access_level(
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: Some(Some(AccessLevel::Comment)),
+ team_share_access_level: None,
channel_share_permissions: None,
}),
share_with_team: None,
@@ -2354,6 +2358,7 @@ async fn patch_call_record_adds_channel_share_permission(
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: None,
+ team_share_access_level: None,
channel_share_permissions: Some(vec![UpdateChannelSharePermission {
operation: UpdateOperation::Add,
channel_id: channel_id.clone(),
@@ -2429,6 +2434,7 @@ async fn patch_call_record_removes_channel_share_permission(
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: None,
+ team_share_access_level: None,
channel_share_permissions: Some(vec![UpdateChannelSharePermission {
operation: UpdateOperation::Remove,
channel_id: channel_id.clone(),
@@ -2473,6 +2479,7 @@ async fn patch_call_record_empty_share_permission_update_is_noop(
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: None,
+ team_share_access_level: None,
channel_share_permissions: None,
}),
share_with_team: None,
diff --git a/crates/chat/src/domain/service/chat/test.rs b/crates/chat/src/domain/service/chat/test.rs
index 01cc832724..9a9a8a50f8 100644
--- a/crates/chat/src/domain/service/chat/test.rs
+++ b/crates/chat/src/domain/service/chat/test.rs
@@ -406,6 +406,7 @@ fn patch_args(share_permission_updated: bool) -> PatchChatArgs {
models_permissions::share_permission::LinkShare::Public,
)),
link_share_access_level: None,
+ team_share_access_level: None,
channel_share_permissions: None,
},
);
diff --git a/crates/chat/src/outbound/postgres/queries/get_permissions.rs b/crates/chat/src/outbound/postgres/queries/get_permissions.rs
index 8671cc232c..c21c4b80ac 100644
--- a/crates/chat/src/outbound/postgres/queries/get_permissions.rs
+++ b/crates/chat/src/outbound/postgres/queries/get_permissions.rs
@@ -61,6 +61,7 @@ pub(crate) async fn get_chat_share_permission(
id: result.id,
link_share,
link_share_access_level: result.link_share_access_level,
+ team_share_access_level: None,
owner: result.owner,
channel_share_permissions,
})
diff --git a/crates/chat/src/outbound/postgres/test.rs b/crates/chat/src/outbound/postgres/test.rs
index 9e006244b2..804ff1fd5e 100644
--- a/crates/chat/src/outbound/postgres/test.rs
+++ b/crates/chat/src/outbound/postgres/test.rs
@@ -1004,6 +1004,7 @@ async fn patch_chat_sets_team_share_and_defaults_explicit_null_level_to_view(poo
UpdateSharePermissionRequestV2 {
link_share: Some(Some(LinkShare::Team)),
link_share_access_level: Some(None),
+ team_share_access_level: None,
channel_share_permissions: None,
},
)
@@ -1028,6 +1029,7 @@ async fn patch_chat_defaults_explicit_null_level_for_existing_link_share(pool: P
UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: Some(Some(AccessLevel::Edit)),
+ team_share_access_level: None,
channel_share_permissions: None,
},
)
@@ -1038,6 +1040,7 @@ async fn patch_chat_defaults_explicit_null_level_for_existing_link_share(pool: P
UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: Some(None),
+ team_share_access_level: None,
channel_share_permissions: None,
},
)
@@ -1062,6 +1065,7 @@ async fn patch_chat_disables_link_sharing_and_clears_both_levels(pool: Pool<Post
UpdateSharePermissionRequestV2 {
link_share: Some(None),
link_share_access_level: Some(Some(AccessLevel::Edit)),
+ team_share_access_level: None,
channel_share_permissions: None,
},
)
diff --git a/crates/documents/src/domain/create.rs b/crates/documents/src/domain/create.rs
index 17856cdf55..f3b78470d0 100644
--- a/crates/documents/src/domain/create.rs
+++ b/crates/documents/src/domain/create.rs
@@ -66,6 +66,7 @@ impl NewDocumentMetadata {
file_type: kind.file_type,
project_id: self.project_id,
team_id: kind.team_id,
+ share_with_team: kind.share_with_team,
created_at: self.created_at,
sub_type: kind.subtype.sub_type(),
skip_history: self.skip_history,
@@ -122,6 +123,7 @@ struct RepoDocumentKind {
sha: String,
subtype: RepoDocumentSubtype,
team_id: Option<uuid::Uuid>,
+ share_with_team: bool,
}
enum RepoDocumentSubtype {
@@ -154,7 +156,8 @@ pub enum MarkdownSubtype {
Task {
/// Optional property values to assign. Defaults are used when omitted.
property_values: Option<Vec<PropertyInput>>,
- /// Whether to share the task with the user's team.
+ /// Consent to share the task with the creator's team. The persisted owner's
+ /// membership, not `team_id`, decides which team receives access.
share_with_team: bool,
/// Team to assign the task number within. If omitted, it is inferred only
/// when the creator belongs to exactly one team.
@@ -169,12 +172,14 @@ pub enum MarkdownSubtype {
}
impl MarkdownSubtype {
- /// Convert a simple task flag into the default markdown subtype.
+ /// Convert a simple task flag into the default markdown subtype. A task is
+ /// shared with the team only when the caller resolved one; teamless creators
+ /// get a private task instead of a failed create.
pub fn from_task_flag(is_task: bool, team_id: Option<uuid::Uuid>) -> Self {
if is_task {
Self::Task {
property_values: None,
- share_with_team: true,
+ share_with_team: team_id.is_some(),
team_id,
}
} else {
@@ -567,6 +572,7 @@ where
MarkdownSubtype::Skill => RepoDocumentSubtype::MarkdownSkill,
},
team_id,
+ share_with_team: task.as_ref().is_some_and(|(_, share, _)| *share),
},
);
let attribution = args.resolved_attribution();
@@ -654,6 +660,7 @@ where
sha: hashes.hex,
subtype: RepoDocumentSubtype::Regular,
team_id: None,
+ share_with_team: false,
},
);
@@ -756,6 +763,7 @@ mod tests {
sha: "sha".to_string(),
subtype: RepoDocumentSubtype::Regular,
team_id: None,
+ share_with_team: false,
}
}
@@ -821,6 +829,28 @@ mod tests {
.unwrap();
}
+ #[test]
+ fn task_flag_shares_only_when_a_team_was_resolved() {
+ let team_id = uuid::Uuid::from_u128(7);
+ for (resolved_team, expected_share) in [(None, false), (Some(team_id), true)] {
+ let MarkdownSubtype::Task {
+ share_with_team,
+ team_id: numbering_team,
+ property_values,
+ } = MarkdownSubtype::from_task_flag(true, resolved_team)
+ else {
+ panic!("a task flag builds a task subtype");
+ };
+ assert_eq!(share_with_team, expected_share);
+ assert_eq!(numbering_team, resolved_team);
+ assert!(property_values.is_none());
+ }
+ assert!(matches!(
+ MarkdownSubtype::from_task_flag(false, Some(team_id)),
+ MarkdownSubtype::Note
+ ));
+ }
+
#[test]
fn test_file_shas() {
let hashes = file_shas(b"hello");
diff --git a/crates/documents/src/domain/models.rs b/crates/documents/src/domain/models.rs
index c296c8c664..89a9faf93a 100644
--- a/crates/documents/src/domain/models.rs
+++ b/crates/documents/src/domain/models.rs
@@ -320,8 +320,11 @@ pub struct CreateDocumentRepoArgs {
pub file_type: Option<FileType>,
/// Project to associate the document with.
pub project_id: Option<uuid::Uuid>,
- /// Team to use when assigning a per-team task number.
+ /// Team to use when assigning a per-team task number, never sharing authority.
pub team_id: Option<uuid::Uuid>,
+ /// Explicit task creation consent. Initializes Comment using the persisted owner's team.
+ /// Ordinary documents, snippets, and imports must leave this false.
+ pub share_with_team: bool,
/// Custom creation timestamp.
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
/// Sub type of the document — task or snippet (MD files only).
@@ -418,6 +421,9 @@ pub struct EditDocumentRepoArgs {
/// Updated share permissions.
pub share_permission:
Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,
+ /// Owner-authorized conditional team update, applied in the metadata transaction.
+ pub team_share:
+ Option<models_permissions::share_permission::team_share::AuthorizedTeamShareCommand>,
/// Whether to revoke direct non-owner user access in the edit transaction.
pub revoke_non_owner_user_access: bool,
/// New file type (None = no change).
@@ -613,7 +619,7 @@ pub struct SystemSkillsResponse {
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct DocumentTeamShareResponse {
- /// Whether the document is currently shared with the owner's team.
+ /// Whether explicit team sharing is enabled; inherited team access does not count.
pub shared_with_team: bool,
/// The owner's team the document is (or would be) shared with. `None` when
/// the owner does not belong to a team.
@@ -635,7 +641,7 @@ pub struct SetDocumentTeamShareRequest {
pub struct DocumentTeamShare {
/// The owner's team, when the owner belongs to one.
pub team_id: Option<uuid::Uuid>,
- /// Whether a team-source access row exists for the document.
+ /// Whether the document has an explicit canonical team-share level.
pub shared_with_team: bool,
}
diff --git a/crates/documents/src/domain/ports.rs b/crates/documents/src/domain/ports.rs
index 30b5ce9858..bb15a8fd13 100644
--- a/crates/documents/src/domain/ports.rs
+++ b/crates/documents/src/domain/ports.rs
@@ -16,6 +16,9 @@ use entity_access::domain::models::{
use entity_access::domain::ports::EntityAccessService;
use macro_user_id::user_id::MacroUserIdStr;
use model::document::{ContentType, DocumentBasic, DocumentMetadata, FileType};
+use models_permissions::share_permission::team_share::{
+ AuthorizedTeamShareCommand, TeamShareFacts,
+};
use models_permissions::share_permission::{SharePermissionV2, TeamLinkShareDefault};
use super::content::DocumentContent;
@@ -137,23 +140,27 @@ pub trait DocumentRepo: Send + Sync + 'static {
/// Always inserts a `Document` row. Email-attachment linking and SHA reuse
/// belong on [`DocumentRepo::import_email_attachment_document`].
///
- /// `share_permission` is the pre-resolved initial share permission — the
+ /// `share_permission` is the pre-resolved initial link permission — the
/// repository persists it verbatim and carries no share-policy of its own.
+ /// Canonical team state starts NULL; `args.share_with_team` initializes explicit
+ /// task consent from the persisted owner's team inside the same transaction and
+ /// fails with `BadRequest` when that owner has no team.
fn create_document(
&self,
args: CreateDocumentRepoArgs,
share_permission: SharePermissionV2,
- ) -> impl Future<Output = Result<DocumentMetadata, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<DocumentMetadata, DocumentError>> + Send;
/// Import an email attachment: link it to a reusable live email document
/// owned by the same user (matching latest-instance sha), or insert a new
/// document and link it. Concurrent first-time creates for the same
/// `(owner, sha)` are serialized so two imports cannot insert duplicates.
+ /// Imports never initialize team consent.
fn import_email_attachment_document(
&self,
args: ImportEmailAttachmentRepoArgs,
share_permission: SharePermissionV2,
- ) -> impl Future<Output = Result<EmailImportRepoOutcome, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<EmailImportRepoOutcome, DocumentError>> + Send;
/// Get the link-share preference of the user's team, or `None` when the
/// user is not on a team.
@@ -175,7 +182,7 @@ pub trait DocumentRepo: Send + Sync + 'static {
fn edit_document(
&self,
args: EditDocumentRepoArgs,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ ) -> impl Future<Output = Result<(), DocumentError>> + Send;
/// Update a document's `updatedAt` timestamp.
fn update_document_modified(
@@ -227,25 +234,26 @@ pub trait DocumentRepo: Send + Sync + 'static {
task_short_id: &str,
) -> impl Future<Output = Result<Vec<String>, Self::Err>> + Send;
- /// Share a document with the given team.
- fn share_with_team(
+ /// Load persisted ownership, membership and explicit sharing facts for policy.
+ ///
+ /// A document whose canonical state is still NULL but whose owner's team holds a
+ /// legacy direct grant is adopted first, so the facts describe that grant.
+ fn get_team_share_facts(
&self,
- team_id: &uuid::Uuid,
document_id: &str,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ ) -> impl Future<Output = Result<TeamShareFacts, DocumentError>> + Send;
- /// Get the team-share state of a document, resolved against the owner's team.
+ /// Get explicit team-share state, never inferred from inherited grants.
fn get_team_share(
&self,
document_id: &str,
- ) -> impl Future<Output = Result<DocumentTeamShare, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<DocumentTeamShare, DocumentError>> + Send;
- /// Grant or revoke the document owner's team's access on the document.
+ /// Apply an owner-authorized update after rechecking its facts atomically.
fn set_team_share(
&self,
- document_id: &str,
- share: bool,
- ) -> impl Future<Output = Result<DocumentTeamShare, Self::Err>> + Send;
+ command: AuthorizedTeamShareCommand,
+ ) -> impl Future<Output = Result<DocumentTeamShare, DocumentError>> + Send;
/// Get document metadata at a specific version ID.
fn get_document_metadata_at_version(
diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rs
index 5c8b51dae7..3fd8f00109 100644
--- a/crates/documents/src/domain/service.rs
+++ b/crates/documents/src/domain/service.rs
@@ -5,6 +5,10 @@ mod tests;
use entity_access_management::domain::ports::EntityAccessManagementService;
use model_entity::EntityType;
+use models_permissions::share_permission::team_share::{
+ AuthorizedTeamShareCommand, TeamShareLevel, TeamSharePolicyError, TeamShareRequest,
+ authorize_team_share,
+};
use models_permissions::share_permission::{
LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2,
};
@@ -314,6 +318,33 @@ impl<
}
}
+ async fn authorize_document_team_share(
+ &self,
+ receipt: &EntityAccessReceipt<EditAccessLevel>,
+ request: TeamShareRequest,
+ ) -> Result<Option<AuthorizedTeamShareCommand>, DocumentError> {
+ if request == TeamShareRequest::default() {
+ return Ok(None);
+ }
+ let facts = self
+ .repo
+ .get_team_share_facts(&receipt.entity().entity_id)
+ .await?;
+ authorize_team_share(
+ receipt.acting_user_id(),
+ &facts,
+ request,
+ TeamShareLevel::Edit,
+ )
+ .map_err(|error| match error {
+ TeamSharePolicyError::MissingActor | TeamSharePolicyError::NotOwner => {
+ DocumentError::Unauthorized
+ }
+ TeamSharePolicyError::InvalidRevision => DocumentError::Conflict(error.to_string()),
+ _ => DocumentError::BadRequest(error.to_string()),
+ })
+ }
+
fn get_signed_options(&self) -> SignedOptions {
let current_unix_timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -574,15 +605,6 @@ impl<
});
}
- fn map_create_repo_error<E: Into<anyhow::Error>>(e: E) -> DocumentError {
- let err: anyhow::Error = e.into();
- if err.to_string().contains("document with ID already exists") {
- DocumentError::Conflict("document with ID already exists".to_string())
- } else {
- DocumentError::Internal(err)
- }
- }
-
async fn reused_email_import_response(
&self,
document_metadata: DocumentMetadata,
@@ -1272,11 +1294,7 @@ impl<
let share_permission =
SharePermissionV2::new_document_share_permission(file_type, team_default);
- let document_metadata = self
- .repo
- .create_document(args, share_permission)
- .await
- .map_err(Self::map_create_repo_error)?;
+ let document_metadata = self.repo.create_document(args, share_permission).await?;
self.finish_created_document(
document_metadata,
@@ -1317,8 +1335,7 @@ impl<
match self
.repo
.import_email_attachment_document(args, share_permission)
- .await
- .map_err(Self::map_create_repo_error)?
+ .await?
{
EmailImportRepoOutcome::Created(document_metadata) => {
self.finish_created_document(
@@ -1353,7 +1370,21 @@ impl<
});
}
- // Check owner-only restrictions for authenticated users
+ let team_share = self
+ .authorize_document_team_share(
+ &entity_access_receipt,
+ TeamShareRequest {
+ access_level: args
+ .share_permission
+ .as_ref()
+ .and_then(|p| p.team_share_access_level),
+ legacy_enabled: None,
+ },
+ )
+ .await?;
+
+ // Team sharing was authorized against the persisted owner above. Project moves and
+ // the remaining permission fields keep requiring effective Owner access.
if let entity_access::domain::models::EntityPermission::AccessLevel { access_level } =
entity_access_receipt.entity_permission()
{
@@ -1364,7 +1395,13 @@ impl<
return Err(DocumentError::Unauthorized);
}
- if args.share_permission.is_some()
+ let requires_legacy_owner_access = args.share_permission.as_ref().is_some_and(|p| {
+ p.team_share_access_level.is_none()
+ || p.link_share.is_some()
+ || p.link_share_access_level.is_some()
+ || p.channel_share_permissions.is_some()
+ });
+ if requires_legacy_owner_access
&& *access_level
!= models_permissions::share_permission::access_level::AccessLevel::Owner
{
@@ -1418,11 +1455,11 @@ impl<
document_name: document_name.clone(),
project_id: args.project_id.clone(),
share_permission: args.share_permission,
+ team_share,
revoke_non_owner_user_access,
file_type: args.file_type.clone(),
})
- .await
- .map_err(|e| DocumentError::Internal(e.into()))?;
+ .await?;
// Update project modified timestamps. args.project_id of None means "no change",
// so only move the document out of its old project when a different project (or
@@ -1847,18 +1884,6 @@ impl<
request: &CreateTaskRequest,
attribution: &Attribution,
) -> Result<(), DocumentError> {
- if request.share_with_team
- && let Some(team_id) = request.team_id
- {
- let _ = self
- .repo
- .share_with_team(&team_id, document_id)
- .await
- .inspect_err(|e| {
- tracing::error!(error=?e, "failed to share task with team");
- });
- }
-
// Use provided properties or assign default ones for task
let properties = if let Some(properties) = request.property_values.as_ref() {
properties
@@ -1910,23 +1935,19 @@ impl<
Ok(())
}
- #[tracing::instrument(skip(self, entity_access_receipt))]
+ #[tracing::instrument(err, skip(self, entity_access_receipt))]
async fn get_team_share(
&self,
entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
) -> Result<DocumentTeamShareResponse, DocumentError> {
let document_id = &entity_access_receipt.entity().entity_id;
- let state = self
- .repo
- .get_team_share(document_id)
- .await
- .map_err(|e| DocumentError::Internal(e.into()))?;
+ let state = self.repo.get_team_share(document_id).await?;
Ok(state.into())
}
- #[tracing::instrument(skip(self, entity_access_receipt))]
+ #[tracing::instrument(err, skip(self, entity_access_receipt))]
async fn set_team_share(
&self,
entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,
@@ -1934,17 +1955,17 @@ impl<
) -> Result<DocumentTeamShareResponse, DocumentError> {
let document_id = entity_access_receipt.entity().entity_id.clone();
- let state = self
- .repo
- .set_team_share(&document_id, share)
- .await
- .map_err(|e| DocumentError::Internal(e.into()))?;
-
- if share && state.team_id.is_none() {
- return Err(DocumentError::BadRequest(
- "document owner does not belong to a team".to_string(),
- ));
- }
+ let command = self
+ .authorize_document_team_share(
+ &entity_access_receipt,
+ TeamShareRequest {
+ access_level: None,
+ legacy_enabled: Some(share),
+ },
+ )
+ .await?
+ .expect("a supplied legacy toggle produces a command");
+ let state = self.repo.set_team_share(command).await?;
let _ = self
.connection_service
diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rs
index e5b75301d2..3698f74f65 100644
--- a/crates/documents/src/domain/service/tests.rs
+++ b/crates/documents/src/domain/service/tests.rs
@@ -181,13 +181,17 @@ impl TaskPropertiesPort for TestTaskPropertiesPort {
}
}
-struct TestConnectionService;
+#[derive(Default)]
+struct TestConnectionService {
+ invalidations: Mutex<usize>,
+}
impl ConnectionService for TestConnectionService {
async fn send_invalidation_event<'a, T: std::fmt::Debug + serde::Serialize + Send>(
&self,
_invalidation_event: InvalidationEvent<'a, T>,
) -> Result<(), connection::domain::models::ConnectionError> {
+ *self.invalidations.lock().unwrap() += 1;
Ok(())
}
@@ -418,7 +422,7 @@ fn make_test_service_with_foreign_entity_service(
),
TestUploadUrlPort,
TestTaskPropertiesPort,
- TestConnectionService,
+ TestConnectionService::default(),
TestEntityAccessManagementService::default(),
foreign_entity_service,
TestEventBroker::default(),
@@ -439,7 +443,7 @@ fn make_test_service_with_entity_access(
),
TestUploadUrlPort,
TestTaskPropertiesPort,
- TestConnectionService,
+ TestConnectionService::default(),
entity_access.clone(),
TestForeignEntityService::default(),
TestEventBroker::default(),
@@ -467,7 +471,7 @@ fn make_test_service_with_configured_event_broker(
),
TestUploadUrlPort,
TestTaskPropertiesPort,
- TestConnectionService,
+ TestConnectionService::default(),
TestEntityAccessManagementService::default(),
TestForeignEntityService::default(),
event_broker.clone(),
@@ -1506,6 +1510,266 @@ fn owner_receipt(document_id: &str) -> EntityAccessReceipt<OwnerAccessLevel> {
)
}
+fn team_share_facts() -> models_permissions::share_permission::team_share::TeamShareFacts {
+ models_permissions::share_permission::team_share::TeamShareFacts {
+ entity: EntityType::Document.with_entity_str("doc-1"),
+ owner: task_document_context("doc-1").owner,
+ owner_team_id: Some(uuid::Uuid::from_u128(1)),
+ current: None,
+ revision: 0,
+ }
+}
+
+#[tokio::test]
+async fn team_toggle_rejects_non_owner_without_writes_or_events() {
+ let mut repo = make_mock_repo();
+ repo.expect_get_team_share_facts()
+ .returning(|_| Box::pin(async { Ok(team_share_facts()) }));
+ let (service, broker) = make_test_service_with_event_broker(repo);
+ let result = service.set_team_share(edit_receipt("doc-1"), true).await;
+ assert!(matches!(result, Err(DocumentError::Unauthorized)));
+ assert!(broker.published().lock().unwrap().is_empty());
+}
+
+fn team_edit_args(
+ level: Option<models_permissions::share_permission::access_level::AccessLevel>,
+) -> EditDocumentServiceArgs {
+ EditDocumentServiceArgs {
+ document_name: Some("renamed".to_string()),
+ project_id: None,
+ file_type: None,
+ share_permission: Some(UpdateSharePermissionRequestV2 {
+ team_share_access_level: Some(level),
+ link_share: None,
+ link_share_access_level: None,
+ channel_share_permissions: None,
+ }),
+ }
+}
+
+fn team_policy_receipts() -> Vec<EntityAccessReceipt<EditAccessLevel>> {
+ use entity_access::domain::models::{AccessLevel, Entity, EntityPermission};
+ let entity = Entity {
+ entity_id: "doc-1".to_string(),
+ entity_type: EntityType::Document,
+ };
+ let non_owner = edit_receipt("doc-1").acting_user_id().unwrap().clone();
+ let mut receipts = Vec::new();
+ for access_level in [AccessLevel::Edit, AccessLevel::Owner] {
+ receipts.push(
+ EntityAccessReceipt::try_new_authenticated_user(
+ non_owner.clone(),
+ entity.clone(),
+ EntityPermission::AccessLevel { access_level },
+ )
+ .unwrap(),
+ );
+ }
+ receipts.push(
+ EntityAccessReceipt::try_new_bot(
+ bot_id().into_storage_id(),
+ bot_receipt_scope(),
+ entity.clone(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ )
+ .unwrap(),
+ );
+ for auth in [
+ EntityAccessAuth::Internal,
+ EntityAccessAuth::Unauthenticated,
+ ] {
+ receipts.push(
+ EntityAccessReceipt::try_new(
+ auth,
+ entity.clone(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ )
+ .unwrap(),
+ );
+ }
+ receipts
+}
+
+#[tokio::test]
+async fn team_policy_rejects_editors_inherited_owners_and_identityless_receipts() {
+ use models_permissions::share_permission::access_level::AccessLevel;
+ for level in [
+ Some(AccessLevel::View),
+ Some(AccessLevel::Comment),
+ Some(AccessLevel::Edit),
+ None,
+ ] {
+ for receipt in team_policy_receipts() {
+ let mut repo = make_mock_repo();
+ repo.expect_get_team_share_facts()
+ .returning(|_| Box::pin(async { Ok(team_share_facts()) }));
+ let (service, broker) = make_test_service_with_event_broker(repo);
+ // Even a context claiming the actor owns it cannot replace persisted facts.
+ let mut context = task_document_context("doc-1");
+ context.owner = edit_receipt("doc-1").acting_user_id().unwrap().clone();
+ assert!(matches!(
+ service
+ .edit_document(receipt, context, team_edit_args(level))
+ .await,
+ Err(DocumentError::Unauthorized)
+ ));
+ assert!(broker.published().lock().unwrap().is_empty());
+ }
+ }
+ for enabled in [true, false] {
+ for receipt in team_policy_receipts() {
+ let mut repo = make_mock_repo();
+ repo.expect_get_team_share_facts()
+ .returning(|_| Box::pin(async { Ok(team_share_facts()) }));
+ assert!(matches!(
+ make_test_service(repo)
+ .set_team_share(receipt, enabled)
+ .await,
+ Err(DocumentError::Unauthorized)
+ ));
+ }
+ }
+}
+
+fn owner_bot_edit_receipt() -> EntityAccessReceipt<EditAccessLevel> {
+ use entity_access::domain::models::{AccessLevel, Entity, EntityPermission};
+ EntityAccessReceipt::try_new_bot(
+ bot_id().into_storage_id(),
+ BotReceiptScope::User {
+ acting_user: team_share_facts().owner,
+ },
+ Entity {
+ entity_id: "doc-1".to_string(),
+ entity_type: EntityType::Document,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ },
+ )
+ .unwrap()
+}
+
+#[tokio::test]
+async fn owner_scoped_bot_can_edit_and_toggle_explicit_team_sharing() {
+ use models_permissions::share_permission::access_level::AccessLevel;
+ for level in [
+ Some(AccessLevel::View),
+ Some(AccessLevel::Comment),
+ Some(AccessLevel::Edit),
+ None,
+ ] {
+ let mut repo = make_mock_repo();
+ repo.expect_get_team_share_facts()
+ .returning(|_| Box::pin(async { Ok(team_share_facts()) }));
+ repo.expect_edit_document()
+ .times(1)
+ .withf(move |args| {
+ let command = args.team_share.as_ref().unwrap();
+ command.expected() == &team_share_facts()
+ && command.target().map(|grant| AccessLevel::from(grant.level)) == level
+ })
+ .returning(|_| Box::pin(async { Ok(()) }));
+ make_test_service(repo)
+ .edit_document(
+ owner_bot_edit_receipt(),
+ task_document_context("doc-1"),
+ team_edit_args(level),
+ )
+ .await
+ .unwrap();
+ }
+ for enabled in [true, false] {
+ let mut repo = make_mock_repo();
+ repo.expect_get_team_share_facts()
+ .returning(|_| Box::pin(async { Ok(team_share_facts()) }));
+ repo.expect_set_team_share()
+ .times(1)
+ .withf(move |command| command.target().is_some() == enabled)
+ .returning(move |_| {
+ Box::pin(async move {
+ Ok(super::super::models::DocumentTeamShare {
+ team_id: team_share_facts().owner_team_id,
+ shared_with_team: enabled,
+ })
+ })
+ });
+ make_test_service(repo)
+ .set_team_share(owner_bot_edit_receipt(), enabled)
+ .await
+ .unwrap();
+ }
+}
+
+#[tokio::test]
+async fn team_edit_conflict_does_not_publish_success() {
+ let mut repo = make_mock_repo();
+ repo.expect_get_team_share_facts()
+ .returning(|_| Box::pin(async { Ok(team_share_facts()) }));
+ repo.expect_edit_document()
+ .returning(|_| Box::pin(async { Err(DocumentError::Conflict("stale facts".to_string())) }));
+ let (service, broker) = make_test_service_with_event_broker(repo);
+ assert!(matches!(
+ service
+ .edit_document(
+ owner_bot_edit_receipt(),
+ task_document_context("doc-1"),
+ team_edit_args(None)
+ )
+ .await,
+ Err(DocumentError::Conflict(_))
+ ));
+ assert!(broker.published().lock().unwrap().is_empty());
+ assert_eq!(*service.connection_service.invalidations.lock().unwrap(), 0);
+}
+
+#[tokio::test]
+async fn team_toggle_conflict_does_not_invalidate() {
+ let mut repo = make_mock_repo();
+ repo.expect_get_team_share_facts()
+ .returning(|_| Box::pin(async { Ok(team_share_facts()) }));
+ repo.expect_set_team_share()
+ .returning(|_| Box::pin(async { Err(DocumentError::Conflict("stale facts".to_string())) }));
+ let service = make_test_service(repo);
+ assert!(matches!(
+ service.set_team_share(owner_bot_edit_receipt(), true).await,
+ Err(DocumentError::Conflict(_))
+ ));
+ assert_eq!(*service.connection_service.invalidations.lock().unwrap(), 0);
+}
+
+#[tokio::test]
+async fn team_edit_rejects_owner_level_and_enable_without_team_before_writes() {
+ use models_permissions::share_permission::access_level::AccessLevel;
+ for (level, has_team) in [(AccessLevel::Owner, true), (AccessLevel::View, false)] {
+ let mut repo = make_mock_repo();
+ repo.expect_get_team_share_facts().returning(move |_| {
+ Box::pin(async move {
+ let mut facts = team_share_facts();
+ if !has_team {
+ facts.owner_team_id = None;
+ }
+ Ok(facts)
+ })
+ });
+ let service = make_test_service(repo);
+ assert!(matches!(
+ service
+ .edit_document(
+ owner_bot_edit_receipt(),
+ task_document_context("doc-1"),
+ team_edit_args(Some(level))
+ )
+ .await,
+ Err(DocumentError::BadRequest(_))
+ ));
+ assert_eq!(*service.connection_service.invalidations.lock().unwrap(), 0);
+ }
+}
+
fn edit_receipt(document_id: &str) -> EntityAccessReceipt<EditAccessLevel> {
let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
@@ -1686,6 +1950,7 @@ async fn edit_document_sets_revocation_intent_from_link_share_target() {
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share,
link_share_access_level: None,
+ team_share_access_level: None,
channel_share_permissions: None,
}),
file_type: None,
@@ -1893,6 +2158,84 @@ async fn copy_document_best_effort_bumps_inherited_project_and_publishes_event()
assert_eq!(event.payload["metadata"]["owner"], "macro|[email protected]");
}
+struct RejectUnexpectedFinalization;
+
+impl crate::domain::ports::markdown::MarkdownInitializationPort for RejectUnexpectedFinalization {
+ async fn initialize_existing_markdown(
+ &self,
+ _: &str,
+ _: &str,
+ ) -> Result<Vec<u8>, DocumentError> {
+ panic!("failed repository creation must not initialize markdown");
+ }
+}
+
+impl crate::domain::ports::create::DocumentBytesUploadPort for RejectUnexpectedFinalization {
+ async fn upload_document_bytes(
+ &self,
+ _: crate::domain::ports::create::DocumentBytesUpload,
+ ) -> Result<(), DocumentError> {
+ panic!("failed repository creation must not upload content");
+ }
+}
+
+#[tokio::test]
+async fn creator_forwards_explicit_consent_and_stops_after_repository_failure() {
+ use crate::domain::create::{
+ DocumentCreator, MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument,
+ };
+
+ for (subtype, expected_share) in [
+ (MarkdownSubtype::Note, false),
+ (MarkdownSubtype::Snippet, false),
+ (
+ MarkdownSubtype::from_task_flag(true, Some(uuid::Uuid::from_u128(7))),
+ true,
+ ),
+ (
+ MarkdownSubtype::Task {
+ property_values: None,
+ share_with_team: false,
+ team_id: None,
+ },
+ false,
+ ),
+ ] {
+ let mut repo = make_mock_repo();
+ repo.expect_get_team_default_link_share()
+ .returning(|_| Box::pin(std::future::ready(Ok(None))));
+ repo.expect_create_document()
+ .withf(move |args, permission| {
+ args.share_with_team == expected_share
+ && permission.team_share_access_level.is_none()
+ })
+ .times(1)
+ .returning(|_, _| {
+ Box::pin(std::future::ready(Err(DocumentError::Internal(
+ anyhow::anyhow!("creation rolled back"),
+ ))))
+ });
+ let (service, event_broker) = make_test_service_with_event_broker(repo);
+ let creator = DocumentCreator::new(
+ service,
+ RejectUnexpectedFinalization,
+ RejectUnexpectedFinalization,
+ );
+ let result = creator
+ .create_markdown_text(
+ create_document_repo_args(FileType::Md).user_id,
+ NewMarkdownTextDocument {
+ metadata: NewDocumentMetadata::new("test"),
+ markdown: String::new(),
+ subtype,
+ },
+ )
+ .await;
+ assert!(result.is_err());
+ assert!(event_broker.published().lock().unwrap().is_empty());
+ }
+}
+
fn create_document_repo_args(file_type: FileType) -> CreateDocumentRepoArgs {
CreateDocumentRepoArgs {
id: None,
@@ -1904,6 +2247,7 @@ fn create_document_repo_args(file_type: FileType) -> CreateDocumentRepoArgs {
file_type: Some(file_type),
project_id: None,
team_id: None,
+ share_with_team: false,
created_at: None,
sub_type: None,
skip_history: false,
@@ -2099,7 +2443,7 @@ async fn handle_task_properties_forwards_create_attribution() {
),
TestUploadUrlPort,
task_properties.clone(),
- TestConnectionService,
+ TestConnectionService::default(),
TestEntityAccessManagementService::default(),
TestForeignEntityService::default(),
TestEventBroker::default(),
diff --git a/crates/documents/src/inbound/axum_router/create_document.rs b/crates/documents/src/inbound/axum_router/create_document.rs
index 6c619f74f3..b1ddcf1256 100644
--- a/crates/documents/src/inbound/axum_router/create_document.rs
+++ b/crates/documents/src/inbound/axum_router/create_document.rs
@@ -96,6 +96,7 @@ pub async fn create_document_handler<
file_type,
project_id: req.project_id,
team_id,
+ share_with_team: false,
created_at: req.created_at,
sub_type: req
.is_task
diff --git a/crates/documents/src/inbound/axum_router/team_share.rs b/crates/documents/src/inbound/axum_router/team_share.rs
index a489ecdf22..a8a173eeef 100644
--- a/crates/documents/src/inbound/axum_router/team_share.rs
+++ b/crates/documents/src/inbound/axum_router/team_share.rs
@@ -47,9 +47,10 @@ pub async fn get_team_share_handler<
Ok(Json(response))
}
-/// Sets the team-share state of a document. Sharing grants the document
-/// owner's team Edit access; unsharing removes the team's access. Requires
-/// Edit access on the document.
+/// Sets explicit team sharing. Requires a verified acting identity matching
+/// the persisted document owner, not merely effective Edit or Owner access.
+/// Initial enable defaults to Edit; repeated enable preserves the chosen level.
+/// Clear removes only the managed direct grant, not inherited team access.
#[utoipa::path(
tag = "document",
put,
@@ -61,9 +62,10 @@ pub async fn get_team_share_handler<
request_body = SetDocumentTeamShareRequest,
responses(
(status = 200, body = DocumentTeamShareResponse),
- (status = 400, body = model_error_response::ErrorResponse),
- (status = 401, body = model_error_response::ErrorResponse),
+ (status = 400, description = "Owner has no team", body = model_error_response::ErrorResponse),
+ (status = 401, description = "Acting identity is absent or is not the actual owner", body = model_error_response::ErrorResponse),
(status = 404, body = model_error_response::ErrorResponse),
+ (status = 409, description = "Sharing facts changed or an untracked grant conflicts", body = model_error_response::ErrorResponse),
(status = 500, body = model_error_response::ErrorResponse),
)
)]
diff --git a/crates/documents/src/outbound/pg_document_repo.rs b/crates/documents/src/outbound/pg_document_repo.rs
index d523933091..4a03ae2037 100644
--- a/crates/documents/src/outbound/pg_document_repo.rs
+++ b/crates/documents/src/outbound/pg_document_repo.rs
@@ -23,8 +23,8 @@ use sqlx::Row;
use crate::domain::content::{DocumentContent, DocumentContentState};
use crate::domain::models::{
BranchNameContext, Comment, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs,
- DocumentTeamShare, EditDocumentRepoArgs, EmailImportRepoOutcome, ImportEmailAttachmentRepoArgs,
- TeamTaskMetadata, Thread,
+ DocumentError, DocumentTeamShare, EditDocumentRepoArgs, EmailImportRepoOutcome,
+ ImportEmailAttachmentRepoArgs, TeamTaskMetadata, Thread,
};
use crate::domain::ports::DocumentRepo;
@@ -43,7 +43,7 @@ impl PgDocumentRepo {
async fn reused_email_document(
&self,
document_id: String,
- ) -> Result<EmailImportRepoOutcome, sqlx::Error> {
+ ) -> Result<EmailImportRepoOutcome, DocumentError> {
let metadata = self.get_document_metadata(&document_id).await?;
Ok(EmailImportRepoOutcome::Reused(metadata))
}
@@ -51,7 +51,7 @@ impl PgDocumentRepo {
async fn reused_linked_email_attachment(
&self,
email_attachment_id: uuid::Uuid,
- ) -> Result<EmailImportRepoOutcome, sqlx::Error> {
+ ) -> Result<EmailImportRepoOutcome, DocumentError> {
let existing_id =
create::find_document_id_for_email_attachment(&self.pool, email_attachment_id)
.await?
@@ -76,7 +76,7 @@ impl PgDocumentRepo {
&self,
document_id: &str,
email_attachment_id: uuid::Uuid,
- ) -> Result<EmailImportRepoOutcome, sqlx::Error> {
+ ) -> Result<EmailImportRepoOutcome, DocumentError> {
let mut transaction = self.pool.begin().await?;
match create::link_document_email(&mut transaction, document_id, email_attachment_id).await
{
@@ -89,7 +89,7 @@ impl PgDocumentRepo {
self.reused_linked_email_attachment(email_attachment_id)
.await
}
- Err(e) => Err(e),
+ Err(e) => Err(e.into()),
}
}
}
@@ -471,7 +471,7 @@ impl DocumentRepo for PgDocumentRepo {
&self,
args: CreateDocumentRepoArgs,
share_permission: SharePermissionV2,
- ) -> Result<DocumentMetadata, Self::Err> {
+ ) -> Result<DocumentMetadata, DocumentError> {
let mut transaction = self.pool.begin().await?;
let metadata =
create::insert_new_document(&mut transaction, args, &share_permission).await?;
@@ -484,11 +484,13 @@ impl DocumentRepo for PgDocumentRepo {
&self,
args: ImportEmailAttachmentRepoArgs,
share_permission: SharePermissionV2,
- ) -> Result<EmailImportRepoOutcome, Self::Err> {
+ ) -> Result<EmailImportRepoOutcome, DocumentError> {
let ImportEmailAttachmentRepoArgs {
email_attachment_id,
- create,
+ mut create,
} = args;
+ // Imports do not carry task-creation consent, including reuse paths.
+ create.share_with_team = false;
// Unlocked reuse: attachment already linked, or a live email doc with
// this sha already exists. The advisory lock is only required when a
@@ -539,7 +541,7 @@ impl DocumentRepo for PgDocumentRepo {
.reused_linked_email_attachment(email_attachment_id)
.await;
}
- Err(e) => return Err(e),
+ Err(e) => return Err(e.into()),
}
transaction.commit().await?;
@@ -547,8 +549,33 @@ impl DocumentRepo for PgDocumentRepo {
}
#[tracing::instrument(err, skip(self, args))]
- async fn edit_document(&self, args: EditDocumentRepoArgs) -> Result<(), Self::Err> {
+ async fn edit_document(&self, args: EditDocumentRepoArgs) -> Result<(), DocumentError> {
+ use share_permission_db_utils::team_share;
+
let mut transaction = self.pool.begin().await?;
+ if let Some(command) = &args.team_share {
+ if command.expected().entity.entity_type != EntityType::Document
+ || command.expected().entity.entity_id != args.document_id
+ || args
+ .share_permission
+ .as_ref()
+ .and_then(|p| p.team_share_access_level)
+ != Some(command.target().map(|grant| grant.level.into()))
+ {
+ return Err(DocumentError::BadRequest(
+ "team-share command does not match edit".to_string(),
+ ));
+ }
+ team_share::apply(&mut transaction, command)
+ .await
+ .map_err(share::map_team_share_error)?;
+ } else if args
+ .share_permission
+ .as_ref()
+ .is_some_and(|p| p.team_share_access_level.is_some())
+ {
+ return Err(DocumentError::Unauthorized);
+ }
use crate::domain::models::FileTypeUpdate;
let file_type_db = args.file_type.map(|update| match update {
@@ -844,26 +871,25 @@ impl DocumentRepo for PgDocumentRepo {
}
#[tracing::instrument(err, skip(self))]
- async fn share_with_team(
+ async fn get_team_share_facts(
&self,
- team_id: &uuid::Uuid,
document_id: &str,
- ) -> Result<(), Self::Err> {
- share::share_with_team(&self.pool, team_id, document_id).await
+ ) -> Result<models_permissions::share_permission::team_share::TeamShareFacts, DocumentError>
+ {
+ share::get_team_share_facts(&self.pool, document_id).await
}
#[tracing::instrument(err, skip(self))]
- async fn get_team_share(&self, document_id: &str) -> Result<DocumentTeamShare, Self::Err> {
+ async fn get_team_share(&self, document_id: &str) -> Result<DocumentTeamShare, DocumentError> {
share::get_team_share(&self.pool, document_id).await
}
#[tracing::instrument(err, skip(self))]
async fn set_team_share(
&self,
- document_id: &str,
- share: bool,
- ) -> Result<DocumentTeamShare, Self::Err> {
- share::set_team_share(&self.pool, document_id, share).await
+ command: models_permissions::share_permission::team_share::AuthorizedTeamShareCommand,
+ ) -> Result<DocumentTeamShare, DocumentError> {
+ share::set_team_share(&self.pool, command).await
}
#[tracing::instrument(err, skip(self))]
diff --git a/crates/documents/src/outbound/pg_document_repo/create.rs b/crates/documents/src/outbound/pg_document_repo/create.rs
index 95f75a3765..67f7f7d29d 100644
--- a/crates/documents/src/outbound/pg_document_repo/create.rs
+++ b/crates/documents/src/outbound/pg_document_repo/create.rs
@@ -2,8 +2,10 @@ use document_sub_type::DocumentSubType;
use macro_user_id::user_id::MacroUserIdStr;
use model::document::{DocumentMetadata, FileType, VersionIDWithTimeStamps};
use models_permissions::share_permission::SharePermissionV2;
+use models_permissions::share_permission::team_share::TeamShareCreation;
+use share_permission_db_utils::team_share::{self, TeamShareError};
-use crate::domain::models::CreateDocumentRepoArgs;
+use crate::domain::models::{CreateDocumentRepoArgs, DocumentError};
/// Inserts a record into the document table
/// Returns the document id
@@ -16,7 +18,7 @@ pub async fn insert_document_row<'a>(
file_type: Option<FileType>,
project_id: Option<&uuid::Uuid>,
created_at: &chrono::DateTime<chrono::Utc>,
-) -> Result<uuid::Uuid, sqlx::Error> {
+) -> Result<uuid::Uuid, DocumentError> {
// Generate id if one is not provided
let id = macro_uuid::generate_uuid_v7();
let document_id: uuid::Uuid = if let Some(id) = document_id { *id } else { id };
@@ -38,16 +40,12 @@ pub async fn insert_document_row<'a>(
.await;
match result {
- Ok(_) => id.to_string().clone(),
- Err(sqlx::Error::Database(ref db_err)) if db_err.is_unique_violation() => {
- return Err(sqlx::Error::Protocol(format!(
- "document with ID already exists: {id}"
- )));
- }
- Err(e) => return Err(e),
- };
-
- Ok(document_id)
+ Ok(_) => Ok(document_id),
+ Err(sqlx::Error::Database(ref db_err)) if db_err.is_unique_violation() => Err(
+ DocumentError::Conflict("document with ID already exists".to_string()),
+ ),
+ Err(e) => Err(e.into()),
+ }
}
/// sets the document sub type if necessary
@@ -155,7 +153,8 @@ pub async fn set_document_version(
/// Sets share permission for the document
///
-/// The permission is resolved by the domain layer; this function persists it verbatim.
+/// Link permission is resolved by the domain layer. Canonical team state always starts
+/// NULL; only guarded explicit task initialization may establish a team share.
#[tracing::instrument(skip(transaction, share_permission), err)]
pub async fn set_share_permission(
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -386,7 +385,7 @@ pub async fn insert_new_document(
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
args: CreateDocumentRepoArgs,
share_permission: &SharePermissionV2,
-) -> Result<DocumentMetadata, sqlx::Error> {
+) -> Result<DocumentMetadata, DocumentError> {
let CreateDocumentRepoArgs {
id,
sha,
@@ -395,6 +394,7 @@ pub async fn insert_new_document(
file_type,
project_id,
team_id,
+ share_with_team,
created_at: provided_created_at,
sub_type: requested_sub_type,
skip_history,
@@ -454,6 +454,19 @@ pub async fn insert_new_document(
)
.await?;
+ if share_with_team {
+ let document_id_string = document_id.to_string();
+ let entity = model_entity::EntityType::Document.with_entity_str(&document_id_string);
+ team_share::initialize(transaction, &entity, TeamShareCreation::ExplicitTask)
+ .await
+ .map_err(|error| match error.current_context() {
+ TeamShareError::InvalidState => DocumentError::BadRequest(
+ "document owner does not belong to a team".to_string(),
+ ),
+ _ => DocumentError::Internal(error.into()),
+ })?;
+ }
+
Ok(DocumentMetadata::new_document(
&document_id.to_string(),
document_version.id,
diff --git a/crates/documents/src/outbound/pg_document_repo/share.rs b/crates/documents/src/outbound/pg_document_repo/share.rs
index 4b3e2a0d52..02cd6aa75e 100644
--- a/crates/documents/src/outbound/pg_document_repo/share.rs
+++ b/crates/documents/src/outbound/pg_document_repo/share.rs
@@ -1,146 +1,120 @@
-use entity_access_db_utils::AccessLevel;
-use sqlx::PgPool;
-use uuid::Uuid;
+use entity_access_db_utils::team_share::direct_level;
+use model_entity::{Entity, EntityType};
+use models_permissions::share_permission::team_share::{
+ AuthorizedTeamShareCommand, TeamShareFacts, TeamShareGrant, TeamShareLevel,
+};
+use share_permission_db_utils::team_share::{self, TeamShareError};
+use sqlx::{PgPool, Postgres, Transaction};
-use crate::domain::models::DocumentTeamShare;
+use crate::domain::models::{DocumentError, DocumentTeamShare};
-/// Share a document with the given team.
+// Existing repository operations retain their SQLx error type; conditional edits
+// expose domain errors so authorization conflicts reach callers without becoming 500s.
+impl From<sqlx::Error> for DocumentError {
+ fn from(error: sqlx::Error) -> Self {
+ Self::Internal(error.into())
+ }
+}
+
+pub(super) fn map_team_share_error(error: rootcause::Report<TeamShareError>) -> DocumentError {
+ match error.current_context() {
+ TeamShareError::NotFound => DocumentError::NotFound("team-share document".to_string()),
+ TeamShareError::ChangedFacts | TeamShareError::UntrackedGrant => {
+ DocumentError::Conflict(error.to_string())
+ }
+ _ => DocumentError::Internal(error.into()),
+ }
+}
+
+/// Read authoritative facts in one guarded snapshot, without creating permissions.
+///
+/// Documents shared before canonical state existed carry a direct grant for the
+/// owner's team but a NULL level and revision zero. Those grants are adopted here so
+/// the toggle reads as enabled and an owner's next update does not conflict.
#[tracing::instrument(err, skip(pool))]
-pub async fn share_with_team(
+pub async fn get_team_share_facts(
pool: &PgPool,
- team_id: &Uuid,
document_id: &str,
-) -> Result<(), sqlx::Error> {
- let document_uuid = macro_uuid::string_to_uuid(document_id)
- .map_err(|e| sqlx::Error::Protocol(e.to_string()))?;
+) -> Result<TeamShareFacts, DocumentError> {
+ let entity = EntityType::Document.with_entity_str(document_id);
+ let mut transaction = pool.begin().await?;
+ let mut facts = team_share::load_facts(&mut transaction, &entity)
+ .await
+ .map_err(map_team_share_error)?;
+ if let Some(legacy) = legacy_grant(&mut transaction, &facts).await? {
+ team_share::adopt(&mut transaction, &facts, legacy)
+ .await
+ .map_err(map_team_share_error)?;
+ facts = team_share::load_facts(&mut transaction, &entity)
+ .await
+ .map_err(map_team_share_error)?;
+ }
+ transaction.commit().await?;
+ Ok(facts)
+}
- sqlx::query!(
- r#"
- INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
- VALUES ($1, 'document', $2, 'team', $3)
- ON CONFLICT DO NOTHING
- "#,
- &document_uuid,
- &team_id.to_string(),
- AccessLevel::Comment as _,
+/// A historical direct grant for the owner's team on a document that canonical
+/// sharing never touched. Inherited rows, foreign teams, and documents with any
+/// revision history are not candidates; their untracked grants still conflict.
+async fn legacy_grant(
+ transaction: &mut Transaction<'_, Postgres>,
+ facts: &TeamShareFacts,
+) -> Result<Option<TeamShareGrant>, DocumentError> {
+ if facts.current.is_some() || facts.revision != 0 {
+ return Ok(None);
+ }
+ let Some(team_id) = facts.owner_team_id else {
+ return Ok(None);
+ };
+ let document_id = document_uuid(&facts.entity)?;
+ let level = direct_level(
+ transaction.as_mut(),
+ &document_id,
+ EntityType::Document,
+ team_id,
)
- .execute(pool)
.await?;
-
- Ok(())
+ Ok(level
+ .and_then(|level| TeamShareLevel::try_from(level).ok())
+ .map(|level| TeamShareGrant { team_id, level }))
}
-/// Resolve the document owner's team. Returns `None` when the owner does not
-/// belong to a team.
-async fn owner_team_id(pool: &PgPool, document_id: &str) -> Result<Option<Uuid>, sqlx::Error> {
- sqlx::query_scalar!(
- r#"
- SELECT tu.team_id
- FROM "Document" d
- JOIN team_user tu ON tu.user_id = d.owner
- WHERE d.id = $1
- LIMIT 1
- "#,
- document_id,
- )
- .fetch_optional(pool)
- .await
+fn document_uuid(entity: &Entity<'_>) -> Result<uuid::Uuid, DocumentError> {
+ uuid::Uuid::parse_str(&entity.entity_id)
+ .map_err(|error| DocumentError::BadRequest(error.to_string()))
}
-/// Get the team-share state of a document, resolved against the owner's team.
+/// Read explicit state; inherited and untracked direct grants do not enable the toggle.
#[tracing::instrument(err, skip(pool))]
pub async fn get_team_share(
pool: &PgPool,
document_id: &str,
-) -> Result<DocumentTeamShare, sqlx::Error> {
- let document_uuid = macro_uuid::string_to_uuid(document_id)
- .map_err(|e| sqlx::Error::Protocol(e.to_string()))?;
-
- let Some(team_id) = owner_team_id(pool, document_id).await? else {
- return Ok(DocumentTeamShare {
- team_id: None,
- shared_with_team: false,
- });
- };
-
- let shared = sqlx::query_scalar!(
- r#"
- SELECT EXISTS (
- SELECT 1 FROM entity_access
- WHERE entity_id = $1
- AND entity_type = 'document'
- AND source_id = $2
- AND source_type = 'team'
- ) as "exists!"
- "#,
- &document_uuid,
- &team_id.to_string(),
- )
- .fetch_one(pool)
- .await?;
-
+) -> Result<DocumentTeamShare, DocumentError> {
+ let facts = get_team_share_facts(pool, document_id).await?;
Ok(DocumentTeamShare {
- team_id: Some(team_id),
- shared_with_team: shared,
+ team_id: facts.owner_team_id,
+ shared_with_team: facts.current.is_some(),
})
}
-/// Grant or revoke the document owner's team's access on the document.
-///
-/// Granting gives the team Edit access so teammates can collaboratively
-/// maintain team snippets; revoking removes the team-source access row
-/// (project-granted rows are left untouched). Returns the new state, or the
-/// unshared state when the owner has no team.
+/// Apply the canonical conditional update and commit before reporting success.
#[tracing::instrument(err, skip(pool))]
pub async fn set_team_share(
pool: &PgPool,
- document_id: &str,
- share: bool,
-) -> Result<DocumentTeamShare, sqlx::Error> {
- let document_uuid = macro_uuid::string_to_uuid(document_id)
- .map_err(|e| sqlx::Error::Protocol(e.to_string()))?;
-
- let Some(team_id) = owner_team_id(pool, document_id).await? else {
- return Ok(DocumentTeamShare {
- team_id: None,
- shared_with_team: false,
- });
- };
-
- if share {
- sqlx::query!(
- r#"
- INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
- VALUES ($1, 'document', $2, 'team', $3)
- ON CONFLICT (entity_id, entity_type, source_id, source_type)
- WHERE granted_from_project_id IS NULL
- DO UPDATE SET access_level = EXCLUDED.access_level, updated_at = NOW()
- "#,
- &document_uuid,
- &team_id.to_string(),
- AccessLevel::Edit as _,
- )
- .execute(pool)
- .await?;
- } else {
- sqlx::query!(
- r#"
- DELETE FROM entity_access
- WHERE entity_id = $1
- AND entity_type = 'document'
- AND source_id = $2
- AND source_type = 'team'
- AND granted_from_project_id IS NULL
- "#,
- &document_uuid,
- &team_id.to_string(),
- )
- .execute(pool)
- .await?;
+ command: AuthorizedTeamShareCommand,
+) -> Result<DocumentTeamShare, DocumentError> {
+ if command.expected().entity.entity_type != EntityType::Document {
+ return Err(DocumentError::BadRequest(
+ "team-share command must target a document".to_string(),
+ ));
}
-
+ let mut transaction = pool.begin().await?;
+ team_share::apply(&mut transaction, &command)
+ .await
+ .map_err(map_team_share_error)?;
+ transaction.commit().await?;
Ok(DocumentTeamShare {
- team_id: Some(team_id),
- shared_with_team: share,
+ team_id: command.expected().owner_team_id,
+ shared_with_team: command.target().is_some(),
})
}
diff --git a/crates/documents/src/outbound/pg_document_repo/tests.rs b/crates/documents/src/outbound/pg_document_repo/tests.rs
index 4a91b73371..0d5783fb2e 100644
--- a/crates/documents/src/outbound/pg_document_repo/tests.rs
+++ b/crates/documents/src/outbound/pg_document_repo/tests.rs
@@ -16,6 +16,448 @@ use crate::domain::models::{
};
use crate::domain::ports::DocumentRepo;
use crate::outbound::pg_document_repo::PgDocumentRepo;
+use models_permissions::share_permission::team_share::{
+ TeamShareGrant, TeamShareLevel, TeamShareRequest, authorize_team_share,
+};
+
+async fn set_legacy_team_share(
+ repo: &PgDocumentRepo,
+ document_id: &str,
+ enabled: bool,
+) -> Result<crate::domain::models::DocumentTeamShare, crate::domain::models::DocumentError> {
+ let facts = repo.get_team_share_facts(document_id).await?;
+ let command = authorize_team_share(
+ Some(&facts.owner),
+ &facts,
+ TeamShareRequest {
+ access_level: None,
+ legacy_enabled: Some(enabled),
+ },
+ TeamShareLevel::Edit,
+ )
+ .map_err(|e| crate::domain::models::DocumentError::BadRequest(e.to_string()))?
+ .unwrap();
+ repo.set_team_share(command).await
+}
+
+async fn set_comment_share(repo: &PgDocumentRepo) {
+ let facts = repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap();
+ let command = authorize_team_share(
+ Some(&facts.owner),
+ &facts,
+ TeamShareRequest {
+ access_level: Some(Some(AccessLevel::Comment)),
+ legacy_enabled: None,
+ },
+ TeamShareLevel::Edit,
+ )
+ .unwrap()
+ .unwrap();
+ repo.set_team_share(command).await.unwrap();
+}
+
+async fn team_edit_args(repo: &PgDocumentRepo, level: Option<AccessLevel>) -> EditDocumentRepoArgs {
+ let facts = repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap();
+ let command = authorize_team_share(
+ Some(&facts.owner),
+ &facts,
+ TeamShareRequest {
+ access_level: Some(level),
+ legacy_enabled: None,
+ },
+ TeamShareLevel::Edit,
+ )
+ .unwrap()
+ .unwrap();
+ EditDocumentRepoArgs {
+ document_id: TEST_DOCUMENT_ID.to_string(),
+ document_name: Some("team-edit".to_string()),
+ project_id: None,
+ share_permission: Some(UpdateSharePermissionRequestV2 {
+ link_share: Some(Some(LinkShare::Team)),
+ link_share_access_level: Some(Some(AccessLevel::Comment)),
+ team_share_access_level: Some(level),
+ channel_share_permissions: Some(vec![UpdateChannelSharePermission {
+ operation: UpdateOperation::Add,
+ channel_id: "c0000000-0000-0000-0000-000000000001".to_string(),
+ access_level: Some(AccessLevel::View),
+ }]),
+ }),
+ team_share: Some(command),
+ revoke_non_owner_user_access: true,
+ file_type: None,
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn team_edit_exact_levels_omission_and_legacy_preservation(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+ let mut revision = 0;
+ for level in [AccessLevel::Edit, AccessLevel::Comment, AccessLevel::View] {
+ let args = team_edit_args(&repo, Some(level)).await;
+ repo.edit_document(args).await.unwrap();
+ revision += 1;
+ let facts = repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap();
+ assert_eq!(facts.revision, revision);
+ assert_eq!(AccessLevel::from(facts.current.unwrap().level), level);
+ let persisted = sqlx::query_scalar!(
+ r#"SELECT sp.team_share_access_level AS "level: AccessLevel"
+ FROM "SharePermission" sp JOIN "DocumentPermission" dp ON dp."sharePermissionId" = sp.id
+ WHERE dp."documentId" = $1"#, TEST_DOCUMENT_ID,
+ ).fetch_one(&pool).await.unwrap();
+ assert_eq!(persisted, Some(level));
+ let direct = sqlx::query_scalar!(
+ r#"SELECT access_level AS "level: AccessLevel" FROM entity_access
+ WHERE entity_id = $1 AND entity_type = 'document' AND source_type = 'team'
+ AND source_id = $2 AND granted_from_project_id IS NULL"#,
+ uuid::Uuid::parse_str(TEST_DOCUMENT_ID).unwrap(),
+ TEST_TEAM_ID.to_string(),
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(direct, level);
+ set_legacy_team_share(&repo, TEST_DOCUMENT_ID, true)
+ .await
+ .unwrap();
+ revision += 1;
+ let facts = repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap();
+ assert_eq!(facts.revision, revision);
+ assert_eq!(AccessLevel::from(facts.current.unwrap().level), level);
+
+ let mut args = team_edit_args(&repo, Some(level)).await;
+ args.team_share = None;
+ args.share_permission
+ .as_mut()
+ .unwrap()
+ .team_share_access_level = None;
+ repo.edit_document(args).await.unwrap();
+ assert_eq!(
+ repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap(),
+ facts
+ );
+ }
+ assert_eq!(
+ repo.get_basic_document(TEST_DOCUMENT_ID)
+ .await
+ .unwrap()
+ .document_name,
+ "team-edit"
+ );
+ assert_eq!(
+ share_permission_columns(&pool, TEST_DOCUMENT_ID)
+ .await
+ .link_share
+ .as_deref(),
+ Some("TEAM")
+ );
+ for _ in 0..2 {
+ repo.edit_document(team_edit_args(&repo, None).await)
+ .await
+ .unwrap();
+ revision += 1;
+ let facts = repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap();
+ assert!(facts.current.is_none());
+ assert_eq!(facts.revision, revision);
+ let remaining = sqlx::query_scalar!(
+ r#"SELECT COUNT(*) as "count!" FROM entity_access
+ WHERE entity_id = $1 AND entity_type = 'document' AND source_type = 'team'
+ AND granted_from_project_id IS NULL"#,
+ uuid::Uuid::parse_str(TEST_DOCUMENT_ID).unwrap(),
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(remaining, 0);
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn team_edit_stale_command_rolls_back_accompanying_changes(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+ let args = team_edit_args(&repo, Some(AccessLevel::View)).await;
+ set_legacy_team_share(&repo, TEST_DOCUMENT_ID, true)
+ .await
+ .unwrap();
+ let before = repo.get_basic_document(TEST_DOCUMENT_ID).await.unwrap();
+ let facts = repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap();
+ assert!(matches!(
+ repo.edit_document(args).await,
+ Err(crate::domain::models::DocumentError::Conflict(_))
+ ));
+ assert_eq!(
+ repo.get_basic_document(TEST_DOCUMENT_ID)
+ .await
+ .unwrap()
+ .document_name,
+ before.document_name
+ );
+ assert_eq!(
+ repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap(),
+ facts
+ );
+ assert_eq!(
+ share_permission_columns(&pool, TEST_DOCUMENT_ID)
+ .await
+ .link_share
+ .as_deref(),
+ Some("PUBLIC")
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn team_edit_channel_failure_rolls_back_metadata_permissions_and_grant(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+ insert_non_owner_user_access(&pool).await;
+ let args = team_edit_args(&repo, Some(AccessLevel::View)).await;
+ let before = repo.get_basic_document(TEST_DOCUMENT_ID).await.unwrap();
+ let facts = repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap();
+ sqlx::raw_sql(
+ r#"
+ CREATE FUNCTION reject_channel_share() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN RAISE EXCEPTION 'injected channel failure'; END $$;
+ CREATE TRIGGER reject_channel_share BEFORE INSERT ON "ChannelSharePermission"
+ FOR EACH ROW EXECUTE FUNCTION reject_channel_share();
+ "#,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(repo.edit_document(args).await.is_err());
+ assert_eq!(
+ repo.get_basic_document(TEST_DOCUMENT_ID)
+ .await
+ .unwrap()
+ .document_name,
+ before.document_name
+ );
+ assert_eq!(
+ repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap(),
+ facts
+ );
+ assert_eq!(
+ share_permission_columns(&pool, TEST_DOCUMENT_ID)
+ .await
+ .link_share
+ .as_deref(),
+ Some("PUBLIC")
+ );
+ assert_eq!(direct_user_access_sources(&pool).await.len(), 2);
+ let team_grants = sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM entity_access WHERE entity_id = $1 AND source_type = 'team'",
+ uuid::Uuid::parse_str(TEST_DOCUMENT_ID).unwrap(),
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(team_grants, Some(0));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn inherited_team_grant_does_not_enable_explicit_toggle(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+ sqlx::query!(
+ r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ($1, 'document', $2, 'team', 'owner', $3)"#,
+ uuid::Uuid::parse_str(TEST_DOCUMENT_ID).unwrap(), TEST_TEAM_ID.to_string(),
+ "d0000000-0000-0000-0000-100000000001",
+ ).execute(&pool).await.unwrap();
+ assert!(
+ !repo
+ .get_team_share(TEST_DOCUMENT_ID)
+ .await
+ .unwrap()
+ .shared_with_team
+ );
+ set_legacy_team_share(&repo, TEST_DOCUMENT_ID, true)
+ .await
+ .unwrap();
+ set_legacy_team_share(&repo, TEST_DOCUMENT_ID, false)
+ .await
+ .unwrap();
+ assert!(
+ !repo
+ .get_team_share(TEST_DOCUMENT_ID)
+ .await
+ .unwrap()
+ .shared_with_team
+ );
+ let inherited = sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM entity_access WHERE entity_id = $1 AND source_type = 'team' AND granted_from_project_id IS NOT NULL",
+ uuid::Uuid::parse_str(TEST_DOCUMENT_ID).unwrap(),
+ ).fetch_one(&pool).await.unwrap();
+ assert_eq!(inherited, Some(1));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn creation_team_consent_is_explicit_and_uses_owner_membership(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+ for subtype in [
+ None,
+ Some(document_sub_type::DocumentSubType::Task),
+ Some(document_sub_type::DocumentSubType::Snippet),
+ ] {
+ let mut args = create_document_args(TEST_DOCUMENT_OWNER_ID, false, None);
+ args.sub_type = subtype;
+ let document = repo
+ .create_document(args, md_share_permission())
+ .await
+ .unwrap();
+ let facts = repo
+ .get_team_share_facts(&document.document_id)
+ .await
+ .unwrap();
+ assert_eq!(facts.current, None);
+ assert_eq!(facts.revision, 0);
+ }
+
+ insert_second_team(&pool).await;
+ let mut args = create_document_args(TEST_DOCUMENT_OWNER_ID, true, Some(SECOND_TEAM_ID));
+ args.share_with_team = true;
+ let document = repo
+ .create_document(args, md_share_permission())
+ .await
+ .unwrap();
+ let facts = repo
+ .get_team_share_facts(&document.document_id)
+ .await
+ .unwrap();
+ let grant = facts.current.unwrap();
+ assert_eq!(grant.team_id, TEST_TEAM_ID);
+ assert_eq!(grant.level, TeamShareLevel::Comment);
+ assert_eq!(facts.revision, 1);
+ assert_eq!(
+ repo.get_team_task_metadata(&document.document_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .team_id,
+ SECOND_TEAM_ID
+ );
+ let level = sqlx::query_scalar!(
+ r#"SELECT access_level AS "level: AccessLevel" FROM entity_access
+ WHERE entity_id = $1 AND source_type = 'team' AND granted_from_project_id IS NULL"#,
+ uuid::Uuid::parse_str(&document.document_id).unwrap(),
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(level, AccessLevel::Comment);
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn task_creation_failure_rolls_back_all_initialization(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+ let permissions_before = sqlx::query_scalar!(r#"SELECT COUNT(*) FROM "SharePermission""#)
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ let id = uuid::Uuid::new_v4();
+ let mut args = create_document_args("macro|[email protected]", true, Some(TEST_TEAM_ID));
+ args.id = Some(id);
+ args.share_with_team = true;
+ assert!(
+ repo.create_document(args, md_share_permission())
+ .await
+ .is_err()
+ );
+ assert!(repo.get_document_metadata(&id.to_string()).await.is_err());
+ assert_eq!(
+ sqlx::query_scalar!(r#"SELECT COUNT(*) FROM "SharePermission""#)
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ permissions_before
+ );
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM entity_access WHERE entity_id = $1",
+ id
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+ assert!(team_task_numbers(&pool, TEST_TEAM_ID).await.is_empty());
+
+ sqlx::raw_sql(
+ r#"
+ CREATE FUNCTION reject_team_grant() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN RAISE EXCEPTION 'injected team grant failure'; END $$;
+ CREATE TRIGGER reject_team_grant BEFORE INSERT ON entity_access
+ FOR EACH ROW WHEN (NEW.source_type = 'team') EXECUTE FUNCTION reject_team_grant();
+ "#,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let mut args = create_document_args(TEST_DOCUMENT_OWNER_ID, true, Some(TEST_TEAM_ID));
+ args.id = Some(id);
+ args.share_with_team = true;
+ assert!(
+ repo.create_document(args, md_share_permission())
+ .await
+ .is_err()
+ );
+ assert!(repo.get_document_metadata(&id.to_string()).await.is_err());
+ assert_eq!(
+ sqlx::query_scalar!(r#"SELECT COUNT(*) FROM "SharePermission""#)
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ permissions_before
+ );
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM entity_access WHERE entity_id = $1",
+ id
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+ assert_eq!(
+ sqlx::query_scalar!(
+ r#"SELECT COUNT(*) FROM "UserHistory" WHERE "itemId" = $1"#,
+ id.to_string()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+ assert_eq!(
+ sqlx::query_scalar!(
+ r#"SELECT COUNT(*) FROM "DocumentInstance" WHERE "documentId" = $1"#,
+ id.to_string()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+ assert!(team_task_numbers(&pool, TEST_TEAM_ID).await.is_empty());
+}
const TEST_TEAM_ID: uuid::Uuid = uuid::uuid!("a0000000-0000-0000-0000-000000000001");
const SECOND_TEAM_ID: uuid::Uuid = uuid::uuid!("a0000000-0000-0000-0000-000000000002");
@@ -42,6 +484,7 @@ fn create_document_args(
file_type: Some(model::document::FileType::Md),
project_id: None,
team_id,
+ share_with_team: false,
created_at: None,
sub_type: is_task.then_some(document_sub_type::DocumentSubType::Task),
skip_history: false,
@@ -116,6 +559,8 @@ async fn insert_github_pr_task(
struct SharePermissionColumns {
link_share: Option<String>,
link_share_access_level: Option<String>,
+ team_share_access_level: Option<AccessLevel>,
+ team_share_team_id: Option<uuid::Uuid>,
}
async fn share_permission_columns(
@@ -127,7 +572,9 @@ async fn share_permission_columns(
r#"
SELECT
sp."linkShare" as "link_share?",
- sp."linkShareAccessLevel"::text as "link_share_access_level?"
+ sp."linkShareAccessLevel"::text as "link_share_access_level?",
+ sp.team_share_access_level as "team_share_access_level?: AccessLevel",
+ sp.team_share_team_id as "team_share_team_id?"
FROM "SharePermission" sp
JOIN "DocumentPermission" dp ON dp."sharePermissionId" = sp.id
WHERE dp."documentId" = $1
@@ -426,6 +873,7 @@ async fn test_edit_document_name(pool: Pool<Postgres>) {
let repo = PgDocumentRepo::new(pool.clone());
repo.edit_document(EditDocumentRepoArgs {
+ team_share: None,
document_id: "d0000000-0000-0000-0000-000000000001".to_string(),
document_name: Some("new-name".to_string()),
project_id: None,
@@ -457,6 +905,7 @@ async fn test_edit_document_set_file_type(pool: Pool<Postgres>) {
share_permission: None,
revoke_non_owner_user_access: false,
file_type: Some(FileTypeUpdate::Set(model::document::FileType::Rs)),
+ team_share: None,
})
.await
.unwrap();
@@ -482,6 +931,7 @@ async fn test_edit_document_clear_file_type(pool: Pool<Postgres>) {
share_permission: None,
revoke_non_owner_user_access: false,
file_type: Some(FileTypeUpdate::Clear),
+ team_share: None,
})
.await
.unwrap();
@@ -501,6 +951,7 @@ async fn test_edit_document_project(pool: Pool<Postgres>) {
let repo = PgDocumentRepo::new(pool.clone());
repo.edit_document(EditDocumentRepoArgs {
+ team_share: None,
document_id: "d0000000-0000-0000-0000-000000000001".to_string(),
document_name: None,
project_id: Some("d0000000-0000-0000-0000-100000000001".to_string()),
@@ -530,6 +981,7 @@ async fn test_edit_document_remove_project(pool: Pool<Postgres>) {
// First set a project
repo.edit_document(EditDocumentRepoArgs {
+ team_share: None,
document_id: "d0000000-0000-0000-0000-000000000001".to_string(),
document_name: None,
project_id: Some("d0000000-0000-0000-0000-100000000001".to_string()),
@@ -551,6 +1003,7 @@ async fn test_edit_document_remove_project(pool: Pool<Postgres>) {
// Then remove it by passing empty string
repo.edit_document(EditDocumentRepoArgs {
+ team_share: None,
document_id: "d0000000-0000-0000-0000-000000000001".to_string(),
document_name: None,
project_id: Some("".to_string()),
@@ -577,12 +1030,14 @@ async fn test_edit_document_public_to_null_revokes_non_owner_access(pool: Pool<P
insert_non_owner_user_access(&pool).await;
repo.edit_document(EditDocumentRepoArgs {
+ team_share: None,
document_id: TEST_DOCUMENT_ID.to_string(),
document_name: None,
project_id: None,
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: Some(None),
link_share_access_level: Some(None),
+ team_share_access_level: None,
channel_share_permissions: None,
}),
revoke_non_owner_user_access: true,
@@ -610,12 +1065,14 @@ async fn test_edit_document_public_to_team_revokes_non_owner_access(pool: Pool<P
insert_non_owner_user_access(&pool).await;
repo.edit_document(EditDocumentRepoArgs {
+ team_share: None,
document_id: TEST_DOCUMENT_ID.to_string(),
document_name: None,
project_id: None,
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: Some(Some(LinkShare::Team)),
link_share_access_level: Some(Some(AccessLevel::Comment)),
+ team_share_access_level: None,
channel_share_permissions: None,
}),
revoke_non_owner_user_access: true,
@@ -649,8 +1106,10 @@ async fn test_edit_document_omitted_link_share_does_not_revoke(pool: Pool<Postgr
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: Some(Some(AccessLevel::Edit)),
+ team_share_access_level: None,
channel_share_permissions: None,
}),
+ team_share: None,
revoke_non_owner_user_access: false,
file_type: None,
})
@@ -669,8 +1128,10 @@ async fn test_edit_document_omitted_link_share_does_not_revoke(pool: Pool<Postgr
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: Some(None),
+ team_share_access_level: None,
channel_share_permissions: None,
}),
+ team_share: None,
revoke_non_owner_user_access: false,
file_type: None,
})
@@ -700,10 +1161,12 @@ async fn test_edit_document_name_and_project(pool: Pool<Postgres>) {
repo.edit_document(EditDocumentRepoArgs {
document_id: "d0000000-0000-0000-0000-000000000001".to_string(),
document_name: Some("renamed".to_string()),
+ team_share: None,
project_id: Some("d0000000-0000-0000-0000-100000000001".to_string()),
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: Some(Some(LinkShare::Public)),
link_share_access_level: Some(Some(AccessLevel::Edit)),
+ team_share_access_level: None,
channel_share_permissions: None,
}),
revoke_non_owner_user_access: false,
@@ -739,11 +1202,9 @@ async fn test_edit_document_name_and_project(pool: Pool<Postgres>) {
async fn test_share_with_team_creates_access_for_team_members(pool: Pool<Postgres>) {
let repo = PgDocumentRepo::new(pool.clone());
- repo.share_with_team(&TEST_TEAM_ID, "d0000000-0000-0000-0000-000000000001")
- .await
- .unwrap();
+ set_comment_share(&repo).await;
- // All 3 team members should have access rows
+ // The owner and team have independent direct access rows.
let doc_uuid = macro_uuid::string_to_uuid("d0000000-0000-0000-0000-000000000001").unwrap();
let rows = sqlx::query!(
r#"
@@ -797,13 +1258,16 @@ async fn test_get_team_ids_for_user_returns_empty_when_user_not_on_team(pool: Po
async fn test_share_with_team_idempotent(pool: Pool<Postgres>) {
let repo = PgDocumentRepo::new(pool.clone());
- // Call twice — second call should be a no-op
- repo.share_with_team(&TEST_TEAM_ID, "d0000000-0000-0000-0000-000000000001")
- .await
- .unwrap();
- repo.share_with_team(&TEST_TEAM_ID, "d0000000-0000-0000-0000-000000000001")
- .await
- .unwrap();
+ // Repeated consent advances revision without duplicating grants.
+ set_comment_share(&repo).await;
+ set_comment_share(&repo).await;
+ assert_eq!(
+ repo.get_team_share_facts(TEST_DOCUMENT_ID)
+ .await
+ .unwrap()
+ .revision,
+ 2
+ );
let doc_uuid = macro_uuid::string_to_uuid("d0000000-0000-0000-0000-000000000001").unwrap();
let count = sqlx::query_scalar!(
@@ -835,7 +1299,9 @@ async fn test_team_share_roundtrip(pool: Pool<Postgres>) {
assert!(!state.shared_with_team);
// Share grants the team Edit access
- let state = repo.set_team_share(document_id, true).await.unwrap();
+ let state = set_legacy_team_share(&repo, document_id, true)
+ .await
+ .unwrap();
assert_eq!(state.team_id, Some(TEST_TEAM_ID));
assert!(state.shared_with_team);
@@ -858,7 +1324,9 @@ async fn test_team_share_roundtrip(pool: Pool<Postgres>) {
assert!(state.shared_with_team);
// Unshare removes the team row
- let state = repo.set_team_share(document_id, false).await.unwrap();
+ let state = set_legacy_team_share(&repo, document_id, false)
+ .await
+ .unwrap();
assert!(!state.shared_with_team);
let count = sqlx::query_scalar!(
@@ -876,37 +1344,156 @@ async fn test_team_share_roundtrip(pool: Pool<Postgres>) {
assert_eq!(count, 0);
}
+async fn insert_untracked_team_grant(pool: &Pool<Postgres>, level: AccessLevel) {
+ sqlx::query!(
+ r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ($1, 'document', $2, 'team', $3)"#,
+ uuid::Uuid::parse_str(TEST_DOCUMENT_ID).unwrap(),
+ TEST_TEAM_ID.to_string(),
+ level as _,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+async fn direct_team_grant_levels(pool: &Pool<Postgres>) -> Vec<Option<String>> {
+ sqlx::query_scalar!(
+ r#"SELECT access_level::text FROM entity_access
+ WHERE entity_id = $1 AND entity_type = 'document' AND source_type = 'team'
+ AND granted_from_project_id IS NULL"#,
+ uuid::Uuid::parse_str(TEST_DOCUMENT_ID).unwrap(),
+ )
+ .fetch_all(pool)
+ .await
+ .unwrap()
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("documents_test_data"))
)]
-async fn test_set_team_share_upgrades_existing_team_grant(pool: Pool<Postgres>) {
+async fn historical_team_grant_is_adopted_as_explicit_consent(pool: Pool<Postgres>) {
let repo = PgDocumentRepo::new(pool.clone());
- let document_id = "d0000000-0000-0000-0000-000000000001";
+ // A task shared before canonical state existed: a direct Comment grant, NULL level.
+ insert_untracked_team_grant(&pool, AccessLevel::Comment).await;
+
+ // Reading adopts the grant exactly once; a second read changes nothing.
+ assert!(
+ repo.get_team_share(TEST_DOCUMENT_ID)
+ .await
+ .unwrap()
+ .shared_with_team
+ );
+ let facts = repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap();
+ assert_eq!(
+ facts.current,
+ Some(TeamShareGrant {
+ team_id: TEST_TEAM_ID,
+ level: TeamShareLevel::Comment,
+ })
+ );
+ assert_eq!(facts.revision, 1);
+ assert_eq!(
+ repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap(),
+ facts
+ );
+ let columns = share_permission_columns(&pool, TEST_DOCUMENT_ID).await;
+ assert_eq!(columns.team_share_access_level, Some(AccessLevel::Comment));
+ assert_eq!(columns.team_share_team_id, Some(TEST_TEAM_ID));
- // Existing Comment-level team grant (e.g. from task creation)
- repo.share_with_team(&TEST_TEAM_ID, document_id)
+ // The owner's legacy enable keeps the adopted level instead of conflicting.
+ let state = set_legacy_team_share(&repo, TEST_DOCUMENT_ID, true)
.await
.unwrap();
+ assert!(state.shared_with_team);
+ let facts = repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap();
+ assert_eq!(facts.revision, 2);
+ assert_eq!(facts.current.unwrap().level, TeamShareLevel::Comment);
+ assert_eq!(
+ direct_team_grant_levels(&pool).await,
+ vec![Some("comment".to_string())]
+ );
- // Toggling share on upgrades the team row to Edit
- repo.set_team_share(document_id, true).await.unwrap();
+ // Disabling removes the adopted grant like any managed grant.
+ set_legacy_team_share(&repo, TEST_DOCUMENT_ID, false)
+ .await
+ .unwrap();
+ assert!(
+ !repo
+ .get_team_share(TEST_DOCUMENT_ID)
+ .await
+ .unwrap()
+ .shared_with_team
+ );
+ assert!(direct_team_grant_levels(&pool).await.is_empty());
+}
- let doc_uuid = macro_uuid::string_to_uuid(document_id).unwrap();
- let rows = sqlx::query!(
- r#"
- SELECT access_level::text as "access_level"
- FROM entity_access
- WHERE entity_id = $1 AND entity_type = 'document'
- AND source_type = 'team'
- "#,
- doc_uuid,
- )
- .fetch_all(&pool)
- .await
- .unwrap();
- assert_eq!(rows.len(), 1);
- assert_eq!(rows[0].access_level, Some("edit".to_string()));
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn untracked_grant_after_canonical_history_still_conflicts(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+ set_comment_share(&repo).await;
+ set_legacy_team_share(&repo, TEST_DOCUMENT_ID, false)
+ .await
+ .unwrap();
+ assert!(direct_team_grant_levels(&pool).await.is_empty());
+
+ // A grant appearing after canonical history is an anomaly, not legacy consent.
+ insert_untracked_team_grant(&pool, AccessLevel::Comment).await;
+ assert!(
+ !repo
+ .get_team_share(TEST_DOCUMENT_ID)
+ .await
+ .unwrap()
+ .shared_with_team
+ );
+ assert!(matches!(
+ set_legacy_team_share(&repo, TEST_DOCUMENT_ID, true).await,
+ Err(crate::domain::models::DocumentError::Conflict(_))
+ ));
+ let facts = repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap();
+ assert_eq!(facts.current, None);
+ assert_eq!(facts.revision, 2);
+ assert_eq!(
+ direct_team_grant_levels(&pool).await,
+ vec![Some("comment".to_string())]
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn owner_level_historical_grant_is_not_adopted(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+ insert_untracked_team_grant(&pool, AccessLevel::Owner).await;
+
+ // Owner is not a team-share level, so the row stays untracked and conflicts.
+ assert!(
+ !repo
+ .get_team_share(TEST_DOCUMENT_ID)
+ .await
+ .unwrap()
+ .shared_with_team
+ );
+ assert_eq!(
+ repo.get_team_share_facts(TEST_DOCUMENT_ID)
+ .await
+ .unwrap()
+ .revision,
+ 0
+ );
+ assert!(matches!(
+ set_legacy_team_share(&repo, TEST_DOCUMENT_ID, true).await,
+ Err(crate::domain::models::DocumentError::Conflict(_))
+ ));
+ assert_eq!(
+ direct_team_grant_levels(&pool).await,
+ vec![Some("owner".to_string())]
+ );
}
#[sqlx::test(
@@ -929,9 +1516,13 @@ async fn test_team_share_no_team_owner(pool: Pool<Postgres>) {
assert_eq!(state.team_id, None);
assert!(!state.shared_with_team);
- // Sharing is a no-op when the owner has no team
- let state = repo
- .set_team_share(&metadata.document_id, true)
+ // Enabling fails without a team, but an explicit clear still succeeds.
+ assert!(
+ set_legacy_team_share(&repo, &metadata.document_id, true)
+ .await
+ .is_err()
+ );
+ let state = set_legacy_team_share(&repo, &metadata.document_id, false)
.await
.unwrap();
assert_eq!(state.team_id, None);
@@ -960,9 +1551,7 @@ async fn test_share_with_team_skips_user_with_existing_direct_access(pool: Pool<
.await
.unwrap();
- repo.share_with_team(&TEST_TEAM_ID, "d0000000-0000-0000-0000-000000000001")
- .await
- .unwrap();
+ set_comment_share(&repo).await;
// teammate1 should still have just their original edit row, not a second comment row
let rows = sqlx::query!(
@@ -986,12 +1575,10 @@ async fn test_share_with_team_skips_user_with_existing_direct_access(pool: Pool<
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("documents_test_data"))
)]
-async fn test_share_with_explicit_team_id(pool: Pool<Postgres>) {
+async fn test_share_with_owner_team(pool: Pool<Postgres>) {
let repo = PgDocumentRepo::new(pool.clone());
- repo.share_with_team(&TEST_TEAM_ID, "d0000000-0000-0000-0000-000000000001")
- .await
- .unwrap();
+ set_comment_share(&repo).await;
let doc_uuid = macro_uuid::string_to_uuid("d0000000-0000-0000-0000-000000000001").unwrap();
let rows = sqlx::query!(
@@ -1412,12 +1999,14 @@ async fn test_edit_document_channel_share_creates_user_item_access(pool: Pool<Po
let channel_id = "c0000000-0000-0000-0000-000000000001";
repo.edit_document(EditDocumentRepoArgs {
+ team_share: None,
document_id: "d0000000-0000-0000-0000-000000000001".to_string(),
document_name: None,
project_id: None,
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: None,
+ team_share_access_level: None,
channel_share_permissions: Some(vec![UpdateChannelSharePermission {
operation: UpdateOperation::Add,
channel_id: channel_id.to_string(),
@@ -1485,12 +2074,14 @@ async fn test_edit_document_channel_share_idempotent(pool: Pool<Postgres>) {
let channel_id = "c0000000-0000-0000-0000-000000000001";
let make_args = || EditDocumentRepoArgs {
+ team_share: None,
document_id: "d0000000-0000-0000-0000-000000000001".to_string(),
document_name: None,
project_id: None,
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: None,
+ team_share_access_level: None,
channel_share_permissions: Some(vec![UpdateChannelSharePermission {
operation: UpdateOperation::Add,
channel_id: channel_id.to_string(),
@@ -1743,6 +2334,32 @@ fn pdf_share_permission() -> SharePermissionV2 {
SharePermissionV2::new_document_share_permission(Some(model::document::FileType::Pdf), None)
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn email_import_does_not_initialize_team_consent(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+ let attachments = insert_email_attachments(&pool, 1).await;
+ let mut args = import_email_document_args(TEST_DOCUMENT_OWNER_ID, "import", attachments[0]);
+ args.create.share_with_team = true;
+ let mut permission = pdf_share_permission();
+ permission.team_share_access_level = Some(AccessLevel::Edit);
+ let EmailImportRepoOutcome::Created(document) = repo
+ .import_email_attachment_document(args, permission)
+ .await
+ .unwrap()
+ else {
+ panic!("expected a new import");
+ };
+ let facts = repo
+ .get_team_share_facts(&document.document_id)
+ .await
+ .unwrap();
+ assert_eq!(facts.current, None);
+ assert_eq!(facts.revision, 0);
+}
+
fn import_email_document_args(
owner: &str,
sha: &str,
@@ -1758,6 +2375,7 @@ fn import_email_document_args(
file_type: Some(model::document::FileType::Pdf),
project_id: None,
team_id: None,
+ share_with_team: false,
created_at: None,
sub_type: None,
skip_history: true,
diff --git a/crates/entity_access_db_utils/fixtures/team_share.sql b/crates/entity_access_db_utils/fixtures/team_share.sql
new file mode 100644
index 0000000000..be3513cf4b
--- /dev/null
+++ b/crates/entity_access_db_utils/fixtures/team_share.sql
@@ -0,0 +1,20 @@
+INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES
+ ('50000000-0000-0000-0000-000000000001', '[email protected]', '[email protected]', 'cus_owner');
+INSERT INTO "User" (id, email, name, macro_user_id) VALUES
+ ('macro|[email protected]', '[email protected]', 'Owner', '50000000-0000-0000-0000-000000000001');
+INSERT INTO "Project" (id, name, "userId") VALUES
+ ('20000000-0000-0000-0000-000000000001', 'Root', 'macro|[email protected]');
+INSERT INTO "Project" (id, name, "userId", "parentId") VALUES
+ ('20000000-0000-0000-0000-000000000003', 'Child', 'macro|[email protected]', '20000000-0000-0000-0000-000000000001');
+INSERT INTO "Document" (id, name, owner, "projectId") VALUES
+ ('20000000-0000-0000-0000-000000000002', 'Document', 'macro|[email protected]', '20000000-0000-0000-0000-000000000003');
+INSERT INTO "Chat" (id, name, "userId", "projectId") VALUES
+ ('20000000-0000-0000-0000-000000000004', 'Chat', 'macro|[email protected]', '20000000-0000-0000-0000-000000000003');
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider) VALUES
+ ('30000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'fusionauth', '[email protected]', 'GMAIL');
+INSERT INTO email_threads (id, link_id, project_id) VALUES
+ ('20000000-0000-0000-0000-000000000005', '30000000-0000-0000-0000-000000000001', '20000000-0000-0000-0000-000000000003');
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id) VALUES
+ ('20000000-0000-0000-0000-000000000002', 'document', '10000000-0000-0000-0000-000000000001', 'team', 'edit', NULL),
+ ('20000000-0000-0000-0000-000000000002', 'document', '10000000-0000-0000-0000-000000000001', 'team', 'comment', '20000000-0000-0000-0000-000000000001'),
+ ('20000000-0000-0000-0000-000000000002', 'document', 'other-team', 'team', 'view', NULL);
diff --git a/crates/entity_access_db_utils/src/lib.rs b/crates/entity_access_db_utils/src/lib.rs
index 2ef75e9c39..e8ccdb5741 100644
--- a/crates/entity_access_db_utils/src/lib.rs
+++ b/crates/entity_access_db_utils/src/lib.rs
@@ -5,6 +5,8 @@
#[cfg(test)]
mod test;
+pub mod team_share;
+
use macro_user_id::user_id::MacroUserIdStr;
pub use model_entity::EntityType;
pub use models_entity_access_management::EntityAccessSourceType;
diff --git a/crates/entity_access_db_utils/src/team_share.rs b/crates/entity_access_db_utils/src/team_share.rs
new file mode 100644
index 0000000000..aac797c63f
--- /dev/null
+++ b/crates/entity_access_db_utils/src/team_share.rs
@@ -0,0 +1,122 @@
+//! Low-level direct team grants for the canonical team-share writer.
+//!
+//! Connection helpers require the caller to hold [`acquire_guard`] in its existing
+//! transaction. They do not infer consent, authorize users, or commit transactions.
+//! Use `share_permission_db_utils::team_share` for canonical mutations.
+
+use crate::{AccessLevel, EntityType};
+use macro_uuid::Uuid;
+use sqlx::{PgConnection, Postgres, Transaction};
+
+#[cfg(test)]
+mod test;
+
+/// Acquire the database-wide TEAM/version-1 transaction guard before any row locks
+/// or mutations affecting team sharing, membership, ownership, or project topology.
+///
+/// Participants must use READ COMMITTED so reads after waiting see the previous
+/// holder's committed facts. The guard is held until the caller commits/rolls back.
+pub async fn acquire_guard(transaction: &mut Transaction<'_, Postgres>) -> Result<(), sqlx::Error> {
+ let isolation = sqlx::query_scalar!("SELECT current_setting('transaction_isolation')")
+ .fetch_one(transaction.as_mut())
+ .await?;
+ if isolation.as_deref() != Some("read committed") {
+ return Err(sqlx::Error::InvalidArgument(
+ "team-share guard requires READ COMMITTED isolation".into(),
+ ));
+ }
+ sqlx::query!("SELECT pg_advisory_xact_lock(1413824845, 1)")
+ .execute(transaction.as_mut())
+ .await?;
+ Ok(())
+}
+
+/// Ensure the authoritative owner's direct grant during lazy permission creation.
+/// Returns false without changing a conflicting non-owner grant. The caller must
+/// hold the guard and must not create a permission association on that conflict.
+pub async fn ensure_owner_direct(
+ connection: &mut PgConnection,
+ entity_id: &Uuid,
+ entity_type: EntityType,
+ owner: &macro_user_id::user_id::MacroUserIdStr<'_>,
+) -> Result<bool, sqlx::Error> {
+ let row = sqlx::query!(
+ r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ($1, $2, $3, 'user', 'owner')
+ ON CONFLICT (entity_id, entity_type, source_id, source_type)
+ WHERE granted_from_project_id IS NULL
+ DO UPDATE SET access_level = EXCLUDED.access_level
+ WHERE entity_access.access_level = 'owner'
+ RETURNING id"#,
+ entity_id,
+ entity_type.as_ref(),
+ owner.as_ref(),
+ )
+ .fetch_optional(connection)
+ .await?;
+ Ok(row.is_some())
+}
+
+/// Read only a team's direct grant; inherited contributions do not count.
+pub async fn direct_level(
+ connection: &mut PgConnection,
+ entity_id: &Uuid,
+ entity_type: EntityType,
+ team_id: Uuid,
+) -> Result<Option<AccessLevel>, sqlx::Error> {
+ sqlx::query_scalar!(
+ r#"SELECT access_level AS "access_level: AccessLevel" FROM entity_access
+ WHERE entity_id = $1 AND entity_type = $2 AND source_type = 'team'
+ AND source_id = $3 AND granted_from_project_id IS NULL"#,
+ entity_id,
+ entity_type.as_ref(),
+ team_id.to_string(),
+ )
+ .fetch_optional(connection)
+ .await
+}
+
+/// Set an already validated managed direct grant to the exact level, including downgrades.
+/// The canonical caller must reject untracked conflicts before invoking this helper.
+pub async fn upsert_direct(
+ connection: &mut PgConnection,
+ entity_id: &Uuid,
+ entity_type: EntityType,
+ team_id: Uuid,
+ level: AccessLevel,
+) -> Result<(), sqlx::Error> {
+ sqlx::query!(
+ r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ($1, $2, $3, 'team', $4)
+ ON CONFLICT (entity_id, entity_type, source_id, source_type)
+ WHERE granted_from_project_id IS NULL
+ DO UPDATE SET access_level = EXCLUDED.access_level, updated_at = NOW()"#,
+ entity_id,
+ entity_type.as_ref(),
+ team_id.to_string(),
+ level as _,
+ )
+ .execute(connection)
+ .await?;
+ Ok(())
+}
+
+/// Delete only the recorded managed team's direct grant, independent of membership.
+pub async fn delete_direct(
+ connection: &mut PgConnection,
+ entity_id: &Uuid,
+ entity_type: EntityType,
+ managed_team_id: Uuid,
+) -> Result<(), sqlx::Error> {
+ sqlx::query!(
+ r#"DELETE FROM entity_access
+ WHERE entity_id = $1 AND entity_type = $2 AND source_type = 'team'
+ AND source_id = $3 AND granted_from_project_id IS NULL"#,
+ entity_id,
+ entity_type.as_ref(),
+ managed_team_id.to_string(),
+ )
+ .execute(connection)
+ .await?;
+ Ok(())
+}
diff --git a/crates/entity_access_db_utils/src/team_share/test.rs b/crates/entity_access_db_utils/src/team_share/test.rs
new file mode 100644
index 0000000000..f88e2ca133
--- /dev/null
+++ b/crates/entity_access_db_utils/src/team_share/test.rs
@@ -0,0 +1,82 @@
+use super::*;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("team_share"))
+)]
+async fn exact_direct_levels_and_attributable_deletion(pool: PgPool) -> Result<(), sqlx::Error> {
+ let mut tx = pool.begin().await?;
+ acquire_guard(&mut tx).await?;
+ let id = Uuid::from_u128(0x20000000000000000000000000000002);
+ let team = Uuid::from_u128(0x10000000000000000000000000000001);
+ upsert_direct(
+ tx.as_mut(),
+ &id,
+ EntityType::Document,
+ team,
+ AccessLevel::View,
+ )
+ .await?;
+ assert_eq!(
+ direct_level(tx.as_mut(), &id, EntityType::Document, team).await?,
+ Some(AccessLevel::View)
+ );
+ delete_direct(tx.as_mut(), &id, EntityType::Document, team).await?;
+ assert_eq!(
+ direct_level(tx.as_mut(), &id, EntityType::Document, team).await?,
+ None
+ );
+ assert_eq!(
+ sqlx::query_scalar!("SELECT count(*) FROM entity_access")
+ .fetch_one(tx.as_mut())
+ .await?,
+ Some(2)
+ );
+ tx.rollback().await?;
+ assert_eq!(
+ sqlx::query_scalar!("SELECT count(*) FROM entity_access")
+ .fetch_one(&pool)
+ .await?,
+ Some(3)
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn guard_uses_documented_key_and_transaction_lifetime(
+ pool: PgPool,
+) -> Result<(), sqlx::Error> {
+ let mut first = pool.begin().await?;
+ acquire_guard(&mut first).await?;
+ acquire_guard(&mut first).await?;
+ let mut second = pool.begin().await?;
+ assert_eq!(
+ sqlx::query_scalar!("SELECT pg_try_advisory_xact_lock(1413824845, 1)")
+ .fetch_one(second.as_mut())
+ .await?,
+ Some(false)
+ );
+ first.rollback().await?;
+ assert_eq!(
+ sqlx::query_scalar!("SELECT pg_try_advisory_xact_lock(1413824845, 1)")
+ .fetch_one(second.as_mut())
+ .await?,
+ Some(true)
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn guard_rejects_stale_snapshot_isolation(pool: PgPool) -> Result<(), sqlx::Error> {
+ let mut tx = pool.begin().await?;
+ sqlx::query!("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")
+ .execute(tx.as_mut())
+ .await?;
+ assert!(matches!(
+ acquire_guard(&mut tx).await,
+ Err(sqlx::Error::InvalidArgument(_))
+ ));
+ Ok(())
+}
diff --git a/crates/graphql_entity_mutation/src/mutations.rs b/crates/graphql_entity_mutation/src/mutations.rs
index b57bd1d893..8a236d7197 100644
--- a/crates/graphql_entity_mutation/src/mutations.rs
+++ b/crates/graphql_entity_mutation/src/mutations.rs
@@ -224,7 +224,7 @@ impl GraphqlLinkShare {
}
}
-/// Shared link/channel share-policy update.
+/// Shared link, explicit team, and channel share-policy update.
#[derive(InputObject)]
pub struct EntitySharePolicyInput {
/// Link-sharing audience. Omit to leave unchanged or pass null to disable link sharing.
@@ -232,6 +232,10 @@ pub struct EntitySharePolicyInput {
/// Link access level. Omit to leave unchanged or pass null to reset it to the default level
/// when a link share exists.
pub link_share_access_level: MaybeUndefined<GraphqlEntityAccessLevel>,
+ /// Explicit team access level. Omit to leave unchanged or pass null to disable team sharing,
+ /// independently of link sharing. Only the actual owner may change this setting;
+ /// enabling it requires the owner to belong to a team. OWNER is not an allowed level.
+ pub team_share_access_level: MaybeUndefined<GraphqlEntityAccessLevel>,
/// Channel access entries to add, remove, or replace.
pub channel_share_permissions: Option<Vec<ChannelSharePolicyInput>>,
}
@@ -248,6 +252,10 @@ impl EntitySharePolicyInput {
.link_share_access_level
.map_value(GraphqlEntityAccessLevel::into_model)
.into(),
+ team_share_access_level: self
+ .team_share_access_level
+ .map_value(GraphqlEntityAccessLevel::into_model)
+ .into(),
channel_share_permissions: self.channel_share_permissions.map(|entries| {
entries
.into_iter()
@@ -263,7 +271,7 @@ impl EntitySharePolicyInput {
pub struct UpdateEntitySharePolicyInput {
/// Entity whose share policy should change.
pub entity: EntityRefInput,
- /// New link/channel policy values.
+ /// New link, explicit team, and channel policy values.
pub policy: EntitySharePolicyInput,
}
@@ -536,7 +544,7 @@ impl<S: EntityMutationService, E: SoupEntityEdges> EntityMutationRoot<S, E> {
))
}
- /// Update link and channel share policies across supported entity kinds.
+ /// Update link, explicit team, and channel share policies across supported entity kinds.
async fn update_entity_share_policies(
&self,
ctx: &Context<'_>,
diff --git a/crates/graphql_entity_mutation/src/mutations/test.rs b/crates/graphql_entity_mutation/src/mutations/test.rs
index fa2b2150a6..c2bd1af113 100644
--- a/crates/graphql_entity_mutation/src/mutations/test.rs
+++ b/crates/graphql_entity_mutation/src/mutations/test.rs
@@ -104,6 +104,17 @@ impl QueryRoot {
true
}
+ /// Exercise input coercion, adapter validation, and conversion without a domain service.
+ async fn convert_share_policy(
+ &self,
+ input: super::UpdateEntitySharePolicyInput,
+ ) -> async_graphql::Result<
+ async_graphql::Json<models_permissions::share_permission::UpdateSharePermissionRequestV2>,
+ > {
+ super::validate_share_policy_inputs(std::slice::from_ref(&input))?;
+ Ok(async_graphql::Json(input.into_model().policy))
+ }
+
/// Return a successful domain outcome whose deletion cannot be represented by Soup.
async fn unsupported_deletion(&self) -> super::GraphqlMutationSuccess<TestSoupEdges> {
super::GraphqlMutationSuccess {
@@ -219,6 +230,98 @@ fn batch_validation_rejects_oversized_and_duplicate_requests() {
assert!(error.message.contains("duplicate entity"));
}
+#[tokio::test]
+async fn graphql_team_share_variables_preserve_undefined_null_and_values() {
+ let schema = Schema::build(QueryRoot, async_graphql::EmptyMutation, EmptySubscription).finish();
+ for (variables, expected) in [
+ (value!({}), value!({ "channelSharePermissions": null })),
+ (
+ value!({ "teamShareAccessLevel": null }),
+ value!({ "teamShareAccessLevel": null, "channelSharePermissions": null }),
+ ),
+ (
+ value!({ "teamShareAccessLevel": "VIEW" }),
+ value!({ "teamShareAccessLevel": "view", "channelSharePermissions": null }),
+ ),
+ (
+ value!({ "teamShareAccessLevel": "COMMENT" }),
+ value!({ "teamShareAccessLevel": "comment", "channelSharePermissions": null }),
+ ),
+ (
+ value!({ "teamShareAccessLevel": "EDIT" }),
+ value!({ "teamShareAccessLevel": "edit", "channelSharePermissions": null }),
+ ),
+ // The adapter forwards OWNER so the domain can reject it per entity.
+ (
+ value!({ "teamShareAccessLevel": "OWNER" }),
+ value!({ "teamShareAccessLevel": "owner", "channelSharePermissions": null }),
+ ),
+ ] {
+ let response = schema
+ .execute(
+ Request::new(
+ r#"query($policy: EntitySharePolicyInput!) {
+ convertSharePolicy(input: {
+ entity: { type: DOCUMENT, id: "document-1" }
+ policy: $policy
+ })
+ }"#,
+ )
+ .variables(async_graphql::Variables::from_value(
+ value!({ "policy": variables }),
+ )),
+ )
+ .await;
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(response.data, value!({ "convertSharePolicy": expected }));
+ }
+}
+
+#[tokio::test]
+async fn graphql_team_share_literals_are_independent_of_link_sharing() {
+ let schema = Schema::build(QueryRoot, async_graphql::EmptyMutation, EmptySubscription).finish();
+ for (policy, expected) in [
+ ("{}", value!({ "channelSharePermissions": null })),
+ (
+ "{ teamShareAccessLevel: null, linkShare: PUBLIC, linkShareAccessLevel: VIEW }",
+ value!({
+ "teamShareAccessLevel": null,
+ "linkShare": "PUBLIC",
+ "linkShareAccessLevel": "view",
+ "channelSharePermissions": null,
+ }),
+ ),
+ (
+ "{ teamShareAccessLevel: EDIT, linkShare: null, linkShareAccessLevel: null }",
+ value!({
+ "teamShareAccessLevel": "edit",
+ "linkShare": null,
+ "linkShareAccessLevel": null,
+ "channelSharePermissions": null,
+ }),
+ ),
+ (
+ "{ linkShare: TEAM, linkShareAccessLevel: COMMENT }",
+ value!({
+ "linkShare": "TEAM",
+ "linkShareAccessLevel": "comment",
+ "channelSharePermissions": null,
+ }),
+ ),
+ ] {
+ let response = schema
+ .execute(format!(
+ r#"{{ convertSharePolicy(input: {{
+ entity: {{ type: DOCUMENT, id: "document-1" }}
+ policy: {policy}
+ }}) }}"#,
+ ))
+ .await;
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(response.data, value!({ "convertSharePolicy": expected }));
+ }
+}
+
fn share_policy_input(
link_share: MaybeUndefined<super::GraphqlLinkShare>,
link_share_access_level: MaybeUndefined<GraphqlEntityAccessLevel>,
@@ -226,6 +329,7 @@ fn share_policy_input(
super::EntitySharePolicyInput {
link_share,
link_share_access_level,
+ team_share_access_level: MaybeUndefined::Undefined,
channel_share_permissions: None,
}
}
@@ -325,6 +429,7 @@ fn share_policy_validation_requires_access_levels_for_channel_grants() {
policy: super::EntitySharePolicyInput {
link_share: MaybeUndefined::Undefined,
link_share_access_level: MaybeUndefined::Undefined,
+ team_share_access_level: MaybeUndefined::Undefined,
channel_share_permissions: Some(vec![super::ChannelSharePolicyInput {
operation: super::GraphqlSharePolicyOperation::Add,
channel_id: "channel-1".into(),
diff --git a/crates/macro_db_client/migrations/20260909153943_add_team_share_access_level.down.sql b/crates/macro_db_client/migrations/20260909153943_add_team_share_access_level.down.sql
new file mode 100644
index 0000000000..546fe11ca6
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260909153943_add_team_share_access_level.down.sql
@@ -0,0 +1,9 @@
+-- Only roll back before canonical writers are enabled: this removes grant attribution.
+-- Neither direction of this migration modifies entity_access grants.
+ALTER TABLE "SharePermission"
+ DROP CONSTRAINT "SharePermission_team_share_access_level_check",
+ DROP CONSTRAINT "SharePermission_team_share_pair_check",
+ DROP CONSTRAINT "SharePermission_team_share_revision_check",
+ DROP COLUMN team_share_access_level,
+ DROP COLUMN team_share_team_id,
+ DROP COLUMN team_share_revision;
diff --git a/crates/macro_db_client/migrations/20260909153943_add_team_share_access_level.up.sql b/crates/macro_db_client/migrations/20260909153943_add_team_share_access_level.up.sql
new file mode 100644
index 0000000000..703c47b872
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260909153943_add_team_share_access_level.up.sql
@@ -0,0 +1,11 @@
+-- Existing permission rows remain unshared; historical grants are reconciled separately.
+ALTER TABLE "SharePermission"
+ ADD COLUMN team_share_access_level "AccessLevel",
+ ADD COLUMN team_share_team_id UUID,
+ ADD COLUMN team_share_revision BIGINT NOT NULL DEFAULT 0,
+ ADD CONSTRAINT "SharePermission_team_share_access_level_check"
+ CHECK (team_share_access_level IN ('view', 'comment', 'edit')),
+ ADD CONSTRAINT "SharePermission_team_share_pair_check"
+ CHECK ((team_share_access_level IS NULL) = (team_share_team_id IS NULL)),
+ ADD CONSTRAINT "SharePermission_team_share_revision_check"
+ CHECK (team_share_revision >= 0);
diff --git a/crates/macro_db_client/src/share_permission/create.rs b/crates/macro_db_client/src/share_permission/create.rs
index 6ff31355af..3ac6d8456a 100644
--- a/crates/macro_db_client/src/share_permission/create.rs
+++ b/crates/macro_db_client/src/share_permission/create.rs
@@ -25,7 +25,8 @@ fn normalize_link_share_access_level(
link_share.map(|_| link_share_access_level_or_default(link_share_access_level))
}
-/// Creates a new share permission
+/// Creates a new share permission with explicit team sharing disabled.
+/// Team sharing requires entity context and synchronized grants, so any supplied team level is ignored.
#[tracing::instrument(skip(transaction))]
pub async fn create_share_permission(
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -61,6 +62,7 @@ pub async fn create_share_permission(
id,
link_share,
link_share_access_level,
+ team_share_access_level: None,
owner: String::new(), // Owner is not stored on the share permission row.
channel_share_permissions: share_permission.channel_share_permissions.clone(),
})
diff --git a/crates/macro_db_client/src/share_permission/create/test.rs b/crates/macro_db_client/src/share_permission/create/test.rs
index a5787564c9..fc92fe13e8 100644
--- a/crates/macro_db_client/src/share_permission/create/test.rs
+++ b/crates/macro_db_client/src/share_permission/create/test.rs
@@ -9,6 +9,7 @@ use super::*;
struct StoredSharePermission {
link_share: Option<String>,
link_share_access_level: Option<String>,
+ team_share_access_level: Option<String>,
}
fn share_permission(
@@ -19,6 +20,7 @@ fn share_permission(
id: String::new(),
link_share,
link_share_access_level,
+ team_share_access_level: None,
owner: String::new(),
channel_share_permissions: None,
}
@@ -33,7 +35,8 @@ async fn get_stored_share_permission(
r#"
SELECT
"linkShare" as link_share,
- "linkShareAccessLevel"::text as link_share_access_level
+ "linkShareAccessLevel"::text as link_share_access_level,
+ team_share_access_level::text as team_share_access_level
FROM "SharePermission"
WHERE id = $1
"#,
@@ -65,6 +68,7 @@ async fn create_share_permission_writes_link_columns(pool: Pool<Postgres>) -> an
StoredSharePermission {
link_share: Some("PUBLIC".to_string()),
link_share_access_level: Some("edit".to_string()),
+ team_share_access_level: None,
}
);
@@ -79,6 +83,7 @@ async fn create_share_permission_writes_link_columns(pool: Pool<Postgres>) -> an
StoredSharePermission {
link_share: Some("TEAM".to_string()),
link_share_access_level: Some("comment".to_string()),
+ team_share_access_level: None,
}
);
@@ -94,12 +99,38 @@ async fn create_share_permission_writes_link_columns(pool: Pool<Postgres>) -> an
StoredSharePermission {
link_share: None,
link_share_access_level: None,
+ team_share_access_level: None,
}
);
Ok(())
}
+#[sqlx::test]
+async fn generic_creation_does_not_copy_explicit_team_sharing(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let mut transaction = pool.begin().await?;
+ for level in [
+ AccessLevel::View,
+ AccessLevel::Comment,
+ AccessLevel::Edit,
+ AccessLevel::Owner,
+ ] {
+ let mut permission = share_permission(None, None);
+ permission.team_share_access_level = Some(level);
+ let created = create_share_permission(&mut transaction, &permission).await?;
+ assert_eq!(created.team_share_access_level, None);
+ assert_eq!(
+ get_stored_share_permission(&mut transaction, &created.id)
+ .await?
+ .team_share_access_level,
+ None
+ );
+ }
+ Ok(())
+}
+
#[sqlx::test]
async fn create_share_permission_defaults_enabled_links_to_view(
pool: Pool<Postgres>,
@@ -117,6 +148,7 @@ async fn create_share_permission_defaults_enabled_links_to_view(
StoredSharePermission {
link_share: Some(link_share.to_string()),
link_share_access_level: Some("view".to_string()),
+ team_share_access_level: None,
}
);
}
diff --git a/crates/macro_db_client/src/share_permission/edit.rs b/crates/macro_db_client/src/share_permission/edit.rs
index 7c1877afdb..48280b4d69 100644
--- a/crates/macro_db_client/src/share_permission/edit.rs
+++ b/crates/macro_db_client/src/share_permission/edit.rs
@@ -17,6 +17,10 @@ pub async fn edit_share_permission(
share_permission_id: &str,
share_permission: &UpdateSharePermissionRequestV2,
) -> anyhow::Result<()> {
+ anyhow::ensure!(
+ share_permission.team_share_access_level.is_none(),
+ "supplied team sharing requires a validated canonical command"
+ );
// The optional update fields determine which assignments are present, so this query must be
// assembled dynamically. Every value remains bound; only trusted SQL fragments are appended.
let mut query =
diff --git a/crates/macro_db_client/src/share_permission/edit/test.rs b/crates/macro_db_client/src/share_permission/edit/test.rs
index 09ad810c89..7b0675938e 100644
--- a/crates/macro_db_client/src/share_permission/edit/test.rs
+++ b/crates/macro_db_client/src/share_permission/edit/test.rs
@@ -22,6 +22,7 @@ fn update_request(
UpdateSharePermissionRequestV2 {
link_share,
link_share_access_level,
+ team_share_access_level: None,
channel_share_permissions: None,
}
}
@@ -60,6 +61,38 @@ async fn edit(
.await
}
+#[sqlx::test]
+async fn supplied_unvalidated_team_fields_reject_before_any_writes(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let mut transaction = pool.begin().await?;
+ let permission = create_share_permission(
+ &mut transaction,
+ &SharePermissionV2::new_document_share_permission(None, None),
+ )
+ .await?;
+ let before = get_stored_share_permission(&mut transaction, &permission.id).await?;
+ for level in [None, Some(AccessLevel::View), Some(AccessLevel::Owner)] {
+ let mut request = update_request(Some(Some(LinkShare::Team)), None);
+ request.team_share_access_level = Some(level);
+ assert!(
+ edit(&mut transaction, &permission.id, request.clone())
+ .await
+ .is_err()
+ );
+ assert!(
+ edit_thread_permission(&mut transaction, &Uuid::nil(), &permission.id, &request)
+ .await
+ .is_err()
+ );
+ assert_eq!(
+ get_stored_share_permission(&mut transaction, &permission.id).await?,
+ before
+ );
+ }
+ Ok(())
+}
+
#[sqlx::test]
async fn edit_share_permission_preserves_update_field_semantics(
pool: Pool<Postgres>,
@@ -71,6 +104,7 @@ async fn edit_share_permission_preserves_update_field_semantics(
id: String::new(),
link_share: Some(LinkShare::Public),
link_share_access_level: Some(AccessLevel::Edit),
+ team_share_access_level: None,
owner: String::new(),
channel_share_permissions: None,
},
diff --git a/crates/macro_db_client/src/share_permission/get.rs b/crates/macro_db_client/src/share_permission/get.rs
index 26e6328d47..57fe7b708d 100644
--- a/crates/macro_db_client/src/share_permission/get.rs
+++ b/crates/macro_db_client/src/share_permission/get.rs
@@ -9,6 +9,7 @@ fn parse_share_permission(
id: String,
link_share: Option<String>,
link_share_access_level: Option<AccessLevel>,
+ team_share_access_level: Option<AccessLevel>,
owner: String,
channel_share_permissions: Option<serde_json::Value>,
) -> anyhow::Result<SharePermissionV2> {
@@ -27,6 +28,7 @@ fn parse_share_permission(
id,
link_share,
link_share_access_level,
+ team_share_access_level,
owner,
channel_share_permissions,
})
@@ -142,6 +144,7 @@ pub async fn get_document_share_permission(
sp.id as id,
sp."linkShare" as "link_share?",
sp."linkShareAccessLevel" as "link_share_access_level?: AccessLevel",
+ sp.team_share_access_level as "team_share_access_level?: AccessLevel",
d."owner" as owner,
COALESCE(
json_agg(json_build_object(
@@ -169,6 +172,7 @@ pub async fn get_document_share_permission(
result.id,
result.link_share,
result.link_share_access_level,
+ result.team_share_access_level,
result.owner,
result.channel_share_permissions,
)
@@ -185,6 +189,7 @@ pub async fn get_chat_share_permission(
sp.id as id,
sp."linkShare" as "link_share?",
sp."linkShareAccessLevel" as "link_share_access_level?: AccessLevel",
+ sp.team_share_access_level as "team_share_access_level?: AccessLevel",
c."userId" as owner,
COALESCE(
json_agg(json_build_object(
@@ -212,6 +217,7 @@ pub async fn get_chat_share_permission(
result.id,
result.link_share,
result.link_share_access_level,
+ result.team_share_access_level,
result.owner,
result.channel_share_permissions,
)
@@ -228,6 +234,7 @@ pub async fn get_macro_share_permission(
sp.id as id,
sp."linkShare" as "link_share?",
sp."linkShareAccessLevel" as "link_share_access_level?: AccessLevel",
+ sp.team_share_access_level as "team_share_access_level?: AccessLevel",
m."user_id" as owner,
COALESCE(
json_agg(json_build_object(
@@ -255,6 +262,7 @@ pub async fn get_macro_share_permission(
result.id,
result.link_share,
result.link_share_access_level,
+ result.team_share_access_level,
result.owner,
result.channel_share_permissions,
)
diff --git a/crates/macro_db_client/src/share_permission/get/test.rs b/crates/macro_db_client/src/share_permission/get/test.rs
index a1a78471ef..d28a815fea 100644
--- a/crates/macro_db_client/src/share_permission/get/test.rs
+++ b/crates/macro_db_client/src/share_permission/get/test.rs
@@ -5,6 +5,45 @@ use sqlx::{Pool, Postgres};
use super::*;
+#[sqlx::test(fixtures(path = "../../../fixtures", scripts("channel_share_permissions")))]
+async fn fresh_permission_reads_distinguish_team_share_levels(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let team_id = uuid::Uuid::now_v7();
+ for level in [
+ None,
+ Some(AccessLevel::View),
+ Some(AccessLevel::Comment),
+ Some(AccessLevel::Edit),
+ None,
+ ] {
+ sqlx::query!(
+ r#"
+ UPDATE "SharePermission"
+ SET team_share_access_level = $1,
+ team_share_team_id = $2
+ WHERE id IN ('sp-d1', 'sp-c1')
+ "#,
+ level as _,
+ level.map(|_| team_id),
+ )
+ .execute(&pool)
+ .await?;
+
+ for permission in [
+ get_document_share_permission(&pool, "d1").await?,
+ get_chat_share_permission(&pool, "c1").await?,
+ ] {
+ assert_eq!(permission.team_share_access_level, level);
+ assert_eq!(permission.link_share, Some(LinkShare::Public));
+ assert_eq!(permission.link_share_access_level, Some(AccessLevel::Edit));
+ assert_eq!(permission.owner, "macro|[email protected]");
+ assert_eq!(permission.channel_share_permissions.unwrap().len(), 2);
+ }
+ }
+ Ok(())
+}
+
#[sqlx::test(fixtures(path = "../../../fixtures", scripts("channel_share_permissions")))]
async fn get_document_share_permission_reads_link_fields(
pool: Pool<Postgres>,
diff --git a/crates/macro_middleware/src/cloud_storage/thread/ensure_thread_exists.rs b/crates/macro_middleware/src/cloud_storage/thread/ensure_thread_exists.rs
index 6d0223e689..78eba9f3c7 100644
--- a/crates/macro_middleware/src/cloud_storage/thread/ensure_thread_exists.rs
+++ b/crates/macro_middleware/src/cloud_storage/thread/ensure_thread_exists.rs
@@ -72,6 +72,7 @@ pub async fn insert_thread_share_permissions(
id: macro_uuid::generate_uuid_v7().to_string(),
link_share: None,
link_share_access_level: None,
+ team_share_access_level: None,
owner: owner_id.to_string(),
channel_share_permissions: None,
};
diff --git a/crates/models_permissions/Cargo.toml b/crates/models_permissions/Cargo.toml
index f0beba3f95..6ee8e9a07e 100644
--- a/crates/models_permissions/Cargo.toml
+++ b/crates/models_permissions/Cargo.toml
@@ -5,11 +5,15 @@ publish = false
version = "0.1.0"
[dependencies]
+macro_user_id = { path = "../macro_user_id" }
+model-entity = { path = "../model-entity" }
model_file_type = { path = "../model_file_type" }
schemars = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
strum = { workspace = true }
+thiserror = { workspace = true }
utoipa = { workspace = true }
+uuid = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/models_permissions/src/share_permission.rs b/crates/models_permissions/src/share_permission.rs
index 7590a95a0e..2244f5fe09 100644
--- a/crates/models_permissions/src/share_permission.rs
+++ b/crates/models_permissions/src/share_permission.rs
@@ -9,6 +9,7 @@ use utoipa::ToSchema;
pub mod access_level;
pub mod channel_share_permission;
mod link_share;
+pub mod team_share;
pub use link_share::LinkShare;
@@ -22,6 +23,8 @@ pub struct SharePermissionV2 {
/// The level of access granted through the share link
#[serde(skip_serializing_if = "Option::is_none")]
pub link_share_access_level: Option<AccessLevel>,
+ /// The explicit access level granted to the owner's team, or `null` when disabled.
+ pub team_share_access_level: Option<AccessLevel>,
/// The owner of the item
pub owner: String,
/// The channel share permissions for the item
@@ -41,6 +44,7 @@ impl SharePermissionV2 {
id: String::new(),
link_share,
link_share_access_level,
+ team_share_access_level: None,
owner: String::new(),
channel_share_permissions: None,
}
@@ -121,6 +125,14 @@ pub struct UpdateSharePermissionRequestV2 {
skip_serializing_if = "Option::is_none"
)]
pub link_share_access_level: Option<Option<AccessLevel>>,
+ /// The explicit team access level. Omit to leave unchanged or pass `null` to disable team
+ /// sharing. Only the actual owner may change this setting; `owner` is not an allowed level.
+ #[serde(
+ default,
+ deserialize_with = "double_option",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub team_share_access_level: Option<Option<AccessLevel>>,
/// Any channel share permissions to be created/updated/removed
pub channel_share_permissions: Option<Vec<UpdateChannelSharePermission>>,
}
diff --git a/crates/models_permissions/src/share_permission/team_share.rs b/crates/models_permissions/src/share_permission/team_share.rs
new file mode 100644
index 0000000000..e8be9c52a5
--- /dev/null
+++ b/crates/models_permissions/src/share_permission/team_share.rs
@@ -0,0 +1,251 @@
+//! Transport-independent policy for explicit sharing with an entity owner's team.
+//!
+//! Entity services supply the verified acting identity and repository-derived facts.
+//! An authorized command is conditional, not a durable authorization token: adapters
+//! must reload and compare **all** expected facts under the shared transaction guard
+//! before changing canonical state or grants. These types are internal, not wire models.
+
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+use uuid::Uuid;
+
+use super::access_level::AccessLevel;
+
+#[cfg(test)]
+mod test;
+
+/// Access levels permitted for an explicit team grant; ownership cannot be granted.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TeamShareLevel {
+ /// Read access.
+ View,
+ /// Read and comment access.
+ Comment,
+ /// Read, comment, and edit access.
+ Edit,
+}
+
+impl TryFrom<AccessLevel> for TeamShareLevel {
+ type Error = TeamSharePolicyError;
+
+ fn try_from(value: AccessLevel) -> Result<Self, Self::Error> {
+ match value {
+ AccessLevel::View => Ok(Self::View),
+ AccessLevel::Comment => Ok(Self::Comment),
+ AccessLevel::Edit => Ok(Self::Edit),
+ AccessLevel::Owner => Err(TeamSharePolicyError::InvalidLevel),
+ }
+ }
+}
+
+impl From<TeamShareLevel> for AccessLevel {
+ fn from(value: TeamShareLevel) -> Self {
+ match value {
+ TeamShareLevel::View => Self::View,
+ TeamShareLevel::Comment => Self::Comment,
+ TeamShareLevel::Edit => Self::Edit,
+ }
+ }
+}
+
+/// A managed direct grant. Keeping team and level together prevents partial NULL state.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TeamShareGrant {
+ /// The team to which the canonical grant is attributed, even after owner departure.
+ pub team_id: Uuid,
+ /// The exact level, including any downgrade from an earlier grant.
+ pub level: TeamShareLevel,
+}
+
+/// Authoritative repository facts for one entity, never inferred from effective access.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TeamShareFacts {
+ /// The entity whose ownership and sharing state were loaded.
+ pub entity: Entity<'static>,
+ /// Persisted actual owner, not an actor with an effective Owner grant.
+ pub owner: MacroUserIdStr<'static>,
+ /// The actual owner's current team membership, if any.
+ pub owner_team_id: Option<Uuid>,
+ /// Canonical explicit state; inherited or unexplained grants must not populate this.
+ pub current: Option<TeamShareGrant>,
+ /// The persisted nonnegative team-share revision (zero for an uninitialized row).
+ pub revision: i64,
+}
+
+/// Inputs to normalize together before any writes, independent of REST or GraphQL.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+pub struct TeamShareRequest {
+ /// Omitted = preserve; explicit None = clear; explicit level = set exactly.
+ pub access_level: Option<Option<AccessLevel>>,
+ /// Optional compatibility toggle from an entity's legacy sharing API.
+ pub legacy_enabled: Option<bool>,
+}
+
+/// A supplied operation approved by actual-owner policy using a snapshot of facts.
+///
+/// Fields are private so callers cannot construct or modify an authorized edit.
+/// Persistence must recheck the entity, owner, membership, state, and revision under
+/// the guard and fail on stale facts. It must atomically update the canonical state,
+/// attributable grants, and revision, even for same-value updates and repeated clears.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct AuthorizedTeamShareCommand {
+ expected: TeamShareFacts,
+ target: Option<TeamShareGrant>,
+ next_revision: i64,
+}
+
+impl AuthorizedTeamShareCommand {
+ /// All facts the adapter must compare against a fresh guarded read.
+ pub fn expected(&self) -> &TeamShareFacts {
+ &self.expected
+ }
+
+ /// The desired explicit state. None clears only the previously managed grant.
+ pub fn target(&self) -> Option<TeamShareGrant> {
+ self.target
+ }
+
+ /// The revision to write atomically with this supplied operation.
+ pub fn next_revision(&self) -> i64 {
+ self.next_revision
+ }
+}
+
+/// Domain failures; transport adapters decide their HTTP/GraphQL representation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum TeamSharePolicyError {
+ /// The verified authorization context has no acting user identity.
+ #[error("team sharing requires an acting user")]
+ MissingActor,
+ /// Effective access cannot substitute for actual ownership.
+ #[error("only the actual owner may update team sharing")]
+ NotOwner,
+ /// Enabling requires the persisted owner's current team.
+ #[error("the owner has no team to share with")]
+ MissingTeam,
+ /// Owner is not a valid team-share level.
+ #[error("owner is not a permitted team-share level")]
+ InvalidLevel,
+ /// Explicit and legacy inputs disagree about whether sharing should be enabled.
+ #[error("legacy and explicit team-share inputs contradict each other")]
+ ContradictoryInputs,
+ /// Persisted revision is negative or cannot be incremented safely.
+ #[error("team-share revision is invalid or exhausted")]
+ InvalidRevision,
+}
+
+/// Authorize and normalize a user edit, returning None only when both inputs are omitted.
+///
+/// The entity service supplies `acting_user` from its verified receipt's
+/// `acting_user_id()`; it must not substitute the persisted owner for a missing actor.
+/// Omission deliberately skips owner/team checks and causes no revision or grant writes.
+/// Document legacy enable uses Edit; call legacy enable uses View. When both inputs
+/// are supplied, the explicit level wins if their enabled/disabled states agree.
+pub fn authorize_team_share(
+ acting_user: Option<&MacroUserIdStr<'_>>,
+ facts: &TeamShareFacts,
+ request: TeamShareRequest,
+ legacy_enable_default: TeamShareLevel,
+) -> Result<Option<AuthorizedTeamShareCommand>, TeamSharePolicyError> {
+ if request.access_level.is_none() && request.legacy_enabled.is_none() {
+ return Ok(None);
+ }
+
+ let actor = acting_user.ok_or(TeamSharePolicyError::MissingActor)?;
+ if actor != &facts.owner {
+ return Err(TeamSharePolicyError::NotOwner);
+ }
+
+ let level = match request.access_level {
+ Some(explicit) => {
+ let level = explicit.map(TeamShareLevel::try_from).transpose()?;
+ if let Some(enabled) = request.legacy_enabled
+ && enabled != level.is_some()
+ {
+ return Err(TeamSharePolicyError::ContradictoryInputs);
+ }
+ level
+ }
+ None => match request.legacy_enabled {
+ Some(true) => Some(
+ facts
+ .current
+ .map_or(legacy_enable_default, |grant| grant.level),
+ ),
+ Some(false) | None => None,
+ },
+ };
+
+ let target = level
+ .map(|level| {
+ let team_id = facts
+ .owner_team_id
+ .ok_or(TeamSharePolicyError::MissingTeam)?;
+ Ok(TeamShareGrant { team_id, level })
+ })
+ .transpose()?;
+ let next_revision = facts
+ .revision
+ .checked_add(1)
+ .filter(|_| facts.revision >= 0)
+ .ok_or(TeamSharePolicyError::InvalidRevision)?;
+
+ Ok(Some(AuthorizedTeamShareCommand {
+ expected: facts.clone(),
+ target,
+ next_revision,
+ }))
+}
+
+/// Internal creation intent, separate from editing an existing entity as an owner.
+///
+/// The creation repository resolves this using the persisted creator's membership
+/// under the guard and initializes permission state and grants in the same transaction.
+/// It must not accept a client-supplied team as authoritative or reuse source consent
+/// when copying. This intent must never be used to reshare an existing entity.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+pub enum TeamShareCreation {
+ /// Ordinary creation and copies initialize NULL explicit sharing.
+ #[default]
+ Unshared,
+ /// An explicitly shared task initializes Comment; missing membership is an error.
+ ExplicitTask,
+ /// A new call initializes View only if its creator currently belongs to a team.
+ Call,
+}
+
+impl TeamShareCreation {
+ /// Resolve initial state from authoritative membership within the creation transaction.
+ pub fn resolve(
+ self,
+ owner_team_id: Option<Uuid>,
+ ) -> Result<Option<TeamShareGrant>, TeamSharePolicyError> {
+ match self {
+ Self::Unshared => Ok(None),
+ Self::ExplicitTask => Ok(Some(TeamShareGrant {
+ team_id: owner_team_id.ok_or(TeamSharePolicyError::MissingTeam)?,
+ level: TeamShareLevel::Comment,
+ })),
+ Self::Call => Ok(owner_team_id.map(|team_id| TeamShareGrant {
+ team_id,
+ level: TeamShareLevel::View,
+ })),
+ }
+ }
+}
+
+/// Trusted lifecycle intent, not authenticated user authority and not a public input.
+///
+/// The lifecycle service establishes why cleanup is required (owner departure, team
+/// deletion, or ownership transfer). Persistence rechecks the expected facts under
+/// the guard, clears only attributable grants, and increments the revision atomically.
+/// No acting identity or current membership is required. Compensation/restoration
+/// needs its own guarded snapshot eligibility check, not an authorized user edit.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum TeamShareMaintenance {
+ /// Clear canonical consent and its managed grant, including after membership is gone.
+ Clear {
+ /// Snapshot to compare before cleanup, retaining historical team attribution.
+ expected: TeamShareFacts,
+ },
+}
diff --git a/crates/models_permissions/src/share_permission/team_share/test.rs b/crates/models_permissions/src/share_permission/team_share/test.rs
new file mode 100644
index 0000000000..f9bcf54549
--- /dev/null
+++ b/crates/models_permissions/src/share_permission/team_share/test.rs
@@ -0,0 +1,305 @@
+use super::*;
+use model_entity::EntityType;
+
+fn owner() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
+}
+
+fn facts() -> TeamShareFacts {
+ TeamShareFacts {
+ entity: EntityType::Document.with_entity_string("document-id".to_string()),
+ owner: owner(),
+ owner_team_id: Some(Uuid::from_u128(1)),
+ current: None,
+ revision: 7,
+ }
+}
+
+fn request(level: Option<AccessLevel>) -> TeamShareRequest {
+ TeamShareRequest {
+ access_level: Some(level),
+ legacy_enabled: None,
+ }
+}
+
+fn authorize(
+ facts: &TeamShareFacts,
+ request: TeamShareRequest,
+) -> Result<Option<AuthorizedTeamShareCommand>, TeamSharePolicyError> {
+ authorize_team_share(Some(&owner()), facts, request, TeamShareLevel::Edit)
+}
+
+#[test]
+fn omission_is_a_no_op_without_an_actor_or_team() {
+ let mut facts = facts();
+ let team_id = facts.owner_team_id.take().unwrap();
+ for current in [
+ None,
+ Some(TeamShareGrant {
+ team_id,
+ level: TeamShareLevel::Comment,
+ }),
+ ] {
+ facts.current = current;
+ assert_eq!(
+ authorize_team_share(
+ None,
+ &facts,
+ TeamShareRequest::default(),
+ TeamShareLevel::Edit
+ ),
+ Ok(None)
+ );
+ }
+}
+
+#[test]
+fn every_supplied_operation_requires_the_actual_owner() {
+ let mut facts = facts();
+ facts.current = Some(TeamShareGrant {
+ team_id: facts.owner_team_id.unwrap(),
+ level: TeamShareLevel::View,
+ });
+ let other = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ for request in [
+ request(Some(AccessLevel::View)),
+ request(Some(AccessLevel::Edit)),
+ request(None),
+ TeamShareRequest {
+ access_level: None,
+ legacy_enabled: Some(true),
+ },
+ TeamShareRequest {
+ access_level: None,
+ legacy_enabled: Some(false),
+ },
+ ] {
+ assert_eq!(
+ authorize_team_share(None, &facts, request, TeamShareLevel::Edit),
+ Err(TeamSharePolicyError::MissingActor)
+ );
+ assert_eq!(
+ authorize_team_share(Some(&other), &facts, request, TeamShareLevel::Edit),
+ Err(TeamSharePolicyError::NotOwner)
+ );
+ assert!(authorize(&facts, request).unwrap().is_some());
+ }
+}
+
+#[test]
+fn repeated_clear_without_a_team_still_requires_the_owner() {
+ let mut facts = facts();
+ facts.owner_team_id = None;
+ let other = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ for request in [
+ request(None),
+ TeamShareRequest {
+ access_level: None,
+ legacy_enabled: Some(false),
+ },
+ ] {
+ assert_eq!(
+ authorize_team_share(None, &facts, request, TeamShareLevel::Edit),
+ Err(TeamSharePolicyError::MissingActor)
+ );
+ assert_eq!(
+ authorize_team_share(Some(&other), &facts, request, TeamShareLevel::Edit),
+ Err(TeamSharePolicyError::NotOwner)
+ );
+ let command = authorize(&facts, request).unwrap().unwrap();
+ assert_eq!(command.target(), None);
+ assert_eq!(command.next_revision(), facts.revision + 1);
+ }
+}
+
+#[test]
+fn allowed_levels_are_exact_and_commands_capture_all_expected_facts() {
+ let facts = facts();
+ for level in [AccessLevel::View, AccessLevel::Comment, AccessLevel::Edit] {
+ let command = authorize(&facts, request(Some(level))).unwrap().unwrap();
+ assert_eq!(command.expected(), &facts);
+ assert_eq!(
+ command.target(),
+ Some(TeamShareGrant {
+ team_id: facts.owner_team_id.unwrap(),
+ level: TeamShareLevel::try_from(level).unwrap(),
+ })
+ );
+ assert_eq!(command.next_revision(), 8);
+ }
+}
+
+#[test]
+fn same_value_and_repeated_clears_still_produce_revisioned_commands() {
+ let mut facts = facts();
+ for level in [None, Some(AccessLevel::View)] {
+ facts.current = level.map(|level| TeamShareGrant {
+ team_id: facts.owner_team_id.unwrap(),
+ level: TeamShareLevel::try_from(level).unwrap(),
+ });
+ let command = authorize(&facts, request(level)).unwrap().unwrap();
+ assert_eq!(command.target(), facts.current);
+ assert_eq!(command.next_revision(), facts.revision + 1);
+ }
+}
+
+#[test]
+fn enable_requires_a_team_but_clear_retains_historical_attribution() {
+ let mut facts = facts();
+ facts.current = Some(TeamShareGrant {
+ team_id: facts.owner_team_id.take().unwrap(),
+ level: TeamShareLevel::Comment,
+ });
+ for request in [
+ request(Some(AccessLevel::View)),
+ TeamShareRequest {
+ access_level: None,
+ legacy_enabled: Some(true),
+ },
+ ] {
+ assert_eq!(
+ authorize(&facts, request),
+ Err(TeamSharePolicyError::MissingTeam)
+ );
+ }
+ for request in [
+ request(None),
+ TeamShareRequest {
+ access_level: None,
+ legacy_enabled: Some(false),
+ },
+ ] {
+ let command = authorize(&facts, request).unwrap().unwrap();
+ assert_eq!(command.target(), None);
+ assert_eq!(command.expected(), &facts);
+ }
+}
+
+#[test]
+fn owner_level_is_rejected_even_with_a_legacy_toggle() {
+ for legacy_enabled in [None, Some(true), Some(false)] {
+ assert_eq!(
+ authorize(
+ &facts(),
+ TeamShareRequest {
+ access_level: Some(Some(AccessLevel::Owner)),
+ legacy_enabled,
+ }
+ ),
+ Err(TeamSharePolicyError::InvalidLevel)
+ );
+ }
+ assert_eq!(
+ TeamShareLevel::try_from(AccessLevel::Owner),
+ Err(TeamSharePolicyError::InvalidLevel)
+ );
+}
+
+#[test]
+fn legacy_enable_uses_entity_default_only_when_unshared() {
+ let mut facts = facts();
+ let request = TeamShareRequest {
+ access_level: None,
+ legacy_enabled: Some(true),
+ };
+ for default in [TeamShareLevel::Edit, TeamShareLevel::View] {
+ let command = authorize_team_share(Some(&owner()), &facts, request, default)
+ .unwrap()
+ .unwrap();
+ assert_eq!(command.target().unwrap().level, default);
+ }
+ for level in [
+ TeamShareLevel::View,
+ TeamShareLevel::Comment,
+ TeamShareLevel::Edit,
+ ] {
+ facts.current = Some(TeamShareGrant {
+ team_id: facts.owner_team_id.unwrap(),
+ level,
+ });
+ let command = authorize(&facts, request).unwrap().unwrap();
+ assert_eq!(command.target(), facts.current);
+ assert_eq!(command.next_revision(), facts.revision + 1);
+ }
+}
+
+#[test]
+fn legacy_and_explicit_inputs_must_agree_on_enabled_state_not_default_level() {
+ let facts = facts();
+ for level in [
+ None,
+ Some(AccessLevel::View),
+ Some(AccessLevel::Comment),
+ Some(AccessLevel::Edit),
+ ] {
+ for enabled in [false, true] {
+ let result = authorize(
+ &facts,
+ TeamShareRequest {
+ access_level: Some(level),
+ legacy_enabled: Some(enabled),
+ },
+ );
+ if enabled == level.is_some() {
+ let target = result.unwrap().unwrap().target();
+ assert_eq!(target.map(|grant| AccessLevel::from(grant.level)), level);
+ } else {
+ assert_eq!(result, Err(TeamSharePolicyError::ContradictoryInputs));
+ }
+ }
+ }
+}
+
+#[test]
+fn invalid_or_exhausted_revisions_cannot_produce_commands() {
+ let mut facts = facts();
+ for revision in [-1, i64::MAX] {
+ facts.revision = revision;
+ assert_eq!(
+ authorize(&facts, request(None)),
+ Err(TeamSharePolicyError::InvalidRevision)
+ );
+ }
+}
+
+#[test]
+fn creation_contract_distinguishes_ordinary_task_and_call_defaults() {
+ let team_id = Uuid::from_u128(1);
+ for team in [None, Some(team_id)] {
+ assert_eq!(TeamShareCreation::Unshared.resolve(team), Ok(None));
+ assert_eq!(
+ TeamShareCreation::Call.resolve(team),
+ Ok(team.map(|team_id| TeamShareGrant {
+ team_id,
+ level: TeamShareLevel::View,
+ }))
+ );
+ }
+ assert_eq!(
+ TeamShareCreation::ExplicitTask.resolve(None),
+ Err(TeamSharePolicyError::MissingTeam)
+ );
+ assert_eq!(
+ TeamShareCreation::ExplicitTask.resolve(Some(team_id)),
+ Ok(Some(TeamShareGrant {
+ team_id,
+ level: TeamShareLevel::Comment,
+ }))
+ );
+}
+
+#[test]
+fn lifecycle_clear_needs_no_actor_or_current_membership() {
+ let mut facts = facts();
+ facts.current = Some(TeamShareGrant {
+ team_id: facts.owner_team_id.take().unwrap(),
+ level: TeamShareLevel::Edit,
+ });
+ let maintenance = TeamShareMaintenance::Clear {
+ expected: facts.clone(),
+ };
+ let TeamShareMaintenance::Clear { expected } = maintenance;
+ assert_eq!(expected, facts);
+ assert!(expected.current.is_some());
+ assert!(expected.owner_team_id.is_none());
+}
diff --git a/crates/models_permissions/src/share_permission/test.rs b/crates/models_permissions/src/share_permission/test.rs
index 90fa43b47e..e179eb3b5d 100644
--- a/crates/models_permissions/src/share_permission/test.rs
+++ b/crates/models_permissions/src/share_permission/test.rs
@@ -14,6 +14,7 @@ fn share(
id: String::new(),
link_share,
link_share_access_level,
+ team_share_access_level: None,
owner: String::new(),
channel_share_permissions: None,
}
@@ -129,6 +130,7 @@ fn resolved_permissions_never_have_a_level_without_a_scope() {
SharePermissionV2::new_chat_share_permission(team_default),
SharePermissionV2::new_project_share_permission(team_default),
] {
+ assert_eq!(permission.team_share_access_level, None);
if permission.link_share.is_none() {
assert_eq!(permission.link_share_access_level, None);
} else {
@@ -143,16 +145,78 @@ fn update_request_round_trip_preserves_omitted_fields() {
let request = UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: None,
+ team_share_access_level: None,
channel_share_permissions: None,
};
let serialized = serde_json::to_value(&request).unwrap();
assert!(serialized.get("linkShare").is_none());
assert!(serialized.get("linkShareAccessLevel").is_none());
+ assert!(serialized.get("teamShareAccessLevel").is_none());
let deserialized: UpdateSharePermissionRequestV2 = serde_json::from_value(serialized).unwrap();
assert_eq!(deserialized.link_share, None);
assert_eq!(deserialized.link_share_access_level, None);
+ assert_eq!(deserialized.team_share_access_level, None);
+}
+
+#[test]
+fn team_share_update_round_trip_preserves_null_and_levels() {
+ for (value, level) in [
+ (json!(null), None),
+ (json!("view"), Some(AccessLevel::View)),
+ (json!("comment"), Some(AccessLevel::Comment)),
+ (json!("edit"), Some(AccessLevel::Edit)),
+ ] {
+ let request: UpdateSharePermissionRequestV2 = serde_json::from_value(json!({
+ "teamShareAccessLevel": value,
+ }))
+ .unwrap();
+ assert_eq!(request.team_share_access_level, Some(level));
+ assert_eq!(
+ serde_json::to_value(&request).unwrap()["teamShareAccessLevel"],
+ value
+ );
+ assert_eq!(request.link_share, None);
+ assert_eq!(request.link_share_access_level, None);
+ }
+}
+
+#[test]
+fn team_share_read_serializes_null_and_levels_without_internal_state() {
+ for level in [
+ None,
+ Some(AccessLevel::View),
+ Some(AccessLevel::Comment),
+ Some(AccessLevel::Edit),
+ ] {
+ let mut permission = share(None, None);
+ permission.team_share_access_level = level;
+ let serialized = serde_json::to_value(&permission).unwrap();
+ assert_eq!(serialized.get("teamShareAccessLevel"), Some(&json!(level)));
+ assert!(serialized.get("teamShareTeamId").is_none());
+ assert!(serialized.get("teamShareRevision").is_none());
+ assert_eq!(
+ serde_json::from_value::<SharePermissionV2>(serialized).unwrap(),
+ permission
+ );
+ }
+}
+
+#[test]
+fn permission_schemas_expose_only_the_public_team_level() {
+ use utoipa::PartialSchema;
+
+ for schema in [
+ SharePermissionV2::schema(),
+ UpdateSharePermissionRequestV2::schema(),
+ ] {
+ let schema = serde_json::to_value(schema).unwrap();
+ let properties = schema["properties"].as_object().unwrap();
+ assert!(properties.contains_key("teamShareAccessLevel"));
+ assert!(!properties.contains_key("teamShareTeamId"));
+ assert!(!properties.contains_key("teamShareRevision"));
+ }
}
#[test]
@@ -160,6 +224,7 @@ fn update_request_distinguishes_omitted_null_and_present_values() {
let omitted: UpdateSharePermissionRequestV2 = serde_json::from_value(json!({})).unwrap();
assert_eq!(omitted.link_share, None);
assert_eq!(omitted.link_share_access_level, None);
+ assert_eq!(omitted.team_share_access_level, None);
let cleared: UpdateSharePermissionRequestV2 = serde_json::from_value(json!({
"linkShare": null,
diff --git a/crates/projects/src/domain/service/tests.rs b/crates/projects/src/domain/service/tests.rs
index b0bcd48626..4e291b99bc 100644
--- a/crates/projects/src/domain/service/tests.rs
+++ b/crates/projects/src/domain/service/tests.rs
@@ -499,6 +499,7 @@ fn share_update() -> UpdateSharePermissionRequestV2 {
UpdateSharePermissionRequestV2 {
link_share: Some(Some(LinkShare::Public)),
link_share_access_level: Some(Some(AccessLevel::View)),
+ team_share_access_level: None,
channel_share_permissions: None,
}
}
diff --git a/crates/projects/src/outbound/pg_project_repo/share.rs b/crates/projects/src/outbound/pg_project_repo/share.rs
index 997c9f9713..e6ed42899d 100644
--- a/crates/projects/src/outbound/pg_project_repo/share.rs
+++ b/crates/projects/src/outbound/pg_project_repo/share.rs
@@ -73,6 +73,7 @@ pub(super) async fn get_project_share_permission(
id: row.id,
link_share,
link_share_access_level: row.link_share_access_level,
+ team_share_access_level: None,
owner: row.owner,
channel_share_permissions,
})
diff --git a/crates/projects/src/outbound/pg_project_repo/tests.rs b/crates/projects/src/outbound/pg_project_repo/tests.rs
index 0978c74d42..af7062eced 100644
--- a/crates/projects/src/outbound/pg_project_repo/tests.rs
+++ b/crates/projects/src/outbound/pg_project_repo/tests.rs
@@ -330,6 +330,7 @@ async fn edit_supports_parent_flags_and_sharing(pool: Pool<Postgres>) -> anyhow:
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: Some(Some(LinkShare::Team)),
link_share_access_level: Some(None),
+ team_share_access_level: None,
channel_share_permissions: None,
}),
})
@@ -351,6 +352,7 @@ async fn edit_supports_parent_flags_and_sharing(pool: Pool<Postgres>) -> anyhow:
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: Some(Some(AccessLevel::Comment)),
+ team_share_access_level: None,
channel_share_permissions: None,
}),
})
@@ -371,6 +373,7 @@ async fn edit_supports_parent_flags_and_sharing(pool: Pool<Postgres>) -> anyhow:
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: Some(Some(LinkShare::Public)),
link_share_access_level: Some(Some(AccessLevel::Edit)),
+ team_share_access_level: None,
channel_share_permissions: None,
}),
})
@@ -392,6 +395,7 @@ async fn edit_supports_parent_flags_and_sharing(pool: Pool<Postgres>) -> anyhow:
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: None,
+ team_share_access_level: None,
channel_share_permissions: None,
}),
})
@@ -409,6 +413,7 @@ async fn edit_supports_parent_flags_and_sharing(pool: Pool<Postgres>) -> anyhow:
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: Some(None),
link_share_access_level: Some(Some(AccessLevel::Edit)),
+ team_share_access_level: None,
channel_share_permissions: None,
}),
})
diff --git a/crates/share_permission_db_utils/Cargo.toml b/crates/share_permission_db_utils/Cargo.toml
index 4512e89878..a516eab226 100644
--- a/crates/share_permission_db_utils/Cargo.toml
+++ b/crates/share_permission_db_utils/Cargo.toml
@@ -9,8 +9,11 @@ anyhow = { workspace = true }
entity_access_db_utils = { path = "../entity_access_db_utils" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
+model-entity = { path = "../model-entity" }
models_permissions = { path = "../models_permissions" }
+rootcause = { workspace = true }
sqlx = { workspace = true }
+thiserror = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
diff --git a/crates/share_permission_db_utils/fixtures/team_share.sql b/crates/share_permission_db_utils/fixtures/team_share.sql
new file mode 100644
index 0000000000..46e7ecef96
--- /dev/null
+++ b/crates/share_permission_db_utils/fixtures/team_share.sql
@@ -0,0 +1,30 @@
+INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES
+ ('50000000-0000-0000-0000-000000000001', '[email protected]', '[email protected]', 'cus_owner'),
+ ('50000000-0000-0000-0000-000000000002', '[email protected]', '[email protected]', 'cus_other');
+INSERT INTO "User" (id, email, name, macro_user_id) VALUES
+ ('macro|[email protected]', '[email protected]', 'Owner', '50000000-0000-0000-0000-000000000001'),
+ ('macro|[email protected]', '[email protected]', 'Other', '50000000-0000-0000-0000-000000000002');
+INSERT INTO team (id, name, owner_id, seat_count) VALUES
+ ('10000000-0000-0000-0000-000000000001', 'Team', 'macro|[email protected]', 2);
+INSERT INTO team_user (team_id, user_id, team_role) VALUES
+ ('10000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'owner');
+INSERT INTO "Project" (id, name, "userId") VALUES
+ ('20000000-0000-0000-0000-000000000001', 'Root', 'macro|[email protected]');
+INSERT INTO "Document" (id, name, owner) VALUES
+ ('20000000-0000-0000-0000-000000000002', 'Document', 'macro|[email protected]');
+INSERT INTO "Chat" (id, name, "userId") VALUES
+ ('20000000-0000-0000-0000-000000000003', 'Chat', 'macro|[email protected]');
+INSERT INTO "SharePermission" (id) VALUES ('project'), ('document'), ('chat'), ('active-call'), ('archived-call');
+INSERT INTO "ProjectPermission" ("projectId", "sharePermissionId") VALUES ('20000000-0000-0000-0000-000000000001', 'project');
+INSERT INTO "DocumentPermission" ("documentId", "sharePermissionId") VALUES ('20000000-0000-0000-0000-000000000002', 'document');
+INSERT INTO "ChatPermission" ("chatId", "sharePermissionId") VALUES ('20000000-0000-0000-0000-000000000003', 'chat');
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider) VALUES
+ ('30000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'fusionauth', '[email protected]', 'GMAIL');
+INSERT INTO email_threads (id, link_id) VALUES
+ ('20000000-0000-0000-0000-000000000004', '30000000-0000-0000-0000-000000000001');
+INSERT INTO comms_channels (id, name, channel_type, owner_id) VALUES
+ ('40000000-0000-0000-0000-000000000001', 'Calls', 'private', 'macro|[email protected]');
+INSERT INTO calls (id, channel_id, room_name, created_by, share_permission_id) VALUES
+ ('20000000-0000-0000-0000-000000000005', '40000000-0000-0000-0000-000000000001', 'active', 'macro|[email protected]', 'active-call');
+INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, duration_ms, share_permission_id) VALUES
+ ('20000000-0000-0000-0000-000000000006', '40000000-0000-0000-0000-000000000001', 'archived', 'macro|[email protected]', now(), 0, 'archived-call');
diff --git a/crates/share_permission_db_utils/src/lib.rs b/crates/share_permission_db_utils/src/lib.rs
index 0ef8e484fd..e9b4b69c98 100644
--- a/crates/share_permission_db_utils/src/lib.rs
+++ b/crates/share_permission_db_utils/src/lib.rs
@@ -1,5 +1,7 @@
//! Small SQL helpers for `SharePermission` and `ChannelSharePermission` rows.
+pub mod team_share;
+
use anyhow::Context;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use models_permissions::share_permission::access_level::AccessLevel;
diff --git a/crates/share_permission_db_utils/src/team_share.rs b/crates/share_permission_db_utils/src/team_share.rs
new file mode 100644
index 0000000000..9a6e12bc0a
--- /dev/null
+++ b/crates/share_permission_db_utils/src/team_share.rs
@@ -0,0 +1,429 @@
+//! Transaction-aware canonical explicit team sharing.
+//!
+//! Acquire [`acquire_guard`] before accompanying metadata/ownership/topology writes.
+//! All public operations acquire it again (transaction advisory locks are reentrant),
+//! read fresh authoritative facts, and never commit the caller's transaction. On any
+//! error the caller must roll back the whole transaction, including metadata changes.
+//! Ordinary reads may use a short transaction and [`load_facts`] before domain policy.
+
+pub use entity_access_db_utils::team_share::acquire_guard;
+use entity_access_db_utils::team_share::{delete_direct, direct_level, upsert_direct};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use macro_uuid::Uuid;
+use model_entity::{Entity, EntityType};
+use models_permissions::share_permission::{
+ access_level::AccessLevel,
+ team_share::{
+ AuthorizedTeamShareCommand, TeamShareCreation, TeamShareFacts, TeamShareGrant,
+ TeamShareLevel, TeamShareMaintenance,
+ },
+};
+use rootcause::prelude::*;
+use sqlx::{PgConnection, Postgres, Transaction};
+
+#[cfg(test)]
+mod test;
+
+/// Conditional-write failures remain distinguishable from database/reporting failures.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum TeamShareError {
+ /// No authoritative entity exists (permission associations alone are insufficient).
+ #[error("team-share entity not found")]
+ NotFound,
+ /// Domain-authorized ownership, membership, or canonical state changed.
+ #[error("team-share facts changed")]
+ ChangedFacts,
+ /// A normal mutation would overwrite an unexplained direct grant.
+ #[error("untracked direct team grant conflicts with team sharing")]
+ UntrackedGrant,
+ /// Reconciliation requires a matching reviewed direct grant and owner team.
+ #[error("team-share adoption candidate no longer matches")]
+ InvalidAdoption,
+ /// The entity kind or identifier is unsupported.
+ #[error("invalid team-share entity")]
+ InvalidEntity,
+ /// Stored permission state is incomplete/invalid, or its revision is exhausted.
+ #[error("invalid canonical team-share state")]
+ InvalidState,
+ /// Database or persisted-identity parsing failure; the report retains the cause.
+ #[error("team-share persistence failed")]
+ Infrastructure,
+}
+
+/// Typed report returned by canonical persistence operations.
+pub type TeamShareResult<T> = Result<T, Report<TeamShareError>>;
+
+/// Historical canonical consent for later conditional lifecycle compensation.
+/// `revision` is the pre-cleanup revision; a successful clear writes revision + 1.
+/// Restoration must check that revision, NULL state, owner eligibility and current
+/// topology under the guard; this snapshot alone is not permission to restore.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TeamShareCleanupSnapshot {
+ /// Explicit sharing root, not a descendant receiving inherited access.
+ pub root: Entity<'static>,
+ /// Actual owner at snapshot time, for ownership-change eligibility checks.
+ pub owner: MacroUserIdStr<'static>,
+ /// Historical managed team, retained after membership removal.
+ pub managed_team_id: Uuid,
+ /// Exact historical level.
+ pub level: TeamShareLevel,
+ /// Revision before cleanup.
+ pub revision: i64,
+}
+
+/// Capture only canonical consent, never infer it from direct or inherited grants.
+pub fn cleanup_snapshot(facts: &TeamShareFacts) -> Option<TeamShareCleanupSnapshot> {
+ facts.current.map(|grant| TeamShareCleanupSnapshot {
+ root: facts.entity.clone(),
+ owner: facts.owner.clone(),
+ managed_team_id: grant.team_id,
+ level: grant.level,
+ revision: facts.revision,
+ })
+}
+
+struct State {
+ facts: TeamShareFacts,
+ permission_id: Option<String>,
+}
+
+fn entity_uuid(entity: &Entity<'_>) -> TeamShareResult<Uuid> {
+ if !matches!(
+ entity.entity_type,
+ EntityType::Document
+ | EntityType::Project
+ | EntityType::Chat
+ | EntityType::EmailThread
+ | EntityType::Call
+ ) {
+ return Err(report!(TeamShareError::InvalidEntity));
+ }
+ Uuid::parse_str(&entity.entity_id).context(TeamShareError::InvalidEntity)
+}
+
+/// Load actual owner, current membership and canonical state under the shared guard.
+/// Threads without permissions read as NULL/revision zero without creating any rows.
+/// Tasks and snippets use Document, and active calls take precedence during archive.
+pub async fn load_facts(
+ transaction: &mut Transaction<'_, Postgres>,
+ entity: &Entity<'_>,
+) -> TeamShareResult<TeamShareFacts> {
+ acquire_guard(transaction)
+ .await
+ .context(TeamShareError::Infrastructure)?;
+ Ok(load_state(transaction.as_mut(), entity).await?.facts)
+}
+
+async fn load_state(connection: &mut PgConnection, entity: &Entity<'_>) -> TeamShareResult<State> {
+ let uuid = entity_uuid(entity)?;
+ let row = sqlx::query!(
+ r#"WITH entity AS (
+ SELECT d.owner, dp."sharePermissionId" AS permission_id
+ FROM "Document" d LEFT JOIN "DocumentPermission" dp ON dp."documentId" = d.id
+ WHERE $2 = 'document' AND d.id = $1
+ UNION ALL
+ SELECT p."userId", pp."sharePermissionId"
+ FROM "Project" p LEFT JOIN "ProjectPermission" pp ON pp."projectId" = p.id
+ WHERE $2 = 'project' AND p.id = $1
+ UNION ALL
+ SELECT c."userId", cp."sharePermissionId"
+ FROM "Chat" c LEFT JOIN "ChatPermission" cp ON cp."chatId" = c.id
+ WHERE $2 = 'chat' AND c.id = $1
+ UNION ALL
+ SELECT l.macro_id, tp."sharePermissionId"
+ FROM email_threads t JOIN email_links l ON l.id = t.link_id
+ LEFT JOIN "EmailThreadPermission" tp ON tp."threadId" = t.id::text
+ WHERE $2 = 'email_thread' AND t.id = $3
+ UNION ALL
+ SELECT c.created_by, c.share_permission_id FROM calls c
+ WHERE $2 = 'call' AND c.id = $3
+ UNION ALL
+ SELECT c.created_by, c.share_permission_id FROM call_records c
+ WHERE $2 = 'call' AND c.id = $3 AND NOT EXISTS (SELECT 1 FROM calls WHERE id = $3)
+ )
+ SELECT e.owner AS "owner!", e.permission_id,
+ sp.id AS "stored_permission_id?",
+ sp.team_share_access_level AS "level: AccessLevel",
+ sp.team_share_team_id AS team_id, sp.team_share_revision AS "revision?",
+ (SELECT tu.team_id FROM team_user tu WHERE tu.user_id = e.owner
+ ORDER BY tu.team_role DESC LIMIT 1) AS owner_team_id
+ FROM entity e LEFT JOIN "SharePermission" sp ON sp.id = e.permission_id"#,
+ entity.entity_id.as_ref(),
+ entity.entity_type.as_ref(),
+ uuid,
+ )
+ .fetch_optional(connection)
+ .await
+ .context(TeamShareError::Infrastructure)?
+ .ok_or_else(|| report!(TeamShareError::NotFound))?;
+
+ if row.stored_permission_id.is_none()
+ && (row.permission_id.is_some() || entity.entity_type != EntityType::EmailThread)
+ {
+ return Err(report!(TeamShareError::InvalidState));
+ }
+ let current = match (row.level, row.team_id) {
+ (Some(level), Some(team_id)) => Some(TeamShareGrant {
+ team_id,
+ level: TeamShareLevel::try_from(level).context(TeamShareError::InvalidState)?,
+ }),
+ (None, None) => None,
+ _ => return Err(report!(TeamShareError::InvalidState)),
+ };
+ let revision = row.revision.unwrap_or(0);
+ if revision < 0 {
+ return Err(report!(TeamShareError::InvalidState));
+ }
+ Ok(State {
+ facts: TeamShareFacts {
+ entity: entity.clone().into_owned(),
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .context(TeamShareError::Infrastructure)?
+ .into_owned(),
+ owner_team_id: row.owner_team_id,
+ current,
+ revision,
+ },
+ permission_id: row.permission_id,
+ })
+}
+
+async fn recheck(
+ transaction: &mut Transaction<'_, Postgres>,
+ expected: &TeamShareFacts,
+) -> TeamShareResult<State> {
+ acquire_guard(transaction)
+ .await
+ .context(TeamShareError::Infrastructure)?;
+ let state = load_state(transaction.as_mut(), &expected.entity).await?;
+ if state.facts != *expected {
+ return Err(report!(TeamShareError::ChangedFacts));
+ }
+ Ok(state)
+}
+
+/// Apply an actual-owner-authorized supplied operation. Omission has no command and
+/// must not call this function. Even same-value sets and repeated clears advance revision.
+pub async fn apply(
+ transaction: &mut Transaction<'_, Postgres>,
+ command: &AuthorizedTeamShareCommand,
+) -> TeamShareResult<()> {
+ let state = recheck(transaction, command.expected()).await?;
+ reject_untracked(transaction.as_mut(), &state.facts, command.target()).await?;
+ write_state(
+ transaction,
+ state,
+ command.target(),
+ command.next_revision(),
+ )
+ .await
+}
+
+async fn reject_untracked(
+ connection: &mut PgConnection,
+ facts: &TeamShareFacts,
+ target: Option<TeamShareGrant>,
+) -> TeamShareResult<()> {
+ let Some(target) = target else {
+ return Ok(());
+ };
+ if facts.current.map(|g| g.team_id) == Some(target.team_id) {
+ return Ok(());
+ }
+ let existing = direct_level(
+ connection,
+ &entity_uuid(&facts.entity)?,
+ facts.entity.entity_type,
+ target.team_id,
+ )
+ .await
+ .context(TeamShareError::Infrastructure)?;
+ if existing.is_some() {
+ return Err(report!(TeamShareError::UntrackedGrant));
+ }
+ Ok(())
+}
+
+fn next_revision(facts: &TeamShareFacts) -> TeamShareResult<i64> {
+ facts
+ .revision
+ .checked_add(1)
+ .ok_or_else(|| report!(TeamShareError::InvalidState))
+}
+
+/// Clear by trusted lifecycle intent, without requiring an acting user or current
+/// membership. Compare freshly loaded facts and retain the historical team attribution.
+pub async fn maintain(
+ transaction: &mut Transaction<'_, Postgres>,
+ intent: &TeamShareMaintenance,
+) -> TeamShareResult<()> {
+ match intent {
+ TeamShareMaintenance::Clear { expected } => {
+ let state = recheck(transaction, expected).await?;
+ let revision = next_revision(&state.facts)?;
+ write_state(transaction, state, None, revision).await
+ }
+ }
+}
+
+/// Conditionally restore lifecycle-cleared consent after membership compensation.
+/// This is not a user-authorized edit: the historical owner/team and the exact cleared
+/// revision must still match. Deleted roots and intervening explicit operations are
+/// ineligible. Project contributions are rebuilt from the current tree by `write_state`.
+/// Returns false for an ineligible snapshot, without changing any state.
+pub async fn restore_cleared(
+ transaction: &mut Transaction<'_, Postgres>,
+ previous: &TeamShareFacts,
+ cleared_revision: i64,
+) -> TeamShareResult<bool> {
+ acquire_guard(transaction)
+ .await
+ .context(TeamShareError::Infrastructure)?;
+ let Some(grant) = previous.current else {
+ return Ok(false);
+ };
+ if previous.revision.checked_add(1) != Some(cleared_revision) {
+ return Ok(false);
+ }
+ let state = match load_state(transaction.as_mut(), &previous.entity).await {
+ Ok(state) => state,
+ Err(error) if *error.current_context() == TeamShareError::NotFound => return Ok(false),
+ Err(error) => return Err(error),
+ };
+ if state.facts.owner != previous.owner
+ || state.facts.owner_team_id != Some(grant.team_id)
+ || state.facts.current.is_some()
+ || state.facts.revision != cleared_revision
+ {
+ return Ok(false);
+ }
+ let deleted = sqlx::query_scalar!(
+ r#"SELECT EXISTS (
+ SELECT 1 FROM "Document" WHERE $2 = 'document' AND id = $1 AND "deletedAt" IS NOT NULL
+ UNION ALL
+ SELECT 1 FROM "Project" WHERE $2 = 'project' AND id = $1 AND "deletedAt" IS NOT NULL
+ UNION ALL
+ SELECT 1 FROM "Chat" WHERE $2 = 'chat' AND id = $1 AND "deletedAt" IS NOT NULL
+ ) AS "deleted!""#,
+ previous.entity.entity_id.as_ref(),
+ previous.entity.entity_type.as_ref(),
+ )
+ .fetch_one(transaction.as_mut())
+ .await
+ .context(TeamShareError::Infrastructure)?;
+ if deleted {
+ return Ok(false);
+ }
+ match reject_untracked(transaction.as_mut(), &state.facts, Some(grant)).await {
+ Ok(()) => {}
+ Err(error) if *error.current_context() == TeamShareError::UntrackedGrant => {
+ return Ok(false);
+ }
+ Err(error) => return Err(error),
+ }
+ let revision = next_revision(&state.facts)?;
+ write_state(transaction, state, Some(grant), revision).await?;
+ Ok(true)
+}
+
+/// Initialize a newly inserted entity in the caller's guarded creation transaction.
+/// Never use this for existing entities or copies with inherited source consent.
+/// Unshared creation does not advance revision; explicit task/call consent does.
+pub async fn initialize(
+ transaction: &mut Transaction<'_, Postgres>,
+ entity: &Entity<'_>,
+ intent: TeamShareCreation,
+) -> TeamShareResult<()> {
+ acquire_guard(transaction)
+ .await
+ .context(TeamShareError::Infrastructure)?;
+ let state = load_state(transaction.as_mut(), entity).await?;
+ if state.facts.current.is_some() || state.facts.revision != 0 {
+ return Err(report!(TeamShareError::ChangedFacts));
+ }
+ let target = intent
+ .resolve(state.facts.owner_team_id)
+ .context(TeamShareError::InvalidState)?;
+ if target.is_none() {
+ return Ok(());
+ }
+ reject_untracked(transaction.as_mut(), &state.facts, target).await?;
+ write_state(transaction, state, target, 1).await
+}
+
+/// Explicit reconciliation-only adoption of a reviewed historical direct grant.
+/// Normal writes never adopt unknown rows. Both canonical facts and the exact
+/// candidate level/team are rechecked; inherited rows cannot qualify for adoption.
+pub async fn adopt(
+ transaction: &mut Transaction<'_, Postgres>,
+ expected: &TeamShareFacts,
+ reviewed: TeamShareGrant,
+) -> TeamShareResult<()> {
+ let state = recheck(transaction, expected).await?;
+ if state.facts.current.is_some() || state.facts.owner_team_id != Some(reviewed.team_id) {
+ return Err(report!(TeamShareError::InvalidAdoption));
+ }
+ let existing = direct_level(
+ transaction.as_mut(),
+ &entity_uuid(&expected.entity)?,
+ expected.entity.entity_type,
+ reviewed.team_id,
+ )
+ .await
+ .context(TeamShareError::Infrastructure)?;
+ if existing != Some(reviewed.level.into()) {
+ return Err(report!(TeamShareError::InvalidAdoption));
+ }
+ let revision = next_revision(&state.facts)?;
+ write_state(transaction, state, Some(reviewed), revision).await
+}
+
+async fn write_state(
+ transaction: &mut Transaction<'_, Postgres>,
+ state: State,
+ target: Option<TeamShareGrant>,
+ revision: i64,
+) -> TeamShareResult<()> {
+ let entity = &state.facts.entity;
+ let uuid = entity_uuid(entity)?;
+ let permission_id = state
+ .permission_id
+ .ok_or_else(|| report!(TeamShareError::InvalidState))?;
+ sqlx::query!(
+ r#"UPDATE "SharePermission" SET team_share_access_level = $2,
+ team_share_team_id = $3, team_share_revision = $4, "updatedAt" = NOW()
+ WHERE id = $1"#,
+ permission_id,
+ target.map(|g| AccessLevel::from(g.level)) as Option<AccessLevel>,
+ target.map(|g| g.team_id),
+ revision,
+ )
+ .execute(transaction.as_mut())
+ .await
+ .context(TeamShareError::Infrastructure)?;
+
+ if let Some(previous) = state.facts.current
+ && target.map(|g| g.team_id) != Some(previous.team_id)
+ {
+ delete_direct(
+ transaction.as_mut(),
+ &uuid,
+ entity.entity_type,
+ previous.team_id,
+ )
+ .await
+ .context(TeamShareError::Infrastructure)?;
+ }
+ if let Some(target) = target {
+ upsert_direct(
+ transaction.as_mut(),
+ &uuid,
+ entity.entity_type,
+ target.team_id,
+ target.level.into(),
+ )
+ .await
+ .context(TeamShareError::Infrastructure)?;
+ }
+ Ok(())
+}
diff --git a/crates/share_permission_db_utils/src/team_share/test.rs b/crates/share_permission_db_utils/src/team_share/test.rs
new file mode 100644
index 0000000000..22b907919f
--- /dev/null
+++ b/crates/share_permission_db_utils/src/team_share/test.rs
@@ -0,0 +1,95 @@
+use super::*;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use models_permissions::share_permission::team_share::{TeamShareRequest, authorize_team_share};
+use sqlx::PgPool;
+
+fn document() -> Entity<'static> {
+ EntityType::Document.with_entity_string("20000000-0000-0000-0000-000000000002".to_string())
+}
+
+fn command(facts: &TeamShareFacts, level: Option<AccessLevel>) -> AuthorizedTeamShareCommand {
+ authorize_team_share(
+ Some(&facts.owner),
+ facts,
+ TeamShareRequest {
+ access_level: Some(level),
+ legacy_enabled: None,
+ },
+ TeamShareLevel::Edit,
+ )
+ .unwrap()
+ .unwrap()
+}
+
+async fn direct_team_rows(
+ tx: &mut Transaction<'_, Postgres>,
+ document_id: &Uuid,
+ team_id: Uuid,
+) -> sqlx::Result<Vec<AccessLevel>> {
+ sqlx::query_scalar!(
+ r#"SELECT access_level AS "access_level: AccessLevel"
+ FROM entity_access
+ WHERE entity_id = $1 AND entity_type = 'document' AND source_type = 'team'
+ AND source_id = $2 AND granted_from_project_id IS NULL
+ ORDER BY access_level"#,
+ document_id,
+ team_id.to_string(),
+ )
+ .fetch_all(tx.as_mut())
+ .await
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("team_share"))
+)]
+async fn apply_inserts_updates_and_deletes_direct_team_entity_access(
+ pool: PgPool,
+) -> rootcause::Result<()> {
+ let entity = document();
+ let uuid = Uuid::parse_str(&entity.entity_id)?;
+ let mut tx = pool.begin().await?;
+ let facts = load_facts(&mut tx, &entity).await?;
+ let team_id = facts
+ .owner_team_id
+ .expect("fixture owner belongs to a team");
+
+ apply(&mut tx, &command(&facts, Some(AccessLevel::Comment))).await?;
+ assert_eq!(
+ direct_team_rows(&mut tx, &uuid, team_id).await?,
+ vec![AccessLevel::Comment]
+ );
+
+ let facts = load_facts(&mut tx, &entity).await?;
+ apply(&mut tx, &command(&facts, Some(AccessLevel::View))).await?;
+ assert_eq!(
+ direct_team_rows(&mut tx, &uuid, team_id).await?,
+ vec![AccessLevel::View]
+ );
+
+ sqlx::query!(
+ r#"INSERT INTO entity_access
+ (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
+ VALUES ($1, 'document', $2, 'team', 'edit', '20000000-0000-0000-0000-000000000001')"#,
+ uuid,
+ team_id.to_string(),
+ )
+ .execute(tx.as_mut())
+ .await?;
+
+ let facts = load_facts(&mut tx, &entity).await?;
+ apply(&mut tx, &command(&facts, None)).await?;
+ assert!(direct_team_rows(&mut tx, &uuid, team_id).await?.is_empty());
+ let inherited = sqlx::query_scalar!(
+ r#"SELECT access_level AS "access_level: AccessLevel"
+ FROM entity_access
+ WHERE entity_id = $1 AND entity_type = 'document' AND source_type = 'team'
+ AND granted_from_project_id IS NOT NULL"#,
+ uuid,
+ )
+ .fetch_one(tx.as_mut())
+ .await?;
+ assert_eq!(inherited, AccessLevel::Edit);
+ assert_eq!(load_facts(&mut tx, &entity).await?.current, None);
+ Ok(())
+}
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index c7993dd043..e80e821872 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -97,7 +97,9 @@ Right side of a doc (toggle with `Hide/Show Side Panel`):
oldest fetched entry (usually `created this`) pinned last; the toggle flips to `Show less`
once expanded.
- Header: `Share`, `Copy Share Link`, overflow menu — use `Share` to inspect or change the
- doc's visibility/permissions.
+ doc's visibility/permissions. Documents also have a `Team access` dropdown (None / View /
+ Comment / Edit) for sharing directly with the owner's team. That is independent of the
+ team-scoped link control.
## Known failure: "expected instance of LoroDoc"
diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.ts
index 046df7f421..cfaba3fc8c 100644
--- a/packages/sdk/generated/cognition/types.gen.ts
+++ b/packages/sdk/generated/cognition/types.gen.ts
@@ -1287,6 +1287,7 @@ export type SharePermissionV2 = {
* The owner of the item
*/
owner: string;
+ teamShareAccessLevel?: null | AccessLevel;
};
/**
@@ -1468,6 +1469,7 @@ export type UpdateSharePermissionRequestV2 = {
channelSharePermissions?: Array<UpdateChannelSharePermission> | null;
linkShare?: null | LinkShare;
linkShareAccessLevel?: null | AccessLevel;
+ teamShareAccessLevel?: null | AccessLevel;
};
/**
diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.ts
index 053eb6a1b2..532449d8b5 100644
--- a/packages/sdk/generated/storage/sdk.gen.ts
+++ b/packages/sdk/generated/storage/sdk.gen.ts
@@ -1405,9 +1405,10 @@ export class Sdk extends HeyApiClient {
}
/**
- * Sets the team-share state of a document. Sharing grants the document
- * owner's team Edit access; unsharing removes the team's access. Requires
- * Edit access on the document.
+ * Sets explicit team sharing. Requires a verified acting identity matching
+ * the persisted document owner, not merely effective Edit or Owner access.
+ * Initial enable defaults to Edit; repeated enable preserves the chosen level.
+ * Clear removes only the managed direct grant, not inherited team access.
*/
public setDocumentTeamShare<ThrowOnError extends boolean = false>(options: Options<SetDocumentTeamShareData, ThrowOnError>): RequestResult<SetDocumentTeamShareResponses, SetDocumentTeamShareErrors, ThrowOnError> {
return (options.client ?? this.client).put<SetDocumentTeamShareResponses, SetDocumentTeamShareErrors, ThrowOnError>({
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 6d822c9e24..b5ded1b509 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -4727,7 +4727,7 @@ export type DocumentSyncContentUpdatedMetadata = {
*/
export type DocumentTeamShareResponse = {
/**
- * Whether the document is currently shared with the owner's team.
+ * Whether explicit team sharing is enabled; inherited team access does not count.
*/
sharedWithTeam: boolean;
/**
@@ -7661,6 +7661,7 @@ export type SharePermissionV2 = {
* The owner of the item
*/
owner: string;
+ teamShareAccessLevel?: null | AccessLevel;
};
/**
@@ -9379,6 +9380,7 @@ export type UpdateSharePermissionRequestV2 = {
channelSharePermissions?: Array<UpdateChannelSharePermission> | null;
linkShare?: null | LinkShare;
linkShareAccessLevel?: null | AccessLevel;
+ teamShareAccessLevel?: null | AccessLevel;
};
/**
@@ -13107,9 +13109,19 @@ export type SetDocumentTeamShareData = {
};
export type SetDocumentTeamShareErrors = {
+ /**
+ * Owner has no team
+ */
400: ErrorResponse;
+ /**
+ * Acting identity is absent or is not the actual owner
+ */
401: ErrorResponse;
404: ErrorResponse;
+ /**
+ * Sharing facts changed or an untracked grant conflicts
+ */
+ 409: ErrorResponse;
500: ErrorResponse;
};
diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.json
index 32d7dae9f2..ddae0a28ef 100644
--- a/packages/sdk/specs/cognition.json
+++ b/packages/sdk/specs/cognition.json
@@ -4366,6 +4366,17 @@
"owner": {
"type": "string",
"description": "The owner of the item"
+ },
+ "teamShareAccessLevel": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "The explicit access level granted to the owner's team, or `null` when disabled."
+ }
+ ]
}
}
},
@@ -4673,6 +4684,17 @@
"description": "The link access level. Omit to leave unchanged or pass `null` to reset it to the default\nlevel when a link share exists."
}
]
+ },
+ "teamShareAccessLevel": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "The explicit team access level. Omit to leave unchanged or pass `null` to disable team\nsharing. Only the actual owner may change this setting; `owner` is not an allowed level."
+ }
+ ]
}
}
},
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index f3010810da..4d03acf883 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -8341,7 +8341,7 @@
},
"put": {
"tags": ["document"],
- "summary": "Sets the team-share state of a document. Sharing grants the document\nowner's team Edit access; unsharing removes the team's access. Requires\nEdit access on the document.",
+ "summary": "Sets explicit team sharing. Requires a verified acting identity matching\nthe persisted document owner, not merely effective Edit or Owner access.\nInitial enable defaults to Edit; repeated enable preserves the chosen level.\nClear removes only the managed direct grant, not inherited team access.",
"operationId": "set_document_team_share",
"parameters": [
{
@@ -8376,7 +8376,7 @@
}
},
"400": {
- "description": "",
+ "description": "Owner has no team",
"content": {
"application/json": {
"schema": {
@@ -8386,7 +8386,7 @@
}
},
"401": {
- "description": "",
+ "description": "Acting identity is absent or is not the actual owner",
"content": {
"application/json": {
"schema": {
@@ -8405,6 +8405,16 @@
}
}
},
+ "409": {
+ "description": "Sharing facts changed or an untracked grant conflicts",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -19621,7 +19631,7 @@
"properties": {
"sharedWithTeam": {
"type": "boolean",
- "description": "Whether the document is currently shared with the owner's team."
+ "description": "Whether explicit team sharing is enabled; inherited team access does not count."
},
"teamId": {
"type": ["string", "null"],
@@ -25034,6 +25044,17 @@
"owner": {
"type": "string",
"description": "The owner of the item"
+ },
+ "teamShareAccessLevel": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "The explicit access level granted to the owner's team, or `null` when disabled."
+ }
+ ]
}
}
},
@@ -27558,6 +27579,17 @@
"description": "The link access level. Omit to leave unchanged or pass `null` to reset it to the default\nlevel when a link share exists."
}
]
+ },
+ "teamShareAccessLevel": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "The explicit team access level. Omit to leave unchanged or pass `null` to disable team\nsharing. Only the actual owner may change this setting; `owner` is not an allowed level."
+ }
+ ]
}
}
},
diff --git a/packages/sdk/tests/team-share.test.ts b/packages/sdk/tests/team-share.test.ts
new file mode 100644
index 0000000000..1491b078da
--- /dev/null
+++ b/packages/sdk/tests/team-share.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, test } from 'bun:test';
+import { createClient } from '../generated/storage/client';
+import { Sdk } from '../generated/storage/sdk.gen';
+import type { EditDocumentData } from '../generated/storage/types.gen';
+
+const documentId = '0198a4cc-e138-7670-a308-a6b766602700';
+const baseUrl = 'https://api.example.test';
+
+function recordingSdk() {
+ const requests: Request[] = [];
+ const transport = (async (input, init): Promise<Response> => {
+ requests.push(input instanceof Request ? input : new Request(input, init));
+ return Response.json({});
+ }) as typeof fetch;
+ const sdk = new Sdk({
+ client: createClient({ baseUrl, fetch: transport, throwOnError: true }),
+ });
+ return { sdk, requests };
+}
+
+const editCases: Array<{
+ name: string;
+ body: EditDocumentData['body'];
+ serializedBody: string;
+}> = [
+ {
+ name: 'omitted share permission',
+ body: {},
+ serializedBody: '{}',
+ },
+ {
+ name: 'omitted team level keeps the link fields alone',
+ body: { sharePermission: { linkShareAccessLevel: 'view' } },
+ serializedBody: '{"sharePermission":{"linkShareAccessLevel":"view"}}',
+ },
+ {
+ name: 'undefined team level is omitted, not cleared',
+ body: { sharePermission: { teamShareAccessLevel: undefined } },
+ serializedBody: '{"sharePermission":{}}',
+ },
+ {
+ name: 'explicit null clears team sharing',
+ body: { sharePermission: { teamShareAccessLevel: null } },
+ serializedBody: '{"sharePermission":{"teamShareAccessLevel":null}}',
+ },
+ {
+ name: 'view',
+ body: { sharePermission: { teamShareAccessLevel: 'view' } },
+ serializedBody: '{"sharePermission":{"teamShareAccessLevel":"view"}}',
+ },
+ {
+ name: 'comment',
+ body: { sharePermission: { teamShareAccessLevel: 'comment' } },
+ serializedBody: '{"sharePermission":{"teamShareAccessLevel":"comment"}}',
+ },
+ {
+ name: 'edit',
+ body: { sharePermission: { teamShareAccessLevel: 'edit' } },
+ serializedBody: '{"sharePermission":{"teamShareAccessLevel":"edit"}}',
+ },
+];
+
+describe('document edit team-share serialization', () => {
+ test.each(editCases)('$name', async ({ body, serializedBody }) => {
+ const { sdk, requests } = recordingSdk();
+
+ await sdk.editDocument({ path: { document_id: documentId }, body });
+
+ expect(requests).toHaveLength(1);
+ const [request] = requests;
+ expect(request.url).toBe(`${baseUrl}/documents/${documentId}`);
+ expect(request.method).toBe('PATCH');
+ expect(request.headers.get('content-type')).toBe('application/json');
+ expect(await request.text()).toBe(serializedBody);
+ });
+});
+
+describe('legacy document team-share toggle', () => {
+ test.each([true, false])('shareWithTeam=%p', async (shareWithTeam) => {
+ const { sdk, requests } = recordingSdk();
+
+ await sdk.setDocumentTeamShare({
+ path: { document_id: documentId },
+ body: { shareWithTeam },
+ });
+ await sdk.getDocumentTeamShare({ path: { document_id: documentId } });
+
+ expect(requests.map((request) => [request.method, request.url])).toEqual([
+ ['PUT', `${baseUrl}/documents/${documentId}/team_share`],
+ ['GET', `${baseUrl}/documents/${documentId}/team_share`],
+ ]);
+ expect(await requests[0].text()).toBe(JSON.stringify({ shareWithTeam }));
+ });
+});
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 028bf86e9f..eef3319f1c 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -76,7 +76,7 @@ type CompleteMutationRoot {
"""
moveEntities(inputs: [MoveEntityInput!]!): EntityMutationPayload!
"""
- Update link and channel share policies across supported entity kinds.
+ Update link, explicit team, and channel share policies across supported entity kinds.
"""
updateEntitySharePolicies(inputs: [UpdateEntitySharePolicyInput!]!): EntityMutationPayload!
"""
@@ -210,7 +210,7 @@ input EntityRefInput {
}
"""
-Shared link/channel share-policy update.
+Shared link, explicit team, and channel share-policy update.
"""
input EntitySharePolicyInput {
"""
@@ -223,6 +223,12 @@ input EntitySharePolicyInput {
"""
linkShareAccessLevel: GraphqlEntityAccessLevel
"""
+ Explicit team access level. Omit to leave unchanged or pass null to disable team sharing,
+ independently of link sharing. Only the actual owner may change this setting;
+ enabling it requires the owner to belong to a team. OWNER is not an allowed level.
+ """
+ teamShareAccessLevel: GraphqlEntityAccessLevel
+ """
Channel access entries to add, remove, or replace.
"""
channelSharePermissions: [ChannelSharePolicyInput!]
@@ -6117,7 +6123,7 @@ input UpdateEntitySharePolicyInput {
"""
entity: EntityRefInput!
"""
- New link/channel policy values.
+ New link, explicit team, and channel policy values.
"""
policy: EntitySharePolicyInput!
}
diff --git a/tooling/seed_cli/src/entity/document.rs b/tooling/seed_cli/src/entity/document.rs
index 8a7ccfc8b1..c2468c1799 100644
--- a/tooling/seed_cli/src/entity/document.rs
+++ b/tooling/seed_cli/src/entity/document.rs
@@ -138,6 +138,7 @@ async fn create(args: CreateArgs, ctx: SeedCliContext) -> anyhow::Result<()> {
id: String::new(),
link_share: args.link_share,
link_share_access_level: args.link_share_access_level,
+ team_share_access_level: None,
owner: owner.as_ref().to_string(),
channel_share_permissions: None,
},
@@ -230,6 +231,7 @@ pub(crate) async fn seed_from_file_ref(
id: String::new(),
link_share: row.link_share,
link_share_access_level: row.link_share_access_level,
+ team_share_access_level: None,
owner: owner.as_ref().to_string(),
channel_share_permissions: None,
},
diff --git a/tooling/seed_cli/src/entity/scenario/apply.rs b/tooling/seed_cli/src/entity/scenario/apply.rs
index 4aae016d27..4548f5ff45 100644
--- a/tooling/seed_cli/src/entity/scenario/apply.rs
+++ b/tooling/seed_cli/src/entity/scenario/apply.rs
@@ -521,6 +521,7 @@ fn share_permission(
id: String::new(),
link_share: Some(link_share),
link_share_access_level: Some(permission_access_level(access_level)),
+ team_share_access_level: None,
owner: spec.user_id(owner_key),
channel_share_permissions: None,
}
@@ -625,6 +626,7 @@ async fn seed_documents(
link_share_access_level: document
.link_share_access_level
.map(permission_access_level),
+ team_share_access_level: None,
owner: owner_id.clone(),
channel_share_permissions: None,
},
@@ -725,6 +727,7 @@ async fn seed_tasks(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result
id: String::new(),
link_share: None,
link_share_access_level: None,
+ team_share_access_level: None,
owner: owner_id.clone(),
channel_share_permissions: None,
},