Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(properties): refuse generic writes to managed team definitions (#6243)
Panat Taranatc629f646fae7
diff --git a/crates/properties/src/domain/error.rs b/crates/properties/src/domain/error.rsindex aad0c7342c..4942f40e9e 100644--- a/crates/properties/src/domain/error.rs+++ b/crates/properties/src/domain/error.rs@@ -48,6 +48,10 @@ pub enum PropertiesErr {#[error("You must be on a team to use team-scoped properties")]TeamMembershipRequired,+ /// The team definition is owned by another feature's settings - maps to 403+ #[error("This property is managed from its feature's settings and cannot be edited here")]+ ManagedDefinition,+/// Repository/database errors - maps to 500#[error(transparent)]Repo(#[from] anyhow::Error),diff --git a/crates/properties/src/inbound/axum_router.rs b/crates/properties/src/inbound/axum_router.rsindex b97c7106f7..c1a00148fa 100644--- a/crates/properties/src/inbound/axum_router.rs+++ b/crates/properties/src/inbound/axum_router.rs@@ -13,6 +13,7 @@ mod test;pub mod definitions;pub mod entities;pub mod extract;+mod managed;pub mod options;pub mod tags;@@ -37,6 +38,7 @@ pub struct PropertiesRouterState<S, A, Auth> {properties_service: Arc<S>,entity_access_service: Arc<A>,authorization_state: MacroAuthorizationState<Auth>,+ managed_team_definitions: Arc<[String]>,}impl<S, A, Auth> Clone for PropertiesRouterState<S, A, Auth> {@@ -45,6 +47,7 @@ impl<S, A, Auth> Clone for PropertiesRouterState<S, A, Auth> {properties_service: self.properties_service.clone(),entity_access_service: self.entity_access_service.clone(),authorization_state: self.authorization_state.clone(),+ managed_team_definitions: self.managed_team_definitions.clone(),}}}@@ -60,8 +63,24 @@ impl<S: PropertiesService, A: EntityAccessService, Auth> PropertiesRouterState<Sproperties_service,entity_access_service,authorization_state,+ managed_team_definitions: Arc::from([]),}}++ /// Team definitions the generic endpoints must not write, by display name.+ pub fn with_managed_team_definitions(+ mut self,+ names: impl IntoIterator<Item = String>,+ ) -> Self {+ self.managed_team_definitions = names.into_iter().collect();+ self+ }++ fn is_managed_team_definition_name(&self, display_name: &str) -> bool {+ self.managed_team_definitions+ .iter()+ .any(|name| name == display_name)+ }}/// Lets the entity access extractors pull the access service out of the state.@@ -96,7 +115,8 @@ pub fn properties_err_status(e: &PropertiesErr) -> StatusCode {PropertiesErr::PermissionDenied| PropertiesErr::SystemPropertyNotModifiable| PropertiesErr::RequiredProperty- | PropertiesErr::TeamMembershipRequired => StatusCode::FORBIDDEN,+ | PropertiesErr::TeamMembershipRequired+ | PropertiesErr::ManagedDefinition => StatusCode::FORBIDDEN,PropertiesErr::Repo(_) | PropertiesErr::PermissionServiceNotConfigured => {StatusCode::INTERNAL_SERVER_ERROR}diff --git a/crates/properties/src/inbound/axum_router/definitions.rs b/crates/properties/src/inbound/axum_router/definitions.rsindex afc7503d75..d19d46fd1f 100644--- a/crates/properties/src/inbound/axum_router/definitions.rs+++ b/crates/properties/src/inbound/axum_router/definitions.rs@@ -211,6 +211,7 @@ pub async fn create_property_definition<) -> Result<(StatusCode, Json<PropertyDefinition>), CreatePropertyDefinitionErr> {let user = user.authorization.user.macro_user_id;tracing::info!(scope = ?request.scope, "creating property definition");+ state.reject_managed_create(request.scope, &request.display_name)?;// The owner is derived in the service from the authenticated caller and// their team receipt - clients never supply owner ids.@@ -334,10 +335,14 @@ pub async fn delete_property_definition<) -> Result<Response, DeletePropertyDefinitionError> {let user = user.authorization.user.macro_user_id;tracing::info!("deleting property definition");+ let team = team.entity_access_receipt.as_ref();+ state+ .reject_managed_definition(property_uuid, &user, team)+ .await?;state.properties_service- .delete_property_definition(property_uuid, &user, team.entity_access_receipt.as_ref())+ .delete_property_definition(property_uuid, &user, team).await?;tracing::info!("successfully deleted property definition");diff --git a/crates/properties/src/inbound/axum_router/managed.rs b/crates/properties/src/inbound/axum_router/managed.rsnew file mode 100644index 0000000000..c4679df395--- /dev/null+++ b/crates/properties/src/inbound/axum_router/managed.rs@@ -0,0 +1,47 @@+use entity_access::domain::ports::EntityAccessService;+use macro_user_id::user_id::MacroUserIdStr;+use models_properties::PropertyOwner;+use models_properties::api::CreatePropertyScope;+use uuid::Uuid;++use crate::domain::error::PropertiesErr;+use crate::domain::service::{PropertiesService, TeamReceipt};++use super::PropertiesRouterState;++impl<S: PropertiesService, A: EntityAccessService, Auth> PropertiesRouterState<S, A, Auth> {+ pub(super) fn reject_managed_create(+ &self,+ scope: CreatePropertyScope,+ display_name: &str,+ ) -> Result<(), PropertiesErr> {+ if scope == CreatePropertyScope::Team && self.is_managed_team_definition_name(display_name)+ {+ return Err(PropertiesErr::ManagedDefinition);+ }+ Ok(())+ }++ pub(super) async fn reject_managed_definition(+ &self,+ definition_id: Uuid,+ user: &MacroUserIdStr<'_>,+ team: Option<&TeamReceipt>,+ ) -> Result<(), PropertiesErr> {+ let definition = match self+ .properties_service+ .get_property_definition(definition_id, user, team)+ .await+ {+ Ok(definition) => definition,+ Err(PropertiesErr::NotFound) => return Ok(()),+ Err(err) => return Err(err),+ };+ if matches!(definition.owner, PropertyOwner::Team { .. })+ && self.is_managed_team_definition_name(&definition.display_name)+ {+ return Err(PropertiesErr::ManagedDefinition);+ }+ Ok(())+ }+}diff --git a/crates/properties/src/inbound/axum_router/options.rs b/crates/properties/src/inbound/axum_router/options.rsindex ceded5f303..fe4b248cd1 100644--- a/crates/properties/src/inbound/axum_router/options.rs+++ b/crates/properties/src/inbound/axum_router/options.rs@@ -137,15 +137,14 @@ pub async fn add_property_option<) -> Result<(StatusCode, Json<PropertyOption>), AddPropertyOptionErr> {let user = user.authorization.user.macro_user_id;tracing::info!("adding property option");+ let team = team.entity_access_receipt.as_ref();+ state+ .reject_managed_definition(property_uuid, &user, team)+ .await?;let option = state.properties_service- .add_property_option(- &user,- team.entity_access_receipt.as_ref(),- property_uuid,- &request,- )+ .add_property_option(&user, team, property_uuid, &request).await?;Ok((StatusCode::CREATED, Json(option)))@@ -209,15 +208,13 @@ pub async fn update_property_option<Json(request): Json<UpdatePropertyOptionRequest>,) -> Result<(StatusCode, Json<PropertyOption>), UpdatePropertyOptionErr> {let user = user.authorization.user.macro_user_id;+ let team = team.entity_access_receipt.as_ref();+ state+ .reject_managed_definition(def_uuid, &user, team)+ .await?;let updated = state.properties_service- .update_property_option(- &user,- team.entity_access_receipt.as_ref(),- def_uuid,- option_uuid,- &request,- )+ .update_property_option(&user, team, def_uuid, option_uuid, &request).await?;Ok((StatusCode::OK, Json(updated)))@@ -277,15 +274,14 @@ pub async fn delete_property_option<) -> Result<StatusCode, DeletePropertyOptionErr> {let user = user.authorization.user.macro_user_id;tracing::info!("deleting property option");+ let team = team.entity_access_receipt.as_ref();+ state+ .reject_managed_definition(def_uuid, &user, team)+ .await?;state.properties_service- .delete_property_option(- &user,- team.entity_access_receipt.as_ref(),- def_uuid,- option_uuid,- )+ .delete_property_option(&user, team, def_uuid, option_uuid).await?;tracing::info!("successfully deleted property option");diff --git a/crates/properties/src/inbound/axum_router/test.rs b/crates/properties/src/inbound/axum_router/test.rsindex b1cffea412..46a9db09f9 100644--- a/crates/properties/src/inbound/axum_router/test.rs+++ b/crates/properties/src/inbound/axum_router/test.rs@@ -814,3 +814,177 @@ async fn promote_tag_without_a_team_is_forbidden() {.expect("request should complete");assert_eq!(response.status(), StatusCode::FORBIDDEN);}++const MANAGED_NAME: &str = "Deal Stage";++fn managed_router(+ service: TestPropertiesService,+ entity_access_service: FakeEntityAccessService,+) -> Router {+ let state = PropertiesRouterState::new(+ Arc::new(service),+ Arc::new(entity_access_service),+ authorization_state(),+ )+ .with_managed_team_definitions([MANAGED_NAME.to_string()]);+ super::router::<TestPropertiesService, FakeEntityAccessService, TestAuthorizationService>()+ .with_state(state)+}++fn select_def(+ id: Uuid,+ owner: models_properties::PropertyOwner,+ display_name: &str,+) -> models_properties::service::property_definition::PropertyDefinition {+ models_properties::service::property_definition::PropertyDefinition {+ id,+ owner,+ display_name: display_name.to_string(),+ data_type: models_properties::DataType::SelectString,+ is_multi_select: false,+ specific_entity_type: None,+ created_at: chrono::Utc::now(),+ updated_at: chrono::Utc::now(),+ is_system: false,+ is_metadata: false,+ }+}++fn repo_with_definition(+ definition: models_properties::service::property_definition::PropertyDefinition,+) -> MockPropertiesRepo {+ let mut repo = MockPropertiesRepo::new();+ let by_id = definition.clone();+ repo.expect_get_property_definition().returning(move |_| {+ let definition = by_id.clone();+ Box::pin(async move { Ok(Some(definition)) })+ });+ repo.expect_get_property_definition_with_owner()+ .returning(move |_, _, _| {+ let definition = definition.clone();+ Box::pin(async move { Ok(Some(definition)) })+ });+ repo+}++fn json_request(method: &str, uri: &str, body: serde_json::Value) -> Request<Body> {+ Request::builder()+ .method(method)+ .uri(uri)+ .header(header::AUTHORIZATION, "Bearer valid")+ .header(header::CONTENT_TYPE, "application/json")+ .body(Body::from(body.to_string()))+ .expect("request should be valid")+}++#[tokio::test]+async fn creating_a_managed_team_definition_is_forbidden() {+ let router = managed_router(+ no_op_properties_service(),+ FakeEntityAccessService::on_team(Uuid::from_u128(0x7EA3)),+ );+ let body = serde_json::json!({+ "scope": "team",+ "display_name": MANAGED_NAME,+ "data_type": { "type": "select_string", "options": [], "multi": false },+ });+ let response = router+ .oneshot(json_request("POST", "/definitions", body))+ .await+ .expect("request should complete");+ assert_eq!(response.status(), StatusCode::FORBIDDEN);+}++#[tokio::test]+async fn writes_to_a_managed_team_definition_are_forbidden() {+ let definition_id = Uuid::from_u128(0xD001);+ let option_id = Uuid::from_u128(0xD002);+ let team_id = Uuid::from_u128(0x7EA3);+ let definition = select_def(+ definition_id,+ models_properties::PropertyOwner::Team { team_id },+ MANAGED_NAME,+ );+ let option_body = serde_json::json!({+ "type": "select_string",+ "option": { "value": "Renewal", "display_order": 0 },+ });+ let requests = [+ json_request(+ "POST",+ &format!("/definitions/{definition_id}/options"),+ option_body,+ ),+ json_request(+ "PATCH",+ &format!("/definitions/{definition_id}/options/{option_id}"),+ serde_json::json!({ "value": "Renamed" }),+ ),+ json_request(+ "DELETE",+ &format!("/definitions/{definition_id}/options/{option_id}"),+ serde_json::json!({}),+ ),+ json_request(+ "DELETE",+ &format!("/definitions/{definition_id}"),+ serde_json::json!({}),+ ),+ ];+ for request in requests {+ let service = PropertiesServiceImpl::new(+ repo_with_definition(definition.clone()),+ None::<MockPermissionService>,+ None::<MockNotificationService>,+ );+ let router = managed_router(service, FakeEntityAccessService::on_team(team_id));+ let response = router+ .oneshot(request)+ .await+ .expect("request should complete");+ assert_eq!(response.status(), StatusCode::FORBIDDEN);+ }+}++#[tokio::test]+async fn the_guard_only_covers_team_definitions_with_a_managed_name() {+ let definition_id = Uuid::from_u128(0xD003);+ let team_id = Uuid::from_u128(0x7EA3);+ let user = MacroUserIdStr::try_from(VALID_USER_ID.to_string()).expect("valid user id");+ let cases = [+ (+ models_properties::PropertyOwner::User {+ user_id: VALID_USER_ID.to_string(),+ },+ MANAGED_NAME,+ true,+ ),+ (+ models_properties::PropertyOwner::Team { team_id },+ "Region",+ true,+ ),+ (+ models_properties::PropertyOwner::Team { team_id },+ MANAGED_NAME,+ false,+ ),+ ];+ for (owner, name, allowed) in cases {+ let service = PropertiesServiceImpl::new(+ repo_with_definition(select_def(definition_id, owner.clone(), name)),+ None::<MockPermissionService>,+ None::<MockNotificationService>,+ );+ let state = PropertiesRouterState::new(+ Arc::new(service),+ Arc::new(FakeEntityAccessService::on_team(team_id)),+ authorization_state(),+ )+ .with_managed_team_definitions([MANAGED_NAME.to_string()]);+ let result = state+ .reject_managed_definition(definition_id, &user, None)+ .await;+ assert_eq!(result.is_ok(), allowed, "{name} owned by {owner:?}");+ }+}diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex 861efe078d..7b651d76ae 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -591,6 +591,9 @@ impl From<&ApiContext> for PropertiesHandlerState {ctx.entity_access_service.clone(),ctx.authorization_state.clone(),)+ .with_managed_team_definitions([+ crm::domain::stages::CRM_TEAM_STAGE_DEFINITION_NAME.to_string(),+ ])}}