Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(activity): attribute starter-doc property writes to system (#5850)

teo223cb932d39f
diff --git a/crates/properties/src/domain/activity.rs b/crates/properties/src/domain/activity.rs
index 719d68aab4..a03db2f160 100644
--- a/crates/properties/src/domain/activity.rs
+++ b/crates/properties/src/domain/activity.rs
@@ -9,7 +9,8 @@
mod test;
use ::activity::{
- Activity, ActivitySource, Actor, CommonAction, EntityType, Ingest, PropertyChange, event_time,
+ Activity, ActivitySource, Actor, Attribution, CommonAction, EntityType, Ingest, PropertyChange,
+ event_time,
};
use macro_user_id::user_id::MacroUserIdStr;
use models_properties::EntityType as PropertyEntityType;
@@ -33,22 +34,37 @@ fn entity_type(property_entity: &PropertyEntityType) -> Option<EntityType> {
}
}
+fn event_attribution(
+ actor: &Option<Actor<'static>>,
+ on_behalf_of: &Option<MacroUserIdStr<'static>>,
+ actor_user_id: &Option<MacroUserIdStr<'static>>,
+) -> Option<Attribution> {
+ if let Some(actor) = actor.clone() {
+ return Some(match on_behalf_of.clone() {
+ Some(subject) => Attribution::delegated(actor, subject),
+ None => Attribution::direct(actor),
+ });
+ }
+ actor_user_id
+ .clone()
+ .map(|user| Attribution::direct(Actor::new_from_user(user)))
+}
+
fn attributed(
event_id: uuid::Uuid,
- actor: &Option<MacroUserIdStr<'static>>,
+ attribution: Option<Attribution>,
property_entity: &PropertyEntityType,
entity_id: &str,
action: CommonAction,
occurred_at: chrono::DateTime<chrono::Utc>,
) -> Ingest {
- let (Some(actor), Some(entity_type)) = (actor, entity_type(property_entity)) else {
+ let (Some(attribution), Some(entity_type)) = (attribution, entity_type(property_entity)) else {
return Ingest::Ignore;
};
- Ingest::Insert(vec![Activity::common(
+ Ingest::Insert(vec![Activity::attributed(
event_id,
0,
- Actor::new_from_user(actor.clone()),
- None,
+ attribution,
entity_type,
entity_id,
action,
@@ -65,7 +81,7 @@ impl ActivitySource for PropertyTopicEvent {
match self {
PropertyTopicEvent::EntityPropertyUpdated(m) => attributed(
event_id,
- &m.actor_user_id,
+ event_attribution(&m.actor, &m.on_behalf_of, &m.actor_user_id),
&m.entity_type,
&m.entity_id,
CommonAction::PropertyChanged(PropertyChange {
@@ -91,7 +107,7 @@ impl ActivitySource for PropertyTopicEvent {
),
PropertyTopicEvent::EntityPropertyDeleted(m) => attributed(
event_id,
- &m.actor_user_id,
+ event_attribution(&m.actor, &m.on_behalf_of, &m.actor_user_id),
&m.entity_type,
&m.entity_id,
CommonAction::PropertyChanged(PropertyChange {
@@ -105,7 +121,7 @@ impl ActivitySource for PropertyTopicEvent {
// mutation of the entity.
PropertyTopicEvent::EntityPropertiesCleared(m) => attributed(
event_id,
- &m.actor_user_id,
+ event_attribution(&m.actor, &m.on_behalf_of, &m.actor_user_id),
&m.entity_type,
&m.entity_id,
CommonAction::Edited,
diff --git a/crates/properties/src/domain/activity/test.rs b/crates/properties/src/domain/activity/test.rs
index 8707fb1504..acfeac1f94 100644
--- a/crates/properties/src/domain/activity/test.rs
+++ b/crates/properties/src/domain/activity/test.rs
@@ -1,4 +1,4 @@
-use ::activity::Action;
+use ::activity::{Action, Actor};
use chrono::Utc;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType as ActivityEntityType;
@@ -25,6 +25,8 @@ fn update(actor: Option<MacroUserIdStr<'static>>) -> EntityPropertyUpdatedMetada
entity_type: PropertyEntityType::Task,
property_definition_id: Uuid::from_u128(3),
actor_user_id: actor,
+ actor: None,
+ on_behalf_of: None,
value: None,
previous_value: None,
updated_at: Utc::now(),
@@ -81,3 +83,23 @@ fn unattributed_property_update_is_dropped() {
let event = envelope(PropertyTopicEvent::EntityPropertyUpdated(update(None)));
assert_eq!(event.event.ingest(event.event_id), Ingest::Ignore);
}
+
+#[test]
+fn delegated_property_update_keeps_the_user_as_subject() {
+ let mut metadata = update(None);
+ metadata.actor = Some(
+ Actor::try_from("bot|00000000-0000-0000-0000-000000005759".to_string())
+ .expect("system bot"),
+ );
+ metadata.on_behalf_of = Some(user("macro|[email protected]"));
+ let event = envelope(PropertyTopicEvent::EntityPropertyUpdated(metadata));
+
+ let Ingest::Insert(activities) = event.event.ingest(event.event_id) else {
+ panic!("expected activities");
+ };
+ assert_eq!(
+ activities[0].actor.as_ref(),
+ "bot|00000000-0000-0000-0000-000000005759"
+ );
+ assert_eq!(activities[0].subject_id, "macro|[email protected]");
+}
diff --git a/crates/properties/src/domain/events.rs b/crates/properties/src/domain/events.rs
index 255c32d61f..2aa3a5289e 100644
--- a/crates/properties/src/domain/events.rs
+++ b/crates/properties/src/domain/events.rs
@@ -6,6 +6,7 @@
#[cfg(test)]
mod test;
+use activity::Actor;
use chrono::{DateTime, Utc};
use macro_event_broker::{Event, MacroEvent, TopicEvent};
use macro_event_topics::MacroPropertiesTopic;
@@ -112,6 +113,15 @@ pub struct EntityPropertyUpdatedMetadata {
pub property_definition_id: Uuid,
/// Authenticated user who changed the value, or `None` for a system operation.
pub actor_user_id: Option<MacroUserIdStr<'static>>,
+ /// Who mechanically changed the value. Absent on events published
+ /// before attribution: ingest then treats [`Self::actor_user_id`] as
+ /// the actor.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub actor: Option<Actor<'static>>,
+ /// The user whose feed this change belongs on, when different from
+ /// [`Self::actor`]. Absent means the actor is also the subject.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub on_behalf_of: Option<MacroUserIdStr<'static>>,
/// Full value after the update, or `None` when cleared without deleting the row.
pub value: Option<PropertyValue>,
/// Full value before the update: `None` when the property was newly
@@ -136,6 +146,15 @@ pub struct EntityPropertyDeletedMetadata {
pub property_definition_id: Uuid,
/// Authenticated user who deleted the value, or `None` for a system operation.
pub actor_user_id: Option<MacroUserIdStr<'static>>,
+ /// Who mechanically deleted the value. Absent on events published
+ /// before attribution: ingest then treats [`Self::actor_user_id`] as
+ /// the actor.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub actor: Option<Actor<'static>>,
+ /// The user whose feed this deletion belongs on, when different from
+ /// [`Self::actor`]. Absent means the actor is also the subject.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub on_behalf_of: Option<MacroUserIdStr<'static>>,
}
/// Metadata for [`PropertyTopicEvent::EntityPropertiesCleared`].
@@ -147,6 +166,15 @@ pub struct EntityPropertiesClearedMetadata {
pub entity_type: EntityType,
/// Authenticated user who cleared the values, or `None` for a system operation.
pub actor_user_id: Option<MacroUserIdStr<'static>>,
+ /// Who mechanically cleared the values. Absent on events published
+ /// before attribution: ingest then treats [`Self::actor_user_id`] as
+ /// the actor.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub actor: Option<Actor<'static>>,
+ /// The user whose feed this clear belongs on, when different from
+ /// [`Self::actor`]. Absent means the actor is also the subject.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub on_behalf_of: Option<MacroUserIdStr<'static>>,
}
/// Property mutation events published to [`MacroPropertiesTopic`].
diff --git a/crates/properties/src/domain/events/test.rs b/crates/properties/src/domain/events/test.rs
index 2af9c06536..037d79070b 100644
--- a/crates/properties/src/domain/events/test.rs
+++ b/crates/properties/src/domain/events/test.rs
@@ -160,6 +160,8 @@ fn topic_events(
entity_type: EntityType::Document,
property_definition_id: uuid(PROPERTY_DEFINITION_ID),
actor_user_id: actor_user_id.clone(),
+ actor: None,
+ on_behalf_of: None,
value: Some(PropertyValue::SelectOption(vec![uuid(OPTION_ID)])),
previous_value: None,
updated_at: timestamp(UPDATED_AT),
@@ -188,6 +190,8 @@ fn topic_events(
entity_type: EntityType::Document,
property_definition_id: uuid(PROPERTY_DEFINITION_ID),
actor_user_id: actor_user_id.clone(),
+ actor: None,
+ on_behalf_of: None,
}),
json!({
"event_type": "entity_property.deleted",
@@ -205,6 +209,8 @@ fn topic_events(
entity_id: ENTITY_ID.to_string(),
entity_type: EntityType::Document,
actor_user_id,
+ actor: None,
+ on_behalf_of: None,
}),
json!({
"event_type": "entity_properties.cleared",
@@ -299,6 +305,33 @@ fn constructors_use_exact_bare_keys_topic_and_schema_version() {
}
}
+#[test]
+fn entity_property_updated_decodes_without_actor_fields() {
+ let json = json!({
+ "event_type": "entity_property.updated",
+ "metadata": {
+ "entity_property_id": ENTITY_PROPERTY_ID,
+ "entity_id": ENTITY_ID,
+ "entity_type": "DOCUMENT",
+ "property_definition_id": PROPERTY_DEFINITION_ID,
+ "actor_user_id": "macro|[email protected]",
+ "value": null,
+ "previous_value": null,
+ "updated_at": UPDATED_AT
+ }
+ });
+ let event: PropertyTopicEvent = serde_json::from_value(json).expect("decodable event");
+ let PropertyTopicEvent::EntityPropertyUpdated(metadata) = event else {
+ panic!("expected entity_property.updated");
+ };
+ assert_eq!(metadata.actor, None);
+ assert_eq!(metadata.on_behalf_of, None);
+ assert_eq!(
+ metadata.actor_user_id,
+ Some(user_id("macro|[email protected]"))
+ );
+}
+
#[test]
fn every_variant_supports_a_null_actor() {
for (event, expected) in topic_events(None) {
diff --git a/crates/properties/src/domain/service_impl/mod.rs b/crates/properties/src/domain/service_impl/mod.rs
index 412f8d0a3d..aa75c83862 100644
--- a/crates/properties/src/domain/service_impl/mod.rs
+++ b/crates/properties/src/domain/service_impl/mod.rs
@@ -5,9 +5,11 @@ mod task_properties;
use std::collections::{HashMap, HashSet};
+use activity::Actor;
use document_sub_type::DocumentSubType;
use entity_access::domain::models::{
- EntityAccessReceipt, EntityType as AccessEntityType, RequiredPermission,
+ BotReceiptScope, EntityAccessAuth, EntityAccessReceipt, EntityType as AccessEntityType,
+ RequiredPermission,
};
use macro_event_broker::{MacroEventBroker, NoopMacroEventBroker};
use macro_user_id::cowlike::CowLike;
@@ -49,6 +51,39 @@ use helpers::{
extract_option_ids_from_property_value, is_property_applicable_to, retain_caller_visible_tags,
};
+struct PublishedEventActors {
+ actor: Option<Actor<'static>>,
+ on_behalf_of: Option<MacroUserIdStr<'static>>,
+ actor_user_id: Option<MacroUserIdStr<'static>>,
+}
+
+fn published_event_actors(access: &EditReceipt) -> PublishedEventActors {
+ match access.auth() {
+ EntityAccessAuth::Authenticated(user) => PublishedEventActors {
+ actor: None,
+ on_behalf_of: None,
+ actor_user_id: Some(user.clone()),
+ },
+ EntityAccessAuth::Bot(bot) => match bot.scope() {
+ BotReceiptScope::User { acting_user } => PublishedEventActors {
+ actor: Some(Actor::new_from_bot(bot.bot_id())),
+ on_behalf_of: Some(acting_user.clone()),
+ actor_user_id: None,
+ },
+ BotReceiptScope::Team { .. } => PublishedEventActors {
+ actor: None,
+ on_behalf_of: None,
+ actor_user_id: None,
+ },
+ },
+ EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => PublishedEventActors {
+ actor: None,
+ on_behalf_of: None,
+ actor_user_id: None,
+ },
+ }
+}
+
/// Implementation of [`PropertiesService`] using repository, permission,
/// notification, and event-publishing ports.
#[derive(Debug)]
@@ -181,12 +216,19 @@ where
previous_value: &Option<PropertyValue>,
access: &EditReceipt,
) -> PropertyMacroEvent {
+ let PublishedEventActors {
+ actor,
+ on_behalf_of,
+ actor_user_id,
+ } = published_event_actors(access);
PropertyMacroEvent::entity_property_updated(EntityPropertyUpdatedMetadata {
entity_property_id: property.id,
entity_id: property.entity_id.clone(),
entity_type: property.entity_type,
property_definition_id: property.property_definition_id,
- actor_user_id: access.authenticated_user().cloned(),
+ actor_user_id,
+ actor,
+ on_behalf_of,
value: value.clone(),
previous_value: previous_value.clone(),
updated_at: property.updated_at,
@@ -392,6 +434,8 @@ where
entity_type: mutation.property.entity_type,
property_definition_id: mutation.property.property_definition_id,
actor_user_id: Some(actor.clone().into_owned()),
+ actor: None,
+ on_behalf_of: None,
value: mutation.value.clone(),
previous_value: mutation.previous_value.clone(),
updated_at: mutation.property.updated_at,
@@ -1603,11 +1647,18 @@ where
.await
.map_err(anyhow::Error::from)?;
+ let PublishedEventActors {
+ actor,
+ on_behalf_of,
+ actor_user_id,
+ } = published_event_actors(access);
self.publish_property_event(PropertyMacroEvent::entity_properties_cleared(
EntityPropertiesClearedMetadata {
entity_id: access.entity_id().to_string(),
entity_type: subject.storage_entity_type,
- actor_user_id: access.authenticated_user().cloned(),
+ actor_user_id,
+ actor,
+ on_behalf_of,
},
));
@@ -1679,13 +1730,20 @@ where
tracing::info!("successfully removed entity property");
+ let PublishedEventActors {
+ actor,
+ on_behalf_of,
+ actor_user_id,
+ } = published_event_actors(access);
self.publish_property_event(PropertyMacroEvent::entity_property_deleted(
EntityPropertyDeletedMetadata {
entity_property_id,
entity_id: property_info.entity_id,
entity_type: property_info.entity_type,
property_definition_id: property_info.property_definition_id,
- actor_user_id: access.authenticated_user().cloned(),
+ actor_user_id,
+ actor,
+ on_behalf_of,
},
));
diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rs
index ff134cc5da..deaabb90e1 100644
--- a/crates/properties/src/domain/test.rs
+++ b/crates/properties/src/domain/test.rs
@@ -1242,9 +1242,67 @@ async fn entity_property_event_actor_is_only_an_authenticated_user() {
published.envelope["metadata"]["actor_user_id"],
serde_json::Value::Null
);
+ assert!(published.envelope["metadata"]["actor"].is_null());
+ assert!(published.envelope["metadata"]["on_behalf_of"].is_null());
}
}
+#[tokio::test]
+async fn entity_property_event_delegates_user_scoped_bot_writes() {
+ let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000005759"));
+ let bot_access = EditReceipt::dangerously_assert_bot(
+ bot_id.into_storage_id(),
+ BotReceiptScope::User {
+ acting_user: caller_user_id(),
+ },
+ "doc1",
+ AccessEntityType::Document,
+ );
+ let property_definition_id = Uuid::from_u128(0xE706);
+ let assignment = entity_property_for_event(
+ Uuid::from_u128(0xE707),
+ "doc1",
+ EntityType::Document,
+ property_definition_id,
+ event_timestamp(),
+ );
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition().return_once(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(property_definition_id, false))) })
+ });
+ repo.expect_upsert_entity_property()
+ .return_once(move |_, _, _, _| {
+ Box::pin(async move {
+ Ok(EntityPropertyMutationSnapshot {
+ property: assignment,
+ value: None,
+ previous_value: None,
+ })
+ })
+ });
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ service
+ .set_entity_property(&bot_access, property_definition_id, None)
+ .await
+ .unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(
+ published.envelope["metadata"]["actor_user_id"],
+ serde_json::Value::Null
+ );
+ assert_eq!(
+ published.envelope["metadata"]["actor"],
+ "bot|00000000-0000-0000-0000-000000005759"
+ );
+ assert_eq!(
+ published.envelope["metadata"]["on_behalf_of"],
+ caller_user_id().as_ref()
+ );
+}
+
#[test]
fn bot_receipt_has_no_authenticated_user_identity() {
let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"));
diff --git a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs
index 2433af9da9..785e976c08 100644
--- a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs
+++ b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs
@@ -295,6 +295,8 @@ fn task_property_updates_map_to_document_updates() {
entity_type: PropertyEntityType::Task,
property_definition_id: Uuid::now_v7(),
actor_user_id: Some(user()),
+ actor: None,
+ on_behalf_of: None,
value: None,
previous_value: None,
updated_at: Utc::now(),
@@ -316,12 +318,16 @@ fn deleting_or_clearing_properties_updates_the_soup_entity() {
entity_type: PropertyEntityType::Thread,
property_definition_id: Uuid::now_v7(),
actor_user_id: Some(user()),
+ actor: None,
+ on_behalf_of: None,
});
let company_id = Uuid::now_v7().to_string();
let cleared = PropertyTopicEvent::EntityPropertiesCleared(EntityPropertiesClearedMetadata {
entity_id: company_id.clone(),
entity_type: PropertyEntityType::Company,
actor_user_id: Some(user()),
+ actor: None,
+ on_behalf_of: None,
});
let deleted = patches_from_property_event(&deleted);
@@ -348,6 +354,8 @@ fn property_events_for_non_property_soup_items_are_ignored() {
entity_id: DOCUMENT_ID.to_string(),
entity_type,
actor_user_id: Some(user()),
+ actor: None,
+ on_behalf_of: None,
});
assert!(patches_from_property_event(&event).is_empty());
}
diff --git a/services/document_storage_service/src/api/documents/initialize_starter_docs.rs b/services/document_storage_service/src/api/documents/initialize_starter_docs.rs
index 24fd7db075..105720a373 100644
--- a/services/document_storage_service/src/api/documents/initialize_starter_docs.rs
+++ b/services/document_storage_service/src/api/documents/initialize_starter_docs.rs
@@ -10,7 +10,7 @@ use documents_hex::domain::{
models::DocumentError,
};
use entity_access::domain::{
- models::{EditAccessLevel, ViewAccessLevel},
+ models::{BotAccessScope, EditAccessLevel, ViewAccessLevel},
ports::EntityAccessService,
};
use favorites::domain::ports::FavoritesService;
@@ -326,9 +326,12 @@ pub async fn handler(
// properties service takes its authorization as this typed receipt.
let receipt = match state
.entity_access_service
- .generate_entity_access_receipt::<EditAccessLevel>(
- &user_context.authorization.user.macro_user_id,
- organization_id,
+ .generate_bot_entity_access_receipt::<EditAccessLevel>(
+ bot_id::MACRO_SYSTEM_BOT_ID,
+ BotAccessScope::User {
+ user_id: user_context.authorization.user.macro_user_id.clone(),
+ user_org_id: organization_id,
+ },
&document_id,
EntityType::Document,
)
diff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rs
index 8e67e701c7..6c522b4ad5 100644
--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs
+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs
@@ -1200,6 +1200,8 @@ fn property_event_cases() -> Vec<(PropertyTopicEvent, PropertyEventDescription<'
entity_type: EntityType::Document,
property_definition_id: PROPERTY_DEFINITION_ID,
actor_user_id: actor_user_id.clone(),
+ actor: None,
+ on_behalf_of: None,
value: None,
previous_value: None,
updated_at: Utc::now(),
@@ -1219,6 +1221,8 @@ fn property_event_cases() -> Vec<(PropertyTopicEvent, PropertyEventDescription<'
entity_type: EntityType::Chat,
property_definition_id: PROPERTY_DEFINITION_ID,
actor_user_id: actor_user_id.clone(),
+ actor: None,
+ on_behalf_of: None,
}),
PropertyEventDescription {
action: PropertyIndexAction::Reindex {
@@ -1233,6 +1237,8 @@ fn property_event_cases() -> Vec<(PropertyTopicEvent, PropertyEventDescription<'
entity_id: PROPERTY_ENTITY_ID.to_string(),
entity_type: EntityType::Thread,
actor_user_id,
+ actor: None,
+ on_behalf_of: None,
}),
PropertyEventDescription {
action: PropertyIndexAction::Reindex {
@@ -1564,6 +1570,8 @@ fn property_envelope_decodes_round_trip_with_entity_key() {
entity_id: PROPERTY_ENTITY_ID.to_string(),
entity_type: EntityType::Document,
actor_user_id: Some(user_id()),
+ actor: None,
+ on_behalf_of: None,
});
let message = encoded_message(
MacroPropertiesTopic::TOPIC_STR,
@@ -1796,6 +1804,8 @@ async fn unsupported_property_schema_message_is_commit_safe() {
entity_id: PROPERTY_ENTITY_ID.to_string(),
entity_type: EntityType::Document,
actor_user_id: Some(user_id()),
+ actor: None,
+ on_behalf_of: None,
});
let message = encoded_message(
MacroPropertiesTopic::TOPIC_STR,