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
fix acl in properties (#4615)
Sean Ayee242dea69c06
diff --git a/js/app/packages/service-clients/service-properties/openapi.json b/js/app/packages/service-clients/service-properties/openapi.jsonindex 804974123c..3b9ef253ea 100644--- a/js/app/packages/service-clients/service-properties/openapi.json+++ b/js/app/packages/service-clients/service-properties/openapi.json@@ -498,6 +498,9 @@"400": {"description": "Invalid request or entity type"},+ "403": {+ "description": "No edit access to the entity"+ },"404": {"description": "Entity or property not found"},@@ -648,7 +651,7 @@"description": "Entity property removed successfully"},"403": {- "description": "Property is required and cannot be removed"+ "description": "Property is required and cannot be removed, or no edit access"},"404": {"description": "Entity property not found"diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 490a9e463b..503a39e812 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3286,6 +3286,7 @@ dependencies = ["chrono","entity_access","macro_db_migrator",+ "macro_user_id","macro_uuid","model-error-response","model_user",@@ -5822,6 +5823,7 @@ dependencies = ["serde_json","soup","tokio",+ "tracing","uuid","workspace-hack",]diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex 339f827242..099fa752f6 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -231,14 +231,13 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)?;+ let access = self+ .properties+ .mint_edit_receipt(&user_id, entity_id, models_properties::EntityType::Task)+ .await?;+self.properties- .set_entity_property(- &user_id,- entity_id,- models_properties::EntityType::Task,- property_definition_id,- value,- )+ .set_entity_property(&access, property_definition_id, value).await.map_err(Into::into)}diff --git a/rust/cloud-storage/crm/Cargo.toml b/rust/cloud-storage/crm/Cargo.tomlindex d19330a03a..d0b62312d0 100644--- a/rust/cloud-storage/crm/Cargo.toml+++ b/rust/cloud-storage/crm/Cargo.toml@@ -8,6 +8,7 @@ version = "0.1.0"ai_tools = ["dep:ai_toolset","dep:async-trait",+ "dep:macro_user_id","dep:models_properties","dep:properties","dep:schemars",@@ -47,6 +48,7 @@ entity_access = { path = "../entity_access", default-features = false }# AI toolset dependenciesai_toolset = { path = "../ai_toolset", optional = true }async-trait = { workspace = true, optional = true }+macro_user_id = { path = "../macro_user_id", optional = true }models_properties = { path = "../models_properties", optional = true }properties = { path = "../properties", default-features = false, features = ["ports",diff --git a/rust/cloud-storage/crm/src/inbound/toolset/get_company.rs b/rust/cloud-storage/crm/src/inbound/toolset/get_company.rsindex 301e285272..76e1c21601 100644--- a/rust/cloud-storage/crm/src/inbound/toolset/get_company.rs+++ b/rust/cloud-storage/crm/src/inbound/toolset/get_company.rs@@ -4,7 +4,10 @@ use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolRuse async_trait::async_trait;use chrono::{DateTime, Utc};use entity_access::domain::{- models::{AccessError, Entity, EntityAccessReceipt, EntityType, ViewAccessLevel},+ models::{+ AccessError, Entity, EntityAccessReceipt, EntityPermission, EntityType, TeamRole,+ ViewAccessLevel,+ },ports::EntityAccessService,};use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;@@ -202,17 +205,42 @@ where.map_err(crm_error)?.ok_or_else(|| crm_error(CrmError::CompanyNotFoundForTeam))?;+ // Asserted rather than minted: view access to this company was just+ // verified above via `get_crm_entity_permission_with_team`.+ let properties_access =+ properties::PropertiesAccessReceipt::dangerously_assert_authenticated_user(+ request_context.user_id.clone(),+ &company_id,+ PropertyEntityType::Company,+ );let properties = service_context.properties- .get_entity_properties_with_definitions(&company_id, PropertyEntityType::Company)+ .get_entity_properties_with_definitions(&properties_access).await.map_err(|e| ToolCallError {description: "failed to load company properties".to_string(),internal_error: e.into(),})?;+ // `get_crm_entity_permission_with_team` resolved `team_id` from the+ // ownership row that granted access, so the caller's membership of+ // that team is proven; Member is the floor every member satisfies.+ let team_receipt = EntityAccessReceipt::try_new_authenticated_user(+ request_context.user_id.clone(),+ Entity {+ entity_id: team_id.to_string(),+ entity_type: EntityType::Team,+ },+ EntityPermission::TeamRole {+ role: TeamRole::Member,+ },+ )+ .map_err(|e| ToolCallError {+ description: "failed to verify access to the CRM company".to_string(),+ internal_error: e.into(),+ })?;let stage_catalog =- load_stage_option_catalog(&*service_context.properties, team_id).await?;+ load_stage_option_catalog(&*service_context.properties, &team_receipt).await?;let crm_props = extract_company_crm_props(&properties, &stage_catalog);let name = record.name.clone();diff --git a/rust/cloud-storage/crm/src/inbound/toolset/list_companies.rs b/rust/cloud-storage/crm/src/inbound/toolset/list_companies.rsindex 21340d0ee6..1bddc1e972 100644--- a/rust/cloud-storage/crm/src/inbound/toolset/list_companies.rs+++ b/rust/cloud-storage/crm/src/inbound/toolset/list_companies.rs@@ -16,7 +16,7 @@ use crate::domain::{};use super::{- CrmToolContext, ToolCompanyStage, caller_team_receipt, company_entity_refs, crm_error,+ CrmToolContext, ToolCompanyStage, caller_team_receipt, company_view_receipts, crm_error,extract_company_crm_props, load_stage_option_catalog,};@@ -125,7 +125,6 @@ wherelet (team_receipt, role) =caller_team_receipt(&*service_context.entity_access_service, &request_context).await?;- let team_id = team_receipt.team_id();let include_hidden = self.include_hidden.unwrap_or(false);if include_hidden && !matches!(role, TeamRole::Admin | TeamRole::Owner) {@@ -188,7 +187,7 @@ where}let stage_catalog =- load_stage_option_catalog(&*service_context.properties, team_id).await?;+ load_stage_option_catalog(&*service_context.properties, team_receipt.receipt()).await?;// Resolve the stage filter to option ids up front so an unknown// stage fails with an actionable error instead of an empty list.@@ -218,7 +217,12 @@ where// Teams with customized pipelines store stage values under a// team-scoped "Stage" definition rather than the system one, so// include those definition ids in the fetch filter too.- let entity_refs = company_entity_refs(companies.iter().map(|c| c.company.id));+ // Access to these companies is proven by the caller's team receipt:+ // the list is the caller's own team's CRM listing.+ let company_access = company_view_receipts(+ &request_context.user_id,+ companies.iter().map(|c| c.company.id),+ );let mut property_ids = vec![SystemPropertyKey::STAGE_UUID,SystemPropertyKey::COMPANY_OWNER_UUID,@@ -227,7 +231,7 @@ whereproperty_ids.extend_from_slice(stage_catalog.team_stage_definition_ids());let properties_map = service_context.properties- .get_bulk_entity_properties(entity_refs, property_ids)+ .get_bulk_entity_properties(&company_access, property_ids).await.map_err(|e| ToolCallError {description: "failed to load company properties".to_string(),diff --git a/rust/cloud-storage/crm/src/inbound/toolset/mod.rs b/rust/cloud-storage/crm/src/inbound/toolset/mod.rsindex eec1d3b159..188f9333bd 100644--- a/rust/cloud-storage/crm/src/inbound/toolset/mod.rs+++ b/rust/cloud-storage/crm/src/inbound/toolset/mod.rs@@ -169,18 +169,18 @@ impl StageOptionCatalog {}}-/// Load the stage option catalog for `team_id`: options of the system-/// Stage definition (id `00000001-0000-0000-0000-000000000010`) plus any-/// team-scoped select definition named "Stage".+/// Load the stage option catalog for the team proven by `team`: options of+/// the system Stage definition (id `00000001-0000-0000-0000-000000000010`)+/// plus any team-scoped select definition named "Stage".pub(crate) async fn load_stage_option_catalog<PSvc>(properties: &PSvc,- team_id: Uuid,+ team: &properties::TeamReceipt,) -> Result<StageOptionCatalog, ToolCallError>wherePSvc: PropertiesService,{let defs = properties- .list_property_definitions_with_options(Some(team_id), None, true, None)+ .list_property_definitions_with_options(Some(team), None, true, None).await.map_err(|e| ToolCallError {description: "failed to load the team's stage options".to_string(),@@ -297,17 +297,23 @@ pub(crate) fn extract_company_crm_props(out}-/// Entity references for a batch of company ids, in `entity_properties`-/// terms (`entity_type = company`).-pub(crate) fn company_entity_refs(+/// Properties view receipts for a batch of company ids+/// (`entity_type = company`). Asserted rather than minted: callers only pass+/// company ids whose access was already verified through the CRM seam (the+/// caller's own team listing, or a company permission check) — re-checking+/// each company here would repeat that lookup per company.+pub(crate) fn company_view_receipts(+ user_id: ¯o_user_id::user_id::MacroUserIdStr<'static>,company_ids: impl IntoIterator<Item = Uuid>,-) -> Vec<models_properties::shared::EntityReference> {+) -> Vec<properties::ViewReceipt> {company_ids.into_iter()- .map(|id| models_properties::shared::EntityReference {- entity_type: PropertyEntityType::Company,- entity_id: id.to_string(),- specific_message_id: None,+ .map(|id| {+ properties::PropertiesAccessReceipt::dangerously_assert_authenticated_user(+ user_id.clone(),+ &id.to_string(),+ PropertyEntityType::Company,+ )}).collect()}diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rsindex 87d8a86b32..ae9e8a3387 100644--- a/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs@@ -104,10 +104,17 @@ pub async fn create_comment_handler(.map(|c| c.sender.as_ref().unwrap_or(&c.owner).clone()).collect();- let task_assignee_ids: Vec<String> = match properties_service- .get_system_property_value(+ // Server-side notification fan-out: read the task assignees+ // outside the commenting user's session. The comment itself was+ // already authorized by the document middleware.+ let task_properties_access =+ properties::PropertiesAccessReceipt::dangerously_assert_internal(&document_id,models_properties::EntityType::Task,+ );+ let task_assignee_ids: Vec<String> = match properties_service+ .get_system_property_value(+ &task_properties_access,SystemPropertyKey::Assignees,).awaitdiff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex a93d98c100..ec1f81073e 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -176,14 +176,13 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)?;+ let access = self+ .properties+ .mint_edit_receipt(&user_id, entity_id, models_properties::EntityType::Task)+ .await?;+self.properties- .set_entity_property(- &user_id,- entity_id,- models_properties::EntityType::Task,- property_definition_id,- value,- )+ .set_entity_property(&access, property_definition_id, value).await.map_err(Into::into)}diff --git a/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rs b/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rsindex 4f01b29587..469c4ba99b 100644--- a/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rs+++ b/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rs@@ -77,7 +77,10 @@ async fn handler(link_ids,team_receipt,})- .data(graphql_soup::entity_properties_loader(property_reader))+ .data(graphql_soup::entity_properties_loader(+ macro_user_id.clone(),+ property_reader,+ )).data(graphql_soup::entity_notifications_loader(macro_user_id,state.graphql_notification_reader.clone(),diff --git a/rust/cloud-storage/entity_access/src/domain/models.rs b/rust/cloud-storage/entity_access/src/domain/models.rsindex b61b717dc6..4830e4c584 100644--- a/rust/cloud-storage/entity_access/src/domain/models.rs+++ b/rust/cloud-storage/entity_access/src/domain/models.rs@@ -281,9 +281,10 @@ pub struct EntityAccessReceipt<T: RequiredPermission> {}impl<T: RequiredPermission> EntityAccessReceipt<T> {- /// Creates an access receipt for an authenticated user after validating the provided permission.- pub fn try_new_authenticated_user(- user_id: MacroUserIdStr<'static>,+ /// Creates an access receipt for the given auth after validating the+ /// provided permission against the required level `T`.+ pub fn try_new(+ auth: EntityAccessAuth,entity: Entity,entity_permission: EntityPermission,) -> Result<EntityAccessReceipt<T>, AccessError> {@@ -292,13 +293,26 @@ impl<T: RequiredPermission> EntityAccessReceipt<T> {}Ok(EntityAccessReceipt {- auth: EntityAccessAuth::Authenticated(user_id),+ auth,entity,entity_permission,_marker: PhantomData,})}+ /// Creates an access receipt for an authenticated user after validating the provided permission.+ pub fn try_new_authenticated_user(+ user_id: MacroUserIdStr<'static>,+ entity: Entity,+ entity_permission: EntityPermission,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ Self::try_new(+ EntityAccessAuth::Authenticated(user_id),+ entity,+ entity_permission,+ )+ }+/// get the authenticated user or errorpub fn get_authenticated_user(&self) -> Result<&MacroUserIdStr<'static>, AccessError> {match &self.auth {diff --git a/rust/cloud-storage/graphql_soup/Cargo.toml b/rust/cloud-storage/graphql_soup/Cargo.tomlindex ff29cd947e..406f53c513 100644--- a/rust/cloud-storage/graphql_soup/Cargo.toml+++ b/rust/cloud-storage/graphql_soup/Cargo.toml@@ -25,6 +25,7 @@ properties = { path = "../properties", default-features = false, features = ["ports",] }rootcause = { workspace = true }+tracing = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }soup = { path = "../soup", default-features = false, features = ["ports"] }diff --git a/rust/cloud-storage/graphql_soup/src/loaders.rs b/rust/cloud-storage/graphql_soup/src/loaders.rsindex 9427b215ee..6f36a7a51b 100644--- a/rust/cloud-storage/graphql_soup/src/loaders.rs+++ b/rust/cloud-storage/graphql_soup/src/loaders.rs@@ -2,7 +2,6 @@ use std::{collections::HashMap, str::FromStr, sync::Arc};use async_graphql::dataloader::{DataLoader, Loader};use macro_user_id::user_id::MacroUserIdStr;-use models_properties::EntityReference;use models_soup::SoupProperty;use notification::domain::models::{UserNotificationRow,@@ -38,9 +37,11 @@ impl EntityPropertiesKey {/// Object-safe reader used by GraphQL property edges.#[async_trait::async_trait]pub trait SoupPropertyEdgeReader: Send + Sync + 'static {- /// Load properties for the requested entity keys.+ /// Load properties for the requested entity keys on behalf of the given+ /// user. Entities the user cannot view yield an empty property list.async fn get_properties(&self,+ user_id: &MacroUserIdStr<'static>,keys: Vec<EntityPropertiesKey>,) -> Result<HashMap<EntityPropertiesKey, Vec<SoupProperty>>, rootcause::Report>;}@@ -52,6 +53,7 @@ where{async fn get_properties(&self,+ user_id: &MacroUserIdStr<'static>,keys: Vec<EntityPropertiesKey>,) -> Result<HashMap<EntityPropertiesKey, Vec<SoupProperty>>, rootcause::Report> {let mut result = keys@@ -60,30 +62,55 @@ where.map(|key| (key, Vec::new())).collect::<HashMap<_, _>>();- let entity_refs = keys- .iter()- .filter_map(|key| match key.property_entity_type() {- Ok(Some(entity_type)) => {- Some(Ok(EntityReference::new(key.entity_id.clone(), entity_type)))+ // Mint a view receipt per entity; entities the caller cannot view are+ // skipped and keep their empty property list.+ let mut receipts = Vec::with_capacity(keys.len());+ for key in &keys {+ let Some(entity_type) = key.property_entity_type()? else {+ continue;+ };+ match self+ .mint_view_receipt(Some(user_id), &key.entity_id, entity_type)+ .await+ {+ Ok(receipt) => receipts.push(receipt),+ Err(err) => {+ tracing::debug!(+ entity_id = %key.entity_id,+ entity_type = %key.entity_type,+ error = ?err,+ "user lacks view permission, skipping property edge"+ );}- Ok(None) => None,- Err(err) => Some(Err(err)),- })- .collect::<Result<Vec<_>, rootcause::Report>>()?;+ }+ }++ if receipts.is_empty() {+ return Ok(result);+ }let properties_by_entity = self- .get_entity_properties_batch(entity_refs)+ .get_bulk_entity_properties(&receipts, Vec::new()).await.map_err(|err| rootcause::report!(err))?;- for (key, properties) in properties_by_entity {- result.insert(- EntityPropertiesKey {- entity_id: key.entity_id,- entity_type: key.entity_type.to_string(),- },- properties.into_iter().map(SoupProperty::from).collect(),- );+ // Merge back under the original loader keys: the batch result is keyed+ // by the normalized entity type, which for alias keys ("email",+ // "email_thread", "crm_company") differs from the requested key.+ for key in &keys {+ let Ok(Some(entity_type)) = key.property_entity_type() else {+ continue;+ };+ let batch_key = properties::EntityPropertiesKey {+ entity_id: key.entity_id.clone(),+ entity_type,+ };+ if let Some(properties) = properties_by_entity.get(&batch_key) {+ result.insert(+ key.clone(),+ properties.iter().cloned().map(SoupProperty::from).collect(),+ );+ }}Ok(result)@@ -92,13 +119,14 @@ where/// DataLoader for entity property edges.pub struct EntityPropertiesLoader {+ user_id: MacroUserIdStr<'static>,reader: Arc<dyn SoupPropertyEdgeReader>,}impl EntityPropertiesLoader {- /// Create a new entity properties DataLoader.- pub fn new(reader: Arc<dyn SoupPropertyEdgeReader>) -> Self {- Self { reader }+ /// Create a new entity properties DataLoader scoped to the requesting user.+ pub fn new(user_id: MacroUserIdStr<'static>, reader: Arc<dyn SoupPropertyEdgeReader>) -> Self {+ Self { user_id, reader }}}@@ -111,17 +139,18 @@ impl Loader<EntityPropertiesKey> for EntityPropertiesLoader {keys: &[EntityPropertiesKey],) -> Result<HashMap<EntityPropertiesKey, Self::Value>, Self::Error> {self.reader- .get_properties(keys.to_vec())+ .get_properties(&self.user_id, keys.to_vec()).await.map_err(Arc::new)}}-/// Build a DataLoader for entity property edges.+/// Build a DataLoader for entity property edges scoped to the requesting user.pub fn entity_properties_loader(+ user_id: MacroUserIdStr<'static>,reader: Arc<dyn SoupPropertyEdgeReader>,) -> DataLoader<EntityPropertiesLoader> {- DataLoader::new(EntityPropertiesLoader::new(reader), tokio::spawn)+ DataLoader::new(EntityPropertiesLoader::new(user_id, reader), tokio::spawn)}/// Key for loading notifications attached to an entity.diff --git a/rust/cloud-storage/properties/Cargo.toml b/rust/cloud-storage/properties/Cargo.tomlindex fb396aec6f..d5dfb894d9 100644--- a/rust/cloud-storage/properties/Cargo.toml+++ b/rust/cloud-storage/properties/Cargo.toml@@ -16,7 +16,6 @@ ai_tools = [default = ["ai_tools", "inbound", "outbound", "ports"]inbound = ["dep:axum",- "dep:entity_access","dep:model","dep:serde","dep:serde_json",@@ -27,7 +26,6 @@ inbound = ["ports",]outbound = [- "dep:entity_access","dep:entity_access_db_utils","dep:futures","dep:macro_uuid",@@ -49,7 +47,7 @@ axum = { workspace = true, optional = true }chrono = { workspace = true }entity_access = { path = "../entity_access", default-features = false, features = ["ports",-], optional = true }+] }entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }futures = { workspace = true, optional = true }macro_user_id = { path = "../macro_user_id" }diff --git a/rust/cloud-storage/properties/src/domain/error.rs b/rust/cloud-storage/properties/src/domain/error.rsindex c2ac8e745a..dd6a788d2c 100644--- a/rust/cloud-storage/properties/src/domain/error.rs+++ b/rust/cloud-storage/properties/src/domain/error.rs@@ -37,6 +37,10 @@ pub enum PropertiesErr {#[error("Cannot modify system properties")]SystemPropertyNotModifiable,+ /// Team scope was requested by a caller with no team - maps to 403+ #[error("You must be on a team to use team-scoped properties")]+ TeamMembershipRequired,+/// Repository/database errors - maps to 500#[error(transparent)]Repo(#[from] anyhow::Error),diff --git a/rust/cloud-storage/properties/src/domain/model.rs b/rust/cloud-storage/properties/src/domain/model.rsindex 11f33ed199..19b349adfb 100644--- a/rust/cloud-storage/properties/src/domain/model.rs+++ b/rust/cloud-storage/properties/src/domain/model.rs@@ -1,5 +1,9 @@//! Domain models for properties.+use entity_access::domain::models::{+ AccessLevel, EditAccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission,+ EntityType as AccessEntityType, RequiredPermission, ViewAccessLevel,+};use macro_user_id::user_id::MacroUserIdStr;use models_properties::service::property_definition::PropertyDefinition;use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};@@ -7,6 +11,135 @@ use models_properties::service::property_value::PropertyValue;use models_properties::{DataType, EntityReference, EntityType, PropertyOwner};use uuid::Uuid;+/// Map a properties entity type onto the entity type used by the access+/// control system. Tasks are stored as documents, so the mapping collapses+/// Task into Document; [`PropertiesAccessReceipt`] preserves the original type.+pub fn access_entity_type(entity_type: EntityType) -> AccessEntityType {+ match entity_type {+ EntityType::Document => AccessEntityType::Document,+ EntityType::Chat => AccessEntityType::Chat,+ EntityType::Project => AccessEntityType::Project,+ EntityType::Thread => AccessEntityType::EmailThread,+ EntityType::Channel => AccessEntityType::Channel,+ // Tasks are stored as documents, so they share document permissions.+ EntityType::Task => AccessEntityType::Document,+ // CRM company access is resolved from the owning team's membership.+ EntityType::Company => AccessEntityType::CrmCompany,+ EntityType::User => AccessEntityType::User,+ }+}++/// Proof that a caller holds (at least) permission `T` on one entity.+///+/// Wraps the [`EntityAccessReceipt`] minted by the permission adapter together+/// with the original properties entity type, which the access-control mapping+/// loses (Task maps to Document). Every entity-scoped+/// [`PropertiesService`](super::service::PropertiesService) method takes one of+/// these, so an unchecked call cannot compile.+#[derive(Debug, Clone)]+pub struct PropertiesAccessReceipt<T: RequiredPermission> {+ receipt: EntityAccessReceipt<T>,+ entity_id: String,+ entity_type: EntityType,+}++/// Proof of view (or better) access to one entity.+pub type ViewReceipt = PropertiesAccessReceipt<ViewAccessLevel>;+/// Proof of edit (or better) access to one entity.+pub type EditReceipt = PropertiesAccessReceipt<EditAccessLevel>;++impl<T: RequiredPermission> PropertiesAccessReceipt<T> {+ /// Wrap a minted access receipt, keeping the original properties entity+ /// type. Only the permission adapter constructs these.+ pub(crate) fn new(receipt: EntityAccessReceipt<T>, entity_type: EntityType) -> Self {+ let entity_id = receipt.entity().entity_id.clone();+ Self {+ receipt,+ entity_id,+ entity_type,+ }+ }++ /// The entity this receipt grants access to.+ pub fn entity_id(&self) -> &str {+ &self.entity_id+ }++ /// The properties entity type this receipt grants access to.+ pub fn entity_type(&self) -> EntityType {+ self.entity_type+ }++ /// How the caller was authenticated.+ pub fn auth(&self) -> &EntityAccessAuth {+ self.receipt.auth()+ }++ /// The authenticated user this receipt was minted for, if any+ /// (`None` for internal and anonymous-public access).+ pub fn authenticated_user(&self) -> Option<&MacroUserIdStr<'static>> {+ match self.receipt.auth() {+ EntityAccessAuth::Authenticated(user) => Some(user),+ EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => None,+ }+ }++ /// Dangerously mint a receipt for an internal (service-to-service or+ /// worker) caller without an access check.+ /// **NOTE** Use only for machine flows that operate outside a user+ /// session; never to bypass a user's permission check.+ pub fn dangerously_assert_internal(entity_id: &str, entity_type: EntityType) -> Self {+ Self {+ receipt: EntityAccessReceipt::dangerously_assert_internal_user(+ entity_id,+ access_entity_type(entity_type),+ ),+ entity_id: entity_id.to_string(),+ entity_type,+ }+ }++ /// Dangerously mint a receipt for an authenticated user without the+ /// underlying access check. **NOTE** Intended for tests, and for callers+ /// that have already verified the user's access to the entity through+ /// another authoritative seam (e.g. a CRM team-scoped listing) — never as+ /// a way to skip a check that hasn't happened.+ pub fn dangerously_assert_authenticated_user(+ user_id: MacroUserIdStr<'static>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Self {+ Self {+ receipt: EntityAccessReceipt::dangerously_assert_authenticated_user(+ user_id,+ entity_id,+ access_entity_type(entity_type),+ ),+ entity_id: entity_id.to_string(),+ entity_type,+ }+ }++ /// Mint a receipt from a resolved permission, validating it satisfies `T`.+ /// Only the permission adapter constructs these.+ pub(crate) fn try_from_permission(+ auth: EntityAccessAuth,+ entity_id: &str,+ entity_type: EntityType,+ access_level: AccessLevel,+ ) -> Result<Self, entity_access::domain::models::AccessError> {+ let receipt = EntityAccessReceipt::try_new(+ auth,+ Entity {+ entity_id: entity_id.to_string(),+ entity_type: access_entity_type(entity_type),+ },+ EntityPermission::AccessLevel { access_level },+ )?;+ Ok(Self::new(receipt, entity_type))+ }+}+/// Key identifying the properties attached to one entity.#[derive(Debug, Clone, PartialEq, Eq, Hash)]pub struct EntityPropertiesKey {diff --git a/rust/cloud-storage/properties/src/domain/ports.rs b/rust/cloud-storage/properties/src/domain/ports.rsindex 06156f71e2..647b78bd44 100644--- a/rust/cloud-storage/properties/src/domain/ports.rs+++ b/rust/cloud-storage/properties/src/domain/ports.rs@@ -18,8 +18,8 @@ use models_properties::{DataType, EntityPropertyReference, EntityReference, Entiuse uuid::Uuid;use super::model::{- EntityPropertiesKey, EntityPropertyInfo, PropertyDefinitionOwner, TaskAssignedNotification,- UpdatePropertyOptionOutcome,+ EditReceipt, EntityPropertiesKey, EntityPropertyInfo, PropertyDefinitionOwner,+ TaskAssignedNotification, UpdatePropertyOptionOutcome, ViewReceipt,};/// Repository trait for property operations.@@ -330,42 +330,38 @@ pub trait PropertiesRepo: Send + Sync + 'static {/// Permission service trait for entity access control.///-/// This trait abstracts permission operations (checking and granting), allowing for different implementations-/// (e.g., database-backed, mock for testing).+/// This trait abstracts permission operations (receipt minting and granting),+/// allowing for different implementations (e.g., database-backed, mock for+/// testing). Minting is the single enforcement point: it encapsulates the+/// properties-specific access rules (Task shares Document permissions, the+/// thread-ownership fallback, and deleted entities being visible only to+/// their owner).#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]pub trait PermissionService: Send + Sync + 'static {type Err;- /// Gets the owner of the entity and whether it's deleted- fn get_owner_and_deleted(- &self,- entity_id: &str,- entity_type: EntityType,- ) -> impl Future<Output = Result<(String, bool), Self::Err>> + Send;-- /// Check if a user has edit access to an entity.- /// Returns an error if the user does not have edit or owner access.+ /// Mint a proof that the user (or the public, for `None`) has view access+ /// to the entity. The owner always has access; deleted entities are only+ /// visible to their owner. Errors if the caller has no access.// Explicit lifetime required by mockall's automock expansion.#[allow(clippy::needless_lifetimes)]- fn check_entity_edit_permission<'a>(+ fn mint_view_receipt<'a>(&self,- user_id: &MacroUserIdStr<'a>,+ user_id: Option<&'a MacroUserIdStr<'a>>,entity_id: &str,entity_type: EntityType,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ ) -> impl Future<Output = Result<ViewReceipt, Self::Err>> + Send;- /// Check if a user has view access to an entity (any access level).- /// The owner always has access; deleted entities are only visible to their- /// owner. For anonymous users (`None`), only allows access to- /// publicly shared entities.+ /// Mint a proof that the user has edit (or owner) access to the entity.+ /// Errors if the caller has no edit access.// Explicit lifetime required by mockall's automock expansion.#[allow(clippy::needless_lifetimes)]- fn check_entity_view_permission<'a>(+ fn mint_edit_receipt<'a>(&self,- user_id: Option<&'a MacroUserIdStr<'a>>,+ user_id: &MacroUserIdStr<'a>,entity_id: &str,entity_type: EntityType,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ ) -> impl Future<Output = Result<EditReceipt, Self::Err>> + Send;/// Grant edit permissions to users for a task./// This is used when task assignees are updated to ensure they can edit the task.diff --git a/rust/cloud-storage/properties/src/domain/service.rs b/rust/cloud-storage/properties/src/domain/service.rsindex 32ff855ffa..087fdac8d3 100644--- a/rust/cloud-storage/properties/src/domain/service.rs+++ b/rust/cloud-storage/properties/src/domain/service.rs@@ -1,7 +1,17 @@//! Service trait for properties.+//!+//! Access control is represented in the method types: every entity-scoped+//! method takes a [`ViewReceipt`] or [`EditReceipt`] proving the caller's+//! access, and owner-scoped methods take the caller's identity plus their+//! team-membership receipt. Receipts are minted at the inbound edges via+//! [`PropertiesService::mint_view_receipt`] /+//! [`PropertiesService::mint_edit_receipt`]; internal (machine) callers mint+//! via [`PropertiesAccessReceipt::dangerously_assert_internal`](super::model::PropertiesAccessReceipt::dangerously_assert_internal),+//! which makes unchecked paths explicit and greppable.use std::collections::HashMap;+use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};use macro_user_id::user_id::MacroUserIdStr;use models_properties::api::requests::SetPropertyValue;use models_properties::api::{@@ -12,57 +22,57 @@ use models_properties::service::property_definition::PropertyDefinition;use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;use models_properties::service::property_option::PropertyOption;use models_properties::service::property_value::PropertyValue;-use models_properties::{EntityReference, EntityType};+use models_properties::{EntityPropertyReference, EntityType};use system_properties::SystemPropertyKey;use uuid::Uuid;use super::error::PropertiesErr;-use super::model::{EntityPropertiesKey, EntityPropertyInfo, PropertyDefinitionOwner, TagSet};+use super::model::{+ EditReceipt, EntityPropertiesKey, EntityPropertyInfo, TagScope, TagSet, ViewReceipt,+};++/// The caller's team-membership proof, used to scope definition/option/tag+/// operations to the team the caller actually belongs to.+pub type TeamReceipt = EntityAccessReceipt<MemberTeamRole>;++/// The team id a team receipt proves membership of, if any.+pub fn team_id_from_receipt(team: Option<&TeamReceipt>) -> Option<Uuid> {+ team.and_then(|receipt| Uuid::parse_str(&receipt.entity().entity_id).ok())+}/// Service trait for property operations.pub trait PropertiesService: Send + Sync + 'static {- /// Set an entity's status system property to "Completed".- /// No-op if the entity doesn't have a status property.- fn set_system_property_status_complete(+ /// Mint a proof that the user (or the public, for `None`) has view access+ /// to the entity. Fails with [`PropertiesErr::PermissionDenied`] otherwise.+ fn mint_view_receipt(&self,+ user_id: Option<&MacroUserIdStr<'_>>,entity_id: &str,entity_type: EntityType,- ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;+ ) -> impl Future<Output = Result<ViewReceipt, PropertiesErr>> + Send;- /// Bidirectionally link or unlink a task's parent.- ///- /// When `parent_task_id` is `Some(parent)`:- /// - Sets task's Parent Task = parent- /// - Adds task to parent's Subtasks- /// - Removes task from old parent's Subtasks (if different)- ///- /// When `parent_task_id` is `None`:- /// - Clears task's Parent Task- /// - Removes task from old parent's Subtasks- fn link_parent_task(+ /// Mint a proof that the user has edit (or owner) access to the entity.+ /// Fails with [`PropertiesErr::PermissionDenied`] otherwise.+ fn mint_edit_receipt(&self,- task_id: Uuid,- parent_task_id: Option<Uuid>,- ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;+ user_id: &MacroUserIdStr<'_>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> impl Future<Output = Result<EditReceipt, PropertiesErr>> + Send;- /// Bidirectionally set a task's subtasks.- ///- /// - Sets task's Subtasks to the new list- /// - For added subtasks: sets their Parent Task = task- /// - For removed subtasks: clears their Parent Task- fn link_subtasks(+ /// Set an entity's status system property to "Completed".+ /// No-op if the entity doesn't have a status property.+ fn set_system_property_status_complete(&self,- task_id: Uuid,- subtask_ids: Vec<Uuid>,+ access: &EditReceipt,) -> impl Future<Output = Result<(), PropertiesErr>> + Send;- /// Get all properties attached to an entity, with definitions, values, and options.- /// Tag properties are restricted to the viewer's own and their teams' definitions.+ /// Get all properties attached to an entity, with definitions, values, and+ /// options. Tag properties are restricted to the viewer's own and their+ /// teams' definitions (the viewer being the receipt's authenticated user).fn get_entity_properties(&self,- entity_id: &str,- entity_type: EntityType,- tag_viewer_user_id: &str,+ access: &ViewReceipt,) -> impl Future<Output = Result<Vec<EntityPropertyInfo>, PropertiesErr>> + Send;/// Get the tag sets visible to a caller — their personal set plus their@@ -72,23 +82,11 @@ pub trait PropertiesService: Send + Sync + 'static {user_id: &str,) -> impl Future<Output = Result<Vec<PropertyDefinitionWithOptions>, PropertiesErr>> + Send;- /// Get all properties attached to multiple entities, keyed by entity id and type.- fn get_entity_properties_batch(- &self,- entity_refs: Vec<EntityReference>,- ) -> impl Future<- Output = Result<- HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>,- PropertiesErr,- >,- > + Send;-/// Get a property value for an entity by property definition ID./// Returns `None` if the property is not attached to the entity.fn get_property_value(&self,- entity_id: &str,- entity_type: EntityType,+ access: &ViewReceipt,property_definition_id: Uuid,) -> impl Future<Output = Result<Option<PropertyValue>, PropertiesErr>> + Send;@@ -96,62 +94,49 @@ pub trait PropertiesService: Send + Sync + 'static {/// Returns `None` if the property is not attached to the entity.fn get_system_property_value(&self,- entity_id: &str,- entity_type: EntityType,+ access: &ViewReceipt,property_key: SystemPropertyKey,) -> impl Future<Output = Result<Option<PropertyValue>, PropertiesErr>> + Send;/// Set or update a property value for an entity, or attach a property without a value./// Validates property options if the value contains select options.- /// Requires edit access to the entity.+ /// Linking Parent Task / Subtasks additionally requires edit access to the+ /// referenced tasks.fn set_entity_property(&self,- user_id: &MacroUserIdStr<'_>,- entity_id: &str,- entity_type: EntityType,+ access: &EditReceipt,property_definition_id: Uuid,value: Option<SetPropertyValue>,) -> impl Future<Output = Result<(), PropertiesErr>> + Send;/// Add one option to a multi-select entity property value atomically./// Attaches the property if needed and dedupes. Validates the option belongs- /// to the (multi-select) property. Requires edit access. Prefer this over- /// `set_entity_property` for add/remove of a single option: it composes with- /// concurrent changes instead of clobbering them.+ /// to the (multi-select) property. Prefer this over `set_entity_property`+ /// for add/remove of a single option: it composes with concurrent changes+ /// instead of clobbering them.fn add_entity_property_option(&self,- user_id: &MacroUserIdStr<'_>,- entity_id: &str,- entity_type: EntityType,+ access: &EditReceipt,property_definition_id: Uuid,option_id: Uuid,) -> impl Future<Output = Result<(), PropertiesErr>> + Send;/// Remove one option from a multi-select entity property value atomically.- /// A no-op if absent. Requires edit access.+ /// A no-op if absent.fn remove_entity_property_option(&self,- user_id: &MacroUserIdStr<'_>,- entity_id: &str,- entity_type: EntityType,+ access: &EditReceipt,property_definition_id: Uuid,option_id: Uuid,) -> impl Future<Output = Result<(), PropertiesErr>> + Send;- /// Gets the owner of the entity and whether it's deleted- fn get_owner_and_deleted(- &self,- entity_id: &str,- entity_type: EntityType,- ) -> impl Future<Output = Result<(String, bool), PropertiesErr>> + Send;-/// List property definitions owned by the given team and/or user, sorted by/// display name. Set `include_system` to true to also include system properties./// When `for_entity_type` is provided, definitions that cannot be attached to/// that entity type are excluded.fn list_property_definitions(&self,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,user_id: Option<&MacroUserIdStr<'_>>,include_system: bool,for_entity_type: Option<EntityType>,@@ -161,17 +146,20 @@ pub trait PropertiesService: Send + Sync + 'static {/// select options.fn list_property_definitions_with_options(&self,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,user_id: Option<&MacroUserIdStr<'_>>,include_system: bool,for_entity_type: Option<EntityType>,) -> impl Future<Output = Result<Vec<PropertyDefinitionWithOptions>, PropertiesErr>> + Send;- /// Create a property definition owned by the given user or team.+ /// Create a property definition owned by the caller (their user property,+ /// or their team's when the request has team scope). Fails with+ /// [`PropertiesErr::TeamMembershipRequired`] for team scope without a team./// Validates the request and creates any select options atomically.fn create_property_definition(&self,- owner: PropertyDefinitionOwner<'_>,+ user_id: &MacroUserIdStr<'_>,+ team: Option<&TeamReceipt>,request: &CreatePropertyDefinitionRequest,) -> impl Future<Output = Result<PropertyDefinition, PropertiesErr>> + Send;@@ -184,7 +172,7 @@ pub trait PropertiesService: Send + Sync + 'static {&self,property_definition_id: Uuid,user_id: &MacroUserIdStr<'_>,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,) -> impl Future<Output = Result<(), PropertiesErr>> + Send;/// Get all options for a property definition readable by the caller (for dropdowns).@@ -192,7 +180,7 @@ pub trait PropertiesService: Send + Sync + 'static {&self,property_definition_id: Uuid,user_id: &MacroUserIdStr<'_>,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,) -> impl Future<Output = Result<Vec<PropertyOption>, PropertiesErr>> + Send;/// Add a new option to a select property owned by the caller.@@ -201,7 +189,7 @@ pub trait PropertiesService: Send + Sync + 'static {fn add_property_option(&self,user_id: &MacroUserIdStr<'_>,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,property_definition_id: Uuid,request: &AddPropertyOptionRequest,) -> impl Future<Output = Result<PropertyOption, PropertiesErr>> + Send;@@ -212,7 +200,7 @@ pub trait PropertiesService: Send + Sync + 'static {fn update_property_option(&self,user_id: &MacroUserIdStr<'_>,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,property_definition_id: Uuid,option_id: Uuid,request: &UpdatePropertyOptionRequest,@@ -223,7 +211,7 @@ pub trait PropertiesService: Send + Sync + 'static {fn delete_property_option(&self,user_id: &MacroUserIdStr<'_>,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,property_definition_id: Uuid,option_id: Uuid,) -> impl Future<Output = Result<(), PropertiesErr>> + Send;@@ -234,22 +222,26 @@ pub trait PropertiesService: Send + Sync + 'static {fn list_tag_sets(&self,user_id: &MacroUserIdStr<'_>,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,) -> impl Future<Output = Result<Vec<TagSet>, PropertiesErr>> + Send;- /// Provision (get-or-create) the owner's tag set and return it.+ /// Provision (get-or-create) the caller's tag set for the scope and return+ /// it. Fails with [`PropertiesErr::TeamMembershipRequired`] for team scope+ /// without a team.fn ensure_tag_set(&self,- owner: PropertyDefinitionOwner<'_>,+ user_id: &MacroUserIdStr<'_>,+ team: Option<&TeamReceipt>,+ scope: TagScope,) -> impl Future<Output = Result<TagSet, PropertiesErr>> + Send;/// Get an entity's stored properties with definitions, values, and options,- /// sorted by display name. Does not include computed metadata properties+ /// sorted by display name. Personal tag properties of other users are+ /// filtered out. Does not include computed metadata properties/// (see [`Self::get_entity_metadata_properties`]).fn get_entity_properties_with_definitions(&self,- entity_id: &str,- entity_type: EntityType,+ access: &ViewReceipt,) -> impl Future<Output = Result<Vec<EntityPropertyWithDefinition>, PropertiesErr>> + Send;/// Get an entity's read-only metadata properties, computed on-the-fly from@@ -258,16 +250,16 @@ pub trait PropertiesService: Send + Sync + 'static {/// entity types without metadata yield `Some(vec![])`.fn get_entity_metadata_properties(&self,- entity_id: &str,- entity_type: EntityType,+ access: &ViewReceipt,) -> impl Future<Output = Result<Option<Vec<EntityPropertyWithDefinition>>, PropertiesErr>> + Send;/// Get properties for multiple entities, keyed by entity id and type./// An empty `property_ids` fetches all properties for the given entities;- /// otherwise only the requested definitions are returned.+ /// otherwise only the requested definitions are returned. Personal tag+ /// properties of other users are filtered out per receipt.fn get_bulk_entity_properties(&self,- entity_refs: Vec<EntityReference>,+ access: &[ViewReceipt],property_ids: Vec<Uuid>,) -> impl Future<Output = Result<@@ -276,36 +268,27 @@ pub trait PropertiesService: Send + Sync + 'static {>,> + Send;- /// Delete all properties attached to an entity (internal operation, no- /// permission checks).+ /// Delete all properties attached to an entity.fn delete_entity_properties(&self,- entity_reference: &EntityReference,+ access: &EditReceipt,) -> impl Future<Output = Result<(), PropertiesErr>> + Send;- /// Delete a single entity property by its ID on behalf of a user.- /// Fails when the property doesn't exist, is required for the entity type,- /// or the user lacks edit access to the entity.- fn delete_entity_property(+ /// Look up an entity property by its ID, returning the entity it is+ /// attached to so the caller can mint an edit receipt for+ /// [`Self::delete_entity_property`]. Returns `None` if it doesn't exist.+ fn lookup_entity_property(&self,entity_property_id: Uuid,- user_id: &MacroUserIdStr<'_>,- ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;-- /// Check that a user has view access to an entity (any access level).- /// For anonymous users (`None`), only allows publicly shared entities.- fn check_entity_view_permission(- &self,- user_id: Option<&MacroUserIdStr<'_>>,- entity_id: &str,- entity_type: EntityType,- ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;+ ) -> impl Future<Output = Result<Option<EntityPropertyReference>, PropertiesErr>> + Send;- /// Check that a user has edit access to an entity (Edit or Owner level).- fn check_entity_edit_permission(+ /// Delete a single entity property by its ID. The receipt must be for the+ /// entity the property is attached to. Fails when the property doesn't+ /// exist, is required for the entity type, or the receipt is for a+ /// different entity.+ fn delete_entity_property(&self,- user_id: &MacroUserIdStr<'_>,- entity_id: &str,- entity_type: EntityType,+ access: &EditReceipt,+ entity_property_id: Uuid,) -> impl Future<Output = Result<(), PropertiesErr>> + Send;}diff --git a/rust/cloud-storage/properties/src/domain/service_impl/helpers.rs b/rust/cloud-storage/properties/src/domain/service_impl/helpers.rsindex 032b3b7873..37b0c6bdff 100644--- a/rust/cloud-storage/properties/src/domain/service_impl/helpers.rs+++ b/rust/cloud-storage/properties/src/domain/service_impl/helpers.rs@@ -1,10 +1,40 @@//! Helper functions for property service implementation.-use models_properties::EntityType;+use entity_access::domain::models::EntityAccessAuth;+use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;use models_properties::service::property_value::PropertyValue;+use models_properties::{DataType, EntityType, PropertyOwner};use system_properties::SystemPropertyKey;use uuid::Uuid;+/// Whether a tag-typed property with the given owner is visible to the caller.+/// A user-owned tag set (personal labels) is visible only to its owner, so+/// personal tags stay private even on a shared entity. Team- and system-owned+/// tags are the shared vocabulary and are always visible. Internal (machine)+/// callers see everything.+fn tag_visible_to(owner: &PropertyOwner, auth: &EntityAccessAuth) -> bool {+ match owner {+ PropertyOwner::User { user_id } => match auth {+ EntityAccessAuth::Authenticated(caller) => user_id == caller.as_ref(),+ EntityAccessAuth::Unauthenticated => false,+ EntityAccessAuth::Internal => true,+ },+ PropertyOwner::Team { .. } | PropertyOwner::System => true,+ }+}++/// Drops tag-typed properties the caller may not see. Non-tag properties are+/// unaffected.+pub fn retain_caller_visible_tags(+ properties: &mut Vec<EntityPropertyWithDefinition>,+ auth: &EntityAccessAuth,+) {+ properties.retain(|property| {+ property.definition.data_type != DataType::Tag+ || tag_visible_to(&property.definition.owner, auth)+ });+}+/// Extract option IDs from a PropertyValue.pub fn extract_option_ids_from_property_value(value: &Option<PropertyValue>) -> Vec<Uuid> {match value {diff --git a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs b/rust/cloud-storage/properties/src/domain/service_impl/mod.rsindex 468f6aafc3..5c5e14cdd4 100644--- a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs+++ b/rust/cloud-storage/properties/src/domain/service_impl/mod.rs@@ -9,8 +9,8 @@ use macro_user_id::user_id::MacroUserIdStr;use models_properties::DataType;use models_properties::api::requests::SetPropertyValue;use models_properties::api::{- AddPropertyOptionRequest, CreatePropertyDefinitionRequest, PropertyDataType,- UpdatePropertyOptionRequest, is_valid_hex_color,+ AddPropertyOptionRequest, CreatePropertyDefinitionRequest, CreatePropertyScope,+ PropertyDataType, UpdatePropertyOptionRequest, is_valid_hex_color,};use models_properties::convert_set_property_value_to_property_value;use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;@@ -18,7 +18,7 @@ use models_properties::service::property_definition::PropertyDefinition;use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};use models_properties::service::property_value::PropertyValue;-use models_properties::{EntityReference, EntityType};+use models_properties::{EntityPropertyReference, EntityReference, EntityType};use system_properties::{StatusOption, SystemPropertyKey};use uuid::Uuid;@@ -27,13 +27,15 @@ use std::sync::Arc;use super::error::PropertiesErr;use super::metadata;use super::model::{- EntityPropertiesKey, EntityPropertyInfo, PropertyDefinitionOwner, TagScope, TagSet,- UpdatePropertyOptionOutcome,+ EditReceipt, EntityPropertiesKey, EntityPropertyInfo, PropertyDefinitionOwner, TagScope,+ TagSet, UpdatePropertyOptionOutcome, ViewReceipt,};use super::ports::{NotificationService, PermissionService, PropertiesRepo, PropertySearchIndexer};-use super::service::PropertiesService;+use super::service::{PropertiesService, TeamReceipt, team_id_from_receipt};-use helpers::{extract_option_ids_from_property_value, is_property_applicable_to};+use helpers::{+ extract_option_ids_from_property_value, is_property_applicable_to, retain_caller_visible_tags,+};/// Entity types whose search index denormalizes property values, i.e. whose/// property mutations must enqueue a search reindex.@@ -89,6 +91,14 @@ whereself}+ /// The permission service, or the error every receipt-minting path maps a+ /// missing one to.+ fn permission_service(&self) -> Result<&P, PropertiesErr> {+ self.permission_service+ .as_ref()+ .ok_or(PropertiesErr::PermissionServiceNotConfigured)+ }+/// Best-effort publish of a property reindex for entity types whose/// search index denormalizes property values. Logs and continues on/// failure so a missed reindex never fails the mutation itself.@@ -213,11 +223,36 @@ whereN: NotificationService,anyhow::Error: From<R::Err> + From<P::Err> + From<N::Err>,{- #[tracing::instrument(skip(self), fields(entity_id = %entity_id, entity_type = ?entity_type))]- async fn set_system_property_status_complete(+ #[tracing::instrument(skip(self), fields(user_id = ?user_id, entity_id = %entity_id, entity_type = ?entity_type))]+ async fn mint_view_receipt(&self,+ user_id: Option<&MacroUserIdStr<'_>>,entity_id: &str,entity_type: EntityType,+ ) -> Result<ViewReceipt, PropertiesErr> {+ self.permission_service()?+ .mint_view_receipt(user_id, entity_id, entity_type)+ .await+ .map_err(|_| PropertiesErr::PermissionDenied)+ }++ #[tracing::instrument(skip(self), fields(user_id = %user_id, entity_id = %entity_id, entity_type = ?entity_type))]+ async fn mint_edit_receipt(+ &self,+ user_id: &MacroUserIdStr<'_>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<EditReceipt, PropertiesErr> {+ self.permission_service()?+ .mint_edit_receipt(user_id, entity_id, entity_type)+ .await+ .map_err(|_| PropertiesErr::PermissionDenied)+ }++ #[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type()))]+ async fn set_system_property_status_complete(+ &self,+ access: &EditReceipt,) -> Result<(), PropertiesErr> {let status_property_id = SystemPropertyKey::STATUS_UUID;let completed_value = PropertyValue::SelectOption(vec![StatusOption::COMPLETED_UUID]);@@ -225,67 +260,35 @@ where// Atomically update status to "Completed" if the property is attachedself.repository.update_entity_property_value_if_exists(- entity_id,- entity_type,+ access.entity_id(),+ access.entity_type(),status_property_id,Some(completed_value),).await.map_err(anyhow::Error::from)?;- self.enqueue_property_upsert(entity_id, entity_type).await;+ self.enqueue_property_upsert(access.entity_id(), access.entity_type())+ .await;Ok(())}- #[tracing::instrument(skip(self))]- async fn link_parent_task(- &self,- task_id: Uuid,- parent_task_id: Option<Uuid>,- ) -> Result<(), PropertiesErr> {- self.repository- .link_parent_task(task_id, parent_task_id)- .await- .map_err(anyhow::Error::from)?;- Ok(())- }-- #[tracing::instrument(skip(self))]- async fn link_subtasks(- &self,- task_id: Uuid,- subtask_ids: Vec<Uuid>,- ) -> Result<(), PropertiesErr> {- self.repository- .link_subtasks(task_id, subtask_ids)- .await- .map_err(anyhow::Error::from)?;- Ok(())- }-- #[tracing::instrument(skip(self), fields(entity_id = %entity_id, entity_type = ?entity_type), err)]+ #[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type()), err)]async fn get_entity_properties(&self,- entity_id: &str,- entity_type: EntityType,- tag_viewer_user_id: &str,+ access: &ViewReceipt,) -> Result<Vec<EntityPropertyInfo>, PropertiesErr> {- // Check view permission first (permission service is required)- let permission_service = self- .permission_service- .as_ref()- .ok_or(PropertiesErr::PermissionServiceNotConfigured)?;- let viewer = MacroUserIdStr::parse_from_str(tag_viewer_user_id)- .map_err(|_| PropertiesErr::PermissionDenied)?;- permission_service- .check_entity_view_permission(Some(&viewer), entity_id, entity_type)- .await- .map_err(|_| PropertiesErr::PermissionDenied)?;-+ // Tag properties are filtered in the query to definitions the viewer+ // can see: their own and their teams'. Receipts without an+ // authenticated user (anonymous public / internal) see no tags.+ let tag_viewer_user_id = access+ .authenticated_user()+ .map(|user| user.as_ref())+ .unwrap_or_default();Ok(self.repository- .get_entity_properties(entity_id, entity_type, tag_viewer_user_id)+ .get_entity_properties(access.entity_id(), access.entity_type(), tag_viewer_user_id).await.map_err(anyhow::Error::from)?)}@@ -302,70 +305,49 @@ where.map_err(anyhow::Error::from)?)}- #[tracing::instrument(skip(self), err)]- async fn get_entity_properties_batch(- &self,- entity_refs: Vec<EntityReference>,- ) -> Result<HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>, PropertiesErr>- {- Ok(self- .repository- .get_entity_properties_batch(entity_refs)- .await- .map_err(anyhow::Error::from)?)- }-- #[tracing::instrument(skip(self), fields(entity_id = %entity_id, entity_type = ?entity_type, property_definition_id = %property_definition_id))]+ #[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type(), property_definition_id = %property_definition_id))]async fn get_property_value(&self,- entity_id: &str,- entity_type: EntityType,+ access: &ViewReceipt,property_definition_id: Uuid,) -> Result<Option<PropertyValue>, PropertiesErr> {Ok(self.repository- .get_entity_property_value(entity_id, entity_type, property_definition_id)+ .get_entity_property_value(+ access.entity_id(),+ access.entity_type(),+ property_definition_id,+ ).await.map_err(anyhow::Error::from)?)}- #[tracing::instrument(skip(self), fields(entity_id = %entity_id, entity_type = ?entity_type, property_key = ?property_key))]+ #[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type(), property_key = ?property_key))]async fn get_system_property_value(&self,- entity_id: &str,- entity_type: EntityType,+ access: &ViewReceipt,property_key: SystemPropertyKey,) -> Result<Option<PropertyValue>, PropertiesErr> {- self.get_property_value(entity_id, entity_type, property_key.uuid())- .await+ self.get_property_value(access, property_key.uuid()).await}#[tracing::instrument(- skip(self),+ skip(self, access),fields(- entity_id = %entity_id,- entity_type = ?entity_type,+ entity_id = %access.entity_id(),+ entity_type = ?access.entity_type(),property_definition_id = %property_definition_id,has_value = value.is_some()))]async fn set_entity_property(&self,- user_id: &MacroUserIdStr<'_>,- entity_id: &str,- entity_type: EntityType,+ access: &EditReceipt,property_definition_id: Uuid,value: Option<SetPropertyValue>,) -> Result<(), PropertiesErr> {- // Check edit permission first (permission service is required)- let permission_service = self- .permission_service- .as_ref()- .ok_or(PropertiesErr::PermissionDenied)?;- permission_service- .check_entity_edit_permission(user_id, entity_id, entity_type)- .await- .map_err(|_| PropertiesErr::PermissionDenied)?;+ let entity_id = access.entity_id();+ let entity_type = access.entity_type();// Get property definition to validate it exists and for validationlet property_definition = self@@ -425,11 +407,11 @@ whereif entity_type == EntityType::Task =>{return self- .handle_task_relationship_property(entity_id, property_definition_id, value)+ .handle_task_relationship_property(access, property_definition_id, value).await;}SystemPropertyKey::ASSIGNEES_UUID if entity_type == EntityType::Task => {- self.handle_task_assignees_property(entity_id, value, user_id)+ self.handle_task_assignees_property(entity_id, value, access.authenticated_user()).await?;}_ => {@@ -455,31 +437,20 @@ where}#[tracing::instrument(- skip(self),+ skip(self, access),fields(- entity_id = %entity_id,- entity_type = ?entity_type,+ entity_id = %access.entity_id(),+ entity_type = ?access.entity_type(),property_definition_id = %property_definition_id,option_id = %option_id))]async fn add_entity_property_option(&self,- user_id: &MacroUserIdStr<'_>,- entity_id: &str,- entity_type: EntityType,+ access: &EditReceipt,property_definition_id: Uuid,option_id: Uuid,) -> Result<(), PropertiesErr> {- let permission_service = self- .permission_service- .as_ref()- .ok_or(PropertiesErr::PermissionDenied)?;- permission_service- .check_entity_edit_permission(user_id, entity_id, entity_type)- .await- .map_err(|_| PropertiesErr::PermissionDenied)?;-let property_definition = self.repository.get_property_definition(property_definition_id)@@ -498,7 +469,7 @@ where));}- if !is_property_applicable_to(property_definition_id, entity_type) {+ if !is_property_applicable_to(property_definition_id, access.entity_type()) {return Err(PropertiesErr::Validation("This property cannot be attached to this entity type".to_string(),));@@ -508,84 +479,63 @@ where.await?;self.repository- .add_entity_property_option(entity_id, entity_type, property_definition_id, option_id)+ .add_entity_property_option(+ access.entity_id(),+ access.entity_type(),+ property_definition_id,+ option_id,+ ).await.map_err(anyhow::Error::from)?;- self.enqueue_property_upsert(entity_id, entity_type).await;+ self.enqueue_property_upsert(access.entity_id(), access.entity_type())+ .await;Ok(())}#[tracing::instrument(- skip(self),+ skip(self, access),fields(- entity_id = %entity_id,- entity_type = ?entity_type,+ entity_id = %access.entity_id(),+ entity_type = ?access.entity_type(),property_definition_id = %property_definition_id,option_id = %option_id))]async fn remove_entity_property_option(&self,- user_id: &MacroUserIdStr<'_>,- entity_id: &str,- entity_type: EntityType,+ access: &EditReceipt,property_definition_id: Uuid,option_id: Uuid,) -> Result<(), PropertiesErr> {- let permission_service = self- .permission_service- .as_ref()- .ok_or(PropertiesErr::PermissionDenied)?;- permission_service- .check_entity_edit_permission(user_id, entity_id, entity_type)- .await- .map_err(|_| PropertiesErr::PermissionDenied)?;-self.repository.remove_entity_property_option(- entity_id,- entity_type,+ access.entity_id(),+ access.entity_type(),property_definition_id,option_id,).await.map_err(anyhow::Error::from)?;- self.enqueue_property_upsert(entity_id, entity_type).await;+ self.enqueue_property_upsert(access.entity_id(), access.entity_type())+ .await;Ok(())}- #[tracing::instrument(skip(self), err)]- async fn get_owner_and_deleted(- &self,- entity_id: &str,- entity_type: EntityType,- ) -> Result<(String, bool), PropertiesErr> {- if let Some(permission_service) = self.permission_service.as_ref() {- let result = permission_service- .get_owner_and_deleted(entity_id, entity_type)- .await- .map_err(anyhow::Error::from)?;-- return Ok(result);- }- Err(PropertiesErr::PermissionServiceNotConfigured)- }-- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self, team), err)]async fn list_property_definitions(&self,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,user_id: Option<&MacroUserIdStr<'_>>,include_system: bool,for_entity_type: Option<EntityType>,) -> Result<Vec<PropertyDefinition>, PropertiesErr> {let definitions = self.repository- .list_property_definitions(team_id, user_id, include_system)+ .list_property_definitions(team_id_from_receipt(team), user_id, include_system).await.map_err(anyhow::Error::from)?;@@ -599,17 +549,21 @@ where.collect())}- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self, team), err)]async fn list_property_definitions_with_options(&self,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,user_id: Option<&MacroUserIdStr<'_>>,include_system: bool,for_entity_type: Option<EntityType>,) -> Result<Vec<PropertyDefinitionWithOptions>, PropertiesErr> {let definitions = self.repository- .list_property_definitions_with_options(team_id, user_id, include_system)+ .list_property_definitions_with_options(+ team_id_from_receipt(team),+ user_id,+ include_system,+ ).await.map_err(anyhow::Error::from)?;@@ -623,12 +577,21 @@ where.collect())}- #[tracing::instrument(skip(self, request), fields(display_name = %request.display_name), err)]+ #[tracing::instrument(skip(self, team, request), fields(display_name = %request.display_name), err)]async fn create_property_definition(&self,- owner: PropertyDefinitionOwner<'_>,+ user_id: &MacroUserIdStr<'_>,+ team: Option<&TeamReceipt>,request: &CreatePropertyDefinitionRequest,) -> Result<PropertyDefinition, PropertiesErr> {+ // Derive the owner from the authenticated caller - clients never supply owner ids.+ let owner = match request.scope {+ CreatePropertyScope::User => PropertyDefinitionOwner::User(user_id),+ CreatePropertyScope::Team => PropertyDefinitionOwner::Team(+ team_id_from_receipt(team).ok_or(PropertiesErr::TeamMembershipRequired)?,+ ),+ };+if let Err(err) = request.validate() {return Err(PropertiesErr::Validation(err.to_string()));}@@ -674,12 +637,12 @@ whereOk(property)}- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self, team), err)]async fn delete_property_definition(&self,property_definition_id: Uuid,user_id: &MacroUserIdStr<'_>,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,) -> Result<(), PropertiesErr> {// First check if the property exists and if it's a system property.let property = self@@ -695,7 +658,11 @@ where// Then verify ownership.self.repository- .get_property_definition_with_owner(property_definition_id, user_id, team_id)+ .get_property_definition_with_owner(+ property_definition_id,+ user_id,+ team_id_from_receipt(team),+ ).await.map_err(anyhow::Error::from)?.ok_or(PropertiesErr::NotFound)?;@@ -710,12 +677,12 @@ whereOk(())}- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self, team), err)]async fn get_property_options(&self,property_definition_id: Uuid,user_id: &MacroUserIdStr<'_>,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,) -> Result<Vec<PropertyOption>, PropertiesErr> {let definition = self.repository@@ -726,7 +693,11 @@ whereif !definition.is_system {self.repository- .get_property_definition_with_owner(property_definition_id, user_id, team_id)+ .get_property_definition_with_owner(+ property_definition_id,+ user_id,+ team_id_from_receipt(team),+ ).await.map_err(anyhow::Error::from)?.ok_or(PropertiesErr::NotFound)?;@@ -739,16 +710,20 @@ where.map_err(anyhow::Error::from)?)}- #[tracing::instrument(skip(self, request), fields(request = ?request), err)]+ #[tracing::instrument(skip(self, team, request), fields(request = ?request), err)]async fn add_property_option(&self,user_id: &MacroUserIdStr<'_>,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,property_definition_id: Uuid,request: &AddPropertyOptionRequest,) -> Result<PropertyOption, PropertiesErr> {let definition = self- .owned_modifiable_definition(property_definition_id, user_id, team_id)+ .owned_modifiable_definition(+ property_definition_id,+ user_id,+ team_id_from_receipt(team),+ ).await?;request@@ -788,17 +763,21 @@ whereOk(option)}- #[tracing::instrument(skip(self, request), fields(request = ?request), err)]+ #[tracing::instrument(skip(self, team, request), fields(request = ?request), err)]async fn update_property_option(&self,user_id: &MacroUserIdStr<'_>,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,property_definition_id: Uuid,option_id: Uuid,request: &UpdatePropertyOptionRequest,) -> Result<PropertyOption, PropertiesErr> {let definition = self- .owned_modifiable_definition(property_definition_id, user_id, team_id)+ .owned_modifiable_definition(+ property_definition_id,+ user_id,+ team_id_from_receipt(team),+ ).await?;let option = self@@ -852,16 +831,20 @@ where}}- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self, team), err)]async fn delete_property_option(&self,user_id: &MacroUserIdStr<'_>,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,property_definition_id: Uuid,option_id: Uuid,) -> Result<(), PropertiesErr> {- self.owned_modifiable_definition(property_definition_id, user_id, team_id)- .await?;+ self.owned_modifiable_definition(+ property_definition_id,+ user_id,+ team_id_from_receipt(team),+ )+ .await?;let option = self.repository@@ -888,11 +871,11 @@ where}}- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self, team), err)]async fn list_tag_sets(&self,user_id: &MacroUserIdStr<'_>,- team_id: Option<Uuid>,+ team: Option<&TeamReceipt>,) -> Result<Vec<TagSet>, PropertiesErr> {let mut sets = Vec::new();@@ -903,7 +886,7 @@ where.map_err(anyhow::Error::from)?;sets.push(self.build_tag_set(TagScope::User, user_definition).await?);- if let Some(team_id) = team_id {+ if let Some(team_id) = team_id_from_receipt(team) {let team_definition = self.repository.get_tag_definition(PropertyDefinitionOwner::Team(team_id))@@ -915,14 +898,18 @@ whereOk(sets)}- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self, team), err)]async fn ensure_tag_set(&self,- owner: PropertyDefinitionOwner<'_>,+ user_id: &MacroUserIdStr<'_>,+ team: Option<&TeamReceipt>,+ scope: TagScope,) -> Result<TagSet, PropertiesErr> {- let scope = match owner {- PropertyDefinitionOwner::User(_) => TagScope::User,- PropertyDefinitionOwner::Team(_) => TagScope::Team,+ let owner = match scope {+ TagScope::User => PropertyDefinitionOwner::User(user_id),+ TagScope::Team => PropertyDefinitionOwner::Team(+ team_id_from_receipt(team).ok_or(PropertiesErr::TeamMembershipRequired)?,+ ),};let definition = self@@ -934,27 +921,28 @@ whereself.build_tag_set(scope, Some(definition)).await}- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type()), err)]async fn get_entity_properties_with_definitions(&self,- entity_id: &str,- entity_type: EntityType,+ access: &ViewReceipt,) -> Result<Vec<EntityPropertyWithDefinition>, PropertiesErr> {- Ok(self+ let mut properties = self.repository- .get_entity_properties_with_definitions(entity_id, entity_type)+ .get_entity_properties_with_definitions(access.entity_id(), access.entity_type()).await- .map_err(anyhow::Error::from)?)+ .map_err(anyhow::Error::from)?;+ retain_caller_visible_tags(&mut properties, access.auth());+ Ok(properties)}- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type()), err)]async fn get_entity_metadata_properties(&self,- entity_id: &str,- entity_type: EntityType,+ access: &ViewReceipt,) -> Result<Option<Vec<EntityPropertyWithDefinition>>, PropertiesErr> {- let properties = match entity_type {- EntityType::Document | EntityType::Task => self+ let entity_id = access.entity_id();+ let properties = match access.entity_type() {+ entity_type @ (EntityType::Document | EntityType::Task) => self.repository.get_document_metadata(entity_id).await@@ -977,7 +965,7 @@ where.await.map_err(anyhow::Error::from)?.map(metadata::project_metadata_properties),- _ => {+ entity_type => {tracing::debug!(entity_type = ?entity_type,"no metadata properties available for this entity type"@@ -989,16 +977,23 @@ whereOk(properties)}- #[tracing::instrument(skip(self, entity_refs, property_ids), fields(entity_count = entity_refs.len(), property_count = property_ids.len()), err)]+ #[tracing::instrument(skip(self, access, property_ids), fields(entity_count = access.len(), property_count = property_ids.len()), err)]async fn get_bulk_entity_properties(&self,- entity_refs: Vec<EntityReference>,+ access: &[ViewReceipt],property_ids: Vec<Uuid>,) -> Result<HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>, PropertiesErr>{+ let entity_refs = access+ .iter()+ .map(|receipt| {+ EntityReference::new(receipt.entity_id().to_string(), receipt.entity_type())+ })+ .collect::<Vec<_>>();+// An empty property_ids means "fetch all properties"; otherwise only// the requested definitions are returned.- let result = if property_ids.is_empty() {+ let mut result = if property_ids.is_empty() {self.repository.get_entity_properties_batch(entity_refs).await@@ -1010,26 +1005,57 @@ where.map_err(anyhow::Error::from)?};+ // Filter each entity's properties by the auth of the receipt that+ // granted access to that entity, so personal tags stay private.+ let auth_by_key: HashMap<EntityPropertiesKey, &ViewReceipt> = access+ .iter()+ .map(|receipt| {+ (+ EntityPropertiesKey {+ entity_id: receipt.entity_id().to_string(),+ entity_type: receipt.entity_type(),+ },+ receipt,+ )+ })+ .collect();+ for (key, properties) in result.iter_mut() {+ if let Some(receipt) = auth_by_key.get(key) {+ retain_caller_visible_tags(properties, receipt.auth());+ }+ }+Ok(result)}- #[tracing::instrument(skip(self), err)]- async fn delete_entity_properties(+ #[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type()), err)]+ async fn delete_entity_properties(&self, access: &EditReceipt) -> Result<(), PropertiesErr> {+ let entity_reference =+ EntityReference::new(access.entity_id().to_string(), access.entity_type());+ Ok(self+ .repository+ .delete_entity_properties(&entity_reference)+ .await+ .map_err(anyhow::Error::from)?)+ }++ #[tracing::instrument(skip(self), fields(entity_property_id = %entity_property_id), err)]+ async fn lookup_entity_property(&self,- entity_reference: &EntityReference,- ) -> Result<(), PropertiesErr> {+ entity_property_id: Uuid,+ ) -> Result<Option<EntityPropertyReference>, PropertiesErr> {Ok(self.repository- .delete_entity_properties(entity_reference)+ .lookup_entity_property(entity_property_id).await.map_err(anyhow::Error::from)?)}- #[tracing::instrument(skip(self), fields(entity_property_id = %entity_property_id, user_id = %user_id), err)]+ #[tracing::instrument(skip(self, access), fields(entity_property_id = %entity_property_id, entity_id = %access.entity_id()), err)]async fn delete_entity_property(&self,+ access: &EditReceipt,entity_property_id: Uuid,- user_id: &MacroUserIdStr<'_>,) -> Result<(), PropertiesErr> {let property_info = self.repository@@ -1038,12 +1064,18 @@ where.map_err(anyhow::Error::from)?.ok_or(PropertiesErr::EntityPropertyNotFound)?;- tracing::debug!(- entity_id = %property_info.entity_id,- entity_type = ?property_info.entity_type,- property_definition_id = %property_info.property_definition_id,- "fetched entity property info"- );+ // The receipt must prove access to the entity this property is+ // actually attached to - a receipt for another entity is no proof.+ if property_info.entity_id != access.entity_id()+ || property_info.entity_type != access.entity_type()+ {+ tracing::warn!(+ receipt_entity_id = %access.entity_id(),+ property_entity_id = %property_info.entity_id,+ "receipt entity does not match the entity the property is attached to"+ );+ return Err(PropertiesErr::PermissionDenied);+ }// Check if this property is required for the entity type (e.g., Task properties)if SystemPropertyKey::is_required_for_entity(@@ -1058,19 +1090,6 @@ wherereturn Err(PropertiesErr::RequiredProperty);}- let permission_service = self- .permission_service- .as_ref()- .ok_or(PropertiesErr::PermissionDenied)?;- permission_service- .check_entity_edit_permission(- user_id,- &property_info.entity_id,- property_info.entity_type,- )- .await- .map_err(|_| PropertiesErr::PermissionDenied)?;-self.repository.delete_entity_property(entity_property_id).await@@ -1080,42 +1099,6 @@ whereOk(())}-- #[tracing::instrument(skip(self), err)]- async fn check_entity_view_permission(- &self,- user_id: Option<&MacroUserIdStr<'_>>,- entity_id: &str,- entity_type: EntityType,- ) -> Result<(), PropertiesErr> {- let permission_service = self- .permission_service- .as_ref()- .ok_or(PropertiesErr::PermissionServiceNotConfigured)?;-- permission_service- .check_entity_view_permission(user_id, entity_id, entity_type)- .await- .map_err(|_| PropertiesErr::PermissionDenied)- }-- #[tracing::instrument(skip(self), err)]- async fn check_entity_edit_permission(- &self,- user_id: &MacroUserIdStr<'_>,- entity_id: &str,- entity_type: EntityType,- ) -> Result<(), PropertiesErr> {- let permission_service = self- .permission_service- .as_ref()- .ok_or(PropertiesErr::PermissionServiceNotConfigured)?;-- permission_service- .check_entity_edit_permission(user_id, entity_id, entity_type)- .await- .map_err(|_| PropertiesErr::PermissionDenied)- }}/// Validate the color rules for a property option: colors are only supporteddiff --git a/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs b/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rsindex 5dd9dd262b..e961d048b2 100644--- a/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs+++ b/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs@@ -11,9 +11,8 @@ use system_properties::SystemPropertyKey;use uuid::Uuid;use crate::domain::error::PropertiesErr;-use crate::domain::model::TaskAssignedNotification;+use crate::domain::model::{EditReceipt, TaskAssignedNotification};use crate::domain::ports::{NotificationService, PermissionService, PropertiesRepo};-use crate::domain::service::PropertiesService;use crate::domain::service_impl::PropertiesServiceImpl;impl<R, P, N> PropertiesServiceImpl<R, P, N>@@ -23,14 +22,40 @@ whereN: NotificationService,anyhow::Error: From<R::Err> + From<P::Err> + From<N::Err>,{+ /// Require edit access to every referenced task before linking: linking+ /// mutates the referenced task's Parent Task / Subtasks property, so edit+ /// access to the primary task alone is not enough. Internal (machine)+ /// callers are trusted and skip the check.+ async fn check_referenced_task_edit_access(+ &self,+ access: &EditReceipt,+ referenced_task_ids: &[Uuid],+ ) -> Result<(), PropertiesErr> {+ if referenced_task_ids.is_empty() {+ return Ok(());+ }+ let Some(user_id) = access.authenticated_user() else {+ // Internal callers operate outside a user session and are trusted.+ return Ok(());+ };+ let permission_service = self.permission_service()?;+ for task_id in referenced_task_ids {+ permission_service+ .mint_edit_receipt(user_id, &task_id.to_string(), EntityType::Task)+ .await+ .map_err(|_| PropertiesErr::PermissionDenied)?;+ }+ Ok(())+ }+/// Handle task relationship properties (Parent Task / Subtasks) with bidirectional linking.- pub async fn handle_task_relationship_property(+ pub(crate) async fn handle_task_relationship_property(&self,- entity_id: &str,+ access: &EditReceipt,property_definition_id: Uuid,value: Option<SetPropertyValue>,) -> Result<(), PropertiesErr> {- let task_id = Uuid::parse_str(entity_id)+ let task_id = Uuid::parse_str(access.entity_id()).map_err(|_| PropertiesErr::Validation("Invalid task ID".to_string()))?;match property_definition_id {@@ -54,7 +79,13 @@ where}};- PropertiesService::link_parent_task(self, task_id, parent_task_id).await?;+ self.check_referenced_task_edit_access(access, parent_task_id.as_slice())+ .await?;++ self.repository+ .link_parent_task(task_id, parent_task_id)+ .await+ .map_err(anyhow::Error::from)?;}SystemPropertyKey::SUBTASKS_UUID => {let subtask_ids = match &value {@@ -80,7 +111,13 @@ where}};- PropertiesService::link_subtasks(self, task_id, subtask_ids).await?;+ self.check_referenced_task_edit_access(access, &subtask_ids)+ .await?;++ self.repository+ .link_subtasks(task_id, subtask_ids)+ .await+ .map_err(anyhow::Error::from)?;}_ => {return Err(PropertiesErr::Validation(@@ -93,11 +130,11 @@ where}/// Handle task assignees property with permissions.- pub async fn handle_task_assignees_property(+ pub(crate) async fn handle_task_assignees_property(&self,entity_id: &str,value: Option<SetPropertyValue>,- assigned_by_user_id: &MacroUserIdStr<'_>,+ assigned_by_user_id: Option<&MacroUserIdStr<'_>>,) -> Result<(), PropertiesErr> {let Some(SetPropertyValue::MultiEntityReference { references }) = &value else {if value.is_some() {@@ -127,17 +164,23 @@ whereOk(())}- /// Handle notifications when task assignees are updated.+ /// Handle notifications when task assignees are updated. Internal+ /// (machine) writes have no assigning user and send no notifications.pub async fn handle_task_assignee_notifications(&self,task_id: Uuid,assignee_ids: &[MacroUserIdStr<'_>],- assigned_by_user_id: &MacroUserIdStr<'_>,+ assigned_by_user_id: Option<&MacroUserIdStr<'_>>,) -> Result<(), PropertiesErr> {if assignee_ids.is_empty() {return Ok(());}+ let Some(assigned_by_user_id) = assigned_by_user_id else {+ tracing::debug!("no assigning user (internal write), skipping notifications");+ return Ok(());+ };+let notification_service = match &self.notification_service {Some(service) => service,None => {@@ -203,10 +246,7 @@ wherereturn Ok(());}- let permission_service = self- .permission_service- .as_ref()- .ok_or(PropertiesErr::PermissionDenied)?;+ let permission_service = self.permission_service()?;tracing::debug!(task_id = %task_id,diff --git a/rust/cloud-storage/properties/src/domain/test.rs b/rust/cloud-storage/properties/src/domain/test.rsindex fbcba0a243..8245c07f24 100644--- a/rust/cloud-storage/properties/src/domain/test.rs+++ b/rust/cloud-storage/properties/src/domain/test.rs@@ -1,6 +1,7 @@//! Unit tests for PropertiesServiceImpl using mockall-generated repo.use super::service_impl::PropertiesServiceImpl;+use crate::domain::model::{EditReceipt, PropertiesAccessReceipt, ViewReceipt};use crate::domain::{ports::{MockNotificationService, MockPermissionService, MockPropertiesRepo},service::PropertiesService,@@ -14,12 +15,41 @@ use models_properties::{use system_properties::{StatusOption, SystemPropertyKey};use uuid::Uuid;-/// Creates a mock permission service with default expectations for entity edit permission checks.+fn caller_user_id() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+}++/// An edit receipt for the test caller, minted without an access check.+fn edit_receipt(entity_id: &str, entity_type: EntityType) -> EditReceipt {+ PropertiesAccessReceipt::dangerously_assert_authenticated_user(+ caller_user_id(),+ entity_id,+ entity_type,+ )+}++/// A view receipt for the test caller, minted without an access check.+fn view_receipt(entity_id: &str, entity_type: EntityType) -> ViewReceipt {+ PropertiesAccessReceipt::dangerously_assert_authenticated_user(+ caller_user_id(),+ entity_id,+ entity_type,+ )+}++/// Creates a mock permission service that mints edit receipts for any entity.fn create_mock_permission_service() -> MockPermissionService {let mut perm_checker = MockPermissionService::new();perm_checker- .expect_check_entity_edit_permission()- .returning(|_, _, _| Box::pin(async { Ok(()) }));+ .expect_mint_edit_receipt()+ .returning(|_, entity_id, entity_type| {+ let receipt = PropertiesAccessReceipt::dangerously_assert_authenticated_user(+ caller_user_id(),+ entity_id,+ entity_type,+ );+ Box::pin(async move { Ok(receipt) })+ });perm_checker}@@ -53,11 +83,8 @@ async fn test_set_system_property_status_complete_happy_path() {None::<MockNotificationService>,);- let entity_id = "e1";- let entity_type = EntityType::Document;-service- .set_system_property_status_complete(entity_id, entity_type)+ .set_system_property_status_complete(&edit_receipt("e1", EntityType::Document)).await.unwrap();@@ -77,7 +104,7 @@ async fn test_set_system_property_status_complete_error_path() {);let err = service- .set_system_property_status_complete("e1", EntityType::Document)+ .set_system_property_status_complete(&edit_receipt("e1", EntityType::Document)).await.unwrap_err();@@ -85,9 +112,32 @@ async fn test_set_system_property_status_complete_error_path() {}// ============================================================================-// link_parent_task unit tests+// task relationship (Parent Task / Subtasks) unit tests// ============================================================================+fn parent_task_value(parent_id: Uuid) -> models_properties::api::requests::SetPropertyValue {+ models_properties::api::requests::SetPropertyValue::EntityReference {+ reference: models_properties::shared::EntityReference {+ entity_type: EntityType::Task,+ entity_id: parent_id.to_string(),+ specific_message_id: None,+ },+ }+}++fn subtasks_value(subtask_ids: &[Uuid]) -> models_properties::api::requests::SetPropertyValue {+ models_properties::api::requests::SetPropertyValue::MultiEntityReference {+ references: subtask_ids+ .iter()+ .map(|id| models_properties::shared::EntityReference {+ entity_type: EntityType::Task,+ entity_id: id.to_string(),+ specific_message_id: None,+ })+ .collect(),+ }+}+#[tokio::test]async fn test_link_parent_task_delegates_to_repo() {let mut repo = MockPropertiesRepo::new();@@ -106,7 +156,11 @@ async fn test_link_parent_task_delegates_to_repo() {);service- .link_parent_task(task_id, Some(parent_id))+ .handle_task_relationship_property(+ &edit_receipt(&task_id.to_string(), EntityType::Task),+ SystemPropertyKey::PARENT_TASK_UUID,+ Some(parent_task_value(parent_id)),+ ).await.unwrap();}@@ -127,7 +181,46 @@ async fn test_link_parent_task_clear_parent() {None::<MockNotificationService>,);- service.link_parent_task(task_id, None).await.unwrap();+ service+ .handle_task_relationship_property(+ &edit_receipt(&task_id.to_string(), EntityType::Task),+ SystemPropertyKey::PARENT_TASK_UUID,+ None,+ )+ .await+ .unwrap();+}++#[tokio::test]+async fn test_link_parent_task_requires_edit_on_parent() {+ // Linking mutates the parent's Subtasks property, so edit access to the+ // parent is required: a failed mint on the parent must deny the link and+ // never touch the repo.+ let mut repo = MockPropertiesRepo::new();+ repo.expect_link_parent_task().times(0);++ let mut perm_service = MockPermissionService::new();+ perm_service+ .expect_mint_edit_receipt()+ .returning(|_, _, _| Box::pin(async { Err(anyhow!("Access denied")) }));++ let service =+ PropertiesServiceImpl::new(repo, Some(perm_service), None::<MockNotificationService>);++ let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);+ let err = service+ .handle_task_relationship_property(+ &edit_receipt(&task_id.to_string(), EntityType::Task),+ SystemPropertyKey::PARENT_TASK_UUID,+ Some(parent_task_value(Uuid::from_u128(0xF00D))),+ )+ .await+ .unwrap_err();++ assert!(matches!(+ err,+ crate::domain::error::PropertiesErr::PermissionDenied+ ));}#[tokio::test]@@ -144,17 +237,17 @@ async fn test_link_parent_task_error_propagates() {);let err = service- .link_parent_task(Uuid::nil(), Some(Uuid::nil()))+ .handle_task_relationship_property(+ &edit_receipt(&Uuid::nil().to_string(), EntityType::Task),+ SystemPropertyKey::PARENT_TASK_UUID,+ Some(parent_task_value(Uuid::nil())),+ ).await.unwrap_err();assert_eq!(err.to_string(), "link failed");}-// ============================================================================-// link_subtasks unit tests-// ============================================================================-#[tokio::test]async fn test_link_subtasks_delegates_to_repo() {let mut repo = MockPropertiesRepo::new();@@ -176,7 +269,11 @@ async fn test_link_subtasks_delegates_to_repo() {);service- .link_subtasks(task_id, vec![subtask_1, subtask_2])+ .handle_task_relationship_property(+ &edit_receipt(&task_id.to_string(), EntityType::Task),+ SystemPropertyKey::SUBTASKS_UUID,+ Some(subtasks_value(&[subtask_1, subtask_2])),+ ).await.unwrap();}@@ -197,7 +294,43 @@ async fn test_link_subtasks_clear_all() {None::<MockNotificationService>,);- service.link_subtasks(task_id, vec![]).await.unwrap();+ service+ .handle_task_relationship_property(+ &edit_receipt(&task_id.to_string(), EntityType::Task),+ SystemPropertyKey::SUBTASKS_UUID,+ None,+ )+ .await+ .unwrap();+}++#[tokio::test]+async fn test_link_subtasks_requires_edit_on_subtasks() {+ let mut repo = MockPropertiesRepo::new();+ repo.expect_link_subtasks().times(0);++ let mut perm_service = MockPermissionService::new();+ perm_service+ .expect_mint_edit_receipt()+ .returning(|_, _, _| Box::pin(async { Err(anyhow!("Access denied")) }));++ let service =+ PropertiesServiceImpl::new(repo, Some(perm_service), None::<MockNotificationService>);++ let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);+ let err = service+ .handle_task_relationship_property(+ &edit_receipt(&task_id.to_string(), EntityType::Task),+ SystemPropertyKey::SUBTASKS_UUID,+ Some(subtasks_value(&[Uuid::from_u128(0xF00D)])),+ )+ .await+ .unwrap_err();++ assert!(matches!(+ err,+ crate::domain::error::PropertiesErr::PermissionDenied+ ));}#[tokio::test]@@ -213,7 +346,11 @@ async fn test_link_subtasks_error_propagates() {);let err = service- .link_subtasks(Uuid::nil(), vec![Uuid::nil()])+ .handle_task_relationship_property(+ &edit_receipt(&Uuid::nil().to_string(), EntityType::Task),+ SystemPropertyKey::SUBTASKS_UUID,+ Some(subtasks_value(&[Uuid::nil()])),+ ).await.unwrap_err();@@ -243,7 +380,7 @@ async fn test_get_property_value_returns_value_when_exists() {);let result = service- .get_property_value("e1", EntityType::Document, prop_id)+ .get_property_value(&view_receipt("e1", EntityType::Document), prop_id).await.unwrap();@@ -264,7 +401,7 @@ async fn test_get_property_value_returns_none_when_not_attached() {);let result = service- .get_property_value("e1", EntityType::Document, Uuid::nil())+ .get_property_value(&view_receipt("e1", EntityType::Document), Uuid::nil()).await.unwrap();@@ -285,7 +422,7 @@ async fn test_get_property_value_error_path() {);let err = service- .get_property_value("e1", EntityType::Document, Uuid::nil())+ .get_property_value(&view_receipt("e1", EntityType::Document), Uuid::nil()).await.unwrap_err();@@ -321,7 +458,10 @@ async fn test_get_system_property_value_returns_value_when_exists() {);let result = service- .get_system_property_value("e1", EntityType::Document, SystemPropertyKey::Status)+ .get_system_property_value(+ &view_receipt("e1", EntityType::Document),+ SystemPropertyKey::Status,+ ).await.unwrap();@@ -347,7 +487,10 @@ async fn test_get_system_property_value_returns_none_when_not_attached() {);let result = service- .get_system_property_value("e1", EntityType::Document, SystemPropertyKey::Status)+ .get_system_property_value(+ &view_receipt("e1", EntityType::Document),+ SystemPropertyKey::Status,+ ).await.unwrap();@@ -368,13 +511,135 @@ async fn test_get_system_property_value_error_path() {);let err = service- .get_system_property_value("e1", EntityType::Document, SystemPropertyKey::Status)+ .get_system_property_value(+ &view_receipt("e1", EntityType::Document),+ SystemPropertyKey::Status,+ ).await.unwrap_err();assert_eq!(err.to_string(), "db error");}+// ============================================================================+// receipt minting unit tests+// ============================================================================++#[tokio::test]+async fn test_mint_edit_receipt_no_permission_service() {+ let repo = MockPropertiesRepo::new();+ let service = PropertiesServiceImpl::new(+ repo,+ None::<MockPermissionService>,+ None::<MockNotificationService>,+ );++ let err = service+ .mint_edit_receipt(&caller_user_id(), "doc1", EntityType::Document)+ .await+ .unwrap_err();++ assert!(matches!(+ err,+ crate::domain::error::PropertiesErr::PermissionServiceNotConfigured+ ));+}++#[tokio::test]+async fn test_mint_edit_receipt_denied() {+ let repo = MockPropertiesRepo::new();+ let mut perm_service = MockPermissionService::new();+ perm_service+ .expect_mint_edit_receipt()+ .returning(|_, _, _| Box::pin(async { Err(anyhow!("Access denied")) }));++ let service =+ PropertiesServiceImpl::new(repo, Some(perm_service), None::<MockNotificationService>);++ let err = service+ .mint_edit_receipt(&caller_user_id(), "doc1", EntityType::Document)+ .await+ .unwrap_err();++ assert!(matches!(+ err,+ crate::domain::error::PropertiesErr::PermissionDenied+ ));+}++// ============================================================================+// delete_entity_property unit tests+// ============================================================================++#[tokio::test]+async fn test_delete_entity_property_rejects_receipt_for_other_entity() {+ let mut repo = MockPropertiesRepo::new();+ let entity_property_id = Uuid::from_u128(0xC3);++ repo.expect_lookup_entity_property().returning(move |_| {+ Box::pin(async move {+ Ok(Some(models_properties::EntityPropertyReference {+ entity_id: "other-entity".to_string(),+ entity_type: EntityType::Document,+ property_definition_id: Uuid::from_u128(0xA1),+ }))+ })+ });+ repo.expect_delete_entity_property().times(0);++ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );++ let err = service+ .delete_entity_property(+ &edit_receipt("doc1", EntityType::Document),+ entity_property_id,+ )+ .await+ .unwrap_err();++ assert!(matches!(+ err,+ crate::domain::error::PropertiesErr::PermissionDenied+ ));+}++#[tokio::test]+async fn test_delete_entity_property_happy_path() {+ let mut repo = MockPropertiesRepo::new();+ let entity_property_id = Uuid::from_u128(0xC3);++ repo.expect_lookup_entity_property().returning(move |_| {+ Box::pin(async move {+ Ok(Some(models_properties::EntityPropertyReference {+ entity_id: "doc1".to_string(),+ entity_type: EntityType::Document,+ property_definition_id: Uuid::from_u128(0xA1),+ }))+ })+ });+ repo.expect_delete_entity_property()+ .withf(move |id| *id == entity_property_id)+ .returning(|_| Box::pin(async { Ok(()) }));++ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );++ service+ .delete_entity_property(+ &edit_receipt("doc1", EntityType::Document),+ entity_property_id,+ )+ .await+ .unwrap();+}+// ============================================================================// handle_task_assignee_permissions unit tests// ============================================================================@@ -447,7 +712,7 @@ async fn test_handle_task_assignee_permissions_no_service() {assert!(matches!(err,- crate::domain::error::PropertiesErr::PermissionDenied+ crate::domain::error::PropertiesErr::PermissionServiceNotConfigured));}@@ -559,7 +824,7 @@ async fn check_notifications(test_case: NotificationTestCase) {let assigned_by = MacroUserIdStr::parse_from_str(&assigned_by).unwrap();service- .handle_task_assignee_notifications(task_id, &assignees, &assigned_by)+ .handle_task_assignee_notifications(task_id, &assignees, Some(&assigned_by)).await.unwrap();}@@ -641,6 +906,26 @@ async fn test_handle_task_assignee_notifications_empty_assignees() {.await;}+#[tokio::test]+async fn test_handle_task_assignee_notifications_internal_write_skips() {+ // Internal (machine) writes have no assigning user and must not notify.+ let repo = MockPropertiesRepo::new();+ let mut notif_service = MockNotificationService::new();+ notif_service.expect_send_task_assigned().times(0);++ let service =+ PropertiesServiceImpl::new(repo, None::<MockPermissionService>, Some(notif_service));++ service+ .handle_task_assignee_notifications(+ Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),+ &[MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()],+ None,+ )+ .await+ .unwrap();+}+// ============================================================================// handle_task_assignees_property integration tests// ============================================================================@@ -695,7 +980,7 @@ async fn test_handle_task_assignees_property_calls_both_handlers() {let assigned_by = MacroUserIdStr::parse_from_str(&assigned_by).unwrap();service- .handle_task_assignees_property(&entity_id, value, &assigned_by)+ .handle_task_assignees_property(&entity_id, value, Some(&assigned_by)).await.unwrap();}@@ -716,7 +1001,7 @@ async fn test_handle_task_assignees_property_clearing_assignees() {.handle_task_assignees_property(&entity_id,None,- &MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ Some(&MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()),).await.unwrap();@@ -726,10 +1011,6 @@ async fn test_handle_task_assignees_property_clearing_assignees() {// add/remove_entity_property_option unit tests// ============================================================================-fn caller_user_id() -> MacroUserIdStr<'static> {- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()-}-fn multi_select_definition(id: Uuid, is_multi_select: bool) -> PropertyDefinition {PropertyDefinition {id,@@ -773,9 +1054,7 @@ async fn test_add_entity_property_option_happy_path() {service.add_entity_property_option(- &caller_user_id(),- "doc1",- EntityType::Document,+ &edit_receipt("doc1", EntityType::Document),def_id,option_id,)@@ -800,9 +1079,7 @@ async fn test_add_entity_property_option_rejects_single_select() {let err = service.add_entity_property_option(- &caller_user_id(),- "doc1",- EntityType::Document,+ &edit_receipt("doc1", EntityType::Document),def_id,Uuid::from_u128(0xB2),)@@ -835,9 +1112,7 @@ async fn test_add_entity_property_option_rejects_invalid_option() {let err = service.add_entity_property_option(- &caller_user_id(),- "doc1",- EntityType::Document,+ &edit_receipt("doc1", EntityType::Document),def_id,Uuid::from_u128(0xB2),)@@ -850,32 +1125,6 @@ async fn test_add_entity_property_option_rejects_invalid_option() {));}-#[tokio::test]-async fn test_add_entity_property_option_no_permission_service() {- let repo = MockPropertiesRepo::new();- let service = PropertiesServiceImpl::new(- repo,- None::<MockPermissionService>,- None::<MockNotificationService>,- );-- let err = service- .add_entity_property_option(- &caller_user_id(),- "doc1",- EntityType::Document,- Uuid::from_u128(0xA1),- Uuid::from_u128(0xB2),- )- .await- .unwrap_err();-- assert!(matches!(- err,- crate::domain::error::PropertiesErr::PermissionDenied- ));-}-#[tokio::test]async fn test_remove_entity_property_option_happy_path() {let mut repo = MockPropertiesRepo::new();@@ -899,9 +1148,7 @@ async fn test_remove_entity_property_option_happy_path() {service.remove_entity_property_option(- &caller_user_id(),- "doc1",- EntityType::Document,+ &edit_receipt("doc1", EntityType::Document),def_id,option_id,)diff --git a/rust/cloud-storage/properties/src/inbound/axum_router.rs b/rust/cloud-storage/properties/src/inbound/axum_router.rsindex f0c2021492..4c46a5fded 100644--- a/rust/cloud-storage/properties/src/inbound/axum_router.rs+++ b/rust/cloud-storage/properties/src/inbound/axum_router.rs@@ -10,6 +10,7 @@pub mod definitions;pub mod entities;+pub mod extract;pub mod options;pub mod tags;@@ -27,7 +28,6 @@ use entity_access::domain::models::MemberTeamRole;use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::OptionalMacroUserTeamExtractor;use tower::{Layer, Service};-use uuid::Uuid;use crate::domain::error::PropertiesErr;use crate::domain::service::PropertiesService;@@ -69,14 +69,6 @@ impl<S, A> FromRef<PropertiesRouterState<S, A>> for Arc<A> {/// the model where anyone on a team can manage that team's properties.pub type PropertyTeamExtractor<A> = OptionalMacroUserTeamExtractor<MemberTeamRole, A>;-/// The team the caller belongs to, if any. A `None` team scopes the caller to their own-/// user properties.-pub fn caller_team_id<A>(team: &PropertyTeamExtractor<A>) -> Option<Uuid> {- team.entity_access_receipt- .as_ref()- .and_then(|receipt| Uuid::parse_str(&receipt.entity().entity_id).ok())-}-/// Map a domain [`PropertiesErr`] to the HTTP status code it represents.pub fn properties_err_status(e: &PropertiesErr) -> StatusCode {match e {@@ -87,7 +79,8 @@ pub fn properties_err_status(e: &PropertiesErr) -> StatusCode {PropertiesErr::DuplicateOptionValue => StatusCode::CONFLICT,PropertiesErr::PermissionDenied| PropertiesErr::SystemPropertyNotModifiable- | PropertiesErr::RequiredProperty => StatusCode::FORBIDDEN,+ | PropertiesErr::RequiredProperty+ | PropertiesErr::TeamMembershipRequired => StatusCode::FORBIDDEN,PropertiesErr::Repo(_) | PropertiesErr::PermissionServiceNotConfigured => {StatusCode::INTERNAL_SERVER_ERROR}diff --git a/rust/cloud-storage/properties/src/inbound/axum_router/definitions.rs b/rust/cloud-storage/properties/src/inbound/axum_router/definitions.rsindex 0787d7dbf9..5c3ffc646f 100644--- a/rust/cloud-storage/properties/src/inbound/axum_router/definitions.rs+++ b/rust/cloud-storage/properties/src/inbound/axum_router/definitions.rs@@ -9,7 +9,7 @@ use axum::{use entity_access::domain::ports::EntityAccessService;use model::user::axum_extractor::MacroUserExtractor;use models_properties::EntityType;-use models_properties::api::{CreatePropertyDefinitionRequest, CreatePropertyScope};+use models_properties::api::CreatePropertyDefinitionRequest;use models_properties::service::property_definition::PropertyDefinition;use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;use serde::{Deserialize, Serialize};@@ -17,9 +17,8 @@ use thiserror::Error;use utoipa::ToSchema;use uuid::Uuid;-use super::{PropertiesRouterState, PropertyTeamExtractor, caller_team_id, properties_err_status};+use super::{PropertiesRouterState, PropertyTeamExtractor, properties_err_status};use crate::domain::error::PropertiesErr;-use crate::domain::model::PropertyDefinitionOwner;use crate::domain::service::PropertiesService;#[derive(Debug, Error)]@@ -108,11 +107,11 @@ pub async fn list_properties<S: PropertiesService, A: EntityAccessService>(}: MacroUserExtractor,team: PropertyTeamExtractor<A>,) -> Result<Json<Vec<PropertyDefinitionResponse>>, ListPropertiesErr> {- let callers_team = caller_team_id(&team);+ let callers_team = team.entity_access_receipt.as_ref();- // Determine query parameters based on scope. Team and user ids are derived from the- // authenticated caller, never from the request.- let (team_id, user_id_opt, include_system) = match query.scope {+ // Determine query parameters based on scope. The team receipt and user id are+ // derived from the authenticated caller, never from the request.+ let (team, user_id_opt, include_system) = match query.scope {PropertyScope::User => (None, Some(&user), false),PropertyScope::Team => (callers_team, None, false),PropertyScope::System => (None, None, true),@@ -120,7 +119,6 @@ pub async fn list_properties<S: PropertiesService, A: EntityAccessService>(};tracing::info!(- team_id = ?team_id,scope = ?query.scope,include_system = include_system,for_entity_type = ?query.for_entity_type,@@ -132,7 +130,7 @@ pub async fn list_properties<S: PropertiesService, A: EntityAccessService>(state.properties_service.list_property_definitions_with_options(- team_id,+ team,user_id_opt,include_system,query.for_entity_type,@@ -144,7 +142,7 @@ pub async fn list_properties<S: PropertiesService, A: EntityAccessService>(} else {state.properties_service- .list_property_definitions(team_id, user_id_opt, include_system, query.for_entity_type)+ .list_property_definitions(team, user_id_opt, include_system, query.for_entity_type).await?.into_iter().map(PropertyDefinitionResponse::Simple)@@ -153,7 +151,6 @@ pub async fn list_properties<S: PropertiesService, A: EntityAccessService>(tracing::info!(properties_count = response.len(),- team_id = ?team_id,scope = ?query.scope,user_id = %user,"successfully retrieved properties"@@ -166,15 +163,12 @@ pub async fn list_properties<S: PropertiesService, A: EntityAccessService>(pub enum CreatePropertyDefinitionErr {#[error(transparent)]Properties(#[from] PropertiesErr),- #[error("You must be on a team to create a team property")]- TeamMembershipRequired,}impl IntoResponse for CreatePropertyDefinitionErr {fn into_response(self) -> Response {let status_code = match &self {CreatePropertyDefinitionErr::Properties(e) => properties_err_status(e),- CreatePropertyDefinitionErr::TeamMembershipRequired => StatusCode::FORBIDDEN,};if status_code.is_server_error() {@@ -212,25 +206,13 @@ pub async fn create_property_definition<S: PropertiesService, A: EntityAccessSerteam: PropertyTeamExtractor<A>,Json(request): Json<CreatePropertyDefinitionRequest>,) -> Result<(StatusCode, Json<PropertyDefinition>), CreatePropertyDefinitionErr> {- // Derive the owner from the authenticated caller - clients never supply owner ids.- let owner = match request.scope {- CreatePropertyScope::User => PropertyDefinitionOwner::User(&user),- CreatePropertyScope::Team => {- let team_id =- caller_team_id(&team).ok_or(CreatePropertyDefinitionErr::TeamMembershipRequired)?;- PropertyDefinitionOwner::Team(team_id)- }- };-- tracing::info!(- owner = ?owner,- scope = ?request.scope,- "creating property definition"- );+ tracing::info!(scope = ?request.scope, "creating property definition");+ // The owner is derived in the service from the authenticated caller and+ // their team receipt - clients never supply owner ids.let property = state.properties_service- .create_property_definition(owner, &request)+ .create_property_definition(&user, team.entity_access_receipt.as_ref(), &request).await?;Ok((StatusCode::CREATED, Json(property)))@@ -290,7 +272,7 @@ pub async fn delete_property_definition<S: PropertiesService, A: EntityAccessSerstate.properties_service- .delete_property_definition(property_uuid, &user, caller_team_id(&team))+ .delete_property_definition(property_uuid, &user, team.entity_access_receipt.as_ref()).await?;tracing::info!("successfully deleted property definition");diff --git a/rust/cloud-storage/properties/src/inbound/axum_router/entities.rs b/rust/cloud-storage/properties/src/inbound/axum_router/entities.rsindex 29d1499ee1..acc1fe0807 100644--- a/rust/cloud-storage/properties/src/inbound/axum_router/entities.rs+++ b/rust/cloud-storage/properties/src/inbound/axum_router/entities.rs@@ -1,4 +1,9 @@//! Entity property endpoints.+//!+//! Access control happens in the receipt extractors ([`super::extract`]): the+//! handlers receive a minted [`ViewReceipt`](crate::domain::model::ViewReceipt)+//! or [`EditReceipt`](crate::domain::model::EditReceipt) and pass it into the+//! service, whose entity-scoped methods only accept receipts.use std::collections::HashMap;@@ -9,16 +14,16 @@ use axum::{response::{IntoResponse, Response},};use entity_access::domain::ports::EntityAccessService;-use macro_user_id::user_id::MacroUserIdStr;-use model::user::axum_extractor::{MacroUserExtractor, OptionalMacroUserExtractor};+use model::user::axum_extractor::MacroUserExtractor;use models_properties::api::SetPropertyValue;use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;-use models_properties::{DataType, EntityReference, EntityType, PropertyOwner};+use models_properties::{EntityReference, EntityType};use serde::{Deserialize, Serialize};use thiserror::Error;use utoipa::ToSchema;use uuid::Uuid;+use super::extract::{EditReceiptExtractor, ViewReceiptExtractor};use super::{PropertiesRouterState, properties_err_status};use crate::domain::error::PropertiesErr;use crate::domain::service::PropertiesService;@@ -56,27 +61,6 @@ const MAX_BULK_ENTITIES: usize = 200;/// Maximum number of property IDs allowed in a single bulk properties request.const MAX_BULK_PROPERTY_IDS: usize = 200;-/// Drops tag-typed properties the caller may not see. A user-owned tag set (personal labels)-/// is visible only to its owner, so personal tags stay private even on a shared entity.-/// Team- and system-owned tags are the shared vocabulary and are left in place. Non-tag-/// properties are unaffected.-pub fn retain_caller_visible_tags(- properties: &mut Vec<EntityPropertyWithDefinition>,- caller_user_id: Option<&MacroUserIdStr<'_>>,-) {- properties.retain(|property| {- if property.definition.data_type != DataType::Tag {- return true;- }- match &property.definition.owner {- PropertyOwner::User { user_id } => {- caller_user_id.is_some_and(|caller| user_id == caller.as_ref())- }- PropertyOwner::Team { .. } | PropertyOwner::System => true,- }- });-}-#[derive(Debug, Error)]pub enum GetEntityPropertiesErr {#[error(transparent)]@@ -124,37 +108,26 @@ impl IntoResponse for GetEntityPropertiesErr {),tag = "Properties")]-#[tracing::instrument(skip(state, user), fields(entity_type = ?entity_type, include_metadata = query.include_metadata), err)]+#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), entity_type = ?access.0.entity_type(), include_metadata = query.include_metadata), err)]pub async fn get_entity_properties<S: PropertiesService, A: EntityAccessService>(- Path((entity_type, entity_id)): Path<(EntityType, String)>,Query(query): Query<EntityQueryParams>,State(state): State<PropertiesRouterState<S, A>>,- // Optional: this route allows anonymous access for publicly shared entities.- OptionalMacroUserExtractor {- macro_user_id: user,- ..- }: OptionalMacroUserExtractor,+ // Anonymous access is allowed for publicly shared entities; the extractor+ // minted a view receipt either way.+ access: ViewReceiptExtractor,) -> Result<Json<EntityPropertiesResponse>, GetEntityPropertiesErr> {- tracing::info!(- entity_id = %entity_id,- "retrieving entity properties"- );-- // Note: This can fail if the entity is marked with "deletedAt"- state- .properties_service- .check_entity_view_permission(user.as_ref(), &entity_id, entity_type)- .await?;+ let ViewReceiptExtractor(access) = access;+ tracing::info!("retrieving entity properties");let (user_properties, metadata_properties) = if query.include_metadata {// Fetch user properties and metadata in parallel when metadata is requestedlet (user_properties_result, metadata_properties_result) = tokio::join!(state.properties_service- .get_entity_properties_with_definitions(&entity_id, entity_type),+ .get_entity_properties_with_definitions(&access),state.properties_service- .get_entity_metadata_properties(&entity_id, entity_type)+ .get_entity_metadata_properties(&access));let user_properties = user_properties_result?;@@ -167,7 +140,7 @@ pub async fn get_entity_properties<S: PropertiesService, A: EntityAccessService>tracing::debug!("skipping metadata properties due to include_metadata=false");let user_properties = state.properties_service- .get_entity_properties_with_definitions(&entity_id, entity_type)+ .get_entity_properties_with_definitions(&access).await?;(user_properties, vec![])@@ -176,15 +149,12 @@ pub async fn get_entity_properties<S: PropertiesService, A: EntityAccessService>let mut all_properties = user_properties;all_properties.extend(metadata_properties);- retain_caller_visible_tags(&mut all_properties, user.as_ref());-let response = EntityPropertiesResponse {- entity_id: entity_id.to_string(),+ entity_id: access.entity_id().to_string(),properties: all_properties,};tracing::info!(- entity_id = %entity_id,properties_count = response.properties.len(),"successfully retrieved entity properties");@@ -247,69 +217,6 @@ fn validate_bulk_request_size(Ok(())}-/// Shared implementation for bulk entity properties retrieval-async fn get_bulk_entity_properties_impl<S: PropertiesService, A: EntityAccessService>(- state: &PropertiesRouterState<S, A>,- request: BulkEntityPropertiesRequest,-) -> Result<HashMap<String, EntityPropertiesResponse>, GetBulkEntityPropertiesErr> {- if request.entities.is_empty() {- tracing::error!("empty entities array in request");- return Err(GetBulkEntityPropertiesErr::InvalidRequest);- }- validate_bulk_request_size(&request)?;-- tracing::info!("retrieving bulk entity properties");-- // An empty property_ids fetches all properties for the given entities.- // Note: the public endpoint requires property_ids, but internal callers can- // pass an empty vec to fetch all properties for the given entities.- let bulk_properties = state- .properties_service- .get_bulk_entity_properties(request.entities, request.property_ids)- .await?;-- let mut result: HashMap<String, EntityPropertiesResponse> = HashMap::new();-- for (key, properties_values) in bulk_properties {- result.insert(- key.entity_id.clone(),- EntityPropertiesResponse {- entity_id: key.entity_id,- properties: properties_values,- },- );- }-- tracing::info!(- successful_entities = result.len(),- "successfully retrieved bulk entity properties"- );-- Ok(result)-}--/// Get properties for multiple entities in bulk (internal endpoint - service-to-service)-#[utoipa::path(- post,- path = "/internal/properties/entities/bulk",- request_body = BulkEntityPropertiesRequest,- responses(- (status = 200, description = "Bulk entity properties retrieved successfully", body = HashMap<String, EntityPropertiesResponse>),- (status = 400, description = "Invalid request body"),- (status = 500, description = "Internal server error")- ),- tag = "Internal"-)]-#[tracing::instrument(skip(state, request), fields(entity_count = request.entities.len()), err)]-pub async fn get_bulk_entity_properties_internal<S: PropertiesService, A: EntityAccessService>(- State(state): State<PropertiesRouterState<S, A>>,- Json(request): Json<BulkEntityPropertiesRequest>,-) -> Result<Json<HashMap<String, EntityPropertiesResponse>>, GetBulkEntityPropertiesErr> {- get_bulk_entity_properties_impl(&state, request)- .await- .map(Json)-}-/// Get properties for multiple entities in bulk (public endpoint with user auth)////// Only returns properties for entities the user has view permission for.@@ -335,26 +242,23 @@ pub async fn get_bulk_entity_properties<S: PropertiesService, A: EntityAccessSer}: MacroUserExtractor,Json(request): Json<BulkEntityPropertiesRequest>,) -> Result<Json<HashMap<String, EntityPropertiesResponse>>, GetBulkEntityPropertiesErr> {- // Unlike the internal endpoint, the public endpoint requires explicit property IDs.- // An empty property_ids means "no properties requested", so return early with empty result.+ // The public endpoint requires explicit property IDs. An empty property_ids+ // means "no properties requested", so return early with empty result.if request.entities.is_empty() || request.property_ids.is_empty() {return Ok(Json(HashMap::new()));}validate_bulk_request_size(&request)?;- // Filter to only entities the user has permission to view- let mut permitted_entities = Vec::with_capacity(request.entities.len());+ // Mint a view receipt per entity, keeping only the entities the user has+ // permission to view.+ let mut receipts = Vec::with_capacity(request.entities.len());for entity_ref in &request.entities {match state.properties_service- .check_entity_view_permission(- Some(&user),- &entity_ref.entity_id,- entity_ref.entity_type,- )+ .mint_view_receipt(Some(&user), &entity_ref.entity_id, entity_ref.entity_type).await{- Ok(()) => permitted_entities.push(entity_ref.clone()),+ Ok(receipt) => receipts.push(receipt),Err(e) => {tracing::debug!(entity_id = %entity_ref.entity_id,@@ -367,23 +271,35 @@ pub async fn get_bulk_entity_properties<S: PropertiesService, A: EntityAccessSer}tracing::info!(- permitted = permitted_entities.len(),+ permitted = receipts.len(),"filtered entities by permission");- if permitted_entities.is_empty() {+ if receipts.is_empty() {return Ok(Json(HashMap::new()));}- let filtered_request = BulkEntityPropertiesRequest {- entities: permitted_entities,- property_ids: request.property_ids.clone(),- };+ let bulk_properties = state+ .properties_service+ .get_bulk_entity_properties(&receipts, request.property_ids)+ .await?;- let mut result = get_bulk_entity_properties_impl(&state, filtered_request).await?;- for response in result.values_mut() {- retain_caller_visible_tags(&mut response.properties, Some(&user));+ let mut result: HashMap<String, EntityPropertiesResponse> = HashMap::new();+ for (key, properties_values) in bulk_properties {+ result.insert(+ key.entity_id.clone(),+ EntityPropertiesResponse {+ entity_id: key.entity_id,+ properties: properties_values,+ },+ );}++ tracing::info!(+ successful_entities = result.len(),+ "successfully retrieved bulk entity properties"+ );+Ok(Json(result))}@@ -424,26 +340,24 @@ impl IntoResponse for SetEntityPropertyErr {responses((status = 204, description = "Entity property set successfully (with or without value)"),(status = 400, description = "Invalid request or entity type"),+ (status = 403, description = "No edit access to the entity"),(status = 404, description = "Entity or property not found"),(status = 500, description = "Internal server error")),tags = ["Properties"])]-#[tracing::instrument(skip(state, user, request), fields(entity_id = %entity_id, property_id = %property_uuid, entity_type = ?entity_type, has_value = request.value.is_some()), err)]+#[tracing::instrument(skip(state, access, request), fields(entity_id = %access.0.entity_id(), property_id = %property_uuid, entity_type = ?access.0.entity_type(), has_value = request.value.is_some()), err)]pub async fn set_entity_property<S: PropertiesService, A: EntityAccessService>(- Path((entity_type, entity_id, property_uuid)): Path<(EntityType, String, Uuid)>,+ Path((_entity_type, _entity_id, property_uuid)): Path<(EntityType, String, Uuid)>,State(state): State<PropertiesRouterState<S, A>>,- MacroUserExtractor {- macro_user_id: user,- ..- }: MacroUserExtractor,+ access: EditReceiptExtractor,Json(request): Json<SetEntityPropertyRequest>,) -> Result<StatusCode, SetEntityPropertyErr> {tracing::info!("setting entity property");state.properties_service- .set_entity_property(&user, &entity_id, entity_type, property_uuid, request.value)+ .set_entity_property(&access.0, property_uuid, request.value).await?;tracing::info!("successfully set entity property");@@ -498,25 +412,22 @@ impl IntoResponse for EntityPropertyOptionErr {),tags = ["Properties"])]-#[tracing::instrument(skip(state, user), fields(entity_id = %entity_id, property_id = %property_uuid, option_id = %option_uuid, entity_type = ?entity_type), err)]+#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), property_id = %property_uuid, option_id = %option_uuid, entity_type = ?access.0.entity_type()), err)]pub async fn add_entity_property_option<S: PropertiesService, A: EntityAccessService>(- Path((entity_type, entity_id, property_uuid, option_uuid)): Path<(+ Path((_entity_type, _entity_id, property_uuid, option_uuid)): Path<(EntityType,String,Uuid,Uuid,)>,State(state): State<PropertiesRouterState<S, A>>,- MacroUserExtractor {- macro_user_id: user,- ..- }: MacroUserExtractor,+ access: EditReceiptExtractor,) -> Result<StatusCode, EntityPropertyOptionErr> {tracing::info!("adding entity property option");state.properties_service- .add_entity_property_option(&user, &entity_id, entity_type, property_uuid, option_uuid)+ .add_entity_property_option(&access.0, property_uuid, option_uuid).await?;Ok(StatusCode::NO_CONTENT)@@ -543,88 +454,27 @@ pub async fn add_entity_property_option<S: PropertiesService, A: EntityAccessSer),tags = ["Properties"])]-#[tracing::instrument(skip(state, user), fields(entity_id = %entity_id, property_id = %property_uuid, option_id = %option_uuid, entity_type = ?entity_type), err)]+#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), property_id = %property_uuid, option_id = %option_uuid, entity_type = ?access.0.entity_type()), err)]pub async fn remove_entity_property_option<S: PropertiesService, A: EntityAccessService>(- Path((entity_type, entity_id, property_uuid, option_uuid)): Path<(+ Path((_entity_type, _entity_id, property_uuid, option_uuid)): Path<(EntityType,String,Uuid,Uuid,)>,State(state): State<PropertiesRouterState<S, A>>,- MacroUserExtractor {- macro_user_id: user,- ..- }: MacroUserExtractor,+ access: EditReceiptExtractor,) -> Result<StatusCode, EntityPropertyOptionErr> {tracing::info!("removing entity property option");state.properties_service- .remove_entity_property_option(&user, &entity_id, entity_type, property_uuid, option_uuid)+ .remove_entity_property_option(&access.0, property_uuid, option_uuid).await?;Ok(StatusCode::NO_CONTENT)}-#[derive(Debug, Error)]-pub enum DeleteEntityErr {- #[error(transparent)]- Properties(#[from] PropertiesErr),-}--impl IntoResponse for DeleteEntityErr {- fn into_response(self) -> Response {- let status_code = match &self {- DeleteEntityErr::Properties(e) => properties_err_status(e),- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "DeleteEntityErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Delete all properties for an entity-#[utoipa::path(- delete,- path = "/internal/properties/entities/{entity_type}/{entity_id}",- params(- ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),- ("entity_id" = String, Path, description = "Entity ID")- ),- responses(- (status = 204, description = "Entity properties deleted successfully"),- (status = 404, description = "Entity not found"),- (status = 500, description = "Internal server error")- ),- tag = "Internal"-)]-#[tracing::instrument(skip(state), err)]-pub async fn delete_entity<S: PropertiesService, A: EntityAccessService>(- Path((entity_type, entity_id)): Path<(EntityType, String)>,- State(state): State<PropertiesRouterState<S, A>>,-) -> Result<StatusCode, DeleteEntityErr> {- tracing::info!("deleting all properties for entity");-- let entity_reference = EntityReference::new(entity_id.clone(), entity_type);-- state- .properties_service- .delete_entity_properties(&entity_reference)- .await?;-- tracing::info!("successfully deleted all properties for entity");-- Ok(StatusCode::NO_CONTENT)-}-#[derive(Debug, Error)]pub enum DeleteEntityPropertyErr {#[error(transparent)]@@ -658,7 +508,7 @@ impl IntoResponse for DeleteEntityPropertyErr {),responses((status = 204, description = "Entity property removed successfully"),- (status = 403, description = "Property is required and cannot be removed"),+ (status = 403, description = "Property is required and cannot be removed, or no edit access"),(status = 404, description = "Entity property not found"),(status = 500, description = "Internal server error")),@@ -675,9 +525,22 @@ pub async fn delete_entity_property<S: PropertiesService, A: EntityAccessService) -> Result<StatusCode, DeleteEntityPropertyErr> {tracing::info!("removing entity property");+ // The entity this property is attached to is only known after a lookup, so+ // the edit receipt is minted here instead of in an extractor.+ let property_info = state+ .properties_service+ .lookup_entity_property(entity_property_uuid)+ .await?+ .ok_or(PropertiesErr::EntityPropertyNotFound)?;++ let access = state+ .properties_service+ .mint_edit_receipt(&user, &property_info.entity_id, property_info.entity_type)+ .await?;+state.properties_service- .delete_entity_property(entity_property_uuid, &user)+ .delete_entity_property(&access, entity_property_uuid).await?;Ok(StatusCode::NO_CONTENT)@@ -725,27 +588,16 @@ impl IntoResponse for SetPropertyStatusCompleteErr {),tags = ["Properties"])]-#[tracing::instrument(skip(state, user), fields(entity_id = %entity_id, entity_type = ?entity_type), err)]+#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), entity_type = ?access.0.entity_type()), err)]pub async fn set_property_status_complete<S: PropertiesService, A: EntityAccessService>(- Path((entity_type, entity_id)): Path<(EntityType, String)>,State(state): State<PropertiesRouterState<S, A>>,- MacroUserExtractor {- macro_user_id: user,- ..- }: MacroUserExtractor,+ access: EditReceiptExtractor,) -> Result<StatusCode, SetPropertyStatusCompleteErr> {tracing::info!("setting entity status to complete");- // Check edit permissions- state- .properties_service- .check_entity_edit_permission(&user, &entity_id, entity_type)- .await?;-- // Delegate to service layer for business logicstate.properties_service- .set_system_property_status_complete(&entity_id, entity_type)+ .set_system_property_status_complete(&access.0).await?;tracing::debug!("status complete handled");diff --git a/rust/cloud-storage/properties/src/inbound/axum_router/extract.rs b/rust/cloud-storage/properties/src/inbound/axum_router/extract.rsnew file mode 100644index 0000000000..6eecfd2356--- /dev/null+++ b/rust/cloud-storage/properties/src/inbound/axum_router/extract.rs@@ -0,0 +1,140 @@+//! Axum extractors that mint entity access receipts for properties routes.+//!+//! Routes with `{entity_type}/{entity_id}` path parameters use these to+//! perform the access check before the handler body runs; the handler then+//! passes the minted receipt into the domain service, whose entity-scoped+//! methods only accept receipts.++use axum::{+ RequestPartsExt,+ extract::{FromRequestParts, Path},+ http::StatusCode,+ http::request::Parts,+ response::{IntoResponse, Response},+};+use entity_access::domain::ports::EntityAccessService;+use model::user::axum_extractor::{MacroUserExtractor, OptionalMacroUserExtractor};+use models_properties::EntityType;++use super::{PropertiesRouterState, properties_err_status};+use crate::domain::error::PropertiesErr;+use crate::domain::model::{EditReceipt, ViewReceipt};+use crate::domain::service::PropertiesService;++/// Path parameters for entity-scoped properties routes.+#[derive(serde::Deserialize)]+struct EntityPathParams {+ entity_type: EntityType,+ entity_id: String,+}++/// Rejection for the receipt extractors.+#[derive(Debug, thiserror::Error)]+pub enum ReceiptRejection {+ /// The route requires an authenticated user.+ #[error("Authentication required")]+ Unauthorized,+ /// The path is missing or has invalid entity parameters.+ #[error("{0}")]+ BadRequest(&'static str),+ /// Minting failed (no access, or the permission backend failed).+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+}++impl IntoResponse for ReceiptRejection {+ fn into_response(self) -> Response {+ let status_code = match &self {+ ReceiptRejection::Unauthorized => StatusCode::UNAUTHORIZED,+ ReceiptRejection::BadRequest(_) => StatusCode::BAD_REQUEST,+ ReceiptRejection::Properties(e) => properties_err_status(e),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "ReceiptRejection",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++async fn entity_path_params(parts: &mut Parts) -> Result<EntityPathParams, ReceiptRejection> {+ let Path(params): Path<EntityPathParams> = parts.extract().await.map_err(|_| {+ ReceiptRejection::BadRequest("Missing or invalid entity_type / entity_id in path")+ })?;+ Ok(params)+}++/// Mints a [`ViewReceipt`] for the `{entity_type}/{entity_id}` in the route.+/// Allows anonymous callers, for publicly shared entities.+pub struct ViewReceiptExtractor(pub ViewReceipt);++impl<S, A> FromRequestParts<PropertiesRouterState<S, A>> for ViewReceiptExtractor+where+ S: PropertiesService,+ A: EntityAccessService,+{+ type Rejection = ReceiptRejection;++ #[tracing::instrument(err, skip(parts, state))]+ async fn from_request_parts(+ parts: &mut Parts,+ state: &PropertiesRouterState<S, A>,+ ) -> Result<Self, Self::Rejection> {+ let params = entity_path_params(parts).await?;++ let OptionalMacroUserExtractor {+ macro_user_id: user,+ ..+ } = parts+ .extract()+ .await+ .map_err(|_| ReceiptRejection::Unauthorized)?;++ let receipt = state+ .properties_service+ .mint_view_receipt(user.as_ref(), ¶ms.entity_id, params.entity_type)+ .await?;++ Ok(Self(receipt))+ }+}++/// Mints an [`EditReceipt`] for the `{entity_type}/{entity_id}` in the route.+/// Requires an authenticated user.+pub struct EditReceiptExtractor(pub EditReceipt);++impl<S, A> FromRequestParts<PropertiesRouterState<S, A>> for EditReceiptExtractor+where+ S: PropertiesService,+ A: EntityAccessService,+{+ type Rejection = ReceiptRejection;++ #[tracing::instrument(err, skip(parts, state))]+ async fn from_request_parts(+ parts: &mut Parts,+ state: &PropertiesRouterState<S, A>,+ ) -> Result<Self, Self::Rejection> {+ let params = entity_path_params(parts).await?;++ let MacroUserExtractor {+ macro_user_id: user,+ ..+ } = parts+ .extract()+ .await+ .map_err(|_| ReceiptRejection::Unauthorized)?;++ let receipt = state+ .properties_service+ .mint_edit_receipt(&user, ¶ms.entity_id, params.entity_type)+ .await?;++ Ok(Self(receipt))+ }+}diff --git a/rust/cloud-storage/properties/src/inbound/axum_router/options.rs b/rust/cloud-storage/properties/src/inbound/axum_router/options.rsindex 4386de44f2..9316500b83 100644--- a/rust/cloud-storage/properties/src/inbound/axum_router/options.rs+++ b/rust/cloud-storage/properties/src/inbound/axum_router/options.rs@@ -13,7 +13,7 @@ use models_properties::service::property_option::PropertyOption;use thiserror::Error;use uuid::Uuid;-use super::{PropertiesRouterState, PropertyTeamExtractor, caller_team_id, properties_err_status};+use super::{PropertiesRouterState, PropertyTeamExtractor, properties_err_status};use crate::domain::error::PropertiesErr;use crate::domain::service::PropertiesService;@@ -69,7 +69,7 @@ pub async fn get_property_options<S: PropertiesService, A: EntityAccessService>(let options = state.properties_service- .get_property_options(property_uuid, &user, caller_team_id(&team))+ .get_property_options(property_uuid, &user, team.entity_access_receipt.as_ref()).await?;tracing::info!(@@ -136,7 +136,12 @@ pub async fn add_property_option<S: PropertiesService, A: EntityAccessService>(let option = state.properties_service- .add_property_option(&user, caller_team_id(&team), property_uuid, &request)+ .add_property_option(+ &user,+ team.entity_access_receipt.as_ref(),+ property_uuid,+ &request,+ ).await?;Ok((StatusCode::CREATED, Json(option)))@@ -202,7 +207,7 @@ pub async fn update_property_option<S: PropertiesService, A: EntityAccessService.properties_service.update_property_option(&user,- caller_team_id(&team),+ team.entity_access_receipt.as_ref(),def_uuid,option_uuid,&request,@@ -267,7 +272,12 @@ pub async fn delete_property_option<S: PropertiesService, A: EntityAccessServicestate.properties_service- .delete_property_option(&user, caller_team_id(&team), def_uuid, option_uuid)+ .delete_property_option(+ &user,+ team.entity_access_receipt.as_ref(),+ def_uuid,+ option_uuid,+ ).await?;tracing::info!("successfully deleted property option");diff --git a/rust/cloud-storage/properties/src/inbound/axum_router/tags.rs b/rust/cloud-storage/properties/src/inbound/axum_router/tags.rsindex 54d2931266..2dca32f49d 100644--- a/rust/cloud-storage/properties/src/inbound/axum_router/tags.rs+++ b/rust/cloud-storage/properties/src/inbound/axum_router/tags.rs@@ -3,7 +3,6 @@use axum::{Json,extract::State,- http::StatusCode,response::{IntoResponse, Response},};use entity_access::domain::ports::EntityAccessService;@@ -13,9 +12,9 @@ use serde::{Deserialize, Serialize};use thiserror::Error;use utoipa::ToSchema;-use super::{PropertiesRouterState, PropertyTeamExtractor, caller_team_id, properties_err_status};+use super::{PropertiesRouterState, PropertyTeamExtractor, properties_err_status};use crate::domain::error::PropertiesErr;-use crate::domain::model::{self as properties_model, PropertyDefinitionOwner};+use crate::domain::model as properties_model;use crate::domain::service::PropertiesService;/// Which owner a tag set belongs to.@@ -37,6 +36,15 @@ impl From<properties_model::TagScope> for TagScope {}}+impl From<TagScope> for properties_model::TagScope {+ fn from(scope: TagScope) -> Self {+ match scope {+ TagScope::User => properties_model::TagScope::User,+ TagScope::Team => properties_model::TagScope::Team,+ }+ }+}+/// A tag set the caller can use. `definition` is absent until the set is provisioned/// (on first label create), in which case `options` is empty.#[derive(Debug, Serialize, ToSchema)]@@ -67,15 +75,12 @@ pub struct EnsureTagSetRequest {pub enum TagsError {#[error(transparent)]Properties(#[from] PropertiesErr),- #[error("You must be on a team to use team tags")]- TeamMembershipRequired,}impl IntoResponse for TagsError {fn into_response(self) -> Response {let status_code = match &self {TagsError::Properties(e) => properties_err_status(e),- TagsError::TeamMembershipRequired => StatusCode::FORBIDDEN,};if status_code.is_server_error() {@@ -108,7 +113,7 @@ pub async fn list_tags<S: PropertiesService, A: EntityAccessService>() -> Result<Json<Vec<TagSetResponse>>, TagsError> {let sets = state.properties_service- .list_tag_sets(&user, caller_team_id(&team))+ .list_tag_sets(&user, team.entity_access_receipt.as_ref()).await?;Ok(Json(sets.into_iter().map(Into::into).collect()))@@ -137,15 +142,14 @@ pub async fn ensure_tag_set<S: PropertiesService, A: EntityAccessService>(team: PropertyTeamExtractor<A>,Json(request): Json<EnsureTagSetRequest>,) -> Result<Json<TagSetResponse>, TagsError> {- let owner = match request.scope {- TagScope::User => PropertyDefinitionOwner::User(&user),- TagScope::Team => {- let team_id = caller_team_id(&team).ok_or(TagsError::TeamMembershipRequired)?;- PropertyDefinitionOwner::Team(team_id)- }- };-- let set = state.properties_service.ensure_tag_set(owner).await?;+ let set = state+ .properties_service+ .ensure_tag_set(+ &user,+ team.entity_access_receipt.as_ref(),+ request.scope.into(),+ )+ .await?;Ok(Json(set.into()))}diff --git a/rust/cloud-storage/properties/src/inbound/toolset/get_entity_properties.rs b/rust/cloud-storage/properties/src/inbound/toolset/get_entity_properties.rsindex 55198be2fa..e861fd80f2 100644--- a/rust/cloud-storage/properties/src/inbound/toolset/get_entity_properties.rs+++ b/rust/cloud-storage/properties/src/inbound/toolset/get_entity_properties.rs@@ -123,13 +123,19 @@ wherelet entity_type = EntityType::from(self.entity_type);+ // Prove the requesting user can view the entity before reading anything.+ let access = service_context+ .service+ .mint_view_receipt(Some(&request_context.user_id), &self.entity_id, entity_type)+ .await+ .map_err(|e| ToolCallError {+ description: "You do not have access to this entity".to_string(),+ internal_error: e.into(),+ })?;+let props = service_context.service- .get_entity_properties(- &self.entity_id,- entity_type,- request_context.user_id.as_ref(),- )+ .get_entity_properties(&access).await.map_err(|e| ToolCallError {description: format!("Failed to get entity properties: {e}"),diff --git a/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rs b/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rsindex c37fd081ea..4181127e8e 100644--- a/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rs+++ b/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rs@@ -214,6 +214,16 @@ wherelet entity_type = EntityType::from(self.entity_type);let set_value = self.to_set_property_value();+ // Prove the requesting user can edit the entity before writing anything.+ let access = service_context+ .service+ .mint_edit_receipt(&request_context.user_id, &self.entity_id, entity_type)+ .await+ .map_err(|e| ToolCallError {+ description: "You do not have edit access to this entity".to_string(),+ internal_error: e.into(),+ })?;+// Delta mode: add/remove specific options atomically so concurrent// edits to the same multi-select value are never overwritten.let add_option_ids = self.add_option_ids.as_deref().unwrap_or_default();@@ -231,13 +241,7 @@ wherefor option_id in add_option_ids {service_context.service- .add_entity_property_option(- &request_context.user_id,- &self.entity_id,- entity_type,- self.property_definition_id,- *option_id,- )+ .add_entity_property_option(&access, self.property_definition_id, *option_id).await.map_err(|e| ToolCallError {description: format!("Failed to add option {option_id}: {e}"),@@ -247,13 +251,7 @@ wherefor option_id in remove_option_ids {service_context.service- .remove_entity_property_option(- &request_context.user_id,- &self.entity_id,- entity_type,- self.property_definition_id,- *option_id,- )+ .remove_entity_property_option(&access, self.property_definition_id, *option_id).await.map_err(|e| ToolCallError {description: format!("Failed to remove option {option_id}: {e}"),@@ -269,13 +267,7 @@ whereservice_context.service- .set_entity_property(- &request_context.user_id,- &self.entity_id,- entity_type,- self.property_definition_id,- set_value,- )+ .set_entity_property(&access, self.property_definition_id, set_value).await.map_err(|e| ToolCallError {description: format!("Failed to set property: {e}"),diff --git a/rust/cloud-storage/properties/src/lib.rs b/rust/cloud-storage/properties/src/lib.rsindex 915dfb90c2..c7e4c73889 100644--- a/rust/cloud-storage/properties/src/lib.rs+++ b/rust/cloud-storage/properties/src/lib.rs@@ -17,11 +17,14 @@ pub mod inbound;pub mod outbound;pub use domain::error::PropertiesErr;-pub use domain::model::{EntityPropertiesKey, EntityPropertyInfo, PropertyOptionInfo};+pub use domain::model::{+ EditReceipt, EntityPropertiesKey, EntityPropertyInfo, PropertiesAccessReceipt,+ PropertyOptionInfo, ViewReceipt,+};pub use domain::ports::{NotificationService, PermissionService, PropertiesRepo, PropertySearchIndexer,};-pub use domain::service::PropertiesService;+pub use domain::service::{PropertiesService, TeamReceipt};pub use domain::service_impl::PropertiesServiceImpl;#[cfg(feature = "outbound")]pub use outbound::notification_service::NotificationServiceImpl;diff --git a/rust/cloud-storage/properties/src/outbound/permission_service.rs b/rust/cloud-storage/properties/src/outbound/permission_service.rsindex 4094f2d54a..83175f9993 100644--- a/rust/cloud-storage/properties/src/outbound/permission_service.rs+++ b/rust/cloud-storage/properties/src/outbound/permission_service.rs@@ -2,16 +2,17 @@use std::sync::Arc;-use entity_access::domain::models::AccessError;+use entity_access::domain::models::{AccessError, EntityAccessAuth};use entity_access::domain::ports::EntityAccessService;+use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;-use model_entity::EntityType as ModelEntityType;use models_permissions::share_permission::access_level::AccessLevel;use models_properties::EntityType;use sqlx::{Pool, Postgres};use uuid::Uuid;use super::permission_queries;+use crate::domain::model::{EditReceipt, PropertiesAccessReceipt, ViewReceipt, access_entity_type};use crate::domain::ports::PermissionService;/// Permission service implementation using database.@@ -37,13 +38,11 @@ impl<Svc: EntityAccessService> PermissionServiceImpl<Svc> {entity_id: &str,entity_type: EntityType,) -> anyhow::Result<Option<AccessLevel>> {- let model_entity_type = match map_entity_type(entity_type) {- Some(t) => t,- None => {- tracing::warn!("property operations not supported for this entity type");- anyhow::bail!("Unsupported entity type");- }- };+ if entity_type == EntityType::User {+ tracing::warn!("property operations not supported for this entity type");+ anyhow::bail!("Unsupported entity type");+ }+ let model_entity_type = access_entity_type(entity_type);let user_id_ref = user_id.map(std::ops::Deref::deref);@@ -86,48 +85,24 @@ impl<Svc: EntityAccessService> PermissionServiceImpl<Svc> {}}-/// Map `models_properties::EntityType` to `model_entity::EntityType`.-fn map_entity_type(entity_type: EntityType) -> Option<ModelEntityType> {- match entity_type {- EntityType::Document => Some(ModelEntityType::Document),- EntityType::Chat => Some(ModelEntityType::Chat),- EntityType::Project => Some(ModelEntityType::Project),- EntityType::Thread => Some(ModelEntityType::EmailThread),- EntityType::Channel => Some(ModelEntityType::Channel),- EntityType::Task => Some(ModelEntityType::Document), // tasks use document permissions- // CRM company access is resolved from the owning team's membership- // (member → View, admin → Edit, owner → Owner).- EntityType::Company => Some(ModelEntityType::CrmCompany),- EntityType::User => None,+/// The auth an authenticated or anonymous caller mints receipts under.+fn caller_auth(user_id: Option<&MacroUserIdStr<'_>>) -> EntityAccessAuth {+ match user_id {+ Some(user_id) => EntityAccessAuth::Authenticated(user_id.copied().into_owned()),+ None => EntityAccessAuth::Unauthenticated,}}impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc> {type Err = anyhow::Error;- #[tracing::instrument(skip(self), fields(user_id = %user_id, entity_id = %entity_id, entity_type = ?entity_type), err)]- async fn check_entity_edit_permission(- &self,- user_id: &MacroUserIdStr<'_>,- entity_id: &str,- entity_type: EntityType,- ) -> Result<(), Self::Err> {- match self- .get_access_level(Some(user_id), entity_id, entity_type)- .await?- {- Some(AccessLevel::Edit) | Some(AccessLevel::Owner) => Ok(()),- Some(_) | None => anyhow::bail!("Access denied"),- }- }-#[tracing::instrument(skip(self), fields(user_id = ?user_id, entity_id = %entity_id, entity_type = ?entity_type), err)]- async fn check_entity_view_permission(+ async fn mint_view_receipt<'a>(&self,- user_id: Option<&MacroUserIdStr<'_>>,+ user_id: Option<&'a MacroUserIdStr<'a>>,entity_id: &str,entity_type: EntityType,- ) -> Result<(), Self::Err> {+ ) -> Result<ViewReceipt, Self::Err> {// Check if entity is deleted: the owner always has access, and deleted// entities are only visible to their owner.match entity_type {@@ -139,7 +114,12 @@ impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc>// If you are the owner fast returnif user_id.is_some_and(|u| owner == u.as_ref()) {- return Ok(());+ return Ok(PropertiesAccessReceipt::try_from_permission(+ caller_auth(user_id),+ entity_id,+ entity_type,+ AccessLevel::Owner,+ )?);}// If the item is deleted and you aren't the owner you are unauthorized@@ -153,11 +133,40 @@ impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc>.get_access_level(user_id, entity_id, entity_type).await?{- Some(_) => Ok(()), // Any access level is sufficient for viewing+ // Any access level is sufficient for viewing+ Some(access_level) => Ok(PropertiesAccessReceipt::try_from_permission(+ caller_auth(user_id),+ entity_id,+ entity_type,+ access_level,+ )?),None => anyhow::bail!("Access denied"),}}+ #[tracing::instrument(skip(self), fields(user_id = %user_id, entity_id = %entity_id, entity_type = ?entity_type), err)]+ async fn mint_edit_receipt<'a>(+ &self,+ user_id: &MacroUserIdStr<'a>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<EditReceipt, Self::Err> {+ match self+ .get_access_level(Some(user_id), entity_id, entity_type)+ .await?+ {+ Some(access_level @ (AccessLevel::Edit | AccessLevel::Owner)) => {+ Ok(PropertiesAccessReceipt::try_from_permission(+ caller_auth(Some(user_id)),+ entity_id,+ entity_type,+ access_level,+ )?)+ }+ Some(_) | None => anyhow::bail!("Access denied"),+ }+ }+#[tracing::instrument(skip(self), fields(task_id = %task_id, user_count = user_ids.len()), err)]async fn grant_permissions_to_task(&self,@@ -180,13 +189,4 @@ impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc>Ok(())}-- #[tracing::instrument(skip(self), err)]- async fn get_owner_and_deleted(- &self,- entity_id: &str,- entity_type: EntityType,- ) -> Result<(String, bool), Self::Err> {- permission_queries::get_owner_and_deleted(&self.db, entity_id, entity_type).await- }}