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(ownership): refactor documents typed owner in document models and access (#6615)
Will Hutchinsona27089201dd4
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 380ec4dc4b..57ea0f4401 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -1424,6 +1424,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_pagination",@@ -1658,6 +1659,7 @@"crates/model-entity","crates/model-error-response","crates/model_notifications",+ "crates/model_owner","crates/model_user","crates/models_pagination","crates/notification",@@ -2382,6 +2384,7 @@"crates/model-error-response","crates/model_file_type","crates/model_notifications",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",@@ -2622,6 +2625,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",@@ -2666,6 +2670,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_pagination",@@ -2743,6 +2748,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_pagination",@@ -3484,6 +3490,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_pagination",@@ -3520,6 +3527,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_pagination",@@ -3922,6 +3930,7 @@"crates/model-entity","crates/model-error-response","crates/model_notifications",+ "crates/model_owner","crates/model_user","crates/models_pagination","crates/notification",@@ -4429,6 +4438,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",@@ -4492,6 +4502,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",@@ -4548,6 +4559,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",@@ -4589,6 +4601,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",@@ -5229,6 +5242,7 @@"crates/model-error-response","crates/model_file_type","crates/model_notifications",+ "crates/model_owner","crates/model_user","crates/models_pagination","crates/models_properties",@@ -5265,6 +5279,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",@@ -5796,6 +5811,7 @@"crates/model-error-response","crates/model_file_type","crates/model_notifications",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",@@ -6125,6 +6141,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_pagination",@@ -6547,6 +6564,7 @@"crates/model-error-response","crates/model_file_type","crates/model_notifications",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",@@ -6592,6 +6610,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_pagination",@@ -6639,6 +6658,7 @@"crates/model-entity","crates/model-error-response","crates/model_notifications",+ "crates/model_owner","crates/model_user","crates/models_pagination","crates/notification",@@ -7035,6 +7055,7 @@"crates/model-entity","crates/model-error-response","crates/model_notifications",+ "crates/model_owner","crates/model_user","crates/models_pagination","crates/notification",@@ -7072,6 +7093,7 @@"crates/model-entity","crates/model-error-response","crates/model_notifications",+ "crates/model_owner","crates/model_user","crates/models_pagination","crates/notification",@@ -7699,6 +7721,7 @@"crates/model-error-response","crates/model_file_type","crates/model_notifications",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",@@ -8220,6 +8243,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_pagination",@@ -8959,6 +8983,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_pagination",@@ -9016,6 +9041,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_pagination",@@ -9102,6 +9128,7 @@"crates/model-error-response","crates/model_file_type","crates/model_notifications",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",diff --git a/Cargo.lock b/Cargo.lockindex 1415a85298..6683862132 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3553,6 +3553,7 @@ dependencies = ["model-entity","model-error-response","model_notifications",+ "model_owner","models_pagination","models_permissions","non_empty",@@ -5559,6 +5560,7 @@ dependencies = ["model","model-entity","model_notifications",+ "model_owner","model_user","models_bulk_upload","models_dcs",@@ -6459,6 +6461,7 @@ dependencies = ["model","model-entity","model-error-response",+ "model_owner","model_user","models_entity_access_management","models_permissions",@@ -10881,6 +10884,7 @@ dependencies = ["model","model-entity","model_notifications",+ "model_owner","models_pagination","notification","rootcause",@@ -11071,6 +11075,7 @@ dependencies = ["model-entity","model-error-response","model_file_type",+ "model_owner","model_user","models_bulk_upload","models_pagination",@@ -11132,6 +11137,7 @@ dependencies = ["macro_user_id","mention_utils","model-entity",+ "model_owner","models_pagination","notification","paste",@@ -13343,6 +13349,7 @@ dependencies = ["mockall","model-entity","model_notifications",+ "model_owner","models_permissions","models_properties","notification",@@ -14909,6 +14916,7 @@ dependencies = ["mention_utils","model","model_file_type",+ "model_owner","models_email","models_opensearch","models_properties",@@ -15114,6 +15122,7 @@ dependencies = ["mockall","model","model-entity",+ "model_owner","models_email","models_permissions","models_properties",@@ -16008,6 +16017,7 @@ dependencies = ["macro_user_id","messages","model-entity",+ "model_owner","models_properties","projects","properties",@@ -18591,6 +18601,7 @@ dependencies = ["macro_uuid","messages","model-error-response",+ "model_owner","model_user","rate_limit","rdkafka",diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentContentUploadedMetadata.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentContentUploadedMetadata.tsindex 0561091f1a..0fdf255fd7 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentContentUploadedMetadata.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentContentUploadedMetadata.ts@@ -6,7 +6,6 @@*/import type { DocumentContentUploadedMetadataDocumentVersionId } from './documentContentUploadedMetadataDocumentVersionId';import type { FileType } from './fileType';-import type { MacroUserIdStr } from './macroUserIdStr';/*** Metadata for [`DocumentTopicEvent::ContentUploaded`].@@ -21,5 +20,5 @@ writes (mirrors `SearchExtractorMessage::document_version_id`). */type, e.g. `pdf` for the converted rendition of a docx). */file_type: FileType;/** The owner of the document (used by the extractor to resolve S3 keys). */- owner: MacroUserIdStr;+ owner: string;}diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 772bc8a825..c6a36d9560 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -20462,7 +20462,7 @@"description": "File type of the uploaded object (may differ from the document's own\ntype, e.g. `pdf` for the converted rendition of a docx)."},"owner": {- "$ref": "#/components/schemas/MacroUserIdStr",+ "type": "string","description": "The owner of the document (used by the extractor to resolve S3 keys)."}}@@ -20497,7 +20497,7 @@]},"owner": {- "$ref": "#/components/schemas/MacroUserIdStr",+ "type": "string","description": "The owner of the new copy (the copier)."},"project_id": {@@ -20571,7 +20571,7 @@]},"owner": {- "$ref": "#/components/schemas/MacroUserIdStr",+ "type": "string","description": "The owner (creator) of the document."},"project_id": {@@ -21402,7 +21402,7 @@]},"owner": {- "$ref": "#/components/schemas/MacroUserIdStr",+ "type": "string","description": "The owner of the document."},"previous_project_id": {diff --git a/crates/channels/Cargo.toml b/crates/channels/Cargo.tomlindex cedf449a46..5717743a16 100644--- a/crates/channels/Cargo.toml+++ b/crates/channels/Cargo.toml@@ -127,6 +127,7 @@ messages = { path = "../messages" }model-entity = { path = "../model-entity", optional = true }model-error-response = { path = "../model-error-response", optional = true }model_notifications = { path = "../model_notifications", optional = true }+model_owner = { path = "../model_owner" }models_pagination = { path = "../models_pagination" }models_permissions = { path = "../models_permissions", optional = true }non_empty = { path = "../non_empty", optional = true }diff --git a/crates/channels/src/outbound/notification_sender.rs b/crates/channels/src/outbound/notification_sender.rsindex 230bee10b9..5310c61622 100644--- a/crates/channels/src/outbound/notification_sender.rs+++ b/crates/channels/src/outbound/notification_sender.rs@@ -11,6 +11,7 @@ use model_notifications::{ChannelReplyMetadata, CommonChannelMetadata, DocumentMentionMetadata,NotificationDocumentSubType,};+use model_owner::Owner;use notification_hex::domain::{models::SendNotificationRequestBuilder, service::NotificationIngress,};@@ -194,7 +195,7 @@ wheresecondary_notification_entity,notification: DocumentMentionMetadata {document_name: document.document_name,- owner: document.owner,+ owner: Owner::User(document.owner),file_type: document.file_type,sub_type: match document.sub_type.as_deref() {Some("task") => Some(NotificationDocumentSubType::Task),diff --git a/crates/documents/Cargo.toml b/crates/documents/Cargo.tomlindex da03d53c25..a2bd5d2dbf 100644--- a/crates/documents/Cargo.toml+++ b/crates/documents/Cargo.toml@@ -68,7 +68,6 @@ outbound = ["dep:base64","dep:entity_access_db_utils","dep:entity_registry_db_utils",- "dep:model_owner","dep:hex","dep:share_permission_db_utils","dep:sqlx",@@ -145,7 +144,7 @@ cloudfront_sign = { workspace = true }comms_db_client = { path = "../comms_db_client", optional = true }entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils", optional = true }-model_owner = { path = "../model_owner", optional = true }+model_owner = { path = "../model_owner" }futures = { workspace = true }share_permission_db_utils = { path = "../share_permission_db_utils", optional = true }hex = { workspace = true, optional = true }diff --git a/crates/documents/src/domain/activity.rs b/crates/documents/src/domain/activity.rsindex 089522be00..f93a54aa36 100644--- a/crates/documents/src/domain/activity.rs+++ b/crates/documents/src/domain/activity.rs@@ -14,6 +14,15 @@ use uuid::Uuid;use super::events::DocumentTopicEvent;use macro_user_id::user_id::MacroUserIdStr;+use model_owner::Owner;++fn actor_from_owner(owner: &Owner) -> Option<Actor<'static>> {+ match owner {+ Owner::User(user) => Some(Actor::new_from_user(user.clone())),+ Owner::Bot(bot_id) => Some(Actor::new_from_bot(*bot_id)),+ Owner::Team(_) => None,+ }+}/// Attribution for `updated` / `deleted` events. Bot receipts publish `actor`;/// user receipts (and events from before attribution) only `actor_user_id`.@@ -52,16 +61,19 @@ impl ActivitySource for DocumentTopicEvent {match self {DocumentTopicEvent::Created(metadata) => {- let actor = metadata+ match metadata.actor.clone()- .unwrap_or_else(|| Actor::new_from_user(metadata.owner.clone()));- single(- Attribution::new(actor, metadata.on_behalf_of.clone()),- CommonAction::Created,- &metadata.document_id,- metadata.created_at.unwrap_or_else(|| event_time(event_id)),- )+ .or_else(|| actor_from_owner(&metadata.owner))+ {+ Some(actor) => single(+ Attribution::new(actor, metadata.on_behalf_of.clone()),+ CommonAction::Created,+ &metadata.document_id,+ metadata.created_at.unwrap_or_else(|| event_time(event_id)),+ ),+ None => Ingest::Ignore,+ }}DocumentTopicEvent::Updated(metadata) => {match mutation_attribution(@@ -94,12 +106,15 @@ impl ActivitySource for DocumentTopicEvent {}}// The copy is a new document; its creation is the activity.- DocumentTopicEvent::Copied(metadata) => single(- Attribution::direct(Actor::new_from_user(metadata.owner.clone())),- CommonAction::Created,- &metadata.document_id,- event_time(event_id),- ),+ DocumentTopicEvent::Copied(metadata) => match actor_from_owner(&metadata.owner) {+ Some(actor) => single(+ Attribution::direct(actor),+ CommonAction::Created,+ &metadata.document_id,+ event_time(event_id),+ ),+ None => Ingest::Ignore,+ },DocumentTopicEvent::Purged(metadata) => {Ingest::Purge(vec![(EntityType::Document, metadata.document_id.clone())])}diff --git a/crates/documents/src/domain/activity/test.rs b/crates/documents/src/domain/activity/test.rsindex 38902e965f..816ed9e5d6 100644--- a/crates/documents/src/domain/activity/test.rs+++ b/crates/documents/src/domain/activity/test.rs@@ -13,6 +13,7 @@ use crate::domain::events::{DocumentInteractionMetadata, DocumentPurgedMetadata, DocumentSyncContentUpdatedMetadata,DocumentUpdatedMetadata, InteractionReason,};+use model_owner::Owner;const DOCUMENT_ID: &str = "11111111-1111-1111-1111-111111111111";@@ -39,7 +40,7 @@ fn created_maps_to_a_created_activity_with_the_metadata_timestamp() {let created_at = Utc.with_ymd_and_hms(2026, 8, 5, 12, 0, 0).unwrap();let event = envelope(DocumentTopicEvent::Created(DocumentCreatedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user("macro|[email protected]"),+ owner: Owner::from_principal_str("macro|[email protected]").unwrap(),actor: None,on_behalf_of: None,document_name: "spec".to_string(),@@ -63,7 +64,7 @@ fn created_maps_to_a_created_activity_with_the_metadata_timestamp() {fn created_with_system_actor_is_not_the_owner_subject() {let event = envelope(DocumentTopicEvent::Created(DocumentCreatedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user("macro|[email protected]"),+ owner: Owner::from_principal_str("macro|[email protected]").unwrap(),actor: Some(Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID)),on_behalf_of: None,document_name: "invoice".to_string(),@@ -89,7 +90,7 @@ fn created_with_system_actor_is_not_the_owner_subject() {fn created_on_behalf_of_the_owner_stays_on_their_feed() {let event = envelope(DocumentTopicEvent::Created(DocumentCreatedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user("macro|[email protected]"),+ owner: Owner::from_principal_str("macro|[email protected]").unwrap(),actor: Some(Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID)),on_behalf_of: Some(user("macro|[email protected]")),document_name: "welcome".to_string(),@@ -111,7 +112,7 @@ fn created_on_behalf_of_the_owner_stays_on_their_feed() {fn attributed_update_and_delete_map_to_activities() {let updated = envelope(DocumentTopicEvent::Updated(DocumentUpdatedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user("macro|[email protected]"),+ owner: Owner::from_principal_str("macro|[email protected]").unwrap(),actor_user_id: Some(user("macro|[email protected]")),actor: None,on_behalf_of: None,@@ -140,7 +141,7 @@ fn attributed_update_and_delete_map_to_activities() {fn delegated_update_stays_on_the_user_feed() {let updated = envelope(DocumentTopicEvent::Updated(DocumentUpdatedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user("macro|[email protected]"),+ owner: Owner::from_principal_str("macro|[email protected]").unwrap(),actor_user_id: None,actor: Some(Actor::new_from_bot(bot_id::MACRO_AI_BOT_ID)),on_behalf_of: Some(user("macro|[email protected]")),@@ -163,7 +164,7 @@ fn delegated_update_stays_on_the_user_feed() {fn unattributable_mutations_are_dropped() {let updated = envelope(DocumentTopicEvent::Updated(DocumentUpdatedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user("macro|[email protected]"),+ owner: Owner::from_principal_str("macro|[email protected]").unwrap(),actor_user_id: None,actor: None,on_behalf_of: None,@@ -191,7 +192,7 @@ fn copied_maps_to_a_created_activity_for_the_new_document() {document_id: "22222222-2222-2222-2222-222222222222".to_string(),source_document_id: DOCUMENT_ID.to_string(),source_version_id: None,- owner: user("macro|[email protected]"),+ owner: Owner::from_principal_str("macro|[email protected]").unwrap(),document_name: "copy".to_string(),file_type: None,project_id: None,diff --git a/crates/documents/src/domain/create/test.rs b/crates/documents/src/domain/create/test.rsindex f86469da78..6d7cc92910 100644--- a/crates/documents/src/domain/create/test.rs+++ b/crates/documents/src/domain/create/test.rs@@ -15,6 +15,7 @@ use crate::domain::response::{CreateDocumentResponseData, DocumentResponse, DocumentResponseMetadataWithContent,};use model::document::response::DocumentResponseMetadata;+use model_owner::Owner;const DOCUMENT_ID: &str = "created-task";const EMAIL_SEED: &str = r#"<m-document-mention>{"documentId":"thread-7","blockName":"email","documentName":"Re: invoice"}</m-document-mention>"#;@@ -43,7 +44,7 @@ impl DocumentCreationService for FakeCreationService {DocumentResponseMetadata {document_id: DOCUMENT_ID.to_string(),document_version_id: 1,- owner: user_id,+ owner: Owner::User(user_id),document_name: "task".to_string(),file_type: file_type.clone(),sha: None,diff --git a/crates/documents/src/domain/events.rs b/crates/documents/src/domain/events.rsindex 2053c6c1dd..ae37a24446 100644--- a/crates/documents/src/domain/events.rs+++ b/crates/documents/src/domain/events.rs@@ -14,6 +14,7 @@ use macro_event_broker::{Event, MacroEvent, TopicEvent};use macro_event_topics::MacroDocumentsTopic;use macro_user_id::user_id::MacroUserIdStr;use model::document::FileType;+use model_owner::Owner;use serde::{Deserialize, Serialize};use super::models::FileTypeUpdate;@@ -25,7 +26,8 @@ pub struct DocumentCreatedMetadata {/// The id of the created document.pub document_id: String,/// The owner (creator) of the document.- pub owner: MacroUserIdStr<'static>,+ #[cfg_attr(feature = "schema", schema(value_type = String))]+ pub owner: Owner,/// Who mechanically created the document. Absent on events published/// before attribution: ingest then treats [`Self::owner`] as the actor.#[serde(default, skip_serializing_if = "Option::is_none")]@@ -54,7 +56,8 @@ pub struct DocumentUpdatedMetadata {/// The id of the updated document.pub document_id: String,/// The owner of the document.- pub owner: MacroUserIdStr<'static>,+ #[cfg_attr(feature = "schema", schema(value_type = String))]+ pub owner: Owner,/// The authenticated user who performed the update; `None` for/// unauthenticated or internal callers.pub actor_user_id: Option<MacroUserIdStr<'static>>,@@ -111,7 +114,8 @@ pub struct DocumentContentUploadedMetadata {/// The id of the document whose stored bytes changed.pub document_id: String,/// The owner of the document (used by the extractor to resolve S3 keys).- pub owner: MacroUserIdStr<'static>,+ #[cfg_attr(feature = "schema", schema(value_type = String))]+ pub owner: Owner,/// File type of the uploaded object (may differ from the document's own/// type, e.g. `pdf` for the converted rendition of a docx).pub file_type: FileType,@@ -203,7 +207,8 @@ pub struct DocumentCopiedMetadata {/// The specific source version copied, when requested.pub source_version_id: Option<i64>,/// The owner of the new copy (the copier).- pub owner: MacroUserIdStr<'static>,+ #[cfg_attr(feature = "schema", schema(value_type = String))]+ pub owner: Owner,/// The name of the new document.pub document_name: String,/// File type of the document, when known.diff --git a/crates/documents/src/domain/events/test.rs b/crates/documents/src/domain/events/test.rsindex 80ced5f1a9..47620724aa 100644--- a/crates/documents/src/domain/events/test.rs+++ b/crates/documents/src/domain/events/test.rs@@ -1,6 +1,6 @@use macro_event_broker::{Event, MacroEvent as _, TopicEvent};-use macro_user_id::user_id::MacroUserIdStr;use model::document::FileType;+use model_owner::Owner;use serde_json::{Value, json};use uuid::Uuid;@@ -12,8 +12,8 @@ use super::{const DOCUMENT_ID: &str = "11111111-1111-1111-1111-111111111111";-fn owner() -> MacroUserIdStr<'static> {- MacroUserIdStr::try_from("macro|[email protected]".to_string()).expect("valid user id")+fn owner() -> Owner {+ Owner::from_principal_str("macro|[email protected]").expect("valid owner")}fn assert_wire_round_trip(event: Event<DocumentTopicEvent>, expected: Value) {@@ -212,7 +212,10 @@ fn created_events_without_attribution_still_decode() {match decoded.event {DocumentTopicEvent::Created(metadata) => {- assert_eq!(metadata.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ metadata.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );assert_eq!(metadata.actor, None);assert_eq!(metadata.on_behalf_of, None);}diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rsindex 5dfa0fb6ae..d096d9769d 100644--- a/crates/documents/src/domain/service.rs+++ b/crates/documents/src/domain/service.rs@@ -41,6 +41,7 @@ use model::document::{ContentType, DocumentBasic, DocumentMetadata, FileAssociation, FileType, FileTypeExt,};use model::response::PresignedUrl;+use model_owner::Owner;use s3_key::{build_cloud_storage_bucket_document_key, build_docx_staging_bucket_document_key,build_docx_to_pdf_converted_document_key,@@ -729,8 +730,9 @@ impl<Ok(None)}Some(FileType::Docx) => {+ let owner = document_metadata.owner.principal_id();let docx_key = build_docx_staging_bucket_document_key(- document_metadata.owner.as_ref(),+ &owner,&document_id,document_metadata.document_version_id,);@@ -740,8 +742,9 @@ impl<.map(Some)}_ => {+ let owner = document_metadata.owner.principal_id();let key = build_cloud_storage_bucket_document_key(- document_metadata.owner.as_ref(),+ &owner,&document_id,document_metadata.document_version_id,);@@ -921,7 +924,7 @@ impl<let is_owner = matches!(team_receipt.auth(),- EntityAccessAuth::Authenticated(user_id) if document.owner == *user_id+ EntityAccessAuth::Authenticated(user_id) if document.owner.is_user(user_id));if document.deleted_at.is_some() && !is_owner {return Err(DocumentError::Unauthorized);@@ -1014,11 +1017,11 @@ impl<return Ok(response);}- let owner = document_context.owner.as_ref();+ let owner = document_context.owner.principal_id();let get_converted_docx_url = params.get_converted_docx_url.unwrap_or(false);let response_data = self.get_presigned_url_by_type(- owner,+ &owner,&document_id,file_type,params.document_version_id,@@ -1685,7 +1688,8 @@ impl<let copy_result = match file_type {Some(FileType::Docx) => {// Copy the converted PDF version- let url_encoded_owner = urlencoding::encode(original_metadata.owner.as_ref());+ let owner = original_metadata.owner.principal_id();+ let url_encoded_owner = urlencoding::encode(&owner);let source_key = build_docx_to_pdf_converted_document_key(&url_encoded_owner,&original_metadata.document_id,@@ -1723,7 +1727,7 @@ impl<.0;let source_key = build_cloud_storage_bucket_document_key(- original_metadata.owner.as_ref(),+ &original_metadata.owner.principal_id(),&original_metadata.document_id,source_version_id,);@@ -1772,7 +1776,7 @@ impl<};let source_key = build_cloud_storage_bucket_document_key(- original_metadata.owner.as_ref(),+ &original_metadata.owner.principal_id(),&original_metadata.document_id,source_version_id,);@@ -1838,7 +1842,7 @@ impl<document_id: new_document_id.clone(),source_document_id: original_metadata.document_id.clone(),source_version_id: query_version_id,- owner: user_id.clone(),+ owner: Owner::User(user_id.clone()),document_name: new_metadata.document_name.clone(),file_type,project_id: new_metadata.project_id.clone(),diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rsindex 65793e6d13..2c0bae2ff6 100644--- a/crates/documents/src/domain/service/tests.rs+++ b/crates/documents/src/domain/service/tests.rs@@ -22,9 +22,7 @@ fn make_test_metadata() -> DocumentMetadata {DocumentMetadata {document_id: "doc-1".to_string(),document_version_id: 1,- owner: macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),+ owner: Owner::from_principal_str("macro|[email protected]").unwrap(),document_name: "test_doc".to_string(),file_type: Some("txt".to_string()),sha: Some("sha-1".to_string()),@@ -60,9 +58,7 @@ fn task_document_context(document_id: &str) -> DocumentBasic {DocumentBasic {document_id: document_id.to_string(),document_name: "Test task".to_string(),- owner: macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),+ owner: Owner::from_principal_str("macro|[email protected]").unwrap(),file_type: Some("md".to_string()),sub_type: Some(DocumentSubType::Task),branched_from_id: None,@@ -1516,9 +1512,12 @@ fn owner_receipt(document_id: &str) -> EntityAccessReceipt<OwnerAccessLevel> {}fn team_share_facts() -> models_permissions::share_permission::team_share::TeamShareFacts {+ let Owner::User(owner) = task_document_context("doc-1").owner else {+ panic!("test document owner is a user");+ };models_permissions::share_permission::team_share::TeamShareFacts {entity: EntityType::Document.with_entity_str("doc-1"),- owner: task_document_context("doc-1").owner,+ owner,owner_team_id: Some(uuid::Uuid::from_u128(1)),current: None,revision: 0,@@ -1615,7 +1614,7 @@ async fn team_policy_rejects_editors_inherited_owners_and_identityless_receipts(let (service, broker) = make_test_service_with_event_broker(repo);// Even a context claiming the actor owns it cannot replace persisted facts.let mut context = task_document_context("doc-1");- context.owner = edit_receipt("doc-1").acting_user_id().unwrap().clone();+ context.owner = Owner::User(edit_receipt("doc-1").acting_user_id().unwrap().clone());assert!(matches!(service.edit_document(receipt, context, team_edit_args(level))diff --git a/crates/documents/src/inbound/axum_router/tests.rs b/crates/documents/src/inbound/axum_router/tests.rsindex 79064cca87..9a10045c10 100644--- a/crates/documents/src/inbound/axum_router/tests.rs+++ b/crates/documents/src/inbound/axum_router/tests.rs@@ -26,6 +26,7 @@ use model::{sync_service::SyncServiceVersionID,};use model_entity::Entity;+use model_owner::Owner;use model_user::UserContext;use rootcause::Report;use serde_json::{Value, json};@@ -208,8 +209,7 @@ impl DocumentService for FakeDocumentService {Ok(DocumentBasic {document_id: document_id.to_string(),document_name: "test document".to_string(),- owner: MacroUserIdStr::try_from(JWT_USER_ID.to_string())- .expect("test user id should be valid"),+ owner: Owner::from_principal_str(JWT_USER_ID).expect("test user id should be valid"),file_type: Some("pdf".to_string()),sub_type: None,branched_from_id: None,@@ -528,7 +528,7 @@ fn create_document_response(user_id: MacroUserIdStr<'static>) -> CreateDocumentRDocumentResponseMetadata {document_id: "created-document".to_string(),document_version_id: 1,- owner: user_id,+ owner: Owner::User(user_id),document_name: "test document".to_string(),file_type: Some("pdf".to_string()),sha: Some("test-sha".to_string()),@@ -556,7 +556,7 @@ fn get_document_response(document_id: &str) -> GetDocumentResponseData {DocumentMetadata {document_id: document_id.to_string(),document_version_id: 1,- owner: MacroUserIdStr::try_from(JWT_USER_ID.to_string())+ owner: Owner::from_principal_str(JWT_USER_ID).expect("test user id should be valid"),document_name: "resolved document".to_string(),file_type: Some("pdf".to_string()),diff --git a/crates/documents/src/inbound/toolset/edit_document/test.rs b/crates/documents/src/inbound/toolset/edit_document/test.rsindex 3533a31d71..e32e3c8ef3 100644--- a/crates/documents/src/inbound/toolset/edit_document/test.rs+++ b/crates/documents/src/inbound/toolset/edit_document/test.rs@@ -23,6 +23,7 @@ use macro_sync_service_jwt::DocumentPermissionToken;use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};use model::{document::DocumentBasic, sync_service::SyncServiceVersionID};use model_entity::Entity;+use model_owner::Owner;use sync_service_client::SyncServiceClient;use uuid::Uuid;@@ -33,8 +34,7 @@ fn document_with_file_type(file_type: Option<&str>) -> DocumentBasic {DocumentBasic {document_id: TEST_DOCUMENT_ID.to_string(),document_name: "Test document".to_string(),- owner: MacroUserIdStr::try_from(TEST_USER_ID.to_string())- .expect("test user id should be valid"),+ owner: Owner::from_principal_str(TEST_USER_ID).expect("test user id should be valid"),file_type: file_type.map(str::to_string),sub_type: None,branched_from_id: None,diff --git a/crates/documents/src/outbound/pg_document_repo.rs b/crates/documents/src/outbound/pg_document_repo.rsindex 89c9fbe5a9..c69445c54f 100644--- a/crates/documents/src/outbound/pg_document_repo.rs+++ b/crates/documents/src/outbound/pg_document_repo.rs@@ -14,6 +14,7 @@ mod share;use document_sub_type::DocumentSubType;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model::document::{DocumentBasic, DocumentMetadata};+use model_owner::Owner;use models_permissions::share_permission::{SharePermissionV2, TeamLinkShareDefault};use sqlx::PgPool;@@ -209,9 +210,8 @@ impl DocumentRepo for PgDocumentRepo {Ok(DocumentMetadata {document_id: row.document_id,document_version_id: row.document_version_id,- owner: MacroUserIdStr::parse_from_str(&row.owner)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),+ owner: Owner::from_principal_str(&row.owner)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,document_name: row.document_name,file_type: row.file_type,sha: row.sha,@@ -281,9 +281,8 @@ impl DocumentRepo for PgDocumentRepo {Ok(DocumentBasic {document_id: row.document_id,document_name: row.document_name,- owner: MacroUserIdStr::parse_from_str(&row.owner)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),+ owner: Owner::from_principal_str(&row.owner)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,file_type: row.file_type,sub_type: row.sub_type,branched_from_id: row.branched_from_id,@@ -607,7 +606,11 @@ impl DocumentRepo for PgDocumentRepo {}if args.revoke_non_owner_user_access {- let owner = edit::get_document_owner(&mut transaction, &args.document_id).await?;+ let owner = Owner::from_principal_str(+ &edit::get_document_owner(&mut transaction, &args.document_id).await?,+ )+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?;+ let owner_principal = owner.principal_id();// SAFETY: document IDs are UUID strings.let entity_id = macro_uuid::string_to_uuid(&args.document_id).unwrap();@@ -616,7 +619,7 @@ impl DocumentRepo for PgDocumentRepo {&mut transaction,&entity_id,EntityType::Document,- &owner,+ &owner_principal,).await?;}@@ -998,9 +1001,8 @@ impl DocumentRepo for PgDocumentRepo {Ok(DocumentMetadata {document_id: row.document_id,document_version_id: row.document_version_id,- owner: MacroUserIdStr::parse_from_str(&row.owner)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),+ owner: Owner::from_principal_str(&row.owner)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,document_name: row.document_name,file_type: row.file_type,sha: row.sha,diff --git a/crates/documents/src/outbound/pg_document_repo/copy.rs b/crates/documents/src/outbound/pg_document_repo/copy.rsindex 630b554edb..7aae82f38c 100644--- a/crates/documents/src/outbound/pg_document_repo/copy.rs+++ b/crates/documents/src/outbound/pg_document_repo/copy.rs@@ -3,6 +3,7 @@ use model::document::{BomPart, DocumentMetadata, IDWithTimeStamps, SaveBomPart, VersionIDWithTimeStamps,VersionIDWithTimeStampsNoSha,};+use model_owner::Owner;use sqlx::{Postgres, Transaction};/// Copies a given docx document (Document + DocumentBom + BomParts).@@ -73,7 +74,7 @@ pub async fn copy_docx_document(Ok(DocumentMetadata {document_id: document.id.clone(),- owner: user_id,+ owner: Owner::User(user_id),document_name: new_document_name.to_string(),file_type: original_document.file_type.clone(),sha: None,@@ -188,7 +189,7 @@ pub async fn copy_non_docx_document(Ok(DocumentMetadata {document_id: document.id.clone(),- owner: user_id,+ owner: Owner::User(user_id),document_name: new_document_name.to_string(),file_type: original_document.file_type.clone(),sha: Some(document_instance.sha),diff --git a/crates/documents/src/outbound/pg_document_repo/create.rs b/crates/documents/src/outbound/pg_document_repo/create.rsindex d3ed387767..0702afc3cd 100644--- a/crates/documents/src/outbound/pg_document_repo/create.rs+++ b/crates/documents/src/outbound/pg_document_repo/create.rs@@ -1,6 +1,7 @@use document_sub_type::DocumentSubType;use macro_user_id::user_id::MacroUserIdStr;use model::document::{DocumentMetadata, FileType, VersionIDWithTimeStamps};+use model_owner::Owner;use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::team_share::TeamShareCreation;use share_permission_db_utils::team_share::{self, TeamShareError};@@ -482,7 +483,7 @@ pub async fn insert_new_document(Ok(DocumentMetadata::new_document(&document_id.to_string(),document_version.id,- user_id,+ Owner::User(user_id),&document_name,file_type,&document_version.sha,diff --git a/crates/documents/src/outbound/pg_document_repo/tests.rs b/crates/documents/src/outbound/pg_document_repo/tests.rsindex 3303b946e5..1c391dbfe4 100644--- a/crates/documents/src/outbound/pg_document_repo/tests.rs+++ b/crates/documents/src/outbound/pg_document_repo/tests.rs@@ -1,6 +1,7 @@use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::cowlike::CowLike;use model_entity::EntityType;+use model_owner::Owner;use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::channel_share_permission::{UpdateChannelSharePermission, UpdateOperation,@@ -730,7 +731,10 @@ async fn test_get_document_metadata(pool: Pool<Postgres>) {.unwrap();assert_eq!(metadata.document_id, "d0000000-0000-0000-0000-000000000001");assert_eq!(metadata.document_name, "test_document_name");- assert_eq!(metadata.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ metadata.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );assert_eq!(metadata.document_version_id, 1);assert_eq!(metadata.file_type, Some("txt".to_string()));@@ -752,7 +756,10 @@ async fn test_get_basic_document(pool: Pool<Postgres>) {.unwrap();assert_eq!(basic.document_id, "d0000000-0000-0000-0000-000000000001");assert_eq!(basic.document_name, "test_document_name");- assert_eq!(basic.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ basic.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );assert_eq!(basic.file_type, Some("txt".to_string()));// Not found@@ -760,6 +767,63 @@ async fn test_get_basic_document(pool: Pool<Postgres>) {assert!(result.is_err());}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn get_document_metadata_and_basic_document_decode_bot_and_team_owners(pool: Pool<Postgres>) {+ const BOT_OWNER: &str = "bot|00000000-0000-0000-0000-00000000a1a1";+ const TEAM_OWNER: &str = "00000000-0000-0000-0000-00000000a2a2";++ sqlx::query(+ r#"+ INSERT INTO "User" (id, email, macro_user_id)+ VALUES ($1, $2, $3), ($4, $5, $6)+ ON CONFLICT (id) DO NOTHING+ "#,+ )+ .bind(BOT_OWNER)+ .bind("[email protected]")+ .bind(uuid::Uuid::parse_str("a1111111-1111-1111-1111-111111111111").unwrap())+ .bind(TEAM_OWNER)+ .bind("[email protected]")+ .bind(uuid::Uuid::parse_str("a2222222-2222-2222-2222-222222222222").unwrap())+ .execute(&pool)+ .await+ .unwrap();++ sqlx::query(r#"UPDATE "Document" SET owner = $1 WHERE id = $2"#)+ .bind(BOT_OWNER)+ .bind(TEST_DOCUMENT_ID)+ .execute(&pool)+ .await+ .unwrap();++ let repo = PgDocumentRepo::new(pool.clone());+ let metadata = repo.get_document_metadata(TEST_DOCUMENT_ID).await.unwrap();+ assert_eq!(+ metadata.owner,+ Owner::from_principal_str(BOT_OWNER).unwrap()+ );+ let basic = repo.get_basic_document(TEST_DOCUMENT_ID).await.unwrap();+ assert_eq!(basic.owner, Owner::from_principal_str(BOT_OWNER).unwrap());++ sqlx::query(r#"UPDATE "Document" SET owner = $1 WHERE id = $2"#)+ .bind(TEAM_OWNER)+ .bind(TEST_DOCUMENT_ID)+ .execute(&pool)+ .await+ .unwrap();++ let metadata = repo.get_document_metadata(TEST_DOCUMENT_ID).await.unwrap();+ assert_eq!(+ metadata.owner,+ Owner::from_principal_str(TEAM_OWNER).unwrap()+ );+ let basic = repo.get_basic_document(TEST_DOCUMENT_ID).await.unwrap();+ assert_eq!(basic.owner, Owner::from_principal_str(TEAM_OWNER).unwrap());+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("documents_test_data"))diff --git a/crates/entity_access/Cargo.toml b/crates/entity_access/Cargo.tomlindex ae83c84d7e..fd5f14037a 100644--- a/crates/entity_access/Cargo.toml+++ b/crates/entity_access/Cargo.toml@@ -59,6 +59,7 @@ axum = { workspace = true, optional = true }macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = ["axum"] }model = { path = "../model", optional = true }model-error-response = { path = "../model-error-response", optional = true }+model_owner = { path = "../model_owner" }# OpenAPI schema (optional)utoipa = { workspace = true, optional = true }diff --git a/crates/entity_access/src/inbound/axum_extractors/document.rs b/crates/entity_access/src/inbound/axum_extractors/document.rsindex 231f5fc075..c7ef7ad63b 100644--- a/crates/entity_access/src/inbound/axum_extractors/document.rs+++ b/crates/entity_access/src/inbound/axum_extractors/document.rs@@ -125,7 +125,7 @@ where// Check ownership only if authenticatedif let Some(ref user_id) = macro_user_id- && document_context.owner == *user_id+ && document_context.owner.is_user(user_id){return Ok(Self {entity_access_receipt: EntityAccessReceipt {diff --git a/crates/entity_access/src/inbound/axum_extractors/document/test.rs b/crates/entity_access/src/inbound/axum_extractors/document/test.rsindex 74185b9905..5d0badce0c 100644--- a/crates/entity_access/src/inbound/axum_extractors/document/test.rs+++ b/crates/entity_access/src/inbound/axum_extractors/document/test.rs@@ -29,6 +29,7 @@ use macro_authorization::{};use macro_user_id::user_id::MacroUserIdStr;use model::document::DocumentBasic;+use model_owner::Owner;use model_user::UserContext;use rootcause::Report;@@ -166,7 +167,7 @@ fn document(deleted: bool) -> DocumentBasic {let mut document = DocumentBasic {document_id: DOCUMENT_ID.to_string(),document_name: "Test document".to_string(),- owner: MacroUserIdStr::parse_from_str(OWNER_ID).expect("owner id should be valid"),+ owner: Owner::from_principal_str(OWNER_ID).expect("owner id should be valid"),file_type: None,sub_type: None,branched_from_id: None,@@ -276,6 +277,54 @@ async fn authenticated_owner_bypasses_access_lookup() {assert!(state.entity_access.calls().is_empty());}+#[tokio::test]+async fn bot_owner_does_not_take_user_owner_fast_path() {+ let state = TestState::new(Some(AccessLevel::Edit));+ let mut document = document(false);+ document.owner = Owner::from_principal_str("bot|00000000-0000-0000-0000-00000000a1a1")+ .expect("bot owner should be valid");++ let extracted = extract::<EditAccessLevel>(request(Some("valid"), document), &state)+ .await+ .expect("non-owner should fall through to entity_access");++ assert!(matches!(+ extracted.entity_access_receipt.entity_permission(),+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Edit+ }+ ));+ assert_eq!(state.entity_access.calls().len(), 1);+ assert_eq!(+ state.entity_access.calls()[0].user_id.as_deref(),+ Some(USER_ID)+ );+}++#[tokio::test]+async fn team_owner_does_not_take_user_owner_fast_path() {+ let state = TestState::new(Some(AccessLevel::View));+ let mut document = document(false);+ document.owner = Owner::from_principal_str("01234567-89ab-cdef-0123-456789abcdef")+ .expect("team owner should be valid");++ let extracted = extract::<ViewAccessLevel>(request(Some("valid"), document), &state)+ .await+ .expect("non-owner should fall through to entity_access");++ assert!(matches!(+ extracted.entity_access_receipt.entity_permission(),+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View+ }+ ));+ assert_eq!(state.entity_access.calls().len(), 1);+ assert_eq!(+ state.entity_access.calls()[0].user_id.as_deref(),+ Some(USER_ID)+ );+}+#[tokio::test]async fn insufficient_access_is_rejected() {let state = TestState::new(Some(AccessLevel::View));diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rsindex 8fbb3162f8..769828b16a 100644--- a/crates/github/src/domain/service/sync/test.rs+++ b/crates/github/src/domain/service/sync/test.rs@@ -108,7 +108,7 @@ impl StubDocumentService {DocumentMetadata {document_id: document_id.to_string(),document_version_id: 1,- owner: MacroUserIdStr::try_from_email("[email protected]").unwrap(),+ owner: "macro|[email protected]".to_string().try_into().unwrap(),document_name: "My Task".to_string(),file_type: Some("md".to_string()),sha: None,diff --git a/crates/macro_db_client/src/convert.rs b/crates/macro_db_client/src/convert.rsindex ef41240b92..bc0109c17b 100644--- a/crates/macro_db_client/src/convert.rs+++ b/crates/macro_db_client/src/convert.rs@@ -1,5 +1,5 @@-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model::document::DocumentMetadata;+use model_owner::Owner;/// Gets all docx files#[tracing::instrument(skip(db))]@@ -81,9 +81,8 @@ pub async fn get_docx_files(Ok(DocumentMetadata {document_id: row.document_id,document_version_id: row.document_version_id,- owner: MacroUserIdStr::parse_from_str(&row.owner)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),+ owner: Owner::from_principal_str(&row.owner)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,document_name: row.document_name,file_type: row.file_type,created_at: row.created_at,diff --git a/crates/macro_db_client/src/document/create_blank_docx.rs b/crates/macro_db_client/src/document/create_blank_docx.rsindex 6271e0014e..040e6d3d2d 100644--- a/crates/macro_db_client/src/document/create_blank_docx.rs+++ b/crates/macro_db_client/src/document/create_blank_docx.rs@@ -13,6 +13,7 @@ use model::document::DocumentMetadata;use model::document::ID;use model::document::VersionID;use model::document::VersionIDWithTimeStamps;+use model_owner::Owner;use tracing::instrument;/// Creates a blank docx document@@ -145,7 +146,7 @@ pub async fn create_blank_docx(Ok(DocumentMetadata {document_id: document.id,document_version_id: document_version.id,- owner: user_id,+ owner: Owner::User(user_id),document_name: document_name.to_string(),file_type: Some(FileType::Docx.as_str().to_string()),sha: None,@@ -186,7 +187,10 @@ mod tests {assert!(!document_metadata.document_id.is_empty());assert_eq!(document_metadata.document_name, "document-name".to_string());- assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ document_metadata.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );Ok(())}diff --git a/crates/macro_db_client/src/document/get_all_documents.rs b/crates/macro_db_client/src/document/get_all_documents.rsindex 12a70c953a..839281e3f6 100644--- a/crates/macro_db_client/src/document/get_all_documents.rs+++ b/crates/macro_db_client/src/document/get_all_documents.rs@@ -1,6 +1,6 @@use document_sub_type::DocumentSubType;-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model::document::DocumentMetadata;+use model_owner::Owner;use sqlx::{Pool, Postgres};/// Used to get all documents in a paginated format@@ -110,9 +110,8 @@ pub async fn get_all_documents(Ok(DocumentMetadata {document_id: row.document_id,document_version_id: row.document_version_id,- owner: MacroUserIdStr::parse_from_str(&row.owner)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),+ owner: Owner::from_principal_str(&row.owner)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,document_name: row.document_name,file_type: row.file_type,sha: row.sha,diff --git a/crates/macro_db_client/src/document/get_document.rs b/crates/macro_db_client/src/document/get_document.rsindex 4d8308a590..d557a710d7 100644--- a/crates/macro_db_client/src/document/get_document.rs+++ b/crates/macro_db_client/src/document/get_document.rs@@ -1,4 +1,4 @@-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use model_owner::Owner;use sqlx::{Pool, Postgres, Transaction};use document_sub_type::DocumentSubType;@@ -156,9 +156,8 @@ pub async fn get_basic_document(Ok(DocumentBasic {document_id: row.document_id,document_name: row.document_name,- owner: MacroUserIdStr::parse_from_str(&row.owner)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),+ owner: Owner::from_principal_str(&row.owner)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,file_type: row.file_type,sub_type: row.sub_type,branched_from_id: row.branched_from_id,@@ -207,9 +206,8 @@ pub async fn get_basic_documents(Ok(DocumentBasic {document_id: row.document_id,document_name: row.document_name,- owner: MacroUserIdStr::parse_from_str(&row.owner)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),+ owner: Owner::from_principal_str(&row.owner)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,file_type: row.file_type,sub_type: row.sub_type,branched_from_id: row.branched_from_id,@@ -255,9 +253,8 @@ pub async fn get_deleted_document_info(Ok(DocumentBasic {document_id: row.document_id,document_name: row.document_name,- owner: MacroUserIdStr::parse_from_str(&row.owner)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),+ owner: Owner::from_principal_str(&row.owner)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,file_type: row.file_type,sub_type: row.sub_type,branched_from_id: row.branched_from_id,@@ -365,9 +362,8 @@ pub async fn get_document(Ok(DocumentMetadata {document_id: row.document_id,document_version_id: row.document_version_id,- owner: MacroUserIdStr::parse_from_str(&row.owner)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),+ owner: Owner::from_principal_str(&row.owner)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,document_name: row.document_name,file_type: row.file_type,sha: row.sha,@@ -481,9 +477,8 @@ pub async fn get_document_version(Ok(DocumentMetadata {document_id: row.document_id,document_version_id: row.document_version_id,- owner: MacroUserIdStr::parse_from_str(&row.owner)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),+ owner: Owner::from_principal_str(&row.owner)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,document_name: row.document_name,file_type: row.file_type,sha: row.sha,@@ -635,9 +630,8 @@ mod tests {get_basic_document(&pool, "document-one").await.unwrap()- .owner- .as_ref(),- "macro|[email protected]",+ .owner,+ Owner::from_principal_str("macro|[email protected]").unwrap());}@@ -660,7 +654,10 @@ mod tests {document_metadata.document_name,"test_document_name".to_string());- assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ document_metadata.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );}#[sqlx::test(fixtures(path = "../../fixtures", scripts("basic_user_with_documents")))]@@ -675,7 +672,10 @@ mod tests {document_metadata.document_name,"test_document_name".to_string());- assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ document_metadata.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );}#[sqlx::test(fixtures(path = "../../fixtures", scripts("basic_user_with_documents")))]@@ -692,7 +692,10 @@ mod tests {document_metadata.document_name,"test_document_name".to_string());- assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ document_metadata.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );}#[sqlx::test(fixtures(path = "../../fixtures", scripts("basic_user_with_documents")))]diff --git a/crates/macro_db_client/src/document/initialize_onboarding_documents.rs b/crates/macro_db_client/src/document/initialize_onboarding_documents.rsindex a4d1e1457d..c81af63422 100644--- a/crates/macro_db_client/src/document/initialize_onboarding_documents.rs+++ b/crates/macro_db_client/src/document/initialize_onboarding_documents.rs@@ -7,6 +7,7 @@ use model::document::{BasicDocument, FileType};use model::document::{ID, SaveBomPart, VersionID};use model::project::Project;use model_entity::EntityType;+use model_owner::Owner;use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::access_level::AccessLevel;use sqlx::{Postgres, Transaction};@@ -157,7 +158,7 @@ pub async fn create_onboarding_documents(documents.push(BasicDocument {document_id: document_id.to_string(),document_version_id: *document_version_id,- owner: user_id.clone(),+ owner: Owner::User(user_id.clone()),document_name: document_names.0.to_string(),file_type: Some(document_names.1.to_string()),sha: None,@@ -222,7 +223,7 @@ pub async fn create_onboarding_docx(Ok(BasicDocument {document_id: document.id,document_version_id: document_bom.id,- owner: user_id,+ owner: Owner::User(user_id),document_name: document_name.to_string(),file_type: Some(FileType::Docx.as_str().to_string()),sha: None,diff --git a/crates/macro_db_client/src/document/save_document.rs b/crates/macro_db_client/src/document/save_document.rsindex 79d806047c..8e989d0423 100644--- a/crates/macro_db_client/src/document/save_document.rs+++ b/crates/macro_db_client/src/document/save_document.rs@@ -1,10 +1,10 @@use document_sub_type::DocumentSubType;-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model::document::{BomPart, DocumentBasic, DocumentMetadata, FileType, SaveBomPart, VersionIDWithTimeStamps,VersionIDWithTimeStampsNoSha, VersionIDWithTimeStampsOptionalSha,modification_data::{PdfModificationData, ThreadPlaceable},};+use model_owner::Owner;use sqlx::{PgPool, Postgres, Transaction, types::Uuid};// A comprehensive function that inserts both comment and highlight data@@ -111,6 +111,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;.collect::<Vec<ThreadPlaceable>>();let now = chrono::Utc::now().naive_utc();+ let owner = document.owner.principal_id();// Insert placeable threadsfor thread in thread_placeables {@@ -121,7 +122,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;VALUES ($1, $2, $3, $4, $5)RETURNING id"#,- document.owner.as_ref(),+ &owner,document.document_id,create_time,create_time,@@ -144,7 +145,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;"#,Uuid::parse_str(&thread.head_id).unwrap(),document.document_id,- document.owner.as_ref(),+ &owner,thread.page,thread.original_page,thread.original_index,@@ -182,7 +183,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;RETURNING id"#,thread_id,- document.owner.as_ref(),+ &owner,comment.sender,comment.content,created_at,@@ -222,7 +223,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;VALUES ($1, $2, $3, $4, $5)RETURNING id"#,- document.owner.as_ref(),+ &owner,document.document_id,first_comment_time,last_comment_time,@@ -254,7 +255,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;RETURNING id"#,thread_id,- document.owner.as_ref(),+ &owner,comment.sender,comment.content,created_at,@@ -298,7 +299,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;"#,highlight_uuid,document.document_id,- document.owner.as_ref(),+ &owner,highlight.page_num as i32,highlight.color.red,highlight.color.green,@@ -327,7 +328,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;RETURNING uuid"#,document.document_id,- document.owner.as_ref(),+ &owner,highlight.page_num as i32,highlight.color.red,highlight.color.green,@@ -468,9 +469,8 @@ pub async fn save_document(Ok(DocumentBasic {document_id: row.document_id,document_name: row.document_name,- owner: MacroUserIdStr::parse_from_str(&row.owner)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),+ owner: Owner::from_principal_str(&row.owner)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,file_type: row.file_type,sub_type: None,branched_from_id: row.branched_from_id,@@ -635,7 +635,10 @@ mod tests {assert!(!document_metadata.document_id.is_empty());assert_eq!(document_metadata.document_version_id, 3);assert_eq!(document_metadata.file_type, Some("txt".to_string()));- assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ document_metadata.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );Ok(())}@@ -662,7 +665,10 @@ mod tests {"test_document_name".to_string());assert_eq!(document_metadata.document_version_id, 3);- assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ document_metadata.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );let bom_parts: Vec<BomPart> =serde_json::from_value(document_metadata.document_bom.unwrap()).unwrap();assert_eq!(bom_parts[0].sha, "sha-1");diff --git a/crates/macro_db_client/src/document/v2/create.rs b/crates/macro_db_client/src/document/v2/create.rsindex 553be213b3..35f8e9a1da 100644--- a/crates/macro_db_client/src/document/v2/create.rs+++ b/crates/macro_db_client/src/document/v2/create.rs@@ -240,7 +240,7 @@ pub async fn create_document_txn(Ok(DocumentMetadata::new_document(&document_id,document_version.id,- user_id,+ model_owner::Owner::User(user_id),document_name,file_type,document_version.sha.as_str(),@@ -334,6 +334,7 @@ mod tests {#[allow(unused_imports)]use super::*;use chrono::TimeZone;+ use model_owner::Owner;use sqlx::{Pool, Postgres};#[sqlx::test(fixtures(path = "../../../fixtures", scripts("basic_user_with_documents")))]@@ -373,7 +374,10 @@ mod tests {assert!(!document_metadata.document_id.is_empty());assert_eq!(document_metadata.document_name, "document-name".to_string());- assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ document_metadata.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );assert_eq!(document_metadata.project_id.as_deref(), Some("project-one"));assert_eq!(document_metadata.project_name.as_deref(), Some("name"));assert_eq!(document_metadata.created_at, Some(ts));@@ -403,7 +407,10 @@ mod tests {assert!(!document_metadata.document_id.is_empty());assert_eq!(document_metadata.document_name, "document-name".to_string());- assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ document_metadata.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );Ok(())}@@ -448,7 +455,10 @@ mod tests {"20f603c2-99db-aaaa-0000-1d8b9f95a52f");assert_eq!(document_metadata.document_name, "document-name".to_string());- assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ document_metadata.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );assert_eq!(document_metadata.project_id.as_deref(), Some("project-one"));assert_eq!(document_metadata.project_name.as_deref(), Some("name"));assert_eq!(document_metadata.created_at, Some(ts));@@ -481,7 +491,10 @@ mod tests {"20f603c2-99db-4f02-aaaa-1d8b9f95a52f");assert_eq!(document_metadata.document_name, "document-name".to_string());- assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");+ assert_eq!(+ document_metadata.owner,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );Ok(())}diff --git a/crates/macro_db_client/src/item_access/get.rs b/crates/macro_db_client/src/item_access/get.rsindex cf2e9ab946..4daceee2e4 100644--- a/crates/macro_db_client/src/item_access/get.rs+++ b/crates/macro_db_client/src/item_access/get.rs@@ -1,4 +1,5 @@use chrono::{DateTime, Utc};+use model_owner::Owner;use models_permissions::share_permission::access_level::AccessLevel;/// A record from entity_access representing a user's access to an entity.@@ -31,7 +32,11 @@ pub async fn get_owner_and_deleted(r#"SELECT owner, "deletedAt" as deleted_at FROM "Document" WHERE id=$1"#,entity_id)- .map(|r| (r.owner, r.deleted_at.is_some()))+ .try_map(|r| {+ let owner = Owner::from_principal_str(&r.owner)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?;+ Ok((owner.principal_id(), r.deleted_at.is_some()))+ }).fetch_one(db).await?}diff --git a/crates/messages/Cargo.toml b/crates/messages/Cargo.tomlindex b843d18e4b..f48d58e725 100644--- a/crates/messages/Cargo.toml+++ b/crates/messages/Cargo.toml@@ -12,6 +12,7 @@ delivery = ["dep:connection_gateway_client","dep:model-entity","dep:model_notifications",+ "dep:model_owner","dep:notification","dep:system_properties","outbound",@@ -48,6 +49,7 @@ mockall = { workspace = true, optional = true }model = { path = "../model", optional = true }model-entity = { path = "../model-entity", optional = true }model_notifications = { path = "../model_notifications", optional = true }+model_owner = { path = "../model_owner", optional = true }models_pagination = { path = "../models_pagination" }notification = { path = "../notification", optional = true }rootcause = { workspace = true, optional = true }diff --git a/crates/messages/src/outbound/notification_sender.rs b/crates/messages/src/outbound/notification_sender.rsindex e07fee0599..bc6d6a985e 100644--- a/crates/messages/src/outbound/notification_sender.rs+++ b/crates/messages/src/outbound/notification_sender.rs@@ -9,6 +9,7 @@ use model_notifications::{CommentedOnDocumentMetadata, MentionedInDocumentCommentMetadata, NotificationDocumentSubType,RepliedToDocumentCommentThreadMetadata,};+use model_owner::Owner;use notification::domain::{models::SendNotificationRequestBuilder, service::NotificationIngress};/// Uses notification ingress with the existing document comment type names.@@ -54,7 +55,7 @@ impl<N: NotificationIngress> DiscussionNotifier for MessageNotificationSender<N>.await?};}- let owner = MacroUserIdStr::try_from(n.context.owner.clone())?;+ let owner = Owner::from_principal_str(&n.context.owner)?;let sub_type = n.context.is_taskdiff --git a/crates/model/Cargo.toml b/crates/model/Cargo.tomlindex 4fd96f7ff5..89bd3dfffc 100644--- a/crates/model/Cargo.toml+++ b/crates/model/Cargo.toml@@ -15,6 +15,7 @@ doppleganger = { workspace = true, features = ["chrono", "uuid"] }macro_user_id = { path = "../macro_user_id", features = ["schema"] }model-entity = { path = "../model-entity" }model-error-response = { path = "../model-error-response" }+model_owner = { path = "../model_owner" }model_file_type = { path = "../model_file_type", features = ["utoipa"] }model_user = { path = "../model_user" }models_bulk_upload = { path = "../models_bulk_upload" }diff --git a/crates/model/src/activity/map_item.rs b/crates/model/src/activity/map_item.rsindex b3ce5bd99f..1f26d64ac9 100644--- a/crates/model/src/activity/map_item.rs+++ b/crates/model/src/activity/map_item.rs@@ -1,5 +1,5 @@use document_sub_type::DocumentSubType;-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use model_owner::Owner;use crate::{chat::Chat,@@ -28,7 +28,7 @@ pub fn map_document_item() -> anyhow::Result<BasicDocument> {Ok(BasicDocument {document_id: id,- owner: MacroUserIdStr::parse_from_str(&user_id)?.into_owned(),+ owner: Owner::from_principal_str(&user_id)?,document_version_id: document_version_id.unwrap().parse::<i64>().unwrap(),document_name: name,created_at,diff --git a/crates/model/src/document.rs b/crates/model/src/document.rsindex f8eefbac88..2ede4268d4 100644--- a/crates/model/src/document.rs+++ b/crates/model/src/document.rs@@ -4,6 +4,7 @@ pub mod response;mod test;use document_sub_type::DocumentSubType;use macro_user_id::user_id::MacroUserIdStr;+use model_owner::Owner;use schemars::JsonSchema;use utoipa::ToSchema;@@ -86,7 +87,7 @@ pub struct BasicDocument {/// The owner of the document#[schema(value_type = String)]#[sqlx(try_from = "String")]- pub owner: MacroUserIdStr<'static>,+ pub owner: Owner,/// The name of the document#[serde(rename = "name", alias = "documentName")]pub document_name: String,@@ -175,7 +176,7 @@ pub struct DocumentMetadata {#[schema(value_type = String)]#[sqlx(try_from = "String")]#[schemars(with = "String")]- pub owner: MacroUserIdStr<'static>,+ pub owner: Owner,/// The name of the documentpub document_name: String,/// The file type of the document (file extension)@@ -231,7 +232,7 @@ impl DocumentMetadata {pub fn new_docx(document_id: &str,document_bom_id: i64,- owner: MacroUserIdStr<'static>,+ owner: Owner,document_name: &str,file_type: &str,document_family_id: Option<i64>,@@ -271,7 +272,7 @@ impl DocumentMetadata {pub fn new_document(document_id: &str,document_instance_id: i64,- owner: MacroUserIdStr<'static>,+ owner: Owner,document_name: &str,file_type: Option<FileType>,sha: &str,diff --git a/crates/model/src/document/basic.rs b/crates/model/src/document/basic.rsindex 1aaa429a14..6f542999f0 100644--- a/crates/model/src/document/basic.rs+++ b/crates/model/src/document/basic.rs@@ -3,7 +3,7 @@ use std::str::FromStr;use super::file_type::FileType;use crate::document::FileTypeExt;use document_sub_type::DocumentSubType;-use macro_user_id::user_id::MacroUserIdStr;+use model_owner::Owner;use utoipa::ToSchema;#[derive(sqlx::FromRow, serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug)]@@ -97,7 +97,7 @@ pub struct DocumentBasic {pub document_id: String,pub document_name: String,#[schema(value_type = String)]- pub owner: MacroUserIdStr<'static>,+ pub owner: Owner,#[serde(skip_serializing_if = "Option::is_none")]pub file_type: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]diff --git a/crates/model/src/document/response.rs b/crates/model/src/document/response.rsindex ae20a640ee..3339ad8c5f 100644--- a/crates/model/src/document/response.rs+++ b/crates/model/src/document/response.rs@@ -2,7 +2,7 @@ mod location;use document_sub_type::DocumentSubType;pub use location::LocationResponseV3;-use macro_user_id::user_id::MacroUserIdStr;+use model_owner::Owner;use std::str::FromStr;use crate::document::{BomPart, FileType};@@ -89,7 +89,7 @@ pub struct DocumentResponseMetadata {pub document_version_id: i64,/// The owner of the document#[schema(value_type = String)]- pub owner: MacroUserIdStr<'static>,+ pub owner: Owner,/// The name of the documentpub document_name: String,/// The file type of the documentdiff --git a/crates/model/src/document/test.rs b/crates/model/src/document/test.rsindex 0423bd9941..057d8f3b05 100644--- a/crates/model/src/document/test.rs+++ b/crates/model/src/document/test.rs@@ -1,12 +1,17 @@use super::basic::DocumentBasic;-use macro_user_id::user_id::MacroUserIdStr;+use model_owner::Owner;+use serde_json::json;++fn user_owner(principal: &str) -> Owner {+ Owner::from_principal_str(principal).unwrap()+}#[test]fn test_document_basic_serde_roundtrip() {let original = DocumentBasic {document_id: "doc-123".to_string(),document_name: "Test Document".to_string(),- owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ owner: user_owner("macro|[email protected]"),file_type: Some("pdf".to_string()),sub_type: None,branched_from_id: Some("parent-doc-456".to_string()),@@ -16,9 +21,10 @@ fn test_document_basic_serde_roundtrip() {deleted_at: None,};- let serialized = serde_json::to_string(&original).expect("Failed to serialize DocumentBasic");+ let serialized = serde_json::to_value(&original).expect("Failed to serialize DocumentBasic");+ assert_eq!(serialized["owner"], "macro|[email protected]");let deserialized: DocumentBasic =- serde_json::from_str(&serialized).expect("Failed to deserialize DocumentBasic");+ serde_json::from_value(serialized).expect("Failed to deserialize DocumentBasic");assert_eq!(original, deserialized);}@@ -28,7 +34,7 @@ fn test_document_basic_serde_minimal() {let original = DocumentBasic {document_id: "doc-minimal".to_string(),document_name: "Minimal Doc".to_string(),- owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ owner: user_owner("macro|[email protected]"),file_type: None,sub_type: None,branched_from_id: None,@@ -51,7 +57,7 @@ fn test_document_basic_serde_with_deleted_at() {let original = DocumentBasic {document_id: "doc-deleted".to_string(),document_name: "Deleted Doc".to_string(),- owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ owner: user_owner("macro|[email protected]"),file_type: Some("docx".to_string()),sub_type: None,branched_from_id: None,@@ -69,6 +75,33 @@ fn test_document_basic_serde_with_deleted_at() {assert_eq!(original.document_name, deserialized.document_name);assert_eq!(original.owner, deserialized.owner);assert_eq!(original.file_type, deserialized.file_type);- // DateTime serializes to ISO 8601 string, preserving microsecond precisionassert_eq!(original.deleted_at, deserialized.deleted_at);}++#[test]+fn document_basic_deserializes_bot_owner_principal() {+ let value = json!({+ "documentId": "doc-bot",+ "documentName": "Bot Doc",+ "owner": "bot|00000000-0000-0000-0000-00000000a1a1"+ });+ let parsed: DocumentBasic = serde_json::from_value(value).unwrap();+ assert_eq!(+ parsed.owner,+ Owner::from_principal_str("bot|00000000-0000-0000-0000-00000000a1a1").unwrap()+ );+}++#[test]+fn document_basic_deserializes_team_owner_principal() {+ let value = json!({+ "documentId": "doc-team",+ "documentName": "Team Doc",+ "owner": "01234567-89ab-cdef-0123-456789abcdef"+ });+ let parsed: DocumentBasic = serde_json::from_value(value).unwrap();+ assert_eq!(+ parsed.owner,+ Owner::from_principal_str("01234567-89ab-cdef-0123-456789abcdef").unwrap()+ );+}diff --git a/crates/model/src/item/map_item.rs b/crates/model/src/item/map_item.rsindex 0feee35c04..a7a45ad903 100644--- a/crates/model/src/item/map_item.rs+++ b/crates/model/src/item/map_item.rs@@ -1,5 +1,5 @@use document_sub_type::DocumentSubType;-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use model_owner::Owner;use crate::{chat::Chat,@@ -30,7 +30,7 @@ pub fn map_document_item() -> anyhow::Result<BasicDocument> {Ok(BasicDocument {document_id: id,- owner: MacroUserIdStr::parse_from_str(&user_id)?.into_owned(),+ owner: Owner::from_principal_str(&user_id)?,document_version_id: document_version_id.unwrap().parse::<i64>().unwrap(),document_name: name,created_at,diff --git a/crates/model/src/item/tests.rs b/crates/model/src/item/tests.rsindex 14f47e1752..70ab649e56 100644--- a/crates/model/src/item/tests.rs+++ b/crates/model/src/item/tests.rs@@ -6,7 +6,7 @@* as a normal rust type.*/use super::*;-use macro_user_id::user_id::MacroUserIdStr;+use model_owner::Owner;use utoipa::ToSchema;#[test]fn test_expected_schema() {@@ -111,7 +111,7 @@ fn test_document_serde() {let doc = BasicDocument {document_id: "doc123".to_string(),document_version_id: 1,- owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ owner: Owner::from_principal_str("macro|[email protected]").unwrap(),document_name: "Test Document".to_string(),file_type: Some("pdf".to_string()),sha: Some("abc123".to_string()),diff --git a/crates/model_notifications/Cargo.toml b/crates/model_notifications/Cargo.tomlindex babb33c96a..e9f5ed4d50 100644--- a/crates/model_notifications/Cargo.toml+++ b/crates/model_notifications/Cargo.toml@@ -11,6 +11,7 @@ chrono-tz = { workspace = true }macro_user_id = { path = "../macro_user_id" }mention_utils = { path = "../mention_utils" }model-entity = { path = "../model-entity" }+model_owner = { path = "../model_owner" }models_pagination = { path = "../models_pagination" }notification = { path = "../notification" }paste = { workspace = true }diff --git a/crates/model_notifications/src/metadata.rs b/crates/model_notifications/src/metadata.rsindex 3f9441f5d5..0c8a3f4ae6 100644--- a/crates/model_notifications/src/metadata.rs+++ b/crates/model_notifications/src/metadata.rs@@ -5,6 +5,7 @@ use macro_user_id::{email::ReadEmailParts, user_id::MacroUserIdStr};use mention_utils::parse::{ParsedXmlText, PlainTextFormatter, XmlFormatter};use model_entity::Entity;use model_entity::EntityType;+use model_owner::Owner;pub use notification::domain::models::NotificationTitle;use notification::domain::models::{NotifCollapseKey, Notification, NotificationExtIos,@@ -643,7 +644,7 @@ pub struct DocumentMentionMetadata {pub document_name: String,/// The owner of the document#[schema(value_type = String)]- pub owner: MacroUserIdStr<'static>,+ pub owner: Owner,/// The file type of the document#[serde(alias = "file_type")]pub file_type: Option<String>,@@ -1190,7 +1191,7 @@ pub struct MentionedInDocumentCommentMetadata {pub document_name: String,/// The owner of the document.#[schema(value_type = String)]- pub owner: MacroUserIdStr<'static>,+ pub owner: Owner,/// The file type of the document.pub file_type: Option<String>,/// The sub type of the document (e.g. task).@@ -1243,7 +1244,7 @@ pub struct RepliedToDocumentCommentThreadMetadata {pub document_name: String,/// The owner of the document.#[schema(value_type = String)]- pub owner: MacroUserIdStr<'static>,+ pub owner: Owner,/// The file type of the document.pub file_type: Option<String>,/// The sub type of the document (e.g. task).@@ -1315,7 +1316,7 @@ pub struct CommentedOnDocumentMetadata {pub document_name: String,/// The owner of the document.#[schema(value_type = String)]- pub owner: MacroUserIdStr<'static>,+ pub owner: Owner,/// The file type of the document.pub file_type: Option<String>,/// The sub type of the document (e.g. task).diff --git a/crates/model_notifications/src/metadata/test.rs b/crates/model_notifications/src/metadata/test.rsindex ef2d51f022..dd4c91410e 100644--- a/crates/model_notifications/src/metadata/test.rs+++ b/crates/model_notifications/src/metadata/test.rs@@ -577,7 +577,7 @@ fn channel_mention_title_falls_back_to_bot_display_name() {fn document_mention(sub_type: Option<NotificationDocumentSubType>) -> DocumentMentionMetadata {DocumentMentionMetadata {document_name: "Q3 plan".to_string(),- owner: uid("macro|[email protected]"),+ owner: Owner::from_principal_str("macro|[email protected]").unwrap(),file_type: Some("md".to_string()),sub_type,channel: ChannelMentionMetadata {diff --git a/crates/model_owner/src/lib.rs b/crates/model_owner/src/lib.rsindex bdd8fad694..d9a4724abd 100644--- a/crates/model_owner/src/lib.rs+++ b/crates/model_owner/src/lib.rs@@ -123,6 +123,22 @@ impl Owner {Self::parse(OwnerType::Team, value)}}++ /// True when this owner is the given user.+ #[must_use]+ pub fn is_user(&self, user: &MacroUserIdStr<'_>) -> bool {+ matches!(self, Self::User(owner) if owner == user)+ }+}++impl Display for Owner {+ fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {+ match self {+ Self::User(user_id) => Display::fmt(user_id, f),+ Self::Bot(bot_id) => Display::fmt(&bot_id.into_storage_id(), f),+ Self::Team(team_id) => write!(f, "{}", team_id.hyphenated()),+ }+ }}impl From<Owner> for String {diff --git a/crates/model_owner/src/test.rs b/crates/model_owner/src/test.rsindex c628af83b3..e10f0f451b 100644--- a/crates/model_owner/src/test.rs+++ b/crates/model_owner/src/test.rs@@ -104,6 +104,34 @@ fn owner_type_lowercase_round_trips() {assert!("unknown".parse::<OwnerType>().is_err());}+#[test]+fn is_user_matches_only_that_user() {+ let owner = Owner::from_principal_str("macro|[email protected]").unwrap();+ let same = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let other = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();++ assert!(owner.is_user(&same));+ assert!(!owner.is_user(&other));+ assert!(+ !Owner::from_principal_str("bot|00000000-0000-0000-0000-00000000a1a1")+ .unwrap()+ .is_user(&same)+ );+}++#[test]+fn display_equals_principal_id() {+ for principal in [+ "macro|[email protected]",+ "bot|00000000-0000-0000-0000-00000000a1a1",+ "01234567-89ab-cdef-0123-456789abcdef",+ ] {+ let owner = Owner::from_principal_str(principal).unwrap();+ assert_eq!(owner.to_string(), principal);+ assert_eq!(owner.to_string(), owner.principal_id());+ }+}+#[test]fn from_principal_str_classifies_by_prefix() {assert_eq!(diff --git a/crates/projects/src/domain/service.rs b/crates/projects/src/domain/service.rsindex b5f7107d52..bd73927be9 100644--- a/crates/projects/src/domain/service.rs+++ b/crates/projects/src/domain/service.rs@@ -872,7 +872,7 @@ wherefn owns(item: &Item, actor: &str) -> bool {match item {Item::Project(project) => project.user_id == actor,- Item::Document(document) => document.owner.as_ref() == actor,+ Item::Document(document) => document.owner.principal_id() == actor,Item::Chat(chat) => chat.user_id == actor,}}diff --git a/crates/projects/src/domain/service/tests.rs b/crates/projects/src/domain/service/tests.rsindex bb8ca9c1da..acf0caba66 100644--- a/crates/projects/src/domain/service/tests.rs+++ b/crates/projects/src/domain/service/tests.rs@@ -1718,7 +1718,7 @@ fn upload_document(id: &str, file_type: FileType) -> DocumentMetadata {DocumentMetadata::new_document(id,7,- user_id("macro|[email protected]"),+ model_owner::Owner::User(user_id("macro|[email protected]")),id,Some(file_type),"0123456789abcdef",diff --git a/crates/projects/src/domain/upload.rs b/crates/projects/src/domain/upload.rsindex cd3c0e2a1c..a870778aaf 100644--- a/crates/projects/src/domain/upload.rs+++ b/crates/projects/src/domain/upload.rs@@ -50,8 +50,9 @@ pub async fn build_destination_map<U: ProjectUploadUrlPort>(continue;}+ let owner = document.owner.principal_id();let key = build_docx_staging_bucket_document_key(- document.owner.as_ref(),+ &owner,&document.document_id,document.document_version_id,);@@ -65,8 +66,9 @@ pub async fn build_destination_map<U: ProjectUploadUrlPort>(continue;}+ let owner = document.owner.principal_id();let key = build_cloud_storage_bucket_document_key(- document.owner.as_ref(),+ &owner,&document.document_id,document.document_version_id,);diff --git a/crates/projects/src/outbound/pg_project_repo/content.rs b/crates/projects/src/outbound/pg_project_repo/content.rsindex ba0cf36922..b3a307cbc1 100644--- a/crates/projects/src/outbound/pg_project_repo/content.rs+++ b/crates/projects/src/outbound/pg_project_repo/content.rs@@ -1,9 +1,9 @@use document_sub_type::DocumentSubType;-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model::chat::Chat;use model::document::{BasicDocument, BasicDocumentSubType};use model::item::Item;use model::project::Project;+use model_owner::Owner;use sqlx::PgPool;use system_properties::{StatusOption, SystemPropertyKey};@@ -102,9 +102,8 @@ async fn get_sub_documents(Ok(BasicDocument {document_id: row.document_id,document_version_id: row.document_version_id,- owner: MacroUserIdStr::parse_from_str(&row.owner)- .map_err(|error| sqlx::Error::Decode(Box::new(error)))?- .into_owned(),+ owner: Owner::from_principal_str(&row.owner)+ .map_err(|error| sqlx::Error::Decode(Box::new(error)))?,document_name: row.document_name,file_type: row.file_type,project_id: row.project_id,diff --git a/crates/projects/src/outbound/pg_project_repo/upload_folder.rs b/crates/projects/src/outbound/pg_project_repo/upload_folder.rsindex 96fd588a88..d337e39780 100644--- a/crates/projects/src/outbound/pg_project_repo/upload_folder.rs+++ b/crates/projects/src/outbound/pg_project_repo/upload_folder.rs@@ -264,7 +264,7 @@ async fn create_empty_document(Ok(DocumentMetadata::new_document(&document.id,version_id,- user_id,+ model_owner::Owner::User(user_id),&document_name,item.file_type,&item.sha,diff --git a/crates/properties/Cargo.toml b/crates/properties/Cargo.tomlindex 3f52f97f91..1b97d581c4 100644--- a/crates/properties/Cargo.toml+++ b/crates/properties/Cargo.toml@@ -53,6 +53,7 @@ macro_authorization = { path = "../macro_authorization", default-features = falsmacro_event_broker = { path = "../macro_event_broker", default-features = false }macro_event_topics = { path = "../macro_event_topics" }macro_user_id = { path = "../macro_user_id" }+model_owner = { path = "../model_owner" }macro_uuid = { path = "../macro_uuid", optional = true }model-entity = { path = "../model-entity", optional = true }model_notifications = { path = "../model_notifications", optional = true }diff --git a/crates/properties/src/outbound/permission_service.rs b/crates/properties/src/outbound/permission_service.rsindex 3d41775b4d..7b01a6d771 100644--- a/crates/properties/src/outbound/permission_service.rs+++ b/crates/properties/src/outbound/permission_service.rs@@ -9,6 +9,7 @@ use entity_access::domain::models::{use entity_access::domain::ports::EntityAccessService;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;+use model_owner::Owner;use models_permissions::share_permission::access_level::AccessLevel;use models_properties::EntityType as StorageEntityType;use sqlx::{Pool, Postgres};@@ -140,9 +141,10 @@ impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc>storage_entity_type(entity_type)?,).await?;+ let owner = Owner::from_principal_str(&owner)?;// If you are the owner fast return- if user_id.is_some_and(|u| owner == u.as_ref()) {+ if user_id.is_some_and(|u| owner.is_user(u)) {return Ok(access_receipt(caller_auth(user_id),entity_id,diff --git a/crates/soup_realtime/Cargo.toml b/crates/soup_realtime/Cargo.tomlindex ab2f4bc5e8..98710a1a15 100644--- a/crates/soup_realtime/Cargo.toml+++ b/crates/soup_realtime/Cargo.toml@@ -46,6 +46,7 @@ macro_event_broker = { path = "../macro_event_broker", default-features = falsemacro_event_topics = { path = "../macro_event_topics" }macro_user_id = { path = "../macro_user_id" }model-entity = { path = "../model-entity" }+model_owner = { path = "../model_owner" }models_properties = { path = "../models_properties", optional = true }projects = { path = "../projects", default-features = false, features = ["service"], optional = true }properties = { path = "../properties", default-features = false, features = ["ports"], optional = true }diff --git a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs b/crates/soup_realtime/src/inbound/kafka_consumer/test.rsindex 3b5e27a5b1..79949c262e 100644--- a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs+++ b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs@@ -26,6 +26,7 @@ use email::domain::events::{use macro_event_broker::{Event, EventBrokerError, MacroEventCollection as _, MessageParts};use macro_user_id::user_id::MacroUserIdStr;use messages::domain::models::SimpleMention;+use model_owner::Owner;use projects::domain::events::{ProjectDeletedMetadata, ProjectTopicEvent};use properties::domain::events::{EntityPropertiesClearedMetadata, EntityPropertyDeletedMetadata, EntityPropertyUpdatedMetadata,@@ -65,7 +66,7 @@ fn user() -> MacroUserIdStr<'static> {fn updated_event() -> Event<DocumentTopicEvent> {Event::new(DocumentTopicEvent::Updated(DocumentUpdatedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user(),+ owner: Owner::User(user()),actor_user_id: None,actor: None,on_behalf_of: None,@@ -127,7 +128,7 @@ fn subscribes_to_all_existing_soup_source_topics() {fn document_lifecycle_events_map_to_updated_and_deleted_patches() {let created = DocumentTopicEvent::Created(DocumentCreatedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user(),+ owner: Owner::User(user()),actor: None,on_behalf_of: None,document_name: "Created".to_string(),@@ -158,7 +159,7 @@ fn moving_a_document_out_of_a_project_updates_the_previous_project() {let previous_project_id = Uuid::now_v7().to_string();let event = DocumentTopicEvent::Updated(DocumentUpdatedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user(),+ owner: Owner::User(user()),actor_user_id: None,actor: None,on_behalf_of: None,@@ -199,7 +200,7 @@ fn search_only_document_events_do_not_emit_patches() {let events = [DocumentTopicEvent::ContentUploaded(DocumentContentUploadedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user(),+ owner: Owner::User(user()),file_type: "pdf".parse().expect("valid file type"),document_version_id: Some("convert".to_string()),}),diff --git a/crates/webhook/Cargo.toml b/crates/webhook/Cargo.tomlindex 38cbd34449..22105c01ae 100644--- a/crates/webhook/Cargo.toml+++ b/crates/webhook/Cargo.toml@@ -73,6 +73,7 @@ agent_trigger = { path = "../agent_trigger", optional = true }channels = { path = "../channels", default-features = false, optional = true }chrono = { workspace = true }documents = { path = "../documents", default-features = false, optional = true }+model_owner = { path = "../model_owner" }entity_access = { path = "../entity_access", default-features = false, features = ["ports",], optional = true }diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rsindex ded1fb5d38..965ff73a63 100644--- a/crates/webhook/src/domain/ingestion/test.rs+++ b/crates/webhook/src/domain/ingestion/test.rs@@ -32,6 +32,7 @@ use entity_access::domain::models::{};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};use messages::domain::models::SimpleMention;+use model_owner::Owner;use serde_json::Value;use std::{collections::BTreeMap,@@ -454,7 +455,7 @@ fn document_event_cases() -> Vec<EventCase> {TestBrokerEvent::Document(Event::with_schema_version(DocumentTopicEvent::Created(DocumentCreatedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user_id("macro|[email protected]"),+ owner: Owner::User(user_id("macro|[email protected]")),actor: None,on_behalf_of: None,document_name: "notes".to_string(),@@ -474,7 +475,7 @@ fn document_event_cases() -> Vec<EventCase> {TestBrokerEvent::Document(Event::with_schema_version(DocumentTopicEvent::Updated(DocumentUpdatedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user_id("macro|[email protected]"),+ owner: Owner::User(user_id("macro|[email protected]")),actor_user_id: Some(user_id("macro|[email protected]")),actor: None,on_behalf_of: None,@@ -513,7 +514,7 @@ fn document_event_cases() -> Vec<EventCase> {document_id: COPIED_DOCUMENT_ID.to_string(),source_document_id: DOCUMENT_ID.to_string(),source_version_id: None,- owner: user_id("macro|[email protected]"),+ owner: Owner::User(user_id("macro|[email protected]")),document_name: "notes (copy)".to_string(),file_type: None,project_id: None,@@ -536,7 +537,7 @@ fn search_only_document_event_cases() -> Vec<(&'static str, Event<DocumentTopicEEvent::new(DocumentTopicEvent::ContentUploaded(DocumentContentUploadedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user_id("macro|[email protected]"),+ owner: Owner::User(user_id("macro|[email protected]")),file_type: "pdf".parse().expect("valid file type"),document_version_id: Some("convert".to_string()),},diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 278913bf01..d76bc3c79b 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -4413,7 +4413,7 @@ export type DocumentContentUploadedMetadata = {/*** The owner of the document (used by the extractor to resolve S3 keys).*/- owner: MacroUserIdStr;+ owner: string;};/**@@ -4432,7 +4432,7 @@ export type DocumentCopiedMetadata = {/*** The owner of the new copy (the copier).*/- owner: MacroUserIdStr;+ owner: string;/*** Project the copy belongs to, when any.*/@@ -4474,7 +4474,7 @@ export type DocumentCreatedMetadata = {/*** The owner (creator) of the document.*/- owner: MacroUserIdStr;+ owner: string;/*** Project the document was created in, when any.*/@@ -4975,7 +4975,7 @@ export type DocumentUpdatedMetadata = {/*** The owner of the document.*/- owner: MacroUserIdStr;+ owner: string;/*** Project id before the update.*/diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 772bc8a825..c6a36d9560 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -20462,7 +20462,7 @@"description": "File type of the uploaded object (may differ from the document's own\ntype, e.g. `pdf` for the converted rendition of a docx)."},"owner": {- "$ref": "#/components/schemas/MacroUserIdStr",+ "type": "string","description": "The owner of the document (used by the extractor to resolve S3 keys)."}}@@ -20497,7 +20497,7 @@]},"owner": {- "$ref": "#/components/schemas/MacroUserIdStr",+ "type": "string","description": "The owner of the new copy (the copier)."},"project_id": {@@ -20571,7 +20571,7 @@]},"owner": {- "$ref": "#/components/schemas/MacroUserIdStr",+ "type": "string","description": "The owner (creator) of the document."},"project_id": {@@ -21402,7 +21402,7 @@]},"owner": {- "$ref": "#/components/schemas/MacroUserIdStr",+ "type": "string","description": "The owner of the document."},"previous_project_id": {diff --git a/services/convert_service/src/api/backfill/backfill_docx.rs b/services/convert_service/src/api/backfill/backfill_docx.rsindex 89566dfc5d..6ee5d208f9 100644--- a/services/convert_service/src/api/backfill/backfill_docx.rs+++ b/services/convert_service/src/api/backfill/backfill_docx.rs@@ -117,10 +117,8 @@ async fn process_docx(serde_json::from_value(bom_parts).context("unable to serialize bom parts")?;// check if the converted item exists in s3- let key = build_docx_to_pdf_converted_document_key(- document.owner.as_ref(),- &document.document_id,- );+ let owner = document.owner.principal_id();+ let key = build_docx_to_pdf_converted_document_key(&owner, &document.document_id);let exists = s3_client.exists(document_storage_bucket, &key)@@ -170,10 +168,8 @@ async fn process_docx(let zipped_docx = zip_bom_parts(bom_parts_with_content).await?;let from_key = build_temp_docx_key(&document.document_id);- let to_key = build_docx_to_pdf_converted_document_key(- document.owner.as_ref(),- &document.document_id,- );+ let owner = document.owner.principal_id();+ let to_key = build_docx_to_pdf_converted_document_key(&owner, &document.document_id);s3_client.put(document_storage_bucket, &from_key, &zipped_docx)diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.tomlindex fba2959be1..5ce675ea01 100644--- a/services/document_storage_service/Cargo.toml+++ b/services/document_storage_service/Cargo.toml@@ -149,6 +149,7 @@ mockall = { workspace = true }model = { path = "../../crates/model" }model-entity = { path = "../../crates/model-entity" }model_notifications = { path = "../../crates/model_notifications" }+model_owner = { path = "../../crates/model_owner" }model_user = { path = "../../crates/model_user" }models_bulk_upload = { path = "../../crates/models_bulk_upload" }models_dcs = { path = "../../crates/models_dcs" }diff --git a/services/document_storage_service/src/api/annotations.rs b/services/document_storage_service/src/api/annotations.rsindex 6fda73daff..c11222b2cc 100644--- a/services/document_storage_service/src/api/annotations.rs+++ b/services/document_storage_service/src/api/annotations.rs@@ -24,6 +24,7 @@ use model_notifications::{CommentedOnDocumentMetadata, MentionedInDocumentCommentMetadata, NotificationDocumentSubType,RepliedToDocumentCommentThreadMetadata,};+use model_owner::Owner;use notification::domain::models::SendNotificationRequestBuilder;use tower::ServiceBuilder;@@ -148,7 +149,7 @@ pub(crate) fn compute_notification_recipients(mentioned_user_ids: &[String],thread_participant_ids: &[String],task_assignee_ids: &[String],- document_owner: &MacroUserIdStr<'_>,+ document_owner: &Owner,is_reply: bool,) -> NotificationRecipients {let mut notified: HashSet<String> = HashSet::new();@@ -191,13 +192,17 @@ pub(crate) fn compute_notification_recipients(}}- // 4. Document owner — only if not sender and not already notified- let owner_normalized = document_owner.as_ref().to_string();- let owner_is_sender = sender_id.is_some_and(|s| s.as_ref() == owner_normalized);- let doc_owner_recipient = if !owner_is_sender && !notified.contains(&owner_normalized) {- Some(owner_normalized)- } else {- None+ let doc_owner_recipient = match document_owner {+ Owner::User(user) => {+ let owner_normalized = user.as_ref().to_string();+ let owner_is_sender = sender_id.is_some_and(|s| s.as_ref() == owner_normalized);+ if !owner_is_sender && !notified.contains(&owner_normalized) {+ Some(owner_normalized)+ } else {+ None+ }+ }+ Owner::Bot(_) | Owner::Team(_) => None,};NotificationRecipients {@@ -255,7 +260,7 @@ pub(crate) struct CommentNotifContext {pub thread_id: i64,pub document_name: String,pub document_id: String,- pub owner: MacroUserIdStr<'static>,+ pub owner: Owner,pub file_type: Option<String>,pub sub_type: Option<NotificationDocumentSubType>,pub sender_id: Option<MacroUserIdStr<'static>>,@@ -346,7 +351,9 @@ impl CommentNotifContext {&self,) -> SendNotificationRequestBuilder<'static, CommentedOnDocumentMetadata> {let mut recipient_ids = HashSet::new();- recipient_ids.insert(self.owner.clone());+ if let Owner::User(owner) = &self.owner {+ recipient_ids.insert(owner.clone());+ }SendNotificationRequestBuilder {notification_entity: EntityType::Document.with_entity_string(self.document_id.clone()),diff --git a/services/document_storage_service/src/api/annotations/edit_comment.rs b/services/document_storage_service/src/api/annotations/edit_comment.rsindex a685ceaf5c..7653bd9616 100644--- a/services/document_storage_service/src/api/annotations/edit_comment.rs+++ b/services/document_storage_service/src/api/annotations/edit_comment.rs@@ -22,6 +22,7 @@ use model::{response::ErrorResponse,};use model_notifications::NotificationDocumentSubType;+use model_owner::Owner;use notification::domain::service::NotificationIngress;use sqlx::PgPool;@@ -77,7 +78,7 @@ pub async fn edit_comment_handler(thread_id: req.thread_id,document_name: res.document_name.clone(),document_id: res.document_id.to_string(),- owner: res.document_owner.clone(),+ owner: Owner::User(res.document_owner.clone()),file_type: res.file_type.clone(),sub_type: res.sub_type.map(|sub_type| match sub_type {document_sub_type::DocumentSubType::Task => {diff --git a/services/document_storage_service/src/api/annotations/test.rs b/services/document_storage_service/src/api/annotations/test.rsindex 07bcd918ee..e612b77f54 100644--- a/services/document_storage_service/src/api/annotations/test.rs+++ b/services/document_storage_service/src/api/annotations/test.rs@@ -5,7 +5,7 @@ fn check_ser_meta() -> Result<(), Box<dyn std::error::Error>> {let m = MentionedInDocumentCommentMetadata {sender_display_name: None,document_name: "test".to_string(),- owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ owner: Owner::from_principal_str("macro|[email protected]").unwrap(),file_type: None,sub_type: None,mention_id: "xxx".to_string(),@@ -25,6 +25,10 @@ fn user_id(s: &str) -> MacroUserIdStr<'static> {MacroUserIdStr::try_from(s.to_string()).unwrap()}+fn document_owner(user: &MacroUserIdStr<'static>) -> Owner {+ Owner::User(user.clone())+}+// ---------------------------------------------------------------------------// No duplicate notifications// ---------------------------------------------------------------------------@@ -39,7 +43,7 @@ fn mentioned_user_who_is_also_thread_participant_gets_only_mention() {&[bob.to_string()], // bob is mentioned&[bob.to_string(), sender.as_ref().to_string()], // bob is also a thread participant&[],- &user_id("macro|[email protected]"),+ &document_owner(&user_id("macro|[email protected]")),true, // is_reply);@@ -68,7 +72,7 @@ fn mentioned_user_who_is_also_doc_owner_gets_only_mention() {&[owner.as_ref().to_string()], // owner is mentioned&[sender.as_ref().to_string()],&[],- &owner,+ &document_owner(&owner),false,);@@ -92,7 +96,7 @@ fn thread_participant_who_is_also_doc_owner_gets_only_thread_reply() {&[], // no mentions&[owner.as_ref().to_string(), sender.as_ref().to_string()], // owner is thread participant&[],- &owner,+ &document_owner(&owner),true,);@@ -116,7 +120,7 @@ fn user_who_is_mentioned_and_thread_participant_and_doc_owner_gets_only_mention(&[owner.as_ref().to_string()], // owner is mentioned&[owner.as_ref().to_string(), sender.as_ref().to_string()], // owner is thread participant&[],- &owner, // and doc owner+ &document_owner(&owner),true,);@@ -144,7 +148,7 @@ fn dedup_works_across_different_casing() {sender.as_ref().to_string(),], // lowercase owner&[],- &owner,+ &document_owner(&owner),true,);@@ -169,7 +173,7 @@ fn dedup_works_for_doc_owner_with_different_casing() {&["macro|[email protected]".to_string()], // mixed case&[sender.as_ref().to_string()],&[],- &owner,+ &document_owner(&owner),false,);@@ -196,7 +200,7 @@ fn sender_never_receives_notification() {&[],&[sender.as_ref().to_string()], // sender is only thread participant&[],- &sender, // sender is also doc owner+ &document_owner(&sender),true,);@@ -220,7 +224,7 @@ fn new_thread_comment_notifies_doc_owner() {&[],&[sender.as_ref().to_string()], // only one comment (the new one)&[],- &owner,+ &document_owner(&owner),false, // not a reply);@@ -240,7 +244,7 @@ fn non_owner_non_assignee_commenter_gets_subsequent_thread_reply() {&[],&[commenter.to_string(), sender.as_ref().to_string()],&[],- &owner,+ &document_owner(&owner),true,);@@ -264,7 +268,7 @@ fn reply_notifies_thread_participants_and_doc_owner() {&[],&[alice.to_string(), sender.as_ref().to_string()],&[],- &owner,+ &document_owner(&owner),true,);@@ -283,7 +287,7 @@ fn no_thread_reply_notifications_for_first_comment() {&[],&[sender.as_ref().to_string()],&[],- &owner,+ &document_owner(&owner),false, // first comment, not a reply);@@ -305,7 +309,7 @@ fn assignee_gets_notification_when_not_in_other_groups() {&[],&[sender.as_ref().to_string()],&[assignee.to_string()],- &owner,+ &document_owner(&owner),false,);@@ -328,7 +332,7 @@ fn mentioned_user_who_is_also_assignee_gets_only_mention() {&[bob.to_string()],&[sender.as_ref().to_string()],&[bob.to_string()],- &owner,+ &document_owner(&owner),false,);@@ -354,7 +358,7 @@ fn thread_participant_who_is_also_assignee_gets_only_thread_reply() {&[],&[alice.to_string(), sender.as_ref().to_string()],&[alice.to_string()],- &owner,+ &document_owner(&owner),true,);@@ -379,7 +383,7 @@ fn assignee_who_is_also_doc_owner_gets_only_assignee() {&[],&[sender.as_ref().to_string()],&[owner.as_ref().to_string()],- &owner,+ &document_owner(&owner),false,);@@ -404,7 +408,7 @@ fn sender_who_is_assignee_gets_no_notification() {&[],&[sender.as_ref().to_string()],&[sender.as_ref().to_string()],- &owner,+ &document_owner(&owner),false,);@@ -432,7 +436,7 @@ fn multiple_assignees_deduped_correctly() {thread_participant.to_string(),pure_assignee.to_string(),],- &owner,+ &document_owner(&owner),true,);@@ -466,7 +470,7 @@ fn assignee_dedup_works_across_different_casing() {&["macro|[email protected]".to_string()],&[sender.as_ref().to_string()],&["macro|[email protected]".to_string()],- &owner,+ &document_owner(&owner),false,);@@ -482,3 +486,26 @@ fn assignee_dedup_works_across_different_casing() {);assert_eq!(result.all_recipients().len(), result.total_count());}++#[test]+fn bot_or_team_document_owner_is_not_a_user_recipient() {+ let sender = user_id("macro|[email protected]");+ let bot_owner = Owner::from_principal_str("bot|00000000-0000-0000-0000-00000000a1a1").unwrap();+ let team_owner = Owner::from_principal_str("01234567-89ab-cdef-0123-456789abcdef").unwrap();++ for owner in [bot_owner, team_owner] {+ let result = compute_notification_recipients(+ Some(&sender),+ &[],+ &[sender.as_ref().to_string()],+ &[],+ &owner,+ false,+ );+ assert!(+ result.doc_owner_recipient.is_none(),+ "non-user owner {owner} should not receive a document-owner notification"+ );+ assert!(result.all_recipients().is_empty());+ }+}diff --git a/services/document_storage_service/src/api/documents/delete_document.rs b/services/document_storage_service/src/api/documents/delete_document.rsindex 71764120f0..b4ccb3bb40 100644--- a/services/document_storage_service/src/api/documents/delete_document.rs+++ b/services/document_storage_service/src/api/documents/delete_document.rs@@ -115,9 +115,10 @@ pub async fn permanently_delete_document_handler(}// Queue document for deletion+ let owner = document_context.owner.principal_id();state.sqs_client- .enqueue_document_delete(document_context.owner.as_ref(), &document_id)+ .enqueue_document_delete(&owner, &document_id).await.map_err(|e| {tracing::error!(error=?e, "unable to enqueue document delete");diff --git a/services/document_storage_service/src/api/documents/export_document.rs b/services/document_storage_service/src/api/documents/export_document.rsindex e322ab0e59..8c41aa91a6 100644--- a/services/document_storage_service/src/api/documents/export_document.rs+++ b/services/document_storage_service/src/api/documents/export_document.rs@@ -85,13 +85,9 @@ pub async fn handler(let presigned_url = match file_type {FileType::Docx => export_docx_document(&state, &document_context.document_id).await,_ => {- export_basic_document(- &state,- document_context.owner.as_ref(),- &document_context.document_id,- file_type,- )- .await+ let owner = document_context.owner.principal_id();+ export_basic_document(&state, &owner, &document_context.document_id, file_type)+ .await}}.map_err(|e| {diff --git a/services/document_storage_service/src/api/documents/get_document_key.rs b/services/document_storage_service/src/api/documents/get_document_key.rsindex c93ed5a929..ae486c70fe 100644--- a/services/document_storage_service/src/api/documents/get_document_key.rs+++ b/services/document_storage_service/src/api/documents/get_document_key.rs@@ -63,6 +63,7 @@ pub async fn get_document_key_handler(.send(StatusCode::BAD_REQUEST);};+ let owner = document_context.owner.principal_id();let key = match file_type {FileType::Pdf => {let document_version_id =@@ -79,15 +80,9 @@ pub async fn get_document_key_handler(}};- build_cloud_storage_bucket_document_key(- document_context.owner.as_ref(),- &document_id,- document_version_id,- )- }- FileType::Docx => {- build_docx_to_pdf_converted_document_key(document_context.owner.as_ref(), &document_id)+ build_cloud_storage_bucket_document_key(&owner, &document_id, document_version_id)}+ FileType::Docx => build_docx_to_pdf_converted_document_key(&owner, &document_id),_ => {tracing::error!("invalid file type");return GenericResponse::builder()diff --git a/services/document_storage_service/src/api/documents/location.rs b/services/document_storage_service/src/api/documents/location.rsindex 1865856c23..65265c6cc1 100644--- a/services/document_storage_service/src/api/documents/location.rs+++ b/services/document_storage_service/src/api/documents/location.rs@@ -67,9 +67,10 @@ pub async fn get_location_handler(.as_deref().and_then(|f| FileType::from_str(f).ok());+ let owner = document_context.owner.principal_id();let response_data = get_presigned_url_by_type(&state,- document_context.owner.as_ref(),+ &owner,&document_id,file_type,params.document_version_id,diff --git a/services/document_storage_service/src/api/documents/simple_save.rs b/services/document_storage_service/src/api/documents/simple_save.rsindex 83723f657b..9078d6443d 100644--- a/services/document_storage_service/src/api/documents/simple_save.rs+++ b/services/document_storage_service/src/api/documents/simple_save.rs@@ -116,8 +116,9 @@ pub async fn handler(}};+ let owner = document.owner.principal_id();let key = build_cloud_storage_bucket_document_key(- document.owner.as_ref(),+ &owner,&document.document_id,document.document_version_id,);diff --git a/services/document_storage_service/src/outbound/entity_mutation.rs b/services/document_storage_service/src/outbound/entity_mutation.rsindex 0c6d2feac4..4eec84e3f8 100644--- a/services/document_storage_service/src/outbound/entity_mutation.rs+++ b/services/document_storage_service/src/outbound/entity_mutation.rs@@ -138,8 +138,9 @@ impl<B: MacroEventBroker> EntityLifecycleService for DssEntityLifecycleAdapter<B.await.inspect_err(|error| tracing::error!(error = ?error, "unable to delete entity mentions")).ok();+ let owner = document.owner.principal_id();self.sqs- .enqueue_document_delete(document.owner.as_ref(), &entity.entity_id)+ .enqueue_document_delete(&owner, &entity.entity_id).await.map_err(|error| internal!(error))?;publish_document_purged_event(&self.event_broker, &entity.entity_id)diff --git a/services/search_processing_service/Cargo.toml b/services/search_processing_service/Cargo.tomlindex 91f9df4da5..568878518b 100644--- a/services/search_processing_service/Cargo.toml+++ b/services/search_processing_service/Cargo.toml@@ -85,6 +85,7 @@ document_sub_type = { path = "../../crates/document_sub_type" }documents = { path = "../../crates/documents", default-features = false, optional = true }doppler-config = { workspace = true }model = { path = "../../crates/model" }+model_owner = { path = "../../crates/model_owner" }s3_key = { path = "../../crates/s3_key" }models_email = { path = "../../crates/models_email" }model_file_type = { path = "../../crates/model_file_type" }diff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rsindex 58761c5913..051fc77d47 100644--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs@@ -48,6 +48,7 @@ use macro_event_topics::{};use macro_user_id::user_id::MacroUserIdStr;use model::document::FileType;+use model_owner::Owner;use models_properties::{DataType, EntityType, PropertyOwner, service::property_option::PropertyOptionValue,};@@ -825,7 +826,8 @@ fn channel_event_cases() -> Vec<(ChannelTopicEvent, ChannelEventDescription)> {}fn document_event_cases() -> Vec<(DocumentTopicEvent, DocumentEventDescription)> {- let owner = user_id();+ let user = user_id();+ let owner = Owner::User(user.clone());vec![(@@ -850,7 +852,7 @@ fn document_event_cases() -> Vec<(DocumentTopicEvent, DocumentEventDescription)>DocumentTopicEvent::Updated(DocumentUpdatedMetadata {document_id: DOCUMENT_ID.to_string(),owner: owner.clone(),- actor_user_id: Some(owner.clone()),+ actor_user_id: Some(user.clone()),actor: None,on_behalf_of: None,document_name: Some("Renamed document".to_string()),@@ -869,7 +871,7 @@ fn document_event_cases() -> Vec<(DocumentTopicEvent, DocumentEventDescription)>DocumentTopicEvent::Updated(DocumentUpdatedMetadata {document_id: DOCUMENT_ID.to_string(),owner: owner.clone(),- actor_user_id: Some(owner.clone()),+ actor_user_id: Some(user.clone()),actor: None,on_behalf_of: None,document_name: None,@@ -887,7 +889,7 @@ fn document_event_cases() -> Vec<(DocumentTopicEvent, DocumentEventDescription)>(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {document_id: DOCUMENT_ID.to_string(),- actor_user_id: Some(owner.clone()),+ actor_user_id: Some(user.clone()),actor: None,on_behalf_of: None,project_id: Some(PROJECT_ID.to_string()),@@ -1406,7 +1408,7 @@ fn maps_all_document_lifecycle_events_to_index_actions() {fn document_extraction_actions_preserve_optional_versions() {let content_uploaded = DocumentTopicEvent::ContentUploaded(DocumentContentUploadedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user_id(),+ owner: Owner::User(user_id()),file_type: FileType::Pdf,document_version_id: None,});@@ -1722,7 +1724,7 @@ fn exact_macro_documents_envelopes_decode_into_document_events() {Uuid::from_u128(1),DocumentTopicEvent::ContentUploaded(DocumentContentUploadedMetadata {document_id: DOCUMENT_ID.to_string(),- owner: user_id(),+ owner: Owner::User(user_id()),file_type: FileType::Pdf,document_version_id: Some("convert".to_string()),}),diff --git a/services/search_processing_service/src/process/document/raw_document/test.rs b/services/search_processing_service/src/process/document/raw_document/test.rsindex f5dca54495..65a74ac5d5 100644--- a/services/search_processing_service/src/process/document/raw_document/test.rs+++ b/services/search_processing_service/src/process/document/raw_document/test.rs@@ -1,5 +1,3 @@-use macro_user_id::user_id::MacroUserIdStr;-use super::*;#[tokio::test]@@ -7,7 +5,7 @@ async fn test_generate_upsert() {let document_info = DocumentMetadata {document_id: "AAA".to_string(),document_version_id: 0,- owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ owner: "macro|[email protected]".to_string().try_into().unwrap(),document_name: "test_document".to_string(),file_type: Some("md".to_string()),sha: None,@@ -52,7 +50,7 @@ async fn test_generate_upsert_with_sub_type() {let document_info = DocumentMetadata {document_id: "BBB".to_string(),document_version_id: 0,- owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ owner: "macro|[email protected]".to_string().try_into().unwrap(),document_name: "test_task".to_string(),file_type: Some("md".to_string()),sha: None,@@ -86,7 +84,7 @@ fn parent_only_document_info(file_type: Option<&str>) -> DocumentMetadata {DocumentMetadata {document_id: "CCC".to_string(),document_version_id: 0,- owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ owner: "macro|[email protected]".to_string().try_into().unwrap(),document_name: "pdf copy".to_string(),file_type: file_type.map(|ft| ft.to_string()),sha: None,diff --git a/tooling/seed_cli/Cargo.toml b/tooling/seed_cli/Cargo.tomlindex feeaaa041f..713a74d365 100644--- a/tooling/seed_cli/Cargo.toml+++ b/tooling/seed_cli/Cargo.toml@@ -31,6 +31,7 @@ macro_uuid = { path = "../../crates/macro_uuid" }mockall = { workspace = true }model = { path = "../../crates/model" }model-entity = { path = "../../crates/model-entity" }+model_owner = { path = "../../crates/model_owner" }models_email = { path = "../../crates/models_email" }models_permissions = { path = "../../crates/models_permissions" }models_properties = { path = "../../crates/models_properties" }diff --git a/tooling/seed_cli/src/entity/document/test.rs b/tooling/seed_cli/src/entity/document/test.rsindex a3c895d7fb..e7c5277759 100644--- a/tooling/seed_cli/src/entity/document/test.rs+++ b/tooling/seed_cli/src/entity/document/test.rs@@ -3,6 +3,7 @@ use std::io::Write;use clap::Parser;use macro_user_id::user_id::MacroUserIdStr;use model::document::{DocumentMetadata, FileType};+use model_owner::Owner;use tempfile::NamedTempFile;use crate::Cli;@@ -181,7 +182,7 @@ fn test_document_metadata() -> DocumentMetadata {DocumentMetadata::new_document("doc-123",1,- owner,+ Owner::User(owner),"My Document",Some(FileType::Pdf),"sha",@@ -201,7 +202,7 @@ fn test_document_metadata_with_type(file_type: FileType) -> DocumentMetadata {DocumentMetadata::new_document("doc-123",1,- owner,+ Owner::User(owner),"Test Doc",Some(file_type),"sha",