Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(calls): use share permissions (#2349)
Will Hutchinsonae23fcfc0e03
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 5d4626c1f2..32b7141568 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -1731,6 +1731,7 @@ dependencies = ["mockall","model-error-response","model_user",+ "models_permissions","serde","sqlx","thiserror 2.0.17",diff --git a/rust/cloud-storage/call/.sqlx/query-f38943ee03436d2c57f710d4592b242fe240c11788d50a36d7b7bac85610114b.json b/rust/cloud-storage/call/.sqlx/query-366e841724500ab94e0ba963e65a3bf35b96899f6b85e9420fae5445c0164cf5.jsonsimilarity index 73%rename from rust/cloud-storage/call/.sqlx/query-f38943ee03436d2c57f710d4592b242fe240c11788d50a36d7b7bac85610114b.jsonrename to rust/cloud-storage/call/.sqlx/query-366e841724500ab94e0ba963e65a3bf35b96899f6b85e9420fae5445c0164cf5.jsonindex 69eb93fd48..e3e8960ef0 100644--- a/rust/cloud-storage/call/.sqlx/query-f38943ee03436d2c57f710d4592b242fe240c11788d50a36d7b7bac85610114b.json+++ b/rust/cloud-storage/call/.sqlx/query-366e841724500ab94e0ba963e65a3bf35b96899f6b85e9420fae5445c0164cf5.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_url\n FROM calls\n WHERE id = $1\n FOR UPDATE\n ",+ "query": "\n SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_url, share_permission_id\n FROM calls\n WHERE id = $1\n FOR UPDATE\n ","describe": {"columns": [{@@ -37,6 +37,11 @@"ordinal": 6,"name": "recording_url","type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "share_permission_id",+ "type_info": "Text"}],"parameters": {@@ -51,8 +56,9 @@false,false,true,- true+ true,+ false]},- "hash": "f38943ee03436d2c57f710d4592b242fe240c11788d50a36d7b7bac85610114b"+ "hash": "366e841724500ab94e0ba963e65a3bf35b96899f6b85e9420fae5445c0164cf5"}diff --git a/rust/cloud-storage/call/.sqlx/query-41f77dad73c881816d91df173411d39329574a7a99ae1d295fcd43afa5963408.json b/rust/cloud-storage/call/.sqlx/query-41f77dad73c881816d91df173411d39329574a7a99ae1d295fcd43afa5963408.jsonnew file mode 100644index 0000000000..13c88a263e--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-41f77dad73c881816d91df173411d39329574a7a99ae1d295fcd43afa5963408.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"ChannelSharePermission\" (\"share_permission_id\", \"channel_id\", \"access_level\")\n VALUES ($1, $2, $3)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "41f77dad73c881816d91df173411d39329574a7a99ae1d295fcd43afa5963408"+}diff --git a/rust/cloud-storage/call/.sqlx/query-dd6e7bbdb4ee903f6769bf2259bbca5c630c1f2bb969d26ca5b3e00530deaa02.json b/rust/cloud-storage/call/.sqlx/query-56636a342b76ec92ee7adf0f779f6a8c14b8b0de4d40764362304046e3e48efd.jsonsimilarity index 66%rename from rust/cloud-storage/call/.sqlx/query-dd6e7bbdb4ee903f6769bf2259bbca5c630c1f2bb969d26ca5b3e00530deaa02.jsonrename to rust/cloud-storage/call/.sqlx/query-56636a342b76ec92ee7adf0f779f6a8c14b8b0de4d40764362304046e3e48efd.jsonindex a4936971aa..4c008e3566 100644--- a/rust/cloud-storage/call/.sqlx/query-dd6e7bbdb4ee903f6769bf2259bbca5c630c1f2bb969d26ca5b3e00530deaa02.json+++ b/rust/cloud-storage/call/.sqlx/query-56636a342b76ec92ee7adf0f779f6a8c14b8b0de4d40764362304046e3e48efd.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_url)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)\n ",+ "query": "\n INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_url, share_permission_id)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ","describe": {"columns": [],"parameters": {@@ -13,10 +13,11 @@"Timestamptz","Int8","Text",+ "Text","Text"]},"nullable": []},- "hash": "dd6e7bbdb4ee903f6769bf2259bbca5c630c1f2bb969d26ca5b3e00530deaa02"+ "hash": "56636a342b76ec92ee7adf0f779f6a8c14b8b0de4d40764362304046e3e48efd"}diff --git a/rust/cloud-storage/call/.sqlx/query-9096710139da4a36b9a11809a30b65ae3b712a0b659b63e366e5f485b8630951.json b/rust/cloud-storage/call/.sqlx/query-9096710139da4a36b9a11809a30b65ae3b712a0b659b63e366e5f485b8630951.jsonnew file mode 100644index 0000000000..ce58f8d552--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-9096710139da4a36b9a11809a30b65ae3b712a0b659b63e366e5f485b8630951.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"SharePermission\" (\"id\", \"isPublic\",\"publicAccessLevel\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, NOW(), NOW())\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Bool",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "9096710139da4a36b9a11809a30b65ae3b712a0b659b63e366e5f485b8630951"+}diff --git a/rust/cloud-storage/call/.sqlx/query-2995844320b8b71c3e61d00a6b91c0b083f404ee8a8541538709acc18f6679ad.json b/rust/cloud-storage/call/.sqlx/query-d0dcb62233091aee045f96c8f2cd8ebee5614196a92bcbc250b9702a8194c329.jsonsimilarity index 74%rename from rust/cloud-storage/call/.sqlx/query-2995844320b8b71c3e61d00a6b91c0b083f404ee8a8541538709acc18f6679ad.jsonrename to rust/cloud-storage/call/.sqlx/query-d0dcb62233091aee045f96c8f2cd8ebee5614196a92bcbc250b9702a8194c329.jsonindex 2134794b8b..b9297391ad 100644--- a/rust/cloud-storage/call/.sqlx/query-2995844320b8b71c3e61d00a6b91c0b083f404ee8a8541538709acc18f6679ad.json+++ b/rust/cloud-storage/call/.sqlx/query-d0dcb62233091aee045f96c8f2cd8ebee5614196a92bcbc250b9702a8194c329.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO calls (id, channel_id, room_name, created_by)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (channel_id) DO NOTHING\n RETURNING id, channel_id, room_name, created_by, created_at, egress_id\n ",+ "query": "\n INSERT INTO calls (id, channel_id, room_name, created_by, share_permission_id)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (channel_id) DO NOTHING\n RETURNING id, channel_id, room_name, created_by, created_at, egress_id\n ","describe": {"columns": [{@@ -39,6 +39,7 @@"Uuid","Uuid","Text",+ "Text","Text"]},@@ -51,5 +52,5 @@true]},- "hash": "2995844320b8b71c3e61d00a6b91c0b083f404ee8a8541538709acc18f6679ad"+ "hash": "d0dcb62233091aee045f96c8f2cd8ebee5614196a92bcbc250b9702a8194c329"}diff --git a/rust/cloud-storage/call/Cargo.toml b/rust/cloud-storage/call/Cargo.tomlindex eb2b3617ce..45e3357c22 100644--- a/rust/cloud-storage/call/Cargo.toml+++ b/rust/cloud-storage/call/Cargo.toml@@ -14,19 +14,29 @@ inbound = ["dep:utoipa","ports",]-outbound = ["dep:livekit-api", "dep:livekit-protocol", "dep:sqlx", "ports"]+outbound = [+ "dep:entity_access",+ "dep:livekit-api",+ "dep:livekit-protocol",+ "dep:models_permissions",+ "dep:sqlx",+ "ports",+]ports = ["dep:tokio"][dependencies]anyhow = { workspace = true }axum = { workspace = true, optional = true }chrono = { workspace = true }-entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["inbound"] }+entity_access = { path = "../entity_access", optional = true, default-features = false, features = [+ "inbound",+] }livekit-api = { workspace = true, optional = true }livekit-protocol = { workspace = true, optional = true }macro_user_id = { path = "../macro_user_id" }model-error-response = { path = "../model-error-response", optional = true }model_user = { path = "../model_user", optional = true, features = ["axum"] }+models_permissions = { path = "../models_permissions", optional = true }serde = { workspace = true }sqlx = { workspace = true, optional = true }thiserror = { workspace = true }diff --git a/rust/cloud-storage/call/fixtures/call_repo.sql b/rust/cloud-storage/call/fixtures/call_repo.sqlindex eca10fbe9b..2dbeb14862 100644--- a/rust/cloud-storage/call/fixtures/call_repo.sql+++ b/rust/cloud-storage/call/fixtures/call_repo.sql@@ -13,11 +13,18 @@ INSERT INTO comms_channels (id, name, channel_type, org_id, owner_id, created_at('00000000-0000-0000-0000-000000000c02', 'empty-channel', 'public', NULL, 'macro|[email protected]','2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');+-- share permission for call1+INSERT INTO "SharePermission" (id, "isPublic", "publicAccessLevel", "createdAt", "updatedAt") VALUES+ ('00000000-0000-0000-0000-00000000sp01', false, NULL, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');++INSERT INTO "ChannelSharePermission" (share_permission_id, channel_id, access_level) VALUES+ ('00000000-0000-0000-0000-00000000sp01', '00000000-0000-0000-0000-000000000c01', 'view');+-- active call in ch1-INSERT INTO calls (id, channel_id, room_name, created_by, created_at) VALUES+INSERT INTO calls (id, channel_id, room_name, created_by, created_at, share_permission_id) VALUES('00000000-0000-0000-0000-0000000ca110', '00000000-0000-0000-0000-000000000c01','00000000-0000-0000-0000-000000000c01', 'macro|[email protected]',- '2024-01-01 12:00:00+00');+ '2024-01-01 12:00:00+00', '00000000-0000-0000-0000-00000000sp01');-- participants in call1INSERT INTO call_participants (call_id, user_id, joined_at) VALUESdiff --git a/rust/cloud-storage/call/src/inbound/axum_router.rs b/rust/cloud-storage/call/src/inbound/axum_router.rsindex 9e39707fbc..fb24579f05 100644--- a/rust/cloud-storage/call/src/inbound/axum_router.rs+++ b/rust/cloud-storage/call/src/inbound/axum_router.rs@@ -17,11 +17,11 @@ use axum::{routing::{get, post},};use entity_access::{- domain::{- models::{EntityAccessReceipt, MemberParticipantRole, RequiredPermission},- ports::EntityAccessService,+ domain::models::MemberParticipantRole,+ domain::ports::EntityAccessService,+ inbound::axum_extractors::{+ CallWithChannelIdAccessLevelExtractor, ChannelAccessLevelExtractor,},- inbound::axum_extractors::ChannelAccessLevelExtractor,};use model_error_response::ErrorResponse;use model_user::axum_extractor::MacroUserExtractor;@@ -67,13 +67,6 @@ impl<S, Svc> FromRef<CallRouterState<S, Svc>> for Arc<Svc> {}}-fn channel_id_from_receipt<T: RequiredPermission>(- receipt: &EntityAccessReceipt<T>,-) -> Result<Uuid, CallError> {- Uuid::parse_str(&receipt.entity().entity_id)- .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid channel_id")))-}-/// Authenticated call router.////// Routes:@@ -163,7 +156,8 @@ pub async fn get_or_create_call_handler<S: CallService, Svc: EntityAccessServiceaccess: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,user: MacroUserExtractor,) -> Result<Json<CallTokenResponse>, CallError> {- let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;+ let channel_id = Uuid::parse_str(&access.entity_access_receipt.entity().entity_id)+ .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid channel_id")))?;let user_id = user.macro_user_id.as_ref();let response = state@@ -192,10 +186,10 @@ pub async fn get_or_create_call_handler<S: CallService, Svc: EntityAccessService#[tracing::instrument(err, skip_all)]pub async fn leave_or_end_call_handler<S: CallService, Svc: EntityAccessService>(State(state): State<CallRouterState<S, Svc>>,- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,+ access: CallWithChannelIdAccessLevelExtractor<MemberParticipantRole, Svc>,user: MacroUserExtractor,) -> Result<Json<LeaveCallResponse>, CallError> {- let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;+ let channel_id = access.channel_id;let user_id = user.macro_user_id.as_ref();let response = state@@ -262,11 +256,11 @@ pub async fn webhook_handler<S: CallService>(#[tracing::instrument(err, skip_all)]pub async fn transcript_handler<S: CallService, Svc: EntityAccessService>(State(state): State<CallRouterState<S, Svc>>,- access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,+ access: CallWithChannelIdAccessLevelExtractor<MemberParticipantRole, Svc>,_user: MacroUserExtractor,Json(segment): Json<TranscriptSegmentRequest>,) -> Result<StatusCode, CallError> {- let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;+ let channel_id = access.channel_id;// Note: we don't enforce speaker_id == authenticated user because the// LiveKit transcription agent publishes text streams attributed to thediff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsindex e73e96b8c7..b750002d27 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -4,6 +4,9 @@mod test;use chrono::Utc;+use entity_access::domain::models::AccessLevel;+use models_permissions::share_permission::SharePermissionV2;+use models_permissions::share_permission::channel_share_permission::ChannelSharePermission;use sqlx::PgPool;use uuid::Uuid;@@ -33,10 +36,54 @@ impl CallRepository for PgCallRepo {room_name: &str,created_by: &str,) -> Result<Option<Call>, Self::Err> {+ // Create share permission+ let share_permission_id = uuid::Uuid::now_v7();+ let share_permission = SharePermissionV2 {+ id: share_permission_id.to_string(),+ is_public: false,+ public_access_level: None,+ owner: created_by.to_string(),+ channel_share_permissions: Some(vec![ChannelSharePermission {+ channel_id: channel_id.to_string(),+ access_level: AccessLevel::View,+ }]),+ };++ let mut tx = self.pool.begin().await?;++ // insert share permission+ sqlx::query!(+ r#"+ INSERT INTO "SharePermission" ("id", "isPublic","publicAccessLevel", "createdAt", "updatedAt")+ VALUES ($1, $2, $3, NOW(), NOW())+ "#,+ share_permission.id,+ share_permission.is_public,+ share_permission+ .public_access_level+ .as_ref()+ .map(|s| s.to_string()),+ )+ .execute(tx.as_mut())+ .await?;++ // insert channel share permission+ sqlx::query!(+ r#"+ INSERT INTO "ChannelSharePermission" ("share_permission_id", "channel_id", "access_level")+ VALUES ($1, $2, $3)+ "#,+ &share_permission.id,+ &channel_id.to_string(),+ share_permission.channel_share_permissions.as_ref().unwrap()[0].access_level as _,+ )+ .execute(tx.as_mut())+ .await?;+let row = sqlx::query!(r#"- INSERT INTO calls (id, channel_id, room_name, created_by)- VALUES ($1, $2, $3, $4)+ INSERT INTO calls (id, channel_id, room_name, created_by, share_permission_id)+ VALUES ($1, $2, $3, $4, $5)ON CONFLICT (channel_id) DO NOTHINGRETURNING id, channel_id, room_name, created_by, created_at, egress_id"#,@@ -44,18 +91,26 @@ impl CallRepository for PgCallRepo {channel_id,room_name,created_by,+ &share_permission_id.to_string(),)- .fetch_optional(&self.pool)+ .fetch_optional(tx.as_mut()).await?;- Ok(row.map(|r| Call {- id: r.id,- channel_id: r.channel_id,- room_name: r.room_name,- created_by: r.created_by,- created_at: r.created_at,- egress_id: r.egress_id,- }))+ // only commit if there is a channel to create+ if let Some(r) = row {+ tx.commit().await?;++ Ok(Some(Call {+ id: r.id,+ channel_id: r.channel_id,+ room_name: r.room_name,+ created_by: r.created_by,+ created_at: r.created_at,+ egress_id: r.egress_id,+ }))+ } else {+ Ok(None)+ }}#[tracing::instrument(err, skip(self))]@@ -236,7 +291,7 @@ impl CallRepository for PgCallRepo {// Fetch and lock the active call so concurrent archive_call callers serialize.let call = sqlx::query!(r#"- SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_url+ SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_url, share_permission_idFROM callsWHERE id = $1FOR UPDATE@@ -252,15 +307,14 @@ impl CallRepository for PgCallRepo {.signed_duration_since(call.created_at).num_milliseconds().max(0);- let record_id = Uuid::now_v7();-// Insert into call_records (including egress_id and any early recording_url).+ // The record keeps the same id as the original call.sqlx::query!(r#"- INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_url)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+ INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_url, share_permission_id)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"#,- record_id,+ call_id,call.channel_id,call.room_name,call.created_by,@@ -269,6 +323,7 @@ impl CallRepository for PgCallRepo {duration_ms,call.egress_id,call.recording_url,+ &call.share_permission_id,).execute(tx.as_mut()).await?;@@ -281,7 +336,7 @@ impl CallRepository for PgCallRepo {FROM call_participantsWHERE call_id = $2"#,- record_id,+ call_id,call_id,).execute(tx.as_mut())@@ -295,7 +350,7 @@ impl CallRepository for PgCallRepo {FROM call_transcriptsWHERE call_id = $2"#,- record_id,+ call_id,call_id,).execute(tx.as_mut())@@ -312,7 +367,7 @@ impl CallRepository for PgCallRepo {.await?;tx.commit().await?;- Ok(record_id)+ Ok(*call_id)}#[tracing::instrument(err, skip(self))]diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rsindex cb341198b1..924f63d56d 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs@@ -290,6 +290,43 @@ async fn archive_call_preserves_soft_deleted_participants(Ok(())}+// -- archive_call preserves id and share_permission_id ------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn archive_call_preserves_id_and_share_permission(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool.clone());++ // Read the share_permission_id from the active call before archiving.+ let active_share_permission_id = sqlx::query_scalar!(+ r#"SELECT share_permission_id FROM calls WHERE id = $1"#,+ CALL1,+ )+ .fetch_one(&pool)+ .await?;++ let record_id = repo.archive_call(&CALL1).await?;++ // The call_record id should be the same as the original call id.+ assert_eq!(record_id, CALL1);++ // The share_permission_id should carry over to the call_record.+ let record_share_permission_id = sqlx::query_scalar!(+ r#"SELECT share_permission_id FROM call_records WHERE id = $1"#,+ record_id,+ )+ .fetch_one(&pool)+ .await?;++ assert_eq!(record_share_permission_id, active_share_permission_id);++ Ok(())+}+// -- set_active_call_recording_url --------------------------------------------#[sqlx::test(diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rsindex e1a3d21c6f..346efa857d 100644--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs@@ -144,6 +144,20 @@ impl EntityAccessService for TestAccessService {AccessMode::NotFound => Err(AccessError::NotFound("Channel not found")),}}++ async fn get_call_channel(+ &self,+ _call_id: &Uuid,+ ) -> Result<Option<entity_access::domain::models::CallChannelInfo>, AccessError> {+ unimplemented!()+ }++ async fn get_call_channel_by_channel_id(+ &self,+ _channel_id: &Uuid,+ ) -> Result<Option<entity_access::domain::models::CallChannelInfo>, AccessError> {+ unimplemented!()+ }}// --- Mock services (business logic only, no auth concerns) ---diff --git a/rust/cloud-storage/chat/src/inbound/test.rs b/rust/cloud-storage/chat/src/inbound/test.rsindex 13ba2661aa..387e2d08e0 100644--- a/rust/cloud-storage/chat/src/inbound/test.rs+++ b/rust/cloud-storage/chat/src/inbound/test.rs@@ -290,6 +290,20 @@ impl EntityAccessService for MockAccessService {) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {Ok(vec![])}++ async fn get_call_channel(+ &self,+ _call_id: &sqlx::types::Uuid,+ ) -> Result<Option<entity_access::domain::models::CallChannelInfo>, AccessError> {+ unimplemented!()+ }++ async fn get_call_channel_by_channel_id(+ &self,+ _channel_id: &sqlx::types::Uuid,+ ) -> Result<Option<entity_access::domain::models::CallChannelInfo>, AccessError> {+ unimplemented!()+ }}fn user_extension() -> Extension<UserContext> {diff --git a/rust/cloud-storage/entity_access/src/domain/models.rs b/rust/cloud-storage/entity_access/src/domain/models.rsindex 218d3f798e..ae1ce562c9 100644--- a/rust/cloud-storage/entity_access/src/domain/models.rs+++ b/rust/cloud-storage/entity_access/src/domain/models.rs@@ -4,6 +4,7 @@ use std::marker::PhantomData;use macro_user_id::user_id::MacroUserIdStr;use serde::{Deserialize, Serialize};+use uuid::Uuid;pub use model_entity::EntityType;pub use models_permissions::share_permission::access_level::AccessLevel;@@ -232,6 +233,15 @@ impl<T: RequiredPermission> EntityAccessReceipt<T> {}}+/// Information about a call's channel association and share permission.+#[derive(Debug, Clone)]+pub struct CallChannelInfo {+ /// The channel the call belongs to.+ pub channel_id: Uuid,+ /// The share permission ID for this call.+ pub share_permission_id: String,+}+/// Errors that can occur during access checking.#[derive(Debug, thiserror::Error)]pub enum AccessError {diff --git a/rust/cloud-storage/entity_access/src/domain/ports.rs b/rust/cloud-storage/entity_access/src/domain/ports.rsindex b8b5d95bcf..2919a33a08 100644--- a/rust/cloud-storage/entity_access/src/domain/ports.rs+++ b/rust/cloud-storage/entity_access/src/domain/ports.rs@@ -4,8 +4,8 @@use super::models::EntityType;use crate::domain::models::{- AccessError, AccessLevel, ChannelRoleResult, EntityAccessReceipt, EntityPermission,- RequiredPermission,+ AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, EntityAccessReceipt,+ EntityPermission, RequiredPermission,};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};use std::future::Future;@@ -109,6 +109,24 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {&self,thread_id: &str,) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, AccessError>> + Send;++ /// Resolve a call ID to its channel ID and share permission ID.+ ///+ /// Checks both the `calls` table (active calls) and the `call_records` table+ /// (archived calls). Returns `None` if the call does not exist in either table.+ fn get_call_channel(+ &self,+ call_id: &Uuid,+ ) -> impl Future<Output = Result<Option<CallChannelInfo>, AccessError>> + Send;++ /// Resolve a channel ID to the call's channel info and share permission ID.+ ///+ /// Checks both the `calls` table (active calls) and the `call_records` table+ /// (archived calls). Returns `None` if no call exists for the channel.+ fn get_call_channel_by_channel_id(+ &self,+ channel_id: &Uuid,+ ) -> impl Future<Output = Result<Option<CallChannelInfo>, AccessError>> + Send;}/// Service for checking entity access levels.@@ -187,4 +205,20 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {entity_id: &str,entity_type: EntityType,) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, AccessError>> + Send;++ /// Resolve a call ID to its channel ID and share permission ID.+ ///+ /// Checks both `calls` (active) and `call_records` (archived) tables.+ fn get_call_channel(+ &self,+ call_id: &Uuid,+ ) -> impl Future<Output = Result<Option<CallChannelInfo>, AccessError>> + Send;++ /// Resolve a channel ID to the call's channel info and share permission ID.+ ///+ /// Checks both `calls` (active) and `call_records` (archived) tables.+ fn get_call_channel_by_channel_id(+ &self,+ channel_id: &Uuid,+ ) -> impl Future<Output = Result<Option<CallChannelInfo>, AccessError>> + Send;}diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rsindex 12b56b1db5..8025e51865 100644--- a/rust/cloud-storage/entity_access/src/domain/service.rs+++ b/rust/cloud-storage/entity_access/src/domain/service.rs@@ -5,8 +5,8 @@ use std::str::FromStr;use crate::domain::{models::{- AccessError, AccessLevel, ChannelRoleResult, Entity, EntityAccessAuth, EntityAccessReceipt,- EntityPermission, EntityType, RequiredPermission,+ AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, Entity, EntityAccessAuth,+ EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission,},ports::{AccessRepository, EntityAccessService},};@@ -219,6 +219,22 @@ where)),}}++ #[tracing::instrument(err, skip(self))]+ async fn get_call_channel(+ &self,+ call_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ self.repo.get_call_channel(call_id).await+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_call_channel_by_channel_id(+ &self,+ channel_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ self.repo.get_call_channel_by_channel_id(channel_id).await+ }}#[cfg(test)]diff --git a/rust/cloud-storage/entity_access/src/domain/service/test.rs b/rust/cloud-storage/entity_access/src/domain/service/test.rsindex 42f84229b8..c0127fc24d 100644--- a/rust/cloud-storage/entity_access/src/domain/service/test.rs+++ b/rust/cloud-storage/entity_access/src/domain/service/test.rs@@ -2,7 +2,7 @@use super::*;use crate::domain::models::{- AdminParticipantRole, CommentAccessLevel, EditAccessLevel, EntityAccessAuth,+ AdminParticipantRole, CallChannelInfo, CommentAccessLevel, EditAccessLevel, EntityAccessAuth,MemberParticipantRole, OwnerParticipantRole, ParticipantRole, ViewAccessLevel,};use macro_user_id::user_id::MacroUserIdStr;@@ -23,6 +23,7 @@ struct MockRepo {chat_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,project_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,thread_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,+ call_channel: Arc<Mutex<Option<CallChannelInfo>>>,}impl MockRepo {@@ -38,6 +39,7 @@ impl MockRepo {chat_users: Arc::new(Mutex::new(vec![])),project_users: Arc::new(Mutex::new(vec![])),thread_users: Arc::new(Mutex::new(vec![])),+ call_channel: Arc::new(Mutex::new(None)),}}@@ -169,6 +171,20 @@ impl AccessRepository for MockRepo {) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {Ok(self.thread_users.lock().await.clone())}++ async fn get_call_channel(+ &self,+ _call_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ Ok(self.call_channel.lock().await.clone())+ }++ async fn get_call_channel_by_channel_id(+ &self,+ _channel_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ Ok(self.call_channel.lock().await.clone())+ }}fn test_user_id() -> MacroUserIdStr<'static> {diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/call.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/call.rsnew file mode 100644index 0000000000..59a6e93375--- /dev/null+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/call.rs@@ -0,0 +1,275 @@+//! Call access extractors.+//!+//! Resolves a call (from both `calls` and `call_records` tables), checks channel+//! membership, and exposes the call's `share_permission_id` for downstream handlers.++use std::marker::PhantomData;+use std::sync::Arc;++use axum::{+ Extension, RequestPartsExt,+ extract::{FromRef, FromRequestParts, Path},+ http::request::Parts,+};+use uuid::Uuid;++use super::{ExtractorError, InternalUser};+use crate::domain::{+ models::{+ Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,+ ParticipantRole, RequiredPermission,+ },+ ports::EntityAccessService,+};+use model_user::axum_extractor::OptionalMacroUserExtractor;++#[derive(Debug, serde::Deserialize)]+struct CallAccessParams {+ call_id: String,+}++#[derive(Debug, serde::Deserialize)]+struct CallWithChannelIdAccessParams {+ channel_id: String,+}++/// Validates that the user satisfies the required permission for the channel+/// that a call belongs to, using a `call_id` path parameter.+///+/// Resolves the call from both `calls` (active) and `call_records` (archived)+/// tables, then checks the user's channel membership.+///+/// Type parameter `T` specifies the required permission marker.+/// Type parameter `Svc` is the entity access service implementation.+#[derive(Debug)]+pub struct CallAccessLevelExtractor<T: RequiredPermission, Svc> {+ /// The entity access receipt (entity is the channel the call belongs to).+ pub entity_access_receipt: EntityAccessReceipt<T>,+ /// The call's share permission ID.+ pub share_permission_id: String,+ /// The channel ID the call belongs to.+ pub channel_id: Uuid,+ _marker: PhantomData<(T, Svc)>,+}++impl<T, S, Svc> FromRequestParts<S> for CallAccessLevelExtractor<T, Svc>+where+ T: RequiredPermission,+ Arc<Svc>: FromRef<S>,+ Svc: EntityAccessService,+ S: Send + Sync + 'static,+{+ type Rejection = ExtractorError;++ #[tracing::instrument(err, skip(state, parts))]+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {+ let service = <Arc<Svc>>::from_ref(state);++ let OptionalMacroUserExtractor {+ macro_user_id,+ user_context,+ ..+ } = parts+ .extract()+ .await+ .map_err(|_| ExtractorError::Internal)?;++ let Path(CallAccessParams { call_id }) = parts+ .extract::<Path<CallAccessParams>>()+ .await+ .map_err(|_| ExtractorError::BadRequest("missing call_id path parameter"))?;++ let call_id_uuid = Uuid::parse_str(&call_id)+ .map_err(|_| ExtractorError::BadRequest("invalid call_id format"))?;++ let call_info = service+ .get_call_channel(&call_id_uuid)+ .await+ .map_err(ExtractorError::from)?+ .ok_or(ExtractorError::NotFound("call not found"))?;++ let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {+ parts+ .extract()+ .await+ .map_err(|_| ExtractorError::Internal)?+ } else {+ None+ };++ if internal_user.is_some() {+ return Ok(Self {+ entity_access_receipt: EntityAccessReceipt {+ entity: Entity {+ entity_id: call_info.channel_id.to_string(),+ entity_type: EntityType::Channel,+ },+ auth: EntityAccessAuth::Internal,+ entity_permission: EntityPermission::ChannelRole {+ role: ParticipantRole::Owner,+ },+ _marker: PhantomData,+ },+ share_permission_id: call_info.share_permission_id,+ channel_id: call_info.channel_id,+ _marker: PhantomData,+ });+ }++ let Some(macro_user_id) = macro_user_id else {+ return Err(ExtractorError::Unauthorized);+ };++ let user_org_id = user_context.organization_id.map(i64::from);+ let channel_id_str = call_info.channel_id.to_string();++ let permission = service+ .get_entity_permission(+ Some(¯o_user_id),+ &channel_id_str,+ EntityType::Channel,+ user_org_id,+ )+ .await+ .map_err(ExtractorError::from)?;++ if !permission.satisfies::<T>() {+ return Err(ExtractorError::Unauthorized);+ }++ Ok(Self {+ entity_access_receipt: EntityAccessReceipt {+ entity: Entity {+ entity_id: channel_id_str,+ entity_type: EntityType::Channel,+ },+ auth: EntityAccessAuth::Authenticated(macro_user_id),+ entity_permission: permission,+ _marker: PhantomData,+ },+ share_permission_id: call_info.share_permission_id,+ channel_id: call_info.channel_id,+ _marker: PhantomData,+ })+ }+}++/// Validates that the user satisfies the required permission for a call's channel,+/// using a `channel_id` path parameter.+///+/// Resolves the call from both `calls` (active) and `call_records` (archived)+/// tables by channel ID, then checks the user's channel membership.+///+/// Type parameter `T` specifies the required permission marker.+/// Type parameter `Svc` is the entity access service implementation.+#[derive(Debug)]+pub struct CallWithChannelIdAccessLevelExtractor<T: RequiredPermission, Svc> {+ /// The entity access receipt (entity is the channel the call belongs to).+ pub entity_access_receipt: EntityAccessReceipt<T>,+ /// The call's share permission ID.+ pub share_permission_id: String,+ /// The channel ID.+ pub channel_id: Uuid,+ _marker: PhantomData<(T, Svc)>,+}++impl<T, S, Svc> FromRequestParts<S> for CallWithChannelIdAccessLevelExtractor<T, Svc>+where+ T: RequiredPermission,+ Arc<Svc>: FromRef<S>,+ Svc: EntityAccessService,+ S: Send + Sync + 'static,+{+ type Rejection = ExtractorError;++ #[tracing::instrument(err, skip(state, parts))]+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {+ let service = <Arc<Svc>>::from_ref(state);++ let OptionalMacroUserExtractor {+ macro_user_id,+ user_context,+ ..+ } = parts+ .extract()+ .await+ .map_err(|_| ExtractorError::Internal)?;++ let Path(CallWithChannelIdAccessParams { channel_id }) = parts+ .extract::<Path<CallWithChannelIdAccessParams>>()+ .await+ .map_err(|_| ExtractorError::BadRequest("missing channel_id path parameter"))?;++ let channel_id_uuid = Uuid::parse_str(&channel_id)+ .map_err(|_| ExtractorError::BadRequest("invalid channel_id format"))?;++ let call_info = service+ .get_call_channel_by_channel_id(&channel_id_uuid)+ .await+ .map_err(ExtractorError::from)?+ .ok_or(ExtractorError::NotFound("call not found for channel"))?;++ let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {+ parts+ .extract()+ .await+ .map_err(|_| ExtractorError::Internal)?+ } else {+ None+ };++ if internal_user.is_some() {+ return Ok(Self {+ entity_access_receipt: EntityAccessReceipt {+ entity: Entity {+ entity_id: channel_id,+ entity_type: EntityType::Channel,+ },+ auth: EntityAccessAuth::Internal,+ entity_permission: EntityPermission::ChannelRole {+ role: ParticipantRole::Owner,+ },+ _marker: PhantomData,+ },+ share_permission_id: call_info.share_permission_id,+ channel_id: channel_id_uuid,+ _marker: PhantomData,+ });+ }++ let Some(macro_user_id) = macro_user_id else {+ return Err(ExtractorError::Unauthorized);+ };++ let user_org_id = user_context.organization_id.map(i64::from);++ let permission = service+ .get_entity_permission(+ Some(¯o_user_id),+ &channel_id,+ EntityType::Channel,+ user_org_id,+ )+ .await+ .map_err(ExtractorError::from)?;++ if !permission.satisfies::<T>() {+ return Err(ExtractorError::Unauthorized);+ }++ Ok(Self {+ entity_access_receipt: EntityAccessReceipt {+ entity: Entity {+ entity_id: channel_id,+ entity_type: EntityType::Channel,+ },+ auth: EntityAccessAuth::Authenticated(macro_user_id),+ entity_permission: permission,+ _marker: PhantomData,+ },+ share_permission_id: call_info.share_permission_id,+ channel_id: channel_id_uuid,+ _marker: PhantomData,+ })+ }+}diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rsindex 58ca5bca04..97e4db8326 100644--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs@@ -3,6 +3,7 @@//! These extractors validate that the requesting user has sufficient//! access to the entity being accessed.+mod call;mod channel;mod chat;mod document;@@ -11,6 +12,7 @@ mod history;mod project;mod thread;+pub use call::{CallAccessLevelExtractor, CallWithChannelIdAccessLevelExtractor};pub use channel::ChannelAccessLevelExtractor;pub use chat::ChatAccessLevelExtractor;pub use document::DocumentAccessExtractor;diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rsindex 92f14f2f4c..8e42d63b3c 100644--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs@@ -3,7 +3,7 @@mod queries;use crate::domain::{- models::{AccessError, AccessLevel, ChannelRoleResult},+ models::{AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult},ports::AccessRepository,};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};@@ -137,4 +137,29 @@ impl AccessRepository for PgAccessRepository {let raw = queries::thread_users::get_thread_users(&self.pool, thread_id).await?;Ok(parse_user_ids(raw))}++ #[tracing::instrument(err, skip(self))]+ async fn get_call_channel(+ &self,+ call_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ let row = queries::call_channel::get_call_channel(&self.pool, call_id).await?;+ Ok(row.map(|r| CallChannelInfo {+ channel_id: r.channel_id,+ share_permission_id: r.share_permission_id,+ }))+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_call_channel_by_channel_id(+ &self,+ channel_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ let row =+ queries::call_channel::get_call_channel_by_channel_id(&self.pool, channel_id).await?;+ Ok(row.map(|r| CallChannelInfo {+ channel_id: r.channel_id,+ share_permission_id: r.share_permission_id,+ }))+ }}diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/call_channel.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/call_channel.rsnew file mode 100644index 0000000000..6ec6a19321--- /dev/null+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/call_channel.rs@@ -0,0 +1,65 @@+//! Queries for resolving a call to its channel ID and share permission ID.++use sqlx::PgPool;+use uuid::Uuid;++/// Row returned by call channel queries.+#[derive(sqlx::FromRow)]+pub struct CallChannelRow {+ /// The channel the call belongs to.+ pub channel_id: Uuid,+ /// The share permission ID for this call.+ pub share_permission_id: String,+}++/// Look up a call's channel and share permission by call ID.+///+/// Checks both active calls and archived call records.+#[tracing::instrument(err, skip(pool))]+pub async fn get_call_channel(+ pool: &PgPool,+ call_id: &Uuid,+) -> Result<Option<CallChannelRow>, sqlx::Error> {+ sqlx::query_as::<_, CallChannelRow>(+ r#"+ SELECT channel_id, share_permission_id+ FROM calls+ WHERE id = $1+ UNION ALL+ SELECT channel_id, share_permission_id+ FROM call_records+ WHERE id = $1+ LIMIT 1+ "#,+ )+ .bind(call_id)+ .fetch_optional(pool)+ .await+}++/// Look up a call's channel and share permission by channel ID.+///+/// Checks both active calls and archived call records.+/// Active calls are checked first.+#[tracing::instrument(err, skip(pool))]+pub async fn get_call_channel_by_channel_id(+ pool: &PgPool,+ channel_id: &Uuid,+) -> Result<Option<CallChannelRow>, sqlx::Error> {+ sqlx::query_as::<_, CallChannelRow>(+ r#"+ SELECT channel_id, share_permission_id+ FROM calls+ WHERE channel_id = $1+ UNION ALL+ SELECT channel_id, share_permission_id+ FROM call_records+ WHERE channel_id = $1+ ORDER BY channel_id+ LIMIT 1+ "#,+ )+ .bind(channel_id)+ .fetch_optional(pool)+ .await+}diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rsindex 28d4928f60..e22060b488 100644--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/mod.rs@@ -2,6 +2,7 @@//!//! Each module contains a single query function for checking access to a specific entity type.+pub mod call_channel;pub mod channel_membership;pub mod channel_role;pub mod chat_access;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260402170841_call_share_permissions.sql b/rust/cloud-storage/macro_db_client/migrations/20260402170841_call_share_permissions.sqlnew file mode 100644index 0000000000..ec372f8349--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260402170841_call_share_permissions.sql@@ -0,0 +1,20 @@+-- Add the share permission to all ephemeral calls+ALTER TABLE calls ADD COLUMN share_permission_id TEXT NOT NULL REFERENCES "SharePermission"(id) ON DELETE CASCADE;++-- Add the share permission to all calls records+ALTER TABLE call_records ADD COLUMN share_permission_id TEXT NOT NULL REFERENCES "SharePermission"(id) ON DELETE CASCADE;++-- Automatically delete the share permission of the call_record when a call record is deleted+-- We only want this for call_records as they are the permanent record of a call not the ephemeral one for active calls+CREATE FUNCTION delete_share_permission_on_call_record_delete()+RETURNS TRIGGER AS $$+BEGIN+ DELETE FROM "SharePermission" WHERE id = OLD.share_permission_id;+ RETURN OLD;+END;+$$ LANGUAGE plpgsql;++CREATE TRIGGER trg_delete_share_permission_call_record+BEFORE DELETE ON call_records+FOR EACH ROW+EXECUTE FUNCTION delete_share_permission_on_call_record_delete();