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(entity-access): Teams support (#3184)
Evan Hutnikc3b9e3bd0464
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermission.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermission.tsindex c2700df3a0..03f863e855 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermission.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermission.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/import type { EntityPermissionOneOf } from './entityPermissionOneOf';+import type { EntityPermissionOneOfFive } from './entityPermissionOneOfFive';import type { EntityPermissionOneOfThree } from './entityPermissionOneOfThree';/**@@ -15,4 +16,5 @@ Channels use participant roles.*/export type EntityPermission =| EntityPermissionOneOf- | EntityPermissionOneOfThree;+ | EntityPermissionOneOfThree+ | EntityPermissionOneOfFive;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfFive.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfFive.tsnew file mode 100644index 0000000000..1313527843--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfFive.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { EntityPermissionOneOfFiveType } from './entityPermissionOneOfFiveType';+import type { TeamRole } from './teamRole';++/**+ * Permission for team-based entities.+ */+export type EntityPermissionOneOfFive = {+ /** The role the user has in the team. */+ role: TeamRole;+ type: EntityPermissionOneOfFiveType;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfFiveType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfFiveType.tsnew file mode 100644index 0000000000..025be0633b--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityPermissionOneOfFiveType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type EntityPermissionOneOfFiveType =+ (typeof EntityPermissionOneOfFiveType)[keyof typeof EntityPermissionOneOfFiveType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const EntityPermissionOneOfFiveType = {+ team_role: 'team_role',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex da8ec9b5bc..d3feae3cfe 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -323,6 +323,8 @@ export * from './entityFilterAst';export * from './entityFilters';export * from './entityPermission';export * from './entityPermissionOneOf';+export * from './entityPermissionOneOfFive';+export * from './entityPermissionOneOfFiveType';export * from './entityPermissionOneOfThree';export * from './entityPermissionOneOfThreeType';export * from './entityPermissionOneOfType';@@ -650,6 +652,7 @@ export * from './successResponse';export * from './syncServiceVersionID';export * from './taskFilters';export * from './taskFiltersIncludeCbmAtmNc';+export * from './teamRole';export * from './thread';export * from './threadCreatedAt';export * from './threadDeletedAt';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/teamRole.ts b/js/app/packages/service-clients/service-storage/generated/schemas/teamRole.tsnew file mode 100644index 0000000000..9b4f99744f--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/teamRole.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The role a user has within a team.++Ordered least to most privileged so comparisons reflect access strength.+ */+export type TeamRole = (typeof TeamRole)[keyof typeof TeamRole];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TeamRole = {+ member: 'member',+ admin: 'admin',+ owner: 'owner',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex b9e0ae9a20..eb767779dc 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -3731,6 +3731,16 @@ export const getEntityPermissionResponse = zodtype: zod.enum(['channel_role']),}).describe('Permission for channel-based entities.'),+ zod+ .object({+ role: zod+ .enum(['member', 'admin', 'owner'])+ .describe(+ 'The role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.'+ ),+ type: zod.enum(['team_role']),+ })+ .describe('Permission for team-based entities.'),]).describe("A user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use participant roles."diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex f6f203d0a3..1ddea63719 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -8598,6 +8598,21 @@"enum": ["channel_role"]}}+ },+ {+ "type": "object",+ "description": "Permission for team-based entities.",+ "required": ["role", "type"],+ "properties": {+ "role": {+ "$ref": "#/components/schemas/TeamRole",+ "description": "The role the user has in the team."+ },+ "type": {+ "type": "string",+ "enum": ["team_role"]+ }+ }}],"description": "A user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use participant roles."@@ -12057,6 +12072,11 @@}}},+ "TeamRole": {+ "type": "string",+ "description": "The role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.",+ "enum": ["member", "admin", "owner"]+ },"Thread": {"type": "object","required": ["threadId", "owner", "resolved", "documentId"],diff --git a/rust/cloud-storage/.sqlx/query-ecd16f9e0fd909784c5831fd73e705b6f12c716417f4d337aa68f73fb05a6dd1.json b/rust/cloud-storage/.sqlx/query-ecd16f9e0fd909784c5831fd73e705b6f12c716417f4d337aa68f73fb05a6dd1.jsonnew file mode 100644index 0000000000..30ceb7ad1d--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-ecd16f9e0fd909784c5831fd73e705b6f12c716417f4d337aa68f73fb05a6dd1.json@@ -0,0 +1,39 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT team_id, team_role as \"role!: TeamRole\"\n FROM team_user\n WHERE user_id = $1\n ORDER BY team_role DESC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "role!: TeamRole",+ "type_info": {+ "Custom": {+ "name": "team_role",+ "kind": {+ "Enum": [+ "member",+ "admin",+ "owner"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "ecd16f9e0fd909784c5831fd73e705b6f12c716417f4d337aa68f73fb05a6dd1"+}diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rsindex 9f356696d8..a36ea70b01 100644--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs@@ -13,7 +13,7 @@ use axum::{use entity_access::domain::{models::{AccessError, AccessLevel, EntityAccessReceipt, EntityPermission, EntityType,- ParticipantRole as EntityParticipantRole, RequiredPermission,+ ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,},ports::EntityAccessService,};@@ -159,6 +159,13 @@ impl EntityAccessService for TestAccessService {) -> Result<Option<entity_access::domain::models::CallChannelInfo>, AccessError> {unimplemented!()}++ async fn get_user_team(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ ) -> Result<Option<UserTeamInfo>, 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 dbdb24e059..6482a5c6b2 100644--- a/rust/cloud-storage/chat/src/inbound/test.rs+++ b/rust/cloud-storage/chat/src/inbound/test.rs@@ -17,7 +17,7 @@ use crate::domain::ports::ChatService;use ai_toolset::tool_object::UserToolResponse;use entity_access::domain::models::{AccessError, AccessLevel, EditAccessLevel, EntityAccessReceipt, EntityPermission, EntityType,- OwnerAccessLevel, ViewAccessLevel,+ OwnerAccessLevel, UserTeamInfo, ViewAccessLevel,};use entity_access::domain::ports::EntityAccessService;use macro_user_id::lowercased::Lowercase;@@ -423,6 +423,13 @@ impl EntityAccessService for MockAccessService {{unimplemented!()}++ async fn get_user_team(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ ) -> std::result::Result<Option<UserTeamInfo>, AccessError> {+ unimplemented!()+ }}fn user_extension() -> Extension<UserContext> {diff --git a/rust/cloud-storage/entity_access/fixtures/user_team.sql b/rust/cloud-storage/entity_access/fixtures/user_team.sqlnew file mode 100644index 0000000000..4cae6c7281--- /dev/null+++ b/rust/cloud-storage/entity_access/fixtures/user_team.sql@@ -0,0 +1,57 @@+-- SQL fixture for team_access::get_user_team tests.+--+-- Covers:+-- - Each team_role (member / admin / owner)+-- - A user with no team membership+-- - A user in two teams with different roles (defensive highest-role case)+-- - A second team scoped to a different user (isolation case)++------------------------------------------------------------+-- macro_user (referenced by "User".macro_user_id)+------------------------------------------------------------++INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES+ ('00000000-0000-0000-0000-000000000a01', 'alpha_owner', '[email protected]', 'cus_alpha_owner'),+ ('00000000-0000-0000-0000-000000000a02', 'beta_owner', '[email protected]', 'cus_beta_owner'),+ ('00000000-0000-0000-0000-000000000a03', 'member', '[email protected]', 'cus_member'),+ ('00000000-0000-0000-0000-000000000a04', 'admin', '[email protected]', 'cus_admin'),+ ('00000000-0000-0000-0000-000000000a05', 'owner', '[email protected]', 'cus_owner'),+ ('00000000-0000-0000-0000-000000000a06', 'multi', '[email protected]', 'cus_multi'),+ ('00000000-0000-0000-0000-000000000a07', 'noteam', '[email protected]', 'cus_noteam');++------------------------------------------------------------+-- Users+------------------------------------------------------------++INSERT INTO "User" (id, email, macro_user_id) VALUES+ ('macro|[email protected]', '[email protected]', '00000000-0000-0000-0000-000000000a01'),+ ('macro|[email protected]', '[email protected]', '00000000-0000-0000-0000-000000000a02'),+ ('macro|[email protected]', '[email protected]', '00000000-0000-0000-0000-000000000a03'),+ ('macro|[email protected]', '[email protected]', '00000000-0000-0000-0000-000000000a04'),+ ('macro|[email protected]', '[email protected]', '00000000-0000-0000-0000-000000000a05'),+ ('macro|[email protected]', '[email protected]', '00000000-0000-0000-0000-000000000a06'),+ ('macro|[email protected]', '[email protected]', '00000000-0000-0000-0000-000000000a07');++------------------------------------------------------------+-- Teams+------------------------------------------------------------++INSERT INTO team (id, name, owner_id) VALUES+ ('00000000-0000-0000-0000-0000000ea001', 'Team Alpha', 'macro|[email protected]'),+ ('00000000-0000-0000-0000-0000000ea002', 'Team Beta', 'macro|[email protected]');++------------------------------------------------------------+-- Memberships+-- Team Alpha: one user per role+-- Team Beta: one user — used to verify we return the actual team_id+-- (not just the first or default)+--+-- Note: the schema enforces UNIQUE (user_id) on team_user, so a user can only+-- belong to one team at a time.+------------------------------------------------------------++INSERT INTO team_user (user_id, team_id, team_role) VALUES+ ('macro|[email protected]', '00000000-0000-0000-0000-0000000ea001', 'member'),+ ('macro|[email protected]', '00000000-0000-0000-0000-0000000ea001', 'admin'),+ ('macro|[email protected]', '00000000-0000-0000-0000-0000000ea001', 'owner'),+ ('macro|[email protected]', '00000000-0000-0000-0000-0000000ea002', 'owner');diff --git a/rust/cloud-storage/entity_access/src/domain/models.rs b/rust/cloud-storage/entity_access/src/domain/models.rsindex a9668b49a9..b19fd5784c 100644--- a/rust/cloud-storage/entity_access/src/domain/models.rs+++ b/rust/cloud-storage/entity_access/src/domain/models.rs@@ -26,6 +26,39 @@ pub enum ParticipantRole {Member,}+/// The role a user has within a team.+///+/// Ordered least to most privileged so comparisons reflect access strength.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[cfg_attr(feature = "outbound", derive(sqlx::Type))]+#[cfg_attr(+ feature = "outbound",+ sqlx(type_name = "\"team_role\"", rename_all = "lowercase")+)]+#[serde(rename_all = "snake_case")]+pub enum TeamRole {+ /// Regular team member.+ #[default]+ Member,+ /// Team administrator.+ Admin,+ /// Team owner with full control.+ Owner,+}++/// Team member role.+#[derive(Debug)]+pub struct MemberTeamRole;++/// Team administrator role.+#[derive(Debug)]+pub struct AdminTeamRole;++/// Team owner role with full control.+#[derive(Debug)]+pub struct OwnerTeamRole;+/// Channel owner role with full control#[derive(Debug)]pub struct OwnerParticipantRole;@@ -62,6 +95,11 @@ pub enum EntityPermission {/// The role the user has in the channel.role: ParticipantRole,},+ /// Permission for team-based entities.+ TeamRole {+ /// The role the user has in the team.+ role: TeamRole,+ },}impl EntityPermission {@@ -96,6 +134,14 @@ impl EntityPermission {)}+ /// Returns whether this permission grants at least the requested team role.+ pub fn allows_team_role(&self, required: TeamRole) -> bool {+ matches!(+ self,+ EntityPermission::TeamRole { role } if *role >= required+ )+ }+/// Returns whether this permission satisfies the provided marker type.pub fn satisfies<T: RequiredPermission>(&self) -> bool {T::is_satisfied_by(self)@@ -144,6 +190,33 @@ impl RequiredPermission for MemberParticipantRole {}}+impl RequiredPermission for MemberTeamRole {+ fn is_satisfied_by(permission: &EntityPermission) -> bool {+ permission.allows_team_role(TeamRole::Member)+ }+}++impl RequiredPermission for AdminTeamRole {+ fn is_satisfied_by(permission: &EntityPermission) -> bool {+ permission.allows_team_role(TeamRole::Admin)+ }+}++impl RequiredPermission for OwnerTeamRole {+ fn is_satisfied_by(permission: &EntityPermission) -> bool {+ permission.allows_team_role(TeamRole::Owner)+ }+}++/// The team a user belongs to and the role they hold in it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct UserTeamInfo {+ /// The team's id.+ pub team_id: Uuid,+ /// The user's role within the team.+ pub role: TeamRole,+}+/// Result of resolving a user's role in a channel.////// Distinguishes between "user has a role", "channel exists but userdiff --git a/rust/cloud-storage/entity_access/src/domain/ports.rs b/rust/cloud-storage/entity_access/src/domain/ports.rsindex ec05fbc55b..79b0f6496e 100644--- a/rust/cloud-storage/entity_access/src/domain/ports.rs+++ b/rust/cloud-storage/entity_access/src/domain/ports.rs@@ -5,7 +5,7 @@use super::models::EntityType;use crate::domain::models::{AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, EntityAccessReceipt,- EntityPermission, RequiredPermission,+ EntityPermission, RequiredPermission, UserTeamInfo,};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};use std::future::Future;@@ -103,6 +103,16 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {&self,channel_id: &Uuid,) -> impl Future<Output = Result<Option<CallChannelInfo>, AccessError>> + Send;++ /// Look up the single team a user belongs to and the role they hold.+ ///+ /// Returns `None` if the user does not belong to any team. If the user is in+ /// more than one team (which is not expected), the highest-privileged role+ /// is returned.+ fn get_user_team(+ &self,+ user_id: &MacroUserId<Lowercase<'_>>,+ ) -> impl Future<Output = Result<Option<UserTeamInfo>, AccessError>> + Send;}/// Service for checking entity access levels.@@ -195,4 +205,12 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {&self,channel_id: &Uuid,) -> impl Future<Output = Result<Option<CallChannelInfo>, AccessError>> + Send;++ /// Look up the team a user belongs to and the role they hold in it.+ ///+ /// Returns `None` if the user has no team membership.+ fn get_user_team(+ &self,+ user_id: &MacroUserId<Lowercase<'_>>,+ ) -> impl Future<Output = Result<Option<UserTeamInfo>, AccessError>> + Send;}diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rsindex 92cf41e019..5fc5877169 100644--- a/rust/cloud-storage/entity_access/src/domain/service.rs+++ b/rust/cloud-storage/entity_access/src/domain/service.rs@@ -6,7 +6,7 @@ use std::str::FromStr;use crate::domain::{models::{AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, Entity, EntityAccessAuth,- EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission,+ EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission, UserTeamInfo,},ports::{AccessRepository, EntityAccessService},};@@ -271,6 +271,14 @@ where) -> Result<Option<CallChannelInfo>, AccessError> {self.repo.get_call_channel_by_channel_id(channel_id).await}++ #[tracing::instrument(err, skip(self))]+ async fn get_user_team(+ &self,+ user_id: &MacroUserId<Lowercase<'_>>,+ ) -> Result<Option<UserTeamInfo>, AccessError> {+ self.repo.get_user_team(user_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 2ea587a096..9fc541bb32 100644--- a/rust/cloud-storage/entity_access/src/domain/service/test.rs+++ b/rust/cloud-storage/entity_access/src/domain/service/test.rs@@ -4,7 +4,7 @@use super::*;use crate::domain::models::{AdminParticipantRole, CallChannelInfo, CommentAccessLevel, EditAccessLevel, EntityAccessAuth,- MemberParticipantRole, OwnerParticipantRole, ParticipantRole, ViewAccessLevel,+ MemberParticipantRole, OwnerParticipantRole, ParticipantRole, UserTeamInfo, ViewAccessLevel,};use macro_user_id::user_id::MacroUserIdStr;use models_permissions::share_permission::access_level::OwnerAccessLevel;@@ -27,6 +27,7 @@ struct MockRepo {thread_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,channel_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,call_channel: Arc<Mutex<Option<CallChannelInfo>>>,+ user_team: Arc<Mutex<Option<UserTeamInfo>>>,}impl MockRepo {@@ -45,6 +46,7 @@ impl MockRepo {thread_users: Arc::new(Mutex::new(vec![])),channel_users: Arc::new(Mutex::new(vec![])),call_channel: Arc::new(Mutex::new(None)),+ user_team: Arc::new(Mutex::new(None)),}}@@ -197,6 +199,13 @@ impl AccessRepository for MockRepo {) -> Result<Option<CallChannelInfo>, AccessError> {Ok(self.call_channel.lock().await.clone())}++ async fn get_user_team(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ ) -> Result<Option<UserTeamInfo>, AccessError> {+ Ok(*self.user_team.lock().await)+ }}fn test_user_id() -> MacroUserIdStr<'static> {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 06d6ca100c..6203a6d35b 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@@ -11,6 +11,7 @@ mod entity_permission;mod history;mod pin;mod project;+mod team;mod thread;pub use call::{CallAccessLevelExtractor, CallWithChannelIdAccessLevelExtractor};@@ -21,6 +22,7 @@ pub use entity_permission::EntityPermissionExtractor;pub use history::HistoryAccessExtractor;pub use pin::PinAccessLevelExtractor;pub use project::{ProjectAccessLevelExtractor, ProjectBodyAccessLevelExtractor};+pub use team::OptionalMacroUserTeamExtractor;pub use thread::ThreadAccessLevelExtractor;use crate::domain::models::{AccessError, AccessLevel};diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/team.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/team.rsnew file mode 100644index 0000000000..0c9a8616d4--- /dev/null+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/team.rs@@ -0,0 +1,93 @@+//! Team access extractor.+//!+//! Unlike the other access extractors, this one does not take a team id from+//! the path — it resolves whichever team the authenticated user belongs to+//! and reports the role they hold.++use std::marker::PhantomData;+use std::sync::Arc;++use axum::{+ RequestPartsExt,+ extract::{FromRef, FromRequestParts},+ http::request::Parts,+};++use super::{ExtractorError, RequiredPermission};+use crate::domain::{+ models::{Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType},+ ports::EntityAccessService,+};+use model_user::axum_extractor::MacroUserExtractor;++/// Resolves the authenticated user's team membership and exposes the receipt+/// when the user satisfies the required permission `T`.+///+/// `entity_access_receipt` is:+/// - `Some(receipt)` if the user belongs to a team and their role satisfies `T`+/// - `None` if the user belongs to a team but their role does not satisfy `T`+/// - `None` if the user belongs to no team+///+/// Returns `ExtractorError::Unauthorized` if there is no authenticated user.+#[derive(Debug)]+pub struct OptionalMacroUserTeamExtractor<T: RequiredPermission, Svc> {+ /// The entity access receipt, if the user has a qualifying team membership.+ pub entity_access_receipt: Option<EntityAccessReceipt<T>>,+ _marker: PhantomData<(T, Svc)>,+}++impl<T, S, Svc> FromRequestParts<S> for OptionalMacroUserTeamExtractor<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 MacroUserExtractor { macro_user_id, .. } = parts+ .extract()+ .await+ .map_err(|_| ExtractorError::Unauthorized)?;++ let team_info = service+ .get_user_team(¯o_user_id)+ .await+ .map_err(ExtractorError::from)?;++ let Some(team_info) = team_info else {+ return Ok(Self {+ entity_access_receipt: None,+ _marker: PhantomData,+ });+ };++ let permission = EntityPermission::TeamRole {+ role: team_info.role,+ };++ if !permission.satisfies::<T>() {+ return Ok(Self {+ entity_access_receipt: None,+ _marker: PhantomData,+ });+ }++ Ok(Self {+ entity_access_receipt: Some(EntityAccessReceipt {+ entity: Entity {+ entity_id: team_info.team_id.to_string(),+ entity_type: EntityType::Team,+ },+ auth: EntityAccessAuth::Authenticated(macro_user_id),+ entity_permission: permission,+ _marker: PhantomData,+ }),+ _marker: PhantomData,+ })+ }+}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 6c19ec2fe2..9bb0ecf3dd 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,9 @@mod queries;use crate::domain::{- models::{AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, EntityType},+ models::{+ AccessError, AccessLevel, CallChannelInfo, ChannelRoleResult, EntityType, UserTeamInfo,+ },ports::AccessRepository,};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};@@ -188,4 +190,12 @@ impl AccessRepository for PgAccessRepository {share_permission_id: r.share_permission_id,}))}++ #[tracing::instrument(err, skip(self))]+ async fn get_user_team(+ &self,+ user_id: &MacroUserId<Lowercase<'_>>,+ ) -> Result<Option<UserTeamInfo>, AccessError> {+ Ok(queries::team_access::get_user_team(&self.pool, user_id).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 4e8a299fa8..c7b9bfab63 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@@ -23,6 +23,7 @@ pub mod channel_users;pub mod chat_access;pub mod document_access;pub mod project_access;+pub mod team_access;pub mod thread_access;/// Type safety for source ids for entity_access tablediff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/team_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/team_access.rsnew file mode 100644index 0000000000..3bf49b74f9--- /dev/null+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/team_access.rs@@ -0,0 +1,39 @@+//! Query for resolving the team a user belongs to and the role they hold.++#[cfg(test)]+mod test;++use crate::domain::models::{TeamRole, UserTeamInfo};+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use sqlx::PgPool;++/// Look up the team a user belongs to and the role they hold.+///+/// Users are expected to belong to at most one team, but this query is+/// defensive — if `team_user` returns multiple rows the highest-privileged+/// role wins. Postgres orders the `team_role` enum as+/// `member < admin < owner`, so `ORDER BY team_role DESC` returns the+/// strongest membership first.+#[tracing::instrument(err, skip(pool))]+pub async fn get_user_team(+ pool: &PgPool,+ user_id: &MacroUserId<Lowercase<'_>>,+) -> Result<Option<UserTeamInfo>, sqlx::Error> {+ let row = sqlx::query!(+ r#"+ SELECT team_id, team_role as "role!: TeamRole"+ FROM team_user+ WHERE user_id = $1+ ORDER BY team_role DESC+ LIMIT 1+ "#,+ user_id.as_ref(),+ )+ .fetch_optional(pool)+ .await?;++ Ok(row.map(|r| UserTeamInfo {+ team_id: r.team_id,+ role: r.role,+ }))+}diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/team_access/test.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/team_access/test.rsnew file mode 100644index 0000000000..24df999a12--- /dev/null+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/team_access/test.rs@@ -0,0 +1,115 @@+#[allow(unused_imports)]+use super::*;+use crate::domain::models::TeamRole;+use anyhow::Result;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserIdStr;+use sqlx::PgPool;+use uuid::Uuid;++const TEAM_ALPHA: &str = "00000000-0000-0000-0000-0000000ea001";+const TEAM_BETA: &str = "00000000-0000-0000-0000-0000000ea002";++fn user(s: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(s.to_string()).unwrap()+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../../fixtures", scripts("user_team"))+)]+async fn returns_none_when_user_has_no_team_membership(pool: PgPool) -> Result<()> {+ let user_id = user("macro|[email protected]");++ let result = get_user_team(&pool, &user_id).await?;++ assert_eq!(result, None);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../../fixtures", scripts("user_team"))+)]+async fn returns_none_when_user_does_not_exist(pool: PgPool) -> Result<()> {+ let user_id = user("macro|[email protected]");++ let result = get_user_team(&pool, &user_id).await?;++ assert_eq!(result, None);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../../fixtures", scripts("user_team"))+)]+async fn returns_member_role_for_member(pool: PgPool) -> Result<()> {+ let user_id = user("macro|[email protected]");++ let result = get_user_team(&pool, &user_id).await?.expect("team info");++ assert_eq!(result.team_id, Uuid::parse_str(TEAM_ALPHA)?);+ assert_eq!(result.role, TeamRole::Member);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../../fixtures", scripts("user_team"))+)]+async fn returns_admin_role_for_admin(pool: PgPool) -> Result<()> {+ let user_id = user("macro|[email protected]");++ let result = get_user_team(&pool, &user_id).await?.expect("team info");++ assert_eq!(result.team_id, Uuid::parse_str(TEAM_ALPHA)?);+ assert_eq!(result.role, TeamRole::Admin);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../../fixtures", scripts("user_team"))+)]+async fn returns_owner_role_for_owner(pool: PgPool) -> Result<()> {+ let user_id = user("macro|[email protected]");++ let result = get_user_team(&pool, &user_id).await?.expect("team info");++ assert_eq!(result.team_id, Uuid::parse_str(TEAM_ALPHA)?);+ assert_eq!(result.role, TeamRole::Owner);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../../fixtures", scripts("user_team"))+)]+async fn returns_team_id_of_the_users_actual_team(pool: PgPool) -> Result<()> {+ // `[email protected]` is the sole member of Team Beta — verifies the query+ // returns the user's real team_id rather than e.g. the first team in the+ // table (Team Alpha).+ let user_id = user("macro|[email protected]");++ let result = get_user_team(&pool, &user_id).await?.expect("team info");++ assert_eq!(result.team_id, Uuid::parse_str(TEAM_BETA)?);+ assert_eq!(result.role, TeamRole::Owner);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../../fixtures", scripts("user_team"))+)]+async fn does_not_leak_other_users_team_memberships(pool: PgPool) -> Result<()> {+ // alpha_owner is referenced as Team Alpha's `owner_id` but has no team_user+ // row — they should not be reported as a team member.+ let user_id = user("macro|[email protected]");++ let result = get_user_team(&pool, &user_id).await?;++ assert_eq!(result, None);+ Ok(())+}