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): documents create with a typed owner distinct from the actor (#6978)
Will Hutchinson991583d42a8c
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 28ef9bb8a5..2e5cc37dae 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -16,6 +16,7 @@"crates/macro_event_topics","crates/macro_user_id","crates/model-entity",+ "crates/model_owner","crates/workspace-hack"],"agent": [@@ -3337,21 +3338,29 @@],"delete_chat_handler": ["crates/bot_id",+ "crates/bot_token","crates/cowlike","crates/entity_access_db_utils","crates/entity_registry/entity_registry","crates/entity_registry/entity_registry_db_utils","crates/entity_registry/shared_entity_registry",+ "crates/harness_id",+ "crates/harness_token",+ "crates/macro_auth",+ "crates/macro_authorization","crates/macro_entrypoint","crates/macro_env","crates/macro_env_var","crates/macro_user_id","crates/macro_uuid","crates/model-entity",+ "crates/model-error-response","crates/model_file_type","crates/model_owner",+ "crates/model_user","crates/models_entity_access_management","crates/models_permissions",+ "crates/remote_env_var","crates/workspace-hack","services/delete_chat_handler"],@@ -3907,6 +3916,7 @@"crates/authentication_service_client","crates/bot_id","crates/bot_token",+ "crates/bots","crates/broadcast","crates/calendar_events","crates/channel_sender",@@ -4935,28 +4945,48 @@],"entity_registry": ["crates/bot_id",+ "crates/bot_token","crates/cowlike","crates/entity_registry/entity_registry","crates/entity_registry/shared_entity_registry",+ "crates/harness_id",+ "crates/harness_token",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_env",+ "crates/macro_env_var","crates/macro_user_id","crates/model-entity",+ "crates/model-error-response","crates/model_owner",+ "crates/model_user",+ "crates/remote_env_var","crates/workspace-hack"],"entity_registry_db_utils": ["crates/bot_id",+ "crates/bot_token","crates/cowlike","crates/entity_access_db_utils","crates/entity_registry/entity_registry","crates/entity_registry/entity_registry_db_utils","crates/entity_registry/shared_entity_registry",+ "crates/harness_id",+ "crates/harness_token",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_env",+ "crates/macro_env_var","crates/macro_user_id","crates/macro_uuid","crates/model-entity",+ "crates/model-error-response","crates/model_file_type","crates/model_owner",+ "crates/model_user","crates/models_entity_access_management","crates/models_permissions",+ "crates/remote_env_var","crates/workspace-hack"],"favorites": [diff --git a/.sqlx/query-14a2188cb52a1529c3593351f08c82f5d13acb89ded253aefa3f759f184d87f3.json b/.sqlx/query-14a2188cb52a1529c3593351f08c82f5d13acb89ded253aefa3f759f184d87f3.jsonnew file mode 100644index 0000000000..1792f99b65--- /dev/null+++ b/.sqlx/query-14a2188cb52a1529c3593351f08c82f5d13acb89ded253aefa3f759f184d87f3.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n (SELECT COUNT(*) FROM \"Project\" WHERE \"uploadRequestId\" = 'lambda-request-id')\n AS \"upload_projects!\",\n (SELECT COUNT(*) FROM \"Document\" WHERE owner = $1) AS \"documents!\",\n (SELECT COUNT(*) FROM entity WHERE owner_id = $1) AS \"entities!\",\n (SELECT COUNT(*) FROM entity_access WHERE source_id = $1) AS \"grants!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "upload_projects!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "documents!",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "entities!",+ "type_info": "Int8"+ },+ {+ "ordinal": 3,+ "name": "grants!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null,+ null,+ null,+ null+ ]+ },+ "hash": "14a2188cb52a1529c3593351f08c82f5d13acb89ded253aefa3f759f184d87f3"+}diff --git a/.sqlx/query-35474f74dc2a75f2dee36ce5570b0a96e18f578389593f64f9ed5e6cbf90f9fb.json b/.sqlx/query-35474f74dc2a75f2dee36ce5570b0a96e18f578389593f64f9ed5e6cbf90f9fb.jsonnew file mode 100644index 0000000000..ee3692d15e--- /dev/null+++ b/.sqlx/query-35474f74dc2a75f2dee36ce5570b0a96e18f578389593f64f9ed5e6cbf90f9fb.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT t.id AS \"team_id!\", t.default_link_share AS \"default_link_share?: LinkShare\"\n FROM owner_team($1) ot\n JOIN team t ON t.id = ot.team_id\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "team_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "default_link_share?: LinkShare",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "35474f74dc2a75f2dee36ce5570b0a96e18f578389593f64f9ed5e6cbf90f9fb"+}diff --git a/.sqlx/query-753c12914c55bc487f0c5fa53ef55e0e3efb7292f770e9761767054c43fd8a47.json b/.sqlx/query-753c12914c55bc487f0c5fa53ef55e0e3efb7292f770e9761767054c43fd8a47.jsonnew file mode 100644index 0000000000..eff329e2e2--- /dev/null+++ b/.sqlx/query-753c12914c55bc487f0c5fa53ef55e0e3efb7292f770e9761767054c43fd8a47.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT source_type::text AS \"source_type!\", source_id\n FROM entity_access\n WHERE entity_id = $1 AND access_level = 'owner'\n ORDER BY source_type::text\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "source_type!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "source_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null,+ false+ ]+ },+ "hash": "753c12914c55bc487f0c5fa53ef55e0e3efb7292f770e9761767054c43fd8a47"+}diff --git a/.sqlx/query-76829ccfdac09457be977dc373b1313620bf709930deccd0fc769ff9567d45d2.json b/.sqlx/query-76829ccfdac09457be977dc373b1313620bf709930deccd0fc769ff9567d45d2.jsonnew file mode 100644index 0000000000..10b5485811--- /dev/null+++ b/.sqlx/query-76829ccfdac09457be977dc373b1313620bf709930deccd0fc769ff9567d45d2.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT COUNT(*) AS \"count!\" FROM \"UserHistory\" WHERE \"itemId\" = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "76829ccfdac09457be977dc373b1313620bf709930deccd0fc769ff9567d45d2"+}diff --git a/.sqlx/query-d610b4b3200be51f79986d70f932e78ffdc7a6bbef7f6c55481d684009002f63.json b/.sqlx/query-d610b4b3200be51f79986d70f932e78ffdc7a6bbef7f6c55481d684009002f63.jsonnew file mode 100644index 0000000000..fc4779206d--- /dev/null+++ b/.sqlx/query-d610b4b3200be51f79986d70f932e78ffdc7a6bbef7f6c55481d684009002f63.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT source_type::text AS \"source_type!\", source_id,\n access_level::text AS \"access_level!\"\n FROM entity_access\n WHERE entity_id::text = $1 AND granted_from_project_id IS NULL\n ORDER BY source_type::text, source_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "source_type!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "source_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "access_level!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null,+ false,+ null+ ]+ },+ "hash": "d610b4b3200be51f79986d70f932e78ffdc7a6bbef7f6c55481d684009002f63"+}diff --git a/.sqlx/query-fff2597beb29f7b5eb8480afc6f45f5df2e7ec46974fc45707f02dcdc3c4bcb5.json b/.sqlx/query-fff2597beb29f7b5eb8480afc6f45f5df2e7ec46974fc45707f02dcdc3c4bcb5.jsonnew file mode 100644index 0000000000..c19b001caa--- /dev/null+++ b/.sqlx/query-fff2597beb29f7b5eb8480afc6f45f5df2e7ec46974fc45707f02dcdc3c4bcb5.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n (SELECT COUNT(*) FROM \"Document\" WHERE owner = $1) AS \"documents!\",\n (SELECT COUNT(*) FROM entity WHERE owner_id = $1) AS \"entities!\",\n (SELECT COUNT(*) FROM entity_access WHERE source_id = $1) AS \"grants!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "documents!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "entities!",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "grants!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null,+ null,+ null+ ]+ },+ "hash": "fff2597beb29f7b5eb8480afc6f45f5df2e7ec46974fc45707f02dcdc3c4bcb5"+}diff --git a/Cargo.lock b/Cargo.lockindex d23ae12cee..7b92083612 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -26,6 +26,7 @@ dependencies = ["macro_event_topics","macro_user_id","model-entity",+ "model_owner","rdkafka","readonly","rootcause",@@ -773,6 +774,8 @@ dependencies = ["email_service_client","entity_access","entity_access_management",+ "entity_registry",+ "entity_registry_db_utils","foreign_entity","frecency","futures",@@ -797,6 +800,7 @@ dependencies = ["model","model-entity","model_notifications",+ "model_owner","models_dcs","models_email","models_pagination",@@ -5502,6 +5506,7 @@ dependencies = ["aws-sdk-secretsmanager","aws-sdk-sqs","axum",+ "bots","call","channels","chat",@@ -5518,6 +5523,8 @@ dependencies = ["email_service_client","entity_access","entity_access_management",+ "entity_registry",+ "entity_registry_db_utils","foreign_entity","frecency","futures",@@ -5650,6 +5657,8 @@ dependencies = ["entity_access","entity_access_management","entity_mutation",+ "entity_registry",+ "entity_registry_db_utils","favorites","foreign_entity","frecency",@@ -5813,7 +5822,10 @@ dependencies = ["aws-sdk-s3","aws-sdk-sqs","aws_lambda_events",+ "bots","documents",+ "entity_registry",+ "entity_registry_db_utils","lambda_runtime","lexical_client","macro_aws_config",@@ -5860,6 +5872,7 @@ dependencies = ["entity_access_db_utils","entity_access_management","entity_mutation",+ "entity_registry","entity_registry_db_utils","foreign_entity","futures",@@ -6680,12 +6693,16 @@ version = "0.1.0"dependencies = ["bot_id","chrono",+ "harness_id",+ "macro_authorization","macro_db_migrator",+ "macro_user_id","model-entity","model_owner","rootcause","shared_entity_registry","sqlx",+ "thiserror 2.0.18","tokio","tracing","uuid",@@ -7547,6 +7564,7 @@ dependencies = ["model-entity","model-error-response","model_notifications",+ "model_owner","model_user","models_permissions","notification",@@ -9214,6 +9232,7 @@ version = "0.1.0"dependencies = ["documents","initiative",+ "model_owner","rootcause","tracing","workspace-hack",@@ -10886,6 +10905,7 @@ dependencies = ["aws-sdk-secretsmanager","aws-sdk-sqs","axum",+ "bots","call","channels","chat",@@ -10898,6 +10918,8 @@ dependencies = ["email_service_client","entity_access","entity_access_management",+ "entity_registry",+ "entity_registry_db_utils","foreign_entity","frecency","fusionauth",@@ -11003,6 +11025,7 @@ dependencies = ["ai_usage","anyhow","axum",+ "bots","call","channels","chrono",@@ -11012,6 +11035,8 @@ dependencies = ["email_service_client","entity_access","entity_access_management",+ "entity_registry",+ "entity_registry_db_utils","foreign_entity","frecency","futures",@@ -13504,6 +13529,7 @@ dependencies = ["entity_access_db_utils","entity_access_management","entity_mutation",+ "entity_registry","entity_registry_db_utils","futures","hex",diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex cc29f6eb06..8257a38871 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -22030,6 +22030,10 @@"document_name"],"properties": {+ "actor": {+ "type": ["string", "null"],+ "description": "Who mechanically created the copy."+ },"document_id": {"type": "string","description": "The id of the newly created copy."@@ -22049,6 +22053,17 @@}]},+ "on_behalf_of": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "The user whose feed this copy belongs on, when different from the actor."+ }+ ]+ },"owner": {"type": "string","description": "The principal who owns the new copy."diff --git a/crates/activity/Cargo.toml b/crates/activity/Cargo.tomlindex 0b28d1d41e..7cc5dfcccb 100644--- a/crates/activity/Cargo.toml+++ b/crates/activity/Cargo.toml@@ -39,6 +39,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" }rdkafka = { workspace = true, optional = true }readonly = { workspace = true }rootcause = { workspace = true, optional = true }diff --git a/crates/activity/src/domain/models.rs b/crates/activity/src/domain/models.rsindex d5fe3c7453..ea71704601 100644--- a/crates/activity/src/domain/models.rs+++ b/crates/activity/src/domain/models.rs@@ -23,6 +23,7 @@ use std::sync::LazyLock;use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;+use model_owner::CreationPrincipal;use serde::{Deserialize, Serialize};use serde_json::Value;use uuid::Uuid;@@ -87,6 +88,18 @@ impl Attribution {}}+impl From<&CreationPrincipal> for Attribution {+ fn from(principal: &CreationPrincipal) -> Self {+ match principal {+ CreationPrincipal::User(user) => Self::direct(Actor::new_from_user(user.clone())),+ CreationPrincipal::BotForUser { bot, user } => {+ Self::delegated(Actor::new_from_bot(*bot), user.clone())+ }+ CreationPrincipal::TeamBot { bot, .. } => Self::direct(Actor::new_from_bot(bot.get())),+ }+ }+}+/// The entity-kind vocabulary activities are recorded against (re-exported/// for domain mappings).pub use model_entity::EntityType;diff --git a/crates/activity/src/domain/models/test.rs b/crates/activity/src/domain/models/test.rsindex f0a5ebe3da..6cd56e964a 100644--- a/crates/activity/src/domain/models/test.rs+++ b/crates/activity/src/domain/models/test.rs@@ -192,6 +192,36 @@ fn attribution_delegated_keeps_actor_and_scopes_the_subject() {assert_eq!(activity.subject_id, "macro|[email protected]");}+#[test]+fn creation_principal_attributes_the_mechanical_actor() {+ let teo = user("macro|[email protected]");+ let bot = bot_id::BotId::new_from_uuid(Uuid::from_u128(0xB07A));+ let team_bot = bot_id::NonSystemBotId::new(bot).unwrap();++ let by_user = Attribution::from(&CreationPrincipal::User(teo.clone()));+ let for_user = Attribution::from(&CreationPrincipal::BotForUser {+ bot,+ user: teo.clone(),+ });+ let by_team_bot = Attribution::from(&CreationPrincipal::TeamBot {+ bot: team_bot,+ team: Uuid::from_u128(9),+ });++ assert_eq!(by_user.actor().as_ref(), "macro|[email protected]");+ assert_eq!(by_user.on_behalf_of(), None);+ assert_eq!(+ for_user.actor().as_ref(),+ "bot|00000000-0000-0000-0000-00000000b07a"+ );+ assert_eq!(for_user.on_behalf_of(), Some(teo));+ assert_eq!(+ by_team_bot.actor().as_ref(),+ "bot|00000000-0000-0000-0000-00000000b07a"+ );+ assert_eq!(by_team_bot.on_behalf_of(), None);+}+#[test]fn subject_is_the_actor_unless_delegated() {let direct = Activity::common(diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rsindex e5df76997e..d41d8bdefd 100644--- a/crates/agent_session/src/outbound/postgres.rs+++ b/crates/agent_session/src/outbound/postgres.rs@@ -297,10 +297,9 @@ impl AgentSessionRepo for PgAgentSessionRepo {} = params;let mcp_servers_json = serde_json::to_value(mcp_servers.servers()).context("serialize agent session mcp servers")?;- // The row's `owner_id` references `"User"`, the owner's grant is a- // user access row, and the session lands in the owner's history:- // this store holds user-owned sessions, and says so before writing- // anything rather than letting the foreign key say it for a bot.+ // The owner's grant is a user access row, and the session lands in+ // the owner's history: this store still holds user-owned sessions,+ // even though the denormalized owner_id no longer references "User".let owner_user = owner_id.as_user().ok_or_else(|| AgentSessionError::OwnerNotUser(owner_id.owner_type()))?;@@ -363,7 +362,6 @@ impl AgentSessionRepo for PgAgentSessionRepo {|error| match error.as_database_error().and_then(|e| e.constraint()) {Some("agent_session_pkey") => AgentSessionError::SessionIdTaken(id),Some("agent_session_thread_bot_unique") => AgentSessionError::ThreadSessionExists,- Some("agent_session_owner_id_fkey") => AgentSessionError::UnknownOwner,_ => AgentSessionError::Unknown(anyhow::Error::new(error).context("failed to create agent session"),),diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex a24aeed5bd..a7e6642120 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -19,8 +19,8 @@ fn user_id(value: &str) -> MacroUserIdStr<'static> {/// The fixed owner every [`new_session`] fixture uses.const OWNER: &str = "macro|[email protected]";-/// Insert a `"User"` row (and its `macro_user` parent) so the id can satisfy-/// `agent_session.owner_id`'s foreign key.+/// Insert a `"User"` row (and its `macro_user` parent) for user-owned sessions+/// and their user history.async fn insert_user(pool: &PgPool, user_id: &str) {let email = user_id.strip_prefix("macro|").unwrap_or(user_id);// The no-op update makes the existing row's id come back when the user@@ -56,9 +56,8 @@ async fn insert_user(pool: &PgPool, user_id: &str) {}pub(super) async fn create_test_bot(pool: &PgPool) -> BotId {- // Every session fixture is owned by the same user, and- // `agent_session.owner_id` references `"User"(id)` - so seed the- // row here, where every session-creating test already passes through.+ // Seed the shared owner here so every session-creating test has a user+ // row for history and other user-specific relations.insert_user(pool, OWNER).await;let owner = user_id("macro|[email protected]");let bot = PgBotsRepo::new(pool.clone())diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.tomlindex c2f2b66cad..e95d5aec1d 100644--- a/crates/ai_tools/Cargo.toml+++ b/crates/ai_tools/Cargo.toml@@ -42,6 +42,8 @@ email = { path = "../email", features = ["ai_schema", "ai_tools", "axum", "outboemail_service_client = { path = "../email_service_client" }entity_access = { path = "../entity_access" }entity_access_management = { path = "../entity_access_management" }+entity_registry = { path = "../entity_registry/entity_registry" }+entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils" }foreign_entity = { path = "../foreign_entity" }frecency = { path = "../frecency", features = ["outbound", "postgres"] }futures.workspace = true@@ -63,6 +65,7 @@ pipedream_mcp = { path = "../pipedream_mcp" }model = { path = "../model" }model-entity = { path = "../model-entity" }model_notifications = { path = "../model_notifications" }+model_owner = { path = "../model_owner" }models_dcs = { path = "../models_dcs" }models_email = { path = "../models_email" }models_pagination = { path = "../models_pagination" }diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex 43ceb051b5..c5d954020a 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -10,6 +10,7 @@ use crate::tool_context::{};use anthropic::toolset::AnthropicToolContext;use anyhow::Context;+use bots::outbound::pg_bots_repo::PgBotsRepo;use channels::domain::list_service::ChannelListServiceImpl;use channels::outbound::pg_channels_repo::PgChannelsRepo;use connection_gateway_client::ConnectionGatewayClient;@@ -24,6 +25,8 @@ use email::outbound::EmailPgRepo;use email_service_client::EmailServiceClientExternal;use entity_access::domain::service::EntityAccessServiceImpl;use entity_access::outbound::PgAccessRepository;+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use foreign_entity::{domain::service::ForeignEntityServiceImpl,outbound::pg_foreign_entity_repo::PgForeignEntityRepo,@@ -237,7 +240,10 @@ pub async fn build_tool_service_context_from_env(env.document_storage_bucket.to_string(),env.docx_document_upload_bucket.to_string(),);- let document_repo = PgDocumentRepo::new(pool.clone());+ let document_repo = PgDocumentRepo::new(+ pool.clone(),+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone()))),+ );let cloudfront_config = CloudFrontConfig {distribution_url: env.document_storage_service_cloudfront_distribution_urldiff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex 3d9d2349ea..15cbdfcd54 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -37,6 +37,8 @@ use email::{};use entity_access::domain::models::EditAccessLevel;use entity_access::domain::ports::EntityAccessService as _;+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use foreign_entity::{domain::service::ForeignEntityServiceImpl,outbound::pg_foreign_entity_repo::PgForeignEntityRepo,@@ -516,11 +518,10 @@ impl TaskPropertiesPort for NoOpTaskProperties {}async fn set_entity_property(&self,- _user_id: &str,+ _principal: &model_owner::CreationPrincipal,_entity_id: &str,_property_definition_id: uuid::Uuid,_value: Option<models_properties::api::requests::SetPropertyValue>,- _attribution: &activity::Attribution,) -> anyhow::Result<()> {Ok(())}@@ -564,22 +565,16 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {async fn set_entity_property(&self,- user_id: &str,+ principal: &model_owner::CreationPrincipal,entity_id: &str,property_definition_id: uuid::Uuid,value: Option<models_properties::api::requests::SetPropertyValue>,- attribution: &activity::Attribution,) -> anyhow::Result<()> {use properties::PropertiesService as _;- let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)?;- let entity_access_receipt = task_property_edit_receipt(- self.entity_access_service.as_ref(),- &user_id,- attribution,- entity_id,- )- .await?;+ let entity_access_receipt =+ task_property_edit_receipt(self.entity_access_service.as_ref(), principal, entity_id)+ .await?;self.properties.set_entity_property(&entity_access_receipt, property_definition_id, value).await@@ -837,7 +832,7 @@ pub type ToolEntityAccessManagementService =/// Type alias for the document service implementation used by AI toolspub type ToolDocumentService = documents::domain::service::DocumentServiceImpl<- documents::outbound::pg_document_repo::PgDocumentRepo,+ documents::outbound::pg_document_repo::PgDocumentRepo<PgBotsRepo>,documents::outbound::s3_upload_url::S3UploadUrlAdapter,TaskPropertiesAdapter,NoOpConnectionService,@@ -1049,7 +1044,7 @@ pub type ToolChatService = ChatServiceImpl<PgChatRepo, (), ToolEntityAccessManag/// tools only create, read, and move projects, never run upload or purge/// flows.pub type ToolProjectService = projects::domain::service::ProjectServiceImpl<- projects::outbound::PgProjectRepo,+ projects::outbound::PgProjectRepo<PgBotsRepo>,projects::domain::ports::UnavailableProjectUploadUrlPort,projects::domain::ports::UnavailableBulkUploadRequestPort,projects::domain::ports::UnavailableShaCounterPort,@@ -1081,7 +1076,10 @@ pub fn build_project_tool_context(email_service: Arc<ToolUserEmailService>,) -> ToolProjectToolContext {let project_service = projects::domain::service::ProjectServiceImpl::new(- projects::outbound::PgProjectRepo::new(pool.clone()),+ projects::outbound::PgProjectRepo::new(+ pool.clone(),+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone()))),+ ),projects::domain::ports::UnavailableProjectUploadUrlPort,projects::domain::ports::UnavailableBulkUploadRequestPort,projects::domain::ports::UnavailableShaCounterPort,@@ -1128,6 +1126,13 @@ pub struct ToolEntityCreator {}impl ToolEntityCreator {+ fn creation_principal(user: &MacroUserIdStr<'static>) -> model_owner::CreationPrincipal {+ model_owner::CreationPrincipal::BotForUser {+ bot: bot_id::MACRO_AI_BOT_ID,+ user: user.clone(),+ }+ }+async fn create_doc(&self,user: &MacroUserIdStr<'static>,@@ -1138,20 +1143,16 @@ impl ToolEntityCreator {) -> anyhow::Result<String> {use std::str::FromStr as _;let document = documents::domain::create::NewPlainTextDocument::builder(- documents::domain::create::NewDocumentMetadata::builder(name.to_string())- .attribution(activity::Attribution::delegated(- activity::Actor::new_from_bot(bot_id::MACRO_AI_BOT_ID),- user.clone(),- ))- .build(),+ documents::domain::create::NewDocumentMetadata::new(name.to_string()),).file_type(model::document::FileType::from_str("md").expect("md is a valid file type")).text(markdown.to_string()).task_flag(is_task, team_id).build()?;+ let ai_for_user = Self::creation_principal(user);let created = self.document_creator- .create_plain_text(user.clone(), document)+ .create_plain_text(&ai_for_user, document).await?;Ok(created.into_response()@@ -1206,8 +1207,7 @@ impl ToolEntityCreator {use models_properties::api::requests::SetPropertyValue;use system_properties::SystemPropertyKey;- let attribution =- activity::Attribution::direct(activity::Actor::new_from_user(user.clone()));+ let principal = Self::creation_principal(user);if let Some(status) = properties.status.as_deref()&& let Err(e) = self@@ -1231,13 +1231,12 @@ impl ToolEntityCreator {if let Err(e) = self.task_properties.set_entity_property(- user.as_ref(),+ &principal,task_id,SystemPropertyKey::Priority.uuid(),Some(SetPropertyValue::SelectOption {option_id: option.uuid(),}),- &attribution,).await{@@ -1255,11 +1254,10 @@ impl ToolEntityCreator {if let Err(e) = self.task_properties.set_entity_property(- user.as_ref(),+ &principal,task_id,SystemPropertyKey::DueDate.uuid(),Some(SetPropertyValue::Date { value }),- &attribution,).await{@@ -1288,13 +1286,12 @@ impl ToolEntityCreator {if let Err(e) = self.task_properties.set_entity_property(- user.as_ref(),+ &principal,task_id,SystemPropertyKey::Assignees.uuid(),Some(SetPropertyValue::MultiEntityReference {references: vec![reference],}),- &attribution,).await{diff --git a/crates/bot_id/src/lib.rs b/crates/bot_id/src/lib.rsindex 7a0ca21455..92b77bb4f7 100644--- a/crates/bot_id/src/lib.rs+++ b/crates/bot_id/src/lib.rs@@ -224,6 +224,23 @@ pub fn is_system_bot(id: BotId) -> bool {system_bot(id).is_some()}+/// A bot id that is not in [`SYSTEM_BOTS`].+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub struct NonSystemBotId(BotId);++impl NonSystemBotId {+ /// Accept `id` only when it is not a first-party bot.+ #[must_use]+ pub fn new(id: BotId) -> Option<Self> {+ (!is_system_bot(id)).then_some(Self(id))+ }++ /// Return the underlying bot id.+ pub const fn get(self) -> BotId {+ self.0+ }+}+/// A bot id UUID.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(transparent)]diff --git a/crates/bot_id/src/test.rs b/crates/bot_id/src/test.rsindex 7bdef2bc88..10a5e43894 100644--- a/crates/bot_id/src/test.rs+++ b/crates/bot_id/src/test.rs@@ -83,6 +83,20 @@ fn claude_is_a_global_system_agent_with_a_distinct_identity() {assert_eq!(ids.len(), SYSTEM_BOTS.len());}+#[test]+fn non_system_bot_id_rejects_every_system_bot() {+ for bot in SYSTEM_BOTS {+ assert_eq!(NonSystemBotId::new(bot.id), None, "{}", bot.handle);+ }+}++#[test]+fn non_system_bot_id_accepts_a_row_bot() {+ let bot = NonSystemBotId::new(BotId::TEST_A).unwrap();++ assert_eq!(bot.get(), BotId::TEST_A);+}+#[test]fn rejects_trailing_storage_content() {let uuid = Uuid::new_v4();diff --git a/crates/documents/Cargo.toml b/crates/documents/Cargo.tomlindex eefdc7598f..83e210f3c4 100644--- a/crates/documents/Cargo.toml+++ b/crates/documents/Cargo.toml@@ -36,6 +36,7 @@ axum = ["dep:axum","dep:axum-extra","dep:base64",+ "dep:entity_registry","dep:jsonwebtoken","dep:lexical_client","dep:macro_authorization",@@ -69,6 +70,7 @@ outbound = ["dep:aws-sdk-s3","dep:base64","dep:entity_access_db_utils",+ "dep:entity_registry","dep:entity_registry_db_utils","dep:hex","dep:redis",@@ -148,6 +150,7 @@ base64 = { workspace = true, optional = true }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 = { path = "../entity_registry/entity_registry", optional = true }entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils", optional = true }model_owner = { path = "../model_owner" }futures = { workspace = true }diff --git a/crates/documents/src/bin/backfill_markdown_content_location.rs b/crates/documents/src/bin/backfill_markdown_content_location.rsindex 7207e119a7..afc4bc4548 100644--- a/crates/documents/src/bin/backfill_markdown_content_location.rs+++ b/crates/documents/src/bin/backfill_markdown_content_location.rs@@ -11,7 +11,7 @@ use documents::domain::markdown_backfill::{use documents::domain::models::DocumentError;use documents::domain::ports::markdown::MarkdownInitializationPort;use documents::outbound::markdown_init::LexicalSyncMarkdownInitializer;-use documents::outbound::pg_document_repo::PgDocumentRepo;+use documents::outbound::pg_document_repo::PgMarkdownBackfillRepo;use documents::outbound::s3_markdown_source::S3MarkdownObjectReader;use lexical_client::LexicalClient;use macro_env_var::env_vars;@@ -120,7 +120,7 @@ async fn main() -> anyhow::Result<()> {.await.context("failed to connect to postgres")?;- let repo = PgDocumentRepo::new(db);+ let repo = PgMarkdownBackfillRepo::new(db);let sync_probe =SyncServiceClient::new(sync_service_auth_key.clone(), sync_service_url.clone());let object_reader = build_object_reader(options.initialize_missing).await?;diff --git a/crates/documents/src/domain/activity.rs b/crates/documents/src/domain/activity.rsindex f72994aad4..681b0b7824 100644--- a/crates/documents/src/domain/activity.rs+++ b/crates/documents/src/domain/activity.rs@@ -32,6 +32,17 @@ fn actor_from_owner(}}+fn creation_attribution(+ owner: &Owner,+ actor: &Option<Actor<'static>>,+ on_behalf_of: &Option<MacroUserIdStr<'static>>,+) -> Attribution {+ let actor = actor+ .clone()+ .unwrap_or_else(|| actor_from_owner(owner, on_behalf_of.as_ref()));+ Attribution::new(actor, on_behalf_of.clone())+}+/// Attribution for `updated` / `deleted` events. Bot receipts publish `actor`;/// user receipts (and events from before attribution) only `actor_user_id`./// `None` when neither is set, e.g. internal callers.@@ -68,17 +79,12 @@ impl ActivitySource for DocumentTopicEvent {};match self {- DocumentTopicEvent::Created(metadata) => {- let actor = metadata.actor.clone().unwrap_or_else(|| {- actor_from_owner(&metadata.owner, metadata.on_behalf_of.as_ref())- });- single(- Attribution::new(actor, metadata.on_behalf_of.clone()),- CommonAction::Created,- &metadata.document_id,- metadata.created_at.unwrap_or_else(|| event_time(event_id)),- )- }+ DocumentTopicEvent::Created(metadata) => single(+ creation_attribution(&metadata.owner, &metadata.actor, &metadata.on_behalf_of),+ CommonAction::Created,+ &metadata.document_id,+ metadata.created_at.unwrap_or_else(|| event_time(event_id)),+ ),DocumentTopicEvent::Updated(metadata) => {match mutation_attribution(&metadata.actor,@@ -111,7 +117,7 @@ impl ActivitySource for DocumentTopicEvent {}// The copy is a new document; its creation is the activity.DocumentTopicEvent::Copied(metadata) => single(- Attribution::direct(actor_from_owner(&metadata.owner, None)),+ creation_attribution(&metadata.owner, &metadata.actor, &metadata.on_behalf_of),CommonAction::Created,&metadata.document_id,event_time(event_id),diff --git a/crates/documents/src/domain/activity/test.rs b/crates/documents/src/domain/activity/test.rsindex 4205802653..b7ecf51e60 100644--- a/crates/documents/src/domain/activity/test.rs+++ b/crates/documents/src/domain/activity/test.rs@@ -188,11 +188,15 @@ fn unattributable_mutations_are_dropped() {#[test]fn copied_maps_to_a_created_activity_for_the_new_document() {+ let copier = user("macro|[email protected]");+ let bot = Actor::new_from_bot(bot_id::MACRO_AI_BOT_ID);let event = envelope(DocumentTopicEvent::Copied(DocumentCopiedMetadata {document_id: "22222222-2222-2222-2222-222222222222".to_string(),source_document_id: DOCUMENT_ID.to_string(),source_version_id: None,- owner: Owner::from_principal_str("macro|[email protected]").unwrap(),+ owner: Owner::User(copier.clone()),+ actor: Some(bot.clone()),+ on_behalf_of: Some(copier.clone()),document_name: "copy".to_string(),file_type: None,project_id: None,@@ -202,6 +206,8 @@ fn copied_maps_to_a_created_activity_for_the_new_document() {let activity = single_activity(event.event.ingest(event.event_id));assert_eq!(activity.action, Action::Created);assert_eq!(activity.entity_id, "22222222-2222-2222-2222-222222222222");+ assert_eq!(activity.actor, bot);+ assert_eq!(activity.subject_id, copier.as_ref());}#[test]@@ -231,6 +237,8 @@ fn creation_and_copy_derive_user_bot_and_team_actors() {source_document_id: "source-document".to_string(),source_version_id: None,owner,+ actor: None,+ on_behalf_of: None,document_name: "copy".to_string(),file_type: None,project_id: None,diff --git a/crates/documents/src/domain/create.rs b/crates/documents/src/domain/create.rsindex 424198f15f..d291de49d6 100644--- a/crates/documents/src/domain/create.rs+++ b/crates/documents/src/domain/create.rs@@ -10,19 +10,17 @@ mod test;pub mod upload;-use activity::Attribution;use anyhow::Context;use base64::Engine;-use macro_user_id::user_id::MacroUserIdStr;use model::document::FileType;+use model_owner::CreationPrincipal;use sha2::{Digest, Sha256};use models_permissions::share_permission::LinkShareState;use crate::domain::content::{DocumentContent, DocumentContentLocation};use crate::domain::models::{- CreateDocumentRepoArgs, CreateTaskRequest, DocumentError, EMPTY_SHA256, InitialLinkShare,- PropertyInput,+ CreateTaskRequest, DocumentError, EMPTY_SHA256, InitialLinkShare, NewDocument, PropertyInput,};use crate::domain::ports::create::{DocumentBytesUpload, DocumentBytesUploadPort, DocumentCreationService,@@ -39,7 +37,6 @@ pub struct NewDocumentMetadata {project_id: Option<uuid::Uuid>,created_at: Option<chrono::DateTime<chrono::Utc>>,skip_history: bool,- attribution: Option<Attribution>,initial_link_share: InitialLinkShare,}@@ -58,22 +55,16 @@ impl NewDocumentMetadata {project_id: None,created_at: None,skip_history: false,- attribution: None,initial_link_share: InitialLinkShare::EntityDefault,},}}- fn into_repo_args(- self,- user_id: MacroUserIdStr<'static>,- kind: RepoDocumentKind,- ) -> CreateDocumentRepoArgs {- CreateDocumentRepoArgs {+ fn into_new_document(self, kind: RepoDocumentKind) -> NewDocument {+ NewDocument {id: self.id,sha: kind.sha,document_name: self.document_name,- user_id,file_type: kind.file_type,project_id: self.project_id,team_id: kind.team_id,@@ -81,7 +72,6 @@ impl NewDocumentMetadata {created_at: self.created_at,sub_type: kind.subtype.sub_type(),skip_history: self.skip_history,- attribution: self.attribution,initial_link_share: self.initial_link_share,}}@@ -118,12 +108,6 @@ impl NewDocumentMetadataBuilder {self}- /// Attribute the create without changing document ownership.- pub fn attribution(mut self, attribution: Attribution) -> Self {- self.metadata.attribution = Some(attribution);- self- }-/// Initialize link share to exactly `state` instead of the entity-type default.pub fn initial_link_share(mut self, state: LinkShareState) -> Self {self.metadata.initial_link_share = InitialLinkShare::Exact(state);@@ -532,21 +516,18 @@ where/// sync room before returning; no browser or object-storage upload is needed.pub async fn create_spreadsheet(&self,- user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,metadata: NewDocumentMetadata,) -> Result<CreatedDocument, DocumentError> {- let args = metadata.into_repo_args(- user_id.clone(),- RepoDocumentKind {- file_type: Some(FileType::Spreadsheet),- sha: EMPTY_SHA256.to_string(),- subtype: RepoDocumentSubtype::Regular,- team_id: None,- share_with_team: false,- },- );+ let document = metadata.into_new_document(RepoDocumentKind {+ file_type: Some(FileType::Spreadsheet),+ sha: EMPTY_SHA256.to_string(),+ subtype: RepoDocumentSubtype::Regular,+ team_id: None,+ share_with_team: false,+ });self.document_service- .create_document(user_id, args, None)+ .create_document(principal, document, None).await.map(CreatedDocument::new)}@@ -555,7 +536,7 @@ where#[tracing::instrument(skip(self, document), err)]pub async fn create_plain_text(&self,- user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,document: NewPlainTextDocument,) -> Result<CreatedDocument, DocumentError> {let NewPlainTextDocument {@@ -567,7 +548,7 @@ wherematch kind {PlainTextDocumentKind::Markdown(subtype) => {self.create_markdown_text(- user_id,+ principal,NewMarkdownTextDocument {metadata,markdown: text,@@ -578,7 +559,7 @@ where}PlainTextDocumentKind::Text(file_type) => {self.create_text_file(- user_id,+ principal,NewTextFileDocument {metadata,file_type,@@ -594,7 +575,7 @@ where#[tracing::instrument(skip(self, document), err)]pub async fn create_markdown_text(&self,- user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,document: NewMarkdownTextDocument,) -> Result<CreatedDocument, DocumentError> {let NewMarkdownTextDocument {@@ -622,30 +603,25 @@ whereNone};- let args = metadata.into_repo_args(- user_id.clone(),- RepoDocumentKind {- file_type: Some(FileType::Md),- sha: EMPTY_SHA256.to_string(),- subtype: match &subtype {- MarkdownSubtype::Note => RepoDocumentSubtype::Regular,- MarkdownSubtype::Task { .. } => RepoDocumentSubtype::MarkdownTask,- MarkdownSubtype::Snippet => RepoDocumentSubtype::MarkdownSnippet,- MarkdownSubtype::Skill => RepoDocumentSubtype::MarkdownSkill,- MarkdownSubtype::InitiativeDescription => {- RepoDocumentSubtype::MarkdownInitiativeDescription- }- },- team_id,- share_with_team: task.as_ref().is_some_and(|(_, share, _)| *share),+ let new_document = metadata.into_new_document(RepoDocumentKind {+ file_type: Some(FileType::Md),+ sha: EMPTY_SHA256.to_string(),+ subtype: match &subtype {+ MarkdownSubtype::Note => RepoDocumentSubtype::Regular,+ MarkdownSubtype::Task { .. } => RepoDocumentSubtype::MarkdownTask,+ MarkdownSubtype::Snippet => RepoDocumentSubtype::MarkdownSnippet,+ MarkdownSubtype::Skill => RepoDocumentSubtype::MarkdownSkill,+ MarkdownSubtype::InitiativeDescription => {+ RepoDocumentSubtype::MarkdownInitiativeDescription+ }},- );- let attribution = args.resolved_attribution();- let mention_user_id = user_id.clone();+ team_id,+ share_with_team: task.as_ref().is_some_and(|(_, share, _)| *share),+ });let mut response = self.document_service- .create_document(user_id.clone(), args, None)+ .create_document(principal, new_document, None).await?;let document_id = response@@ -659,7 +635,7 @@ whereif let Some((property_values, share_with_team, team_id)) = task {self.document_service.handle_task_properties(- user_id,+ principal,&document_id,&CreateTaskRequest {task_name,@@ -669,7 +645,6 @@ whereproperty_values,share_with_team,},- &attribution,).await?;}@@ -700,7 +675,7 @@ whereif let Err(error) = self.mention_tracker- .track_document_mentions(&document_id, &mention_user_id, &markdown)+ .track_document_mentions(&document_id, principal.user(), &markdown).await{tracing::error!(error=?error, document_id=%document_id, "unable to track document mentions");@@ -716,7 +691,7 @@ where#[tracing::instrument(skip(self, document), err)]pub async fn create_text_file(&self,- user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,document: NewTextFileDocument,) -> Result<CreatedDocument, DocumentError> {let NewTextFileDocument {@@ -727,20 +702,17 @@ wherelet bytes = text.into_bytes();let hashes = file_shas(&bytes);- let args = metadata.into_repo_args(- user_id.clone(),- RepoDocumentKind {- file_type: Some(file_type.into_file_type()),- sha: hashes.hex,- subtype: RepoDocumentSubtype::Regular,- team_id: None,- share_with_team: false,- },- );+ let new_document = metadata.into_new_document(RepoDocumentKind {+ file_type: Some(file_type.into_file_type()),+ sha: hashes.hex,+ subtype: RepoDocumentSubtype::Regular,+ team_id: None,+ share_with_team: false,+ });let mut response = self.document_service- .create_document(user_id, args, None)+ .create_document(principal, new_document, None).await?;let document_id = response@@ -811,174 +783,3 @@ fn file_shas(file_content: &[u8]) -> FileShas {FileShas { hex, base64 }}--#[cfg(test)]-mod tests {- use super::{- MarkdownSubtype, NewDocumentMetadata, NewPlainTextDocument, RepoDocumentKind,- RepoDocumentSubtype, file_shas,- };- use crate::domain::models::{ImportEmailAttachmentRepoArgs, InitialLinkShare};- use activity::{Actor, Attribution};- use macro_user_id::user_id::MacroUserIdStr;- use model::document::FileType;-- fn metadata() -> NewDocumentMetadata {- NewDocumentMetadata::new("test")- }-- fn owner() -> MacroUserIdStr<'static> {- MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()- }-- fn repo_kind() -> RepoDocumentKind {- RepoDocumentKind {- file_type: Some(FileType::Md),- sha: "sha".to_string(),- subtype: RepoDocumentSubtype::Regular,- team_id: None,- share_with_team: false,- }- }-- #[test]- fn creation_attribution_defaults_to_none() {- let args = metadata().into_repo_args(owner(), repo_kind());- assert_eq!(args.attribution, None);- assert_eq!(- args.resolved_attribution(),- Attribution::direct(Actor::new_from_user(owner()))- );- }-- #[test]- fn email_import_resolves_to_the_system_principal() {- let args = ImportEmailAttachmentRepoArgs {- email_attachment_id: uuid::Uuid::from_u128(1),- create: metadata().into_repo_args(owner(), repo_kind()),- };-- assert_eq!(args.create.user_id.as_ref(), "macro|[email protected]");- assert_eq!(- args.resolved_attribution(),- Attribution::direct(Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID))- );- }-- #[test]- fn creation_attribution_can_be_set_without_changing_owner() {- let attribution =- Attribution::delegated(Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID), owner());- let args = NewDocumentMetadata::builder("welcome")- .attribution(attribution.clone())- .build()- .into_repo_args(owner(), repo_kind());-- assert_eq!(args.user_id.as_ref(), "macro|[email protected]");- assert_eq!(args.resolved_attribution(), attribution);- }-- #[test]- fn link_share_defaults_to_the_entity_default_unless_set_exactly() {- use models_permissions::share_permission::access_level::AccessLevel;- use models_permissions::share_permission::{LinkShare, LinkShareState};-- let args = metadata().into_repo_args(owner(), repo_kind());- assert_eq!(args.initial_link_share, InitialLinkShare::EntityDefault);-- let state = LinkShareState::On {- scope: LinkShare::Team,- level: AccessLevel::View,- };- let args = NewDocumentMetadata::builder("description")- .initial_link_share(state)- .build()- .into_repo_args(owner(), repo_kind());- assert_eq!(args.initial_link_share, InitialLinkShare::Exact(state));- }-- #[test]- fn initiative_description_is_a_markdown_only_subtype_without_task_properties() {- let err = NewPlainTextDocument::builder(metadata())- .file_type(FileType::Txt)- .text("hello")- .markdown_subtype(MarkdownSubtype::InitiativeDescription)- .build()- .unwrap_err();- assert_eq!(- err.to_string(),- "bad request: initiative descriptions must be markdown documents"- );-- NewPlainTextDocument::builder(metadata())- .file_type(FileType::Md)- .text("# goals")- .markdown_subtype(MarkdownSubtype::InitiativeDescription)- .build()- .unwrap();- assert_eq!(- RepoDocumentSubtype::MarkdownInitiativeDescription.sub_type(),- Some(document_sub_type::DocumentSubType::InitiativeDescription)- );- }-- #[test]- fn new_plain_text_rejects_non_markdown_task() {- let err = NewPlainTextDocument::builder(metadata())- .file_type(FileType::Txt)- .text("hello")- .markdown_subtype(MarkdownSubtype::from_task_flag(true, None))- .build()- .unwrap_err();-- assert_eq!(- err.to_string(),- "bad request: tasks must be markdown documents"- );- }-- #[test]- fn new_plain_text_accepts_markdown_task() {- NewPlainTextDocument::builder(metadata())- .file_type(FileType::Md)- .text("# hello")- .task_flag(true, None)- .build()- .unwrap();- }-- #[test]- fn task_flag_shares_only_when_a_team_was_resolved() {- let team_id = uuid::Uuid::from_u128(7);- for (resolved_team, expected_share) in [(None, false), (Some(team_id), true)] {- let MarkdownSubtype::Task {- share_with_team,- team_id: numbering_team,- property_values,- } = MarkdownSubtype::from_task_flag(true, resolved_team)- else {- panic!("a task flag builds a task subtype");- };- assert_eq!(share_with_team, expected_share);- assert_eq!(numbering_team, resolved_team);- assert!(property_values.is_none());- }- assert!(matches!(- MarkdownSubtype::from_task_flag(false, Some(team_id)),- MarkdownSubtype::Note- ));- }-- #[test]- fn test_file_shas() {- let hashes = file_shas(b"hello");- assert_eq!(- hashes.hex,- "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"- );- assert_eq!(- hashes.base64,- "LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ="- );- }-}diff --git a/crates/documents/src/domain/create/test.rs b/crates/documents/src/domain/create/test.rsindex 6d7cc92910..ffaf5265d3 100644--- a/crates/documents/src/domain/create/test.rs+++ b/crates/documents/src/domain/create/test.rs@@ -1,11 +1,16 @@use std::sync::Mutex;-use activity::Attribution;+use bot_id::{BotId, NonSystemBotId};use macro_user_id::user_id::MacroUserIdStr;+use model::document::FileType;+use model_owner::CreationPrincipal;-use super::{DocumentCreator, MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument};+use super::{+ DocumentCreator, MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument,+ NewPlainTextDocument, RepoDocumentKind, RepoDocumentSubtype, file_shas,+};use crate::domain::content::DocumentContent;-use crate::domain::models::{CreateDocumentRepoArgs, CreateTaskRequest, DocumentError};+use crate::domain::models::{CreateTaskRequest, DocumentError, InitialLinkShare, NewDocument};use crate::domain::ports::create::{DocumentBytesUpload, DocumentBytesUploadPort, DocumentCreationService,};@@ -15,7 +20,6 @@ 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>"#;@@ -24,27 +28,38 @@ fn owner() -> MacroUserIdStr<'static> {MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()}+fn team_bot() -> CreationPrincipal {+ CreationPrincipal::TeamBot {+ bot: NonSystemBotId::new(BotId::TEST_A).unwrap(),+ team: uuid::Uuid::from_u128(7),+ }+}+#[derive(Default)]struct FakeCreationService {- calls: Mutex<Vec<CreateDocumentRepoArgs>>,+ calls: Mutex<Vec<(CreationPrincipal, NewDocument)>>,+ task_principals: Mutex<Vec<CreationPrincipal>>,}impl DocumentCreationService for FakeCreationService {async fn create_document(&self,- user_id: MacroUserIdStr<'static>,- args: CreateDocumentRepoArgs,+ principal: &CreationPrincipal,+ document: NewDocument,_job_id: Option<String>,) -> Result<CreateDocumentResponseData, DocumentError> {- let file_type = args.file_type.map(|kind| kind.to_string());- self.calls.lock().unwrap().push(args);+ let file_type = document.file_type.map(|kind| kind.to_string());+ self.calls+ .lock()+ .unwrap()+ .push((principal.clone(), document));Ok(CreateDocumentResponseData {document_response: DocumentResponse {document_metadata: DocumentResponseMetadataWithContent::new(DocumentResponseMetadata {document_id: DOCUMENT_ID.to_string(),document_version_id: 1,- owner: Owner::User(user_id),+ owner: principal.owner(),document_name: "task".to_string(),file_type: file_type.clone(),sha: None,@@ -68,11 +83,11 @@ impl DocumentCreationService for FakeCreationService {async fn handle_task_properties(&self,- _user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,_document_id: &str,_request: &CreateTaskRequest,- _attribution: &Attribution,) -> Result<(), DocumentError> {+ self.task_principals.lock().unwrap().push(principal.clone());Ok(())}@@ -118,7 +133,7 @@ impl DocumentBytesUploadPort for FakeBytesUploader {#[derive(Default)]struct RecordingMentionTracker {- calls: Mutex<Vec<(String, String, String)>>,+ calls: Mutex<Vec<(String, Option<String>, String)>>,fail: bool,}@@ -130,7 +145,7 @@ impl RecordingMentionTracker {}}- fn calls(&self) -> Vec<(String, String, String)> {+ fn calls(&self) -> Vec<(String, Option<String>, String)> {self.calls.lock().unwrap().clone()}}@@ -139,12 +154,12 @@ impl DocumentMentionTrackingPort for &RecordingMentionTracker {async fn track_document_mentions(&self,document_id: &str,- user_id: &MacroUserIdStr<'static>,+ user_id: Option<&MacroUserIdStr<'static>>,markdown: &str,) -> anyhow::Result<()> {self.calls.lock().unwrap().push((document_id.to_string(),- user_id.as_ref().to_string(),+ user_id.map(|user| user.as_ref().to_string()),markdown.to_string(),));if self.fail {@@ -166,18 +181,38 @@ fn task_document(markdown: &str) -> NewMarkdownTextDocument {}}-#[tokio::test]-async fn markdown_creation_tracks_the_seeded_mentions_once() {- let tracker = RecordingMentionTracker::default();- let creator = DocumentCreator::new(+fn creator(+ tracker: &RecordingMentionTracker,+) -> DocumentCreator<+ FakeCreationService,+ FakeMarkdownInitializer,+ FakeBytesUploader,+ &RecordingMentionTracker,+> {+ DocumentCreator::new(FakeCreationService::default(),FakeMarkdownInitializer,FakeBytesUploader,- &tracker,- );+ tracker,+ )+}++fn repo_kind() -> RepoDocumentKind {+ RepoDocumentKind {+ file_type: Some(FileType::Md),+ sha: "sha".to_string(),+ subtype: RepoDocumentSubtype::Regular,+ team_id: None,+ share_with_team: false,+ }+}++#[tokio::test]+async fn markdown_creation_tracks_the_seeded_mentions_once() {+ let tracker = RecordingMentionTracker::default();- creator- .create_markdown_text(owner(), task_document(EMAIL_SEED))+ creator(&tracker)+ .create_markdown_text(&CreationPrincipal::User(owner()), task_document(EMAIL_SEED)).await.expect("creation should succeed");@@ -185,7 +220,7 @@ async fn markdown_creation_tracks_the_seeded_mentions_once() {tracker.calls(),vec![(DOCUMENT_ID.to_string(),- "macro|[email protected]".to_string(),+ Some("macro|[email protected]".to_string()),EMAIL_SEED.to_string(),)]);@@ -194,15 +229,9 @@ async fn markdown_creation_tracks_the_seeded_mentions_once() {#[tokio::test]async fn mention_tracking_failure_does_not_fail_creation() {let tracker = RecordingMentionTracker::failing();- let creator = DocumentCreator::new(- FakeCreationService::default(),- FakeMarkdownInitializer,- FakeBytesUploader,- &tracker,- );- let created = creator- .create_markdown_text(owner(), task_document(EMAIL_SEED))+ let created = creator(&tracker)+ .create_markdown_text(&CreationPrincipal::User(owner()), task_document(EMAIL_SEED)).await.expect("creation should survive a mention tracking failure");@@ -210,25 +239,71 @@ async fn mention_tracking_failure_does_not_fail_creation() {assert_eq!(tracker.calls().len(), 1);}+#[tokio::test]+async fn a_task_is_created_and_propertied_as_one_principal() {+ let bot_for_user = CreationPrincipal::BotForUser {+ bot: bot_id::MACRO_AI_BOT_ID,+ user: owner(),+ };+ for principal in [CreationPrincipal::User(owner()), bot_for_user, team_bot()] {+ let tracker = RecordingMentionTracker::default();+ let creator = creator(&tracker);++ creator+ .create_markdown_text(&principal, task_document(EMAIL_SEED))+ .await+ .expect("creation should succeed");++ let calls = creator.document_service.calls.lock().unwrap();+ assert_eq!(calls.len(), 1);+ assert_eq!(calls[0].0, principal);+ assert_eq!(+ *creator.document_service.task_principals.lock().unwrap(),+ vec![principal.clone()]+ );+ }+}++#[tokio::test]+async fn mentions_are_tracked_with_an_optional_acting_user() {+ let bot_for_user = CreationPrincipal::BotForUser {+ bot: bot_id::MACRO_AI_BOT_ID,+ user: owner(),+ };+ for (principal, expected_user) in [+ (bot_for_user, Some("macro|[email protected]")),+ (team_bot(), None),+ ] {+ let tracker = RecordingMentionTracker::default();++ creator(&tracker)+ .create_markdown_text(&principal, task_document(EMAIL_SEED))+ .await+ .expect("creation should succeed");++ let tracked_users: Vec<Option<String>> = tracker+ .calls()+ .into_iter()+ .map(|(_, user, _)| user)+ .collect();+ assert_eq!(tracked_users, vec![expected_user.map(str::to_string)]);+ }+}+#[tokio::test]async fn native_spreadsheet_creation_uses_shared_service_without_upload_or_markdown() {let tracker = RecordingMentionTracker::default();- let creator = DocumentCreator::new(- FakeCreationService::default(),- FakeMarkdownInitializer,- FakeBytesUploader,- &tracker,- );+ let creator = creator(&tracker);let project = uuid::Uuid::new_v4();+ let principal = CreationPrincipal::BotForUser {+ bot: bot_id::MACRO_AI_BOT_ID,+ user: MacroUserIdStr::try_from_email("[email protected]").unwrap(),+ };let result = creator.create_spreadsheet(- MacroUserIdStr::try_from_email("[email protected]").unwrap(),+ &principal,NewDocumentMetadata::builder("Budget").project_id(project)- .attribution(Attribution::delegated(- activity::Actor::new_from_bot(bot_id::MACRO_AI_BOT_ID),- MacroUserIdStr::try_from_email("[email protected]").unwrap(),- )).build(),).await@@ -237,16 +312,116 @@ async fn native_spreadsheet_creation_uses_shared_service_without_upload_or_markdassert_eq!(result.file_type.as_deref(), Some("spreadsheet"));let calls = creator.document_service.calls.lock().unwrap();assert_eq!(calls.len(), 1);- let args = &calls[0];- assert_eq!(args.file_type, Some(model::document::FileType::Spreadsheet));- assert_eq!(args.sha, crate::domain::models::EMPTY_SHA256);- assert_eq!(args.document_name, "Budget");- assert_eq!(args.project_id, Some(project));+ let (called_principal, document) = &calls[0];+ assert_eq!(*called_principal, principal);+ assert_eq!(document.file_type, Some(FileType::Spreadsheet));+ assert_eq!(document.sha, crate::domain::models::EMPTY_SHA256);+ assert_eq!(document.document_name, "Budget");+ assert_eq!(document.project_id, Some(project));+ assert!(document.sub_type.is_none());+ assert!(tracker.calls().is_empty());+}++#[test]+fn link_share_defaults_to_the_entity_default_unless_set_exactly() {+ use models_permissions::share_permission::access_level::AccessLevel;+ use models_permissions::share_permission::{LinkShare, LinkShareState};++ let document = NewDocumentMetadata::new("test").into_new_document(repo_kind());+ assert_eq!(document.initial_link_share, InitialLinkShare::EntityDefault);++ let state = LinkShareState::On {+ scope: LinkShare::Team,+ level: AccessLevel::View,+ };+ let document = NewDocumentMetadata::builder("description")+ .initial_link_share(state)+ .build()+ .into_new_document(repo_kind());+ assert_eq!(document.initial_link_share, InitialLinkShare::Exact(state));+}++#[test]+fn initiative_description_is_a_markdown_only_subtype_without_task_properties() {+ let err = NewPlainTextDocument::builder(NewDocumentMetadata::new("test"))+ .file_type(FileType::Txt)+ .text("hello")+ .markdown_subtype(MarkdownSubtype::InitiativeDescription)+ .build()+ .unwrap_err();assert_eq!(- args.user_id,- MacroUserIdStr::try_from_email("[email protected]").unwrap()+ err.to_string(),+ "bad request: initiative descriptions must be markdown documents"+ );++ NewPlainTextDocument::builder(NewDocumentMetadata::new("test"))+ .file_type(FileType::Md)+ .text("# goals")+ .markdown_subtype(MarkdownSubtype::InitiativeDescription)+ .build()+ .unwrap();+ assert_eq!(+ RepoDocumentSubtype::MarkdownInitiativeDescription.sub_type(),+ Some(document_sub_type::DocumentSubType::InitiativeDescription)+ );+}++#[test]+fn new_plain_text_rejects_non_markdown_task() {+ let err = NewPlainTextDocument::builder(NewDocumentMetadata::new("test"))+ .file_type(FileType::Txt)+ .text("hello")+ .markdown_subtype(MarkdownSubtype::from_task_flag(true, None))+ .build()+ .unwrap_err();++ assert_eq!(+ err.to_string(),+ "bad request: tasks must be markdown documents"+ );+}++#[test]+fn new_plain_text_accepts_markdown_task() {+ NewPlainTextDocument::builder(NewDocumentMetadata::new("test"))+ .file_type(FileType::Md)+ .text("# hello")+ .task_flag(true, None)+ .build()+ .unwrap();+}++#[test]+fn task_flag_shares_only_when_a_team_was_resolved() {+ let team_id = uuid::Uuid::from_u128(7);+ for (resolved_team, expected_share) in [(None, false), (Some(team_id), true)] {+ let MarkdownSubtype::Task {+ share_with_team,+ team_id: numbering_team,+ property_values,+ } = MarkdownSubtype::from_task_flag(true, resolved_team)+ else {+ panic!("a task flag builds a task subtype");+ };+ assert_eq!(share_with_team, expected_share);+ assert_eq!(numbering_team, resolved_team);+ assert!(property_values.is_none());+ }+ assert!(matches!(+ MarkdownSubtype::from_task_flag(false, Some(team_id)),+ MarkdownSubtype::Note+ ));+}++#[test]+fn test_file_shas() {+ let hashes = file_shas(b"hello");+ assert_eq!(+ hashes.hex,+ "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"+ );+ assert_eq!(+ hashes.base64,+ "LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=");- assert!(args.attribution.is_some());- assert!(args.sub_type.is_none());- assert!(tracker.calls().is_empty());}diff --git a/crates/documents/src/domain/create/upload.rs b/crates/documents/src/domain/create/upload.rsindex 29279ec99b..1deb988af9 100644--- a/crates/documents/src/domain/create/upload.rs+++ b/crates/documents/src/domain/create/upload.rs@@ -3,10 +3,11 @@use std::str::FromStr;use std::time::Duration;-use activity::Attribution;-use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, EntityType};-use macro_user_id::user_id::MacroUserIdStr;+use entity_access::domain::models::{+ EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, EntityType,+};use model::document::{FileType, FileTypeExt};+use model_owner::CreationPrincipal;use rootcause::compat::anyhow1::IntoAnyhow;use tracing::Instrument;@@ -33,10 +34,9 @@ pub struct NewFileUpload {pub file_name: String,/// Original file bytes.pub bytes: Vec<u8>,- /// Edit capability for the destination project; absent for top-level files.+ /// Edit capability for the destination project, minted for the uploading+ /// principal; absent for top-level files.pub project: Option<EntityAccessReceipt<EditAccessLevel>>,- /// Actor responsible for the upload on behalf of the owner.- pub attribution: Attribution,}impl<Svc, MarkdownInit, BytesUpload, MentionTracker>@@ -53,14 +53,13 @@ where#[tracing::instrument(skip_all, err)]pub async fn upload_file(&self,- user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,upload: NewFileUpload,) -> Result<CreatedDocument, DocumentError> {let NewFileUpload {file_name,bytes,project,- attribution,} = upload;if bytes.len() > MAX_INLINE_UPLOAD_BYTES {return Err(DocumentError::BadRequest(@@ -100,10 +99,10 @@ where));}- let mut metadata = NewDocumentMetadata::builder(document_name).attribution(attribution);+ let mut metadata = NewDocumentMetadata::builder(document_name);if let Some(project) = project {if project.entity().entity_type != EntityType::Project- || project.acting_user_id() != Some(&user_id)+ || !receipt_is_for(&project, principal){return Err(DocumentError::Unauthorized);}@@ -115,16 +114,14 @@ where}let hashes = file_shas(&bytes);- let args = metadata.build().into_repo_args(- user_id.clone(),- RepoDocumentKind {- file_type,- sha: hashes.hex,- subtype: RepoDocumentSubtype::Regular,- team_id: None,- share_with_team: false,- },- );+ let document = metadata.build().into_new_document(RepoDocumentKind {+ file_type,+ sha: hashes.hex,+ subtype: RepoDocumentSubtype::Regular,+ team_id: None,+ share_with_team: false,+ });+ let principal = principal.clone();let document_service = self.document_service.clone();let bytes_uploader = self.bytes_uploader.clone();// Own the entire write so dropping the caller cannot interrupt metadata@@ -132,7 +129,7 @@ wheretokio::spawn(async move {let response = document_service- .create_document(user_id, args, None)+ .create_document(&principal, document, None).await.inspect_err(|error| {tracing::error!(error=?error, "file upload metadata creation failed");@@ -184,3 +181,21 @@ where.map_err(|error| DocumentError::Internal(rootcause::report!(error).into_anyhow()))?}}++fn receipt_is_for(+ receipt: &EntityAccessReceipt<EditAccessLevel>,+ principal: &CreationPrincipal,+) -> bool {+ match (receipt.auth(), principal) {+ (EntityAccessAuth::Authenticated(receipt_user), CreationPrincipal::User(user)) => {+ receipt_user == user+ }+ (EntityAccessAuth::Bot(auth), CreationPrincipal::BotForUser { bot, user }) => {+ auth.bot_id() == *bot && auth.scope().acting_user_id() == Some(user)+ }+ (EntityAccessAuth::Bot(auth), CreationPrincipal::TeamBot { bot, team }) => {+ auth.bot_id() == bot.get() && auth.scope().team_id() == Some(*team)+ }+ _ => false,+ }+}diff --git a/crates/documents/src/domain/create/upload/test.rs b/crates/documents/src/domain/create/upload/test.rsindex 72e204d8ce..470dbea724 100644--- a/crates/documents/src/domain/create/upload/test.rs+++ b/crates/documents/src/domain/create/upload/test.rs@@ -2,24 +2,45 @@ use super::*;use std::sync::{Arc, Mutex};use tokio::sync::Notify;-use activity::Actor;+use bot_id::{BotId, NonSystemBotId};use entity_access::domain::models::{BotReceiptScope, Entity, EntityPermission};+use macro_user_id::user_id::MacroUserIdStr;use model::document::response::DocumentResponseMetadata;use models_permissions::share_permission::access_level::AccessLevel;+use uuid::Uuid;use crate::domain::{content::DocumentContent,- models::{CreateDocumentRepoArgs, CreateTaskRequest},+ models::{CreateTaskRequest, NewDocument},response::{CreateDocumentResponseData, DocumentResponse, DocumentResponseMetadataWithContent},};const DOCUMENT_ID: &str = "00000000-0000-0000-0000-000000000123";const PROJECT_ID: &str = "00000000-0000-0000-0000-000000000456";+const TEAM_ID: Uuid = Uuid::from_u128(7);fn owner() -> MacroUserIdStr<'static> {MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()}+fn other_user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()+}++fn principal() -> CreationPrincipal {+ CreationPrincipal::BotForUser {+ bot: bot_id::MACRO_AI_BOT_ID,+ user: owner(),+ }+}++fn team_bot() -> CreationPrincipal {+ CreationPrincipal::TeamBot {+ bot: NonSystemBotId::new(BotId::TEST_A).unwrap(),+ team: TEAM_ID,+ }+}+#[derive(Default)]struct Gate {entered: Notify,@@ -41,7 +62,7 @@ async fn wait_for(notification: &Notify) {#[derive(Default)]struct RecordingService {- creates: Mutex<Vec<CreateDocumentRepoArgs>>,+ creates: Mutex<Vec<(CreationPrincipal, NewDocument)>>,cleanups: Mutex<Vec<String>>,omit_url: bool,create_gate: Option<Arc<Gate>>,@@ -52,13 +73,16 @@ struct RecordingService {impl DocumentCreationService for RecordingService {async fn create_document(&self,- user_id: MacroUserIdStr<'static>,- args: CreateDocumentRepoArgs,+ principal: &CreationPrincipal,+ document: NewDocument,_job_id: Option<String>,) -> Result<CreateDocumentResponseData, DocumentError> {- let file_type = args.file_type.map(|kind| kind.to_string());- let document_name = args.document_name.clone();- self.creates.lock().unwrap().push(args);+ let file_type = document.file_type.map(|kind| kind.to_string());+ let document_name = document.document_name.clone();+ self.creates+ .lock()+ .unwrap()+ .push((principal.clone(), document));if let Some(gate) = &self.create_gate {gate.wait().await;}@@ -68,7 +92,7 @@ impl DocumentCreationService for RecordingService {DocumentResponseMetadata {document_id: DOCUMENT_ID.to_string(),document_version_id: 1,- owner: model_owner::Owner::User(user_id),+ owner: principal.owner(),document_name,file_type: file_type.clone(),sha: None,@@ -93,10 +117,9 @@ impl DocumentCreationService for RecordingService {async fn handle_task_properties(&self,- _: MacroUserIdStr<'static>,+ _: &CreationPrincipal,_: &str,_: &CreateTaskRequest,- _: &Attribution,) -> Result<(), DocumentError> {panic!("file uploads do not create tasks")}@@ -148,37 +171,55 @@ fn upload(name: &str, bytes: Vec<u8>) -> NewFileUpload {file_name: name.to_string(),bytes,project: None,- attribution: Attribution::delegated(Actor::new_from_bot(bot_id::MACRO_AI_BOT_ID), owner()),}}+fn project(entity_type: EntityType) -> Entity {+ Entity {+ entity_id: PROJECT_ID.to_string(),+ entity_type,+ }+}++fn edit() -> EntityPermission {+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Edit,+ }+}++fn bot_receipt(+ bot: BotId,+ scope: BotReceiptScope,+ entity_type: EntityType,+) -> EntityAccessReceipt<EditAccessLevel> {+ EntityAccessReceipt::try_new_bot(bot.into(), scope, project(entity_type), edit()).unwrap()+}+fn project_receipt(user: MacroUserIdStr<'static>,entity_type: EntityType,) -> EntityAccessReceipt<EditAccessLevel> {- EntityAccessReceipt::try_new_bot(- bot_id::MACRO_AI_BOT_ID.into(),+ bot_receipt(+ bot_id::MACRO_AI_BOT_ID,BotReceiptScope::User { acting_user: user },- Entity {- entity_id: PROJECT_ID.to_string(),- entity_type,- },- EntityPermission::AccessLevel {- access_level: AccessLevel::Edit,- },+ entity_type,)- .unwrap()+}++fn user_receipt(user: MacroUserIdStr<'static>) -> EntityAccessReceipt<EditAccessLevel> {+ EntityAccessReceipt::try_new_authenticated_user(user, project(EntityType::Project), edit())+ .unwrap()}#[tokio::test]-async fn uploads_exact_bytes_with_checksums_owner_project_and_attribution() {+async fn uploads_exact_bytes_with_checksums_principal_and_project() {let service = Arc::new(RecordingService::default());let uploader = Arc::new(RecordingUploader::default());let creator = DocumentCreator::new(service.clone(), (), uploader.clone(), ());let bytes = vec![0, 255, 128, 13, 10];let mut file = upload("Report.PDF", bytes.clone());file.project = Some(project_receipt(owner(), EntityType::Project));- let created = creator.upload_file(owner(), file).await.unwrap();+ let created = creator.upload_file(&principal(), file).await.unwrap();assert_eq!(created.document_id(), DOCUMENT_ID);assert_eq!(created@@ -190,12 +231,12 @@ async fn uploads_exact_bytes_with_checksums_owner_project_and_attribution() {);let creates = service.creates.lock().unwrap();assert_eq!(creates.len(), 1);- assert_eq!(creates[0].document_name, "Report");- assert_eq!(creates[0].file_type, Some(FileType::Pdf));- assert_eq!(creates[0].user_id, owner());- assert_eq!(creates[0].project_id, Some(PROJECT_ID.parse().unwrap()));- assert!(creates[0].attribution.is_some());- assert_eq!(creates[0].sha, file_shas(&bytes).hex);+ let (created_for, document) = &creates[0];+ assert_eq!(*created_for, principal());+ assert_eq!(document.document_name, "Report");+ assert_eq!(document.file_type, Some(FileType::Pdf));+ assert_eq!(document.project_id, Some(PROJECT_ID.parse().unwrap()));+ assert_eq!(document.sha, file_shas(&bytes).hex);let uploads = uploader.uploads.lock().unwrap();assert_eq!(uploads.len(), 1);assert_eq!(uploads[0].bytes, bytes);@@ -216,12 +257,12 @@ async fn preserves_unknown_extensions_and_leaves_conversion_to_the_pipeline() {let uploader = Arc::new(RecordingUploader::default());let creator = DocumentCreator::new(service.clone(), (), uploader.clone(), ());creator- .upload_file(owner(), upload(name, b"contents".to_vec()))+ .upload_file(&principal(), upload(name, b"contents".to_vec())).await.unwrap();let creates = service.creates.lock().unwrap();- assert_eq!(creates[0].document_name, expected_name);- assert_eq!(creates[0].file_type, expected_type);+ assert_eq!(creates[0].1.document_name, expected_name);+ assert_eq!(creates[0].1.file_type, expected_type);}}@@ -241,7 +282,7 @@ async fn rejects_invalid_files_before_creating_metadata() {upload("large.pdf", vec![0; MAX_INLINE_UPLOAD_BYTES + 1]),] {assert!(matches!(- creator.upload_file(owner(), file).await,+ creator.upload_file(&principal(), file).await,Err(DocumentError::BadRequest(_))));}@@ -250,26 +291,98 @@ async fn rejects_invalid_files_before_creating_metadata() {}#[tokio::test]-async fn rejects_receipts_for_another_user_or_entity_type() {- let service = Arc::new(RecordingService::default());- let uploader = Arc::new(RecordingUploader::default());- let creator = DocumentCreator::new(service.clone(), (), uploader.clone(), ());- for receipt in [- project_receipt(- MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),+async fn accepts_only_project_receipts_minted_for_the_uploading_principal() {+ let project_id: Uuid = PROJECT_ID.parse().unwrap();+ let team_receipt = || {+ bot_receipt(+ BotId::TEST_A,+ BotReceiptScope::Team { team_id: TEAM_ID },EntityType::Project,+ )+ };+ for (uploader_principal, receipt, accepted) in [+ (+ principal(),+ project_receipt(owner(), EntityType::Project),+ true,+ ),+ (+ CreationPrincipal::User(owner()),+ user_receipt(owner()),+ true,+ ),+ (team_bot(), team_receipt(), true),+ (+ principal(),+ project_receipt(other_user(), EntityType::Project),+ false,+ ),+ (+ principal(),+ project_receipt(owner(), EntityType::Document),+ false,+ ),+ (+ principal(),+ bot_receipt(+ BotId::TEST_A,+ BotReceiptScope::User {+ acting_user: owner(),+ },+ EntityType::Project,+ ),+ false,+ ),+ (principal(), user_receipt(owner()), false),+ (+ CreationPrincipal::User(owner()),+ project_receipt(owner(), EntityType::Project),+ false,+ ),+ (+ CreationPrincipal::User(owner()),+ user_receipt(other_user()),+ false,+ ),+ (+ team_bot(),+ bot_receipt(+ BotId::TEST_A,+ BotReceiptScope::Team {+ team_id: Uuid::from_u128(8),+ },+ EntityType::Project,+ ),+ false,+ ),+ (+ team_bot(),+ bot_receipt(+ BotId::TEST_B,+ BotReceiptScope::Team { team_id: TEAM_ID },+ EntityType::Project,+ ),+ false,),- project_receipt(owner(), EntityType::Document),] {+ let service = Arc::new(RecordingService::default());+ let uploader = Arc::new(RecordingUploader::default());+ let creator = DocumentCreator::new(service.clone(), (), uploader.clone(), ());let mut file = upload("report.pdf", vec![]);file.project = Some(receipt);- assert!(matches!(- creator.upload_file(owner(), file).await,- Err(DocumentError::Unauthorized)- ));+ let result = creator.upload_file(&uploader_principal, file).await;+ let creates = service.creates.lock().unwrap();+ if accepted {+ result.unwrap();+ assert_eq!(creates.len(), 1);+ assert_eq!(creates[0].0, uploader_principal);+ assert_eq!(creates[0].1.project_id, Some(project_id));+ } else {+ assert!(matches!(result, Err(DocumentError::Unauthorized)));+ assert!(creates.is_empty());+ assert!(uploader.uploads.lock().unwrap().is_empty());+ }}- assert!(service.creates.lock().unwrap().is_empty());- assert!(uploader.uploads.lock().unwrap().is_empty());}#[tokio::test]@@ -286,7 +399,7 @@ async fn cleans_up_when_storage_upload_fails_or_url_is_missing() {let creator = DocumentCreator::new(service.clone(), (), uploader.clone(), ());assert!(creator- .upload_file(owner(), upload("report.pdf", vec![1]))+ .upload_file(&principal(), upload("report.pdf", vec![1])).await.is_err());@@ -305,7 +418,7 @@ async fn accepts_empty_files_and_the_exact_size_limit() {let creator = DocumentCreator::new(service, (), uploader.clone(), ());for size in [0, MAX_INLINE_UPLOAD_BYTES] {creator- .upload_file(owner(), upload("file.bin", vec![0; size]))+ .upload_file(&principal(), upload("file.bin", vec![0; size])).await.unwrap();}@@ -323,7 +436,7 @@ async fn dropping_the_caller_during_metadata_creation_finishes_the_upload() {let creator = DocumentCreator::new(service.clone(), (), uploader.clone(), ());let caller = tokio::spawn(async move {creator- .upload_file(owner(), upload("report.pdf", vec![1]))+ .upload_file(&principal(), upload("report.pdf", vec![1])).await});@@ -351,7 +464,7 @@ async fn dropping_the_caller_during_upload_finishes_or_cleans_up() {let creator = DocumentCreator::new(service.clone(), (), uploader.clone(), ());let caller = tokio::spawn(async move {creator- .upload_file(owner(), upload("report.pdf", vec![1]))+ .upload_file(&principal(), upload("report.pdf", vec![1])).await});@@ -384,7 +497,7 @@ async fn dropping_the_caller_during_cleanup_does_not_interrupt_cleanup() {let creator = DocumentCreator::new(service.clone(), (), uploader, ());let caller = tokio::spawn(async move {creator- .upload_file(owner(), upload("report.pdf", vec![1]))+ .upload_file(&principal(), upload("report.pdf", vec![1])).await});@@ -406,7 +519,7 @@ async fn storage_upload_timeout_cleans_up_metadata() {});let creator = DocumentCreator::new(service.clone(), (), uploader.clone(), ());let error = creator- .upload_file(owner(), upload("report.pdf", vec![1]))+ .upload_file(&principal(), upload("report.pdf", vec![1])).await.unwrap_err();diff --git a/crates/documents/src/domain/entity_mutation.rs b/crates/documents/src/domain/entity_mutation.rsindex 9d53484097..9fbabc5c75 100644--- a/crates/documents/src/domain/entity_mutation.rs+++ b/crates/documents/src/domain/entity_mutation.rs@@ -16,6 +16,7 @@ use entity_mutation::{use macro_user_id::user_id::MacroUserIdStr;use model::document::DocumentBasic;use model_entity::{Entity, EntityType};+use model_owner::CreationPrincipal;use models_permissions::share_permission::UpdateSharePermissionRequestV2;use crate::domain::ports::sync::DocumentSyncPort;@@ -260,8 +261,9 @@ wherelet document = self.internal_get_basic_document(&entity.entity_id).await?;let display_name =display_name.unwrap_or_else(|| format!("{} copy", document.document_name));+ let principal = CreationPrincipal::User(user_id);let response = self- .copy_document(receipt, document, user_id, display_name, None, None)+ .copy_document(receipt, document, &principal, display_name, None, None).await?;Ok(vec![EntityMutationEffect::updated(EntityType::Documentdiff --git a/crates/documents/src/domain/events.rs b/crates/documents/src/domain/events.rsindex e92589d44e..24be04a55a 100644--- a/crates/documents/src/domain/events.rs+++ b/crates/documents/src/domain/events.rs@@ -224,6 +224,13 @@ pub struct DocumentCopiedMetadata {/// The principal who owns the new copy.#[cfg_attr(feature = "schema", schema(value_type = String))]pub owner: Owner,+ /// Who mechanically created the copy.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[cfg_attr(feature = "schema", schema(value_type = Option<String>))]+ pub actor: Option<Actor<'static>>,+ /// The user whose feed this copy belongs on, when different from the actor.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub on_behalf_of: Option<MacroUserIdStr<'static>>,/// 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 337d029ade..2e2567ad41 100644--- a/crates/documents/src/domain/events/test.rs+++ b/crates/documents/src/domain/events/test.rs@@ -71,6 +71,8 @@ fn owner_bearing_events_round_trip_all_owner_kinds_as_strings() {source_document_id: "source-document".to_string(),source_version_id: None,owner,+ actor: None,+ on_behalf_of: None,document_name: "copy".to_string(),file_type: None,project_id: None,diff --git a/crates/documents/src/domain/models.rs b/crates/documents/src/domain/models.rsindex 1a0d3c62a3..1cfd509cf6 100644--- a/crates/documents/src/domain/models.rs+++ b/crates/documents/src/domain/models.rs@@ -1,11 +1,11 @@//! Domain models for the documents crate.-use activity::{Actor, Attribution};use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;use model::document::response::DocumentResponseMetadata;use model::document::{DocumentMetadata, FileType};-use models_permissions::share_permission::LinkShareState;+use model_owner::Owner;+use models_permissions::share_permission::{LinkShareState, TeamLinkShareDefault};use super::response::DocumentResponse;use model::sync_service::SyncServiceVersionID;@@ -72,8 +72,8 @@ pub struct CopyDocumentResponse {pub struct CopyDocumentRepoArgs {/// The original document metadata to copy from.pub original_document: DocumentMetadata,- /// The new owner/copier user ID.- pub user_id: MacroUserIdStr<'static>,+ /// Who owns the copy.+ pub owner: Owner,/// The name for the new document.pub document_name: String,/// The file type of the document.@@ -317,16 +317,16 @@ pub enum InitialLinkShare {Exact(LinkShareState),}-/// Arguments for creating a document in the repository.-pub struct CreateDocumentRepoArgs {+/// A document to create, before its owner is known.+///+/// The service derives the owner from the verified creation principal.+pub struct NewDocument {/// Optional user-provided document ID.pub id: Option<uuid::Uuid>,/// SHA256 hash of the document content.pub sha: String,/// Document name without extension.pub document_name: String,- /// The owner/creator of the document.- pub user_id: MacroUserIdStr<'static>,/// File type of the document.pub file_type: Option<FileType>,/// Project to associate the document with.@@ -342,42 +342,35 @@ pub struct CreateDocumentRepoArgs {pub sub_type: Option<document_sub_type::DocumentSubType>,/// Whether to skip adding to user history.pub skip_history: bool,- /// Explicit activity attribution. Unset uses [`Self::resolved_attribution`].- pub attribution: Option<Attribution>,/// How the new document's link share is initialized.pub initial_link_share: InitialLinkShare,}-impl CreateDocumentRepoArgs {- /// Resolves who created this document for activity recording.- ///- /// Ownership (`user_id`) is unchanged.- pub fn resolved_attribution(&self) -> Attribution {- self.attribution- .clone()- .unwrap_or_else(|| Attribution::direct(Actor::new_from_user(self.user_id.clone())))- }+/// Arguments for creating a document in the repository.+pub struct CreateDocumentRepoArgs {+ /// Who owns the document.+ pub owner: Owner,+ /// The document to create.+ pub document: NewDocument,}/// Arguments for importing an email attachment as a document.pub struct ImportEmailAttachmentRepoArgs {/// The email attachment being imported.pub email_attachment_id: uuid::Uuid,+ /// The mailbox owner, who owns the imported document.+ pub owner: MacroUserIdStr<'static>,/// How to create the document when no reusable import exists.- pub create: CreateDocumentRepoArgs,-}--impl ImportEmailAttachmentRepoArgs {- /// Resolves who created this import for activity recording.- ///- /// Unset attribution is the system bot: email import is an internal- /// pipeline, not a user-authored create. Ownership (`create.user_id`)- /// is unchanged.- pub fn resolved_attribution(&self) -> Attribution {- self.create.attribution.clone().unwrap_or_else(|| {- Attribution::direct(Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID))- })- }+ pub document: NewDocument,+}++/// The team an owner resolves to, with the team's link-share preference.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct OwnerTeam {+ /// The owner's team.+ pub team_id: uuid::Uuid,+ /// The team's default link share for new documents.+ pub default_link_share: TeamLinkShareDefault,}/// Fact returned by the repository for an email-attachment import.diff --git a/crates/documents/src/domain/permission_token.rs b/crates/documents/src/domain/permission_token.rsindex 20007ad502..79e91d2ee3 100644--- a/crates/documents/src/domain/permission_token.rs+++ b/crates/documents/src/domain/permission_token.rs@@ -1,9 +1,13 @@//! Helpers for issuing document permission tokens (signed JWTs) used by the//! sync service to authorize document access.+#[cfg(test)]+mod test;+use crate::domain::models::DocumentError;use macro_sync_service_jwt::{DocumentPermissionToken, ISSUER, TOKEN_TTL_SECS};use macro_user_id::user_id::MacroUserIdStr;+use model_owner::CreationPrincipal;use models_permissions::share_permission::access_level::AccessLevel;use std::time::{SystemTime, UNIX_EPOCH};@@ -52,6 +56,25 @@ pub fn encode_permission_token()?)}+/// Sign a document permission token for `principal`.+///+/// A bot principal is the token's actor. A team bot acts for no user, so its+/// token carries no user id.+pub fn encode_principal_permission_token(+ principal: &CreationPrincipal,+ document_id: String,+ access_level: AccessLevel,+ jwt_secret: &str,+) -> Result<DocumentPermissionToken, DocumentError> {+ encode_permission_token(+ principal.user().map(|user| user.as_ref().to_string()),+ document_id,+ access_level,+ jwt_secret,+ principal.bot().map(|bot| bot.into_storage_id().to_string()),+ )+}+/// Read claims from a token minted by [`encode_permission_token`].#[cfg(test)]pub(crate) fn decode_permission_token(diff --git a/crates/documents/src/domain/permission_token/test.rs b/crates/documents/src/domain/permission_token/test.rsnew file mode 100644index 0000000000..01d83536ac--- /dev/null+++ b/crates/documents/src/domain/permission_token/test.rs@@ -0,0 +1,68 @@+use bot_id::{BotId, MACRO_AI_BOT_ID, NonSystemBotId};+use macro_user_id::user_id::MacroUserIdStr;+use model_owner::CreationPrincipal;+use models_permissions::share_permission::access_level::AccessLevel;+use uuid::Uuid;++use super::{decode_permission_token, encode_principal_permission_token};++const SECRET: &str = "creation-token-secret";++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).expect("valid user id")+}++fn identity_claims(principal: &CreationPrincipal) -> (Option<String>, Option<String>) {+ let token = encode_principal_permission_token(+ principal,+ "doc-1".to_string(),+ AccessLevel::Edit,+ SECRET,+ )+ .expect("token should encode");+ let claims = decode_permission_token(&token, SECRET).expect("token should decode");+ assert_eq!(claims.document_id, "doc-1");+ assert_eq!(claims.access_level, AccessLevel::Edit);+ (+ claims.user_id.map(|user| user.as_ref().to_string()),+ claims.actor,+ )+}++#[test]+fn user_token_names_the_user_without_an_actor() {+ assert_eq!(+ identity_claims(&CreationPrincipal::User(user())),+ (Some("macro|[email protected]".to_string()), None),+ );+}++#[test]+fn bot_for_user_token_names_the_user_and_the_bot_actor() {+ let principal = CreationPrincipal::BotForUser {+ bot: MACRO_AI_BOT_ID,+ user: user(),+ };+ assert_eq!(+ identity_claims(&principal),+ (+ Some("macro|[email protected]".to_string()),+ Some("bot|00000000-0000-0000-0000-00000000a1a1".to_string()),+ ),+ );+}++#[test]+fn team_bot_token_names_the_bot_actor_without_a_user() {+ let principal = CreationPrincipal::TeamBot {+ bot: NonSystemBotId::new(BotId::TEST_A).expect("test bot is not a system bot"),+ team: Uuid::from_u128(7),+ };+ assert_eq!(+ identity_claims(&principal),+ (+ None,+ Some("bot|00000000-0000-0000-0000-00000000b07a".to_string()),+ ),+ );+}diff --git a/crates/documents/src/domain/ports.rs b/crates/documents/src/domain/ports.rsindex 039140457a..bd75e2e405 100644--- a/crates/documents/src/domain/ports.rs+++ b/crates/documents/src/domain/ports.rs@@ -18,10 +18,11 @@ use entity_access::domain::models::{use entity_access::domain::ports::EntityAccessService;use macro_user_id::user_id::MacroUserIdStr;use model::document::{ContentType, DocumentBasic, DocumentMetadata, FileType};+use model_owner::{CreationPrincipal, Owner};+use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::team_share::{AuthorizedTeamShareCommand, TeamShareFacts,};-use models_permissions::share_permission::{SharePermissionV2, TeamLinkShareDefault};use super::content::DocumentContent;use super::events::InteractionReason;@@ -33,13 +34,12 @@ use model::sync_service::SyncServiceVersionID;use model_entity::Entity;-use activity::Attribution;-use super::models::{BranchNameContext, CopyDocumentRepoArgs, CreateDocumentRepoArgs, CreateTaskRequest,DocumentError, DocumentTeamShare, DocumentTeamShareResponse, EditDocumentRepoArgs,EditDocumentServiceArgs, EmailImportRepoOutcome, GithubPullRequestsResponse,- ImportEmailAttachmentRepoArgs, LocationQueryParams, TaskBranchName, TeamTaskMetadata,+ ImportEmailAttachmentRepoArgs, LocationQueryParams, NewDocument, OwnerTeam, TaskBranchName,+ TeamTaskMetadata,};/// Repository for accessing document data from the database.@@ -137,9 +137,10 @@ pub trait DocumentRepo: Send + Sync + 'static {////// `share_permission` is the pre-resolved initial link permission — the/// repository persists it verbatim and carries no share-policy of its own.- /// Canonical team state starts NULL; `args.share_with_team` initializes explicit- /// task consent from the persisted owner's team inside the same transaction and- /// fails with `BadRequest` when that owner has no team.+ /// Canonical team state starts NULL; `args.document.share_with_team`+ /// initializes explicit task consent from the persisted owner's team inside+ /// the same transaction and fails with `BadRequest` when that owner has no team.+ /// The entity row and its owner grants are registered in the same transaction.fn create_document(&self,args: CreateDocumentRepoArgs,@@ -157,12 +158,12 @@ pub trait DocumentRepo: Send + Sync + 'static {share_permission: SharePermissionV2,) -> impl Future<Output = Result<EmailImportRepoOutcome, DocumentError>> + Send;- /// Get the link-share preference of the user's team, or `None` when the- /// user is not on a team.- fn get_team_default_link_share(+ /// Get the team `owner` resolves to and its link-share preference, or+ /// `None` when the owner has no team.+ fn get_owner_team(&self,- user_id: &str,- ) -> impl Future<Output = Result<Option<TeamLinkShareDefault>, Self::Err>> + Send;+ owner: &Owner,+ ) -> impl Future<Output = Result<Option<OwnerTeam>, Self::Err>> + Send;/// Update an upload job to associate it with a document.fn update_upload_job(@@ -278,7 +279,9 @@ pub trait DocumentRepo: Send + Sync + 'static {/// Copy a document's DB records in a single transaction.////// Creates: Document row, version (DocumentBom or DocumentInstance),- /// SharePermission, DocumentPermission, UserItemAccess, and user history.+ /// SharePermission, DocumentPermission, the registered entity with its+ /// owner grants, and access history. The returned metadata carries the+ /// persisted owner.////// `share_permission` is the pre-resolved initial share permission for the/// copy — the repository persists it verbatim.@@ -350,14 +353,13 @@ pub trait TaskPropertiesPort: Send + Sync + 'static {status: &str,) -> impl Future<Output = anyhow::Result<()>> + Send;- /// Set a property value on an entity.+ /// Set a property value on an entity as the principal that created it.fn set_entity_property(&self,- user_id: &str,+ principal: &CreationPrincipal,entity_id: &str,property_definition_id: uuid::Uuid,value: Option<models_properties::api::requests::SetPropertyValue>,- attribution: &Attribution,) -> impl Future<Output = anyhow::Result<()>> + Send;/// Copy all task property values from one task to another.@@ -371,30 +373,40 @@ pub trait TaskPropertiesPort: Send + Sync + 'static {/// Mint the edit receipt a [`TaskPropertiesPort`] adapter writes task/// properties with.///-/// A bot creating the task for a user gets a bot receipt scoped to that user,-/// so the property write publishes the same delegated attribution as the-/// document itself. Every other attribution writes as `user_id`.+/// The receipt carries the same principal as the task's creation, so the+/// property write publishes the same attribution as the document itself.pub async fn task_property_edit_receipt<A: EntityAccessService>(entity_access: &A,- user_id: &MacroUserIdStr<'_>,- attribution: &Attribution,+ principal: &CreationPrincipal,task_id: &str,) -> Result<EntityAccessReceipt<EditAccessLevel>, AccessError> {- if let Attribution::Delegated { actor, subject } = attribution- && let Some(bot) = actor.as_bot()- {- return entity_access- .generate_bot_entity_access_receipt(- bot.bot_id(),- BotAccessScope::user(subject.clone()),- task_id,- EntityType::Document,- )- .await;+ match principal {+ CreationPrincipal::User(user) => {+ entity_access+ .generate_entity_access_receipt(user, None, task_id, EntityType::Document)+ .await+ }+ CreationPrincipal::BotForUser { bot, user } => {+ entity_access+ .generate_bot_entity_access_receipt(+ *bot,+ BotAccessScope::user(user.clone()),+ task_id,+ EntityType::Document,+ )+ .await+ }+ CreationPrincipal::TeamBot { bot, team } => {+ entity_access+ .generate_bot_entity_access_receipt(+ bot.get(),+ BotAccessScope::Team { team_id: *team },+ task_id,+ EntityType::Document,+ )+ .await+ }}- entity_access- .generate_entity_access_receipt(user_id, None, task_id, EntityType::Document)- .await}/// Use cases for relaying document content-change events.@@ -460,22 +472,22 @@ pub trait DocumentService: Send + Sync + 'static {entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,) -> impl Future<Output = Result<String, DocumentError>> + Send;- /// Create a new document, generate an S3 presigned upload URL, and- /// optionally attach task properties and update project modified.+ /// Create a new document owned as `principal` decides, generate an S3+ /// presigned upload URL, and optionally attach task properties and update+ /// project modified.fn create_document(&self,- user_id: MacroUserIdStr<'static>,- args: CreateDocumentRepoArgs,+ principal: &CreationPrincipal,+ document: NewDocument,job_id: Option<String>,) -> impl Future<Output = Result<CreateDocumentResponseData, DocumentError>> + Send;- /// Import an email attachment as a document.+ /// Import an email attachment as a document owned by the mailbox owner.////// Reuse returns existing content and no upload URL. A first import/// follows the same post-create lifecycle as [`DocumentService::create_document`].fn import_email_attachment(&self,- user_id: MacroUserIdStr<'static>,args: ImportEmailAttachmentRepoArgs,) -> impl Future<Output = Result<CreateDocumentResponseData, DocumentError>> + Send;@@ -523,12 +535,13 @@ pub trait DocumentService: Send + Sync + 'static {status: &str,) -> impl Future<Output = Result<(), DocumentError>> + Send;- /// Copy an existing document, creating a new document with the same content.+ /// Copy an existing document, creating a new document with the same content+ /// owned as `principal` decides.fn copy_document(&self,entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,document_context: DocumentBasic,- user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,document_name: String,query_version_id: Option<i64>,sync_version_id: Option<SyncServiceVersionID>,@@ -546,13 +559,12 @@ pub trait DocumentService: Send + Sync + 'static {project_id: &str,) -> impl Future<Output = Result<Vec<Entity<'static>>, DocumentError>> + Send;- /// Assigns the task properties to a document+ /// Assigns the task properties to a document as the principal that created it.fn handle_task_properties(&self,- user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,document_id: &str,request: &CreateTaskRequest,- attribution: &Attribution,) -> impl Future<Output = Result<(), DocumentError>> + Send;/// Returns the raw bytes of the cached Loro snapshot, or `None` if no snapshot exists.diff --git a/crates/documents/src/domain/ports/create.rs b/crates/documents/src/domain/ports/create.rsindex 86a924730b..9ddd655737 100644--- a/crates/documents/src/domain/ports/create.rs+++ b/crates/documents/src/domain/ports/create.rs@@ -3,11 +3,10 @@use std::future::Future;use std::sync::Arc;-use activity::Attribution;-use macro_user_id::user_id::MacroUserIdStr;+use model_owner::CreationPrincipal;use crate::domain::content::DocumentContent;-use crate::domain::models::{CreateDocumentRepoArgs, CreateTaskRequest, DocumentError};+use crate::domain::models::{CreateTaskRequest, DocumentError, NewDocument};use crate::domain::response::CreateDocumentResponseData;/// Uploaded document bytes and metadata for a presigned object-storage URL.@@ -36,18 +35,17 @@ pub trait DocumentCreationService: Send + Sync {/// Create a document metadata row and any service-owned creation side effects.fn create_document(&self,- user_id: MacroUserIdStr<'static>,- args: CreateDocumentRepoArgs,+ principal: &CreationPrincipal,+ document: NewDocument,job_id: Option<String>,) -> impl Future<Output = Result<CreateDocumentResponseData, DocumentError>> + Send;/// Assign task properties to a markdown task document.fn handle_task_properties(&self,- user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,document_id: &str,request: &CreateTaskRequest,- attribution: &Attribution,) -> impl Future<Output = Result<(), DocumentError>> + Send;/// Mark a created document's upload/finalization lifecycle as complete.@@ -73,22 +71,21 @@ where{async fn create_document(&self,- user_id: MacroUserIdStr<'static>,- args: CreateDocumentRepoArgs,+ principal: &CreationPrincipal,+ document: NewDocument,job_id: Option<String>,) -> Result<CreateDocumentResponseData, DocumentError> {- (**self).create_document(user_id, args, job_id).await+ (**self).create_document(principal, document, job_id).await}async fn handle_task_properties(&self,- user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,document_id: &str,request: &CreateTaskRequest,- attribution: &Attribution,) -> Result<(), DocumentError> {(**self)- .handle_task_properties(user_id, document_id, request, attribution)+ .handle_task_properties(principal, document_id, request).await}diff --git a/crates/documents/src/domain/ports/mentions.rs b/crates/documents/src/domain/ports/mentions.rsindex 35eff7288f..3ac1be5b0c 100644--- a/crates/documents/src/domain/ports/mentions.rs+++ b/crates/documents/src/domain/ports/mentions.rs@@ -8,11 +8,11 @@ use macro_user_id::user_id::MacroUserIdStr;/// mentioned entity can surface the mentioning document in its references.pub trait DocumentMentionTrackingPort: Send + Sync {/// Record every mention embedded in `markdown` as a reference owned by- /// `document_id`, attributed to `user_id`.+ /// `document_id`, attributed to `user_id` when one acted.fn track_document_mentions(&self,document_id: &str,- user_id: &MacroUserIdStr<'static>,+ user_id: Option<&MacroUserIdStr<'static>>,markdown: &str,) -> impl Future<Output = anyhow::Result<()>> + Send;}@@ -25,7 +25,7 @@ impl DocumentMentionTrackingPort for NoOpDocumentMentionTracker {async fn track_document_mentions(&self,_document_id: &str,- _user_id: &MacroUserIdStr<'static>,+ _user_id: Option<&MacroUserIdStr<'static>>,_markdown: &str,) -> anyhow::Result<()> {Ok(())diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rsindex 03efed36fa..791cbd34ce 100644--- a/crates/documents/src/domain/service.rs+++ b/crates/documents/src/domain/service.rs@@ -41,7 +41,7 @@ use model::document::{ContentType, DocumentBasic, DocumentMetadata, FileAssociation, FileType, FileTypeExt,};use model::response::PresignedUrl;-use model_owner::Owner;+use model_owner::{CreationPrincipal, Owner};use s3_key::{build_cloud_storage_bucket_document_key, build_docx_staging_bucket_document_key,build_docx_to_pdf_converted_document_key, document_key_url_path,@@ -63,7 +63,8 @@ use super::models::{CloudFrontConfig, CopyDocumentRepoArgs, CreateDocumentRepoArgs, CreateTaskRequest,DocumentError, DocumentTeamShareResponse, EditDocumentRepoArgs, EditDocumentServiceArgs,EmailImportRepoOutcome, FileTypeUpdate, GithubPullRequest, GithubPullRequestsResponse,- ImportEmailAttachmentRepoArgs, LocationQueryParams, TaskBranchName, TeamTaskMetadata,+ ImportEmailAttachmentRepoArgs, LocationQueryParams, NewDocument, TaskBranchName,+ TeamTaskMetadata,};#[cfg(feature = "document_create")]use super::ports::create::DocumentCreationService;@@ -831,28 +832,21 @@ impl<{async fn create_document(&self,- user_id: MacroUserIdStr<'static>,- args: CreateDocumentRepoArgs,+ principal: &CreationPrincipal,+ document: NewDocument,job_id: Option<String>,) -> Result<CreateDocumentResponseData, DocumentError> {- <Self as DocumentService>::create_document(self, user_id, args, job_id).await+ <Self as DocumentService>::create_document(self, principal, document, job_id).await}async fn handle_task_properties(&self,- user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,document_id: &str,request: &CreateTaskRequest,- attribution: &Attribution,) -> Result<(), DocumentError> {- <Self as DocumentService>::handle_task_properties(- self,- user_id,- document_id,- request,- attribution,- )- .await+ <Self as DocumentService>::handle_task_properties(self, principal, document_id, request)+ .await}#[tracing::instrument(err, skip(self))]@@ -1282,53 +1276,69 @@ impl<.await}- #[tracing::instrument(err, skip(self, args))]+ #[tracing::instrument(err, skip(self, document))]async fn create_document(&self,- _user_id: MacroUserIdStr<'static>,- args: CreateDocumentRepoArgs,+ principal: &CreationPrincipal,+ mut document: NewDocument,job_id: Option<String>,) -> Result<CreateDocumentResponseData, DocumentError> {- validate_spreadsheet_creation(args.file_type, &args.sha)?;- if args.document_name.graphemes(true).count() > MAX_DOCUMENT_NAME_GRAPHEMES {+ validate_spreadsheet_creation(document.file_type, &document.sha)?;+ if document.document_name.graphemes(true).count() > MAX_DOCUMENT_NAME_GRAPHEMES {return Err(DocumentError::NameTooLong {max: MAX_DOCUMENT_NAME_GRAPHEMES,});}- if args.sub_type == Some(DocumentSubType::InitiativeDescription)- && matches!(args.initial_link_share, InitialLinkShare::EntityDefault)+ if document.sub_type == Some(DocumentSubType::InitiativeDescription)+ && matches!(document.initial_link_share, InitialLinkShare::EntityDefault){return Err(DocumentError::BadRequest("initiative descriptions must set an exact initial link share".to_string(),));}+ if let CreationPrincipal::TeamBot { team, .. } = principal+ && document.sub_type == Some(DocumentSubType::Task)+ {+ if document.team_id.is_some_and(|requested| requested != *team) {+ return Err(DocumentError::BadRequest(+ "task team does not match the creating bot's team".to_string(),+ ));+ }+ document.team_id = Some(*team);+ }- let file_type = args.file_type;- let project_id = args.project_id;- let sha = args.sha.clone();- let attribution = args.resolved_attribution();+ let owner = principal.owner();+ let file_type = document.file_type;+ let project_id = document.project_id;+ let sha = document.sha.clone();- let share_permission = match args.initial_link_share {+ let share_permission = match document.initial_link_share {InitialLinkShare::EntityDefault => {- let team_default = self+ let owner_team = self.repo- .get_team_default_link_share(args.user_id.as_ref())+ .get_owner_team(&owner).await.map_err(|e| DocumentError::Internal(e.into()))?;- SharePermissionV2::new_document_share_permission(file_type, team_default)+ SharePermissionV2::new_document_share_permission(+ file_type,+ owner_team.map(|team| team.default_link_share),+ )}InitialLinkShare::Exact(state) => SharePermissionV2::from_link_share_state(state),};- let document_metadata = self.repo.create_document(args, share_permission).await?;+ let document_metadata = self+ .repo+ .create_document(CreateDocumentRepoArgs { owner, document }, share_permission)+ .await?;self.finish_created_document(document_metadata,file_type,project_id,sha,- attribution,+ Attribution::from(principal),job_id,).await@@ -1337,28 +1347,29 @@ impl<#[tracing::instrument(err, skip(self, args))]async fn import_email_attachment(&self,- _user_id: MacroUserIdStr<'static>,args: ImportEmailAttachmentRepoArgs,) -> Result<CreateDocumentResponseData, DocumentError> {- validate_spreadsheet_creation(args.create.file_type, &args.create.sha)?;- if args.create.document_name.graphemes(true).count() > MAX_DOCUMENT_NAME_GRAPHEMES {+ validate_spreadsheet_creation(args.document.file_type, &args.document.sha)?;+ if args.document.document_name.graphemes(true).count() > MAX_DOCUMENT_NAME_GRAPHEMES {return Err(DocumentError::NameTooLong {max: MAX_DOCUMENT_NAME_GRAPHEMES,});}- let file_type = args.create.file_type;- let project_id = args.create.project_id;- let sha = args.create.sha.clone();- let attribution = args.resolved_attribution();+ let file_type = args.document.file_type;+ let project_id = args.document.project_id;+ let sha = args.document.sha.clone();+ let attribution = Attribution::direct(Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID));- let team_default = self+ let owner_team = self.repo- .get_team_default_link_share(args.create.user_id.as_ref())+ .get_owner_team(&Owner::User(args.owner.clone())).await.map_err(|e| DocumentError::Internal(e.into()))?;- let share_permission =- SharePermissionV2::new_document_share_permission(file_type, team_default);+ let share_permission = SharePermissionV2::new_document_share_permission(+ file_type,+ owner_team.map(|team| team.default_link_share),+ );match self.repo@@ -1565,7 +1576,7 @@ impl<&self,entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,document_context: DocumentBasic,- user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,document_name: String,query_version_id: Option<i64>,sync_version_id: Option<model::sync_service::SyncServiceVersionID>,@@ -1599,11 +1610,12 @@ impl<.map_err(|e| DocumentError::Internal(e.into()))?};- // Check project ownership - only copy project_id if the user owns the project+ let owner = principal.owner();+if let Some(project_id) = &original_metadata.project_id {match self.repo.get_project_owner(project_id).await {Ok(project_owner) => {- if project_owner.as_ref() != user_id.as_ref() {+ if !owner.is_user(&project_owner) {original_metadata.project_id = None;original_metadata.project_name = None;}@@ -1628,29 +1640,18 @@ impl<// Clean the document namelet document_name = FileType::clean_document_name(&document_name).unwrap_or(document_name);- let copy_team_id = if original_metadata.sub_type == Some(DocumentSubType::Task) {- let team_id = self- .repo- .get_team_ids_for_user(user_id.as_ref())- .await- .map_err(|e| DocumentError::Internal(e.into()))?;-- let team_id = team_id.first();-- team_id.copied()- } else {- None- };-- // The copier becomes the owner, so their team default decides the- // copy's initial share permission.- let team_default = self+ let owner_team = self.repo- .get_team_default_link_share(user_id.as_ref())+ .get_owner_team(&owner).await.map_err(|e| DocumentError::Internal(e.into()))?;- let share_permission =- SharePermissionV2::new_document_share_permission(file_type, team_default);+ let copy_team_id = owner_team+ .filter(|_| original_metadata.sub_type == Some(DocumentSubType::Task))+ .map(|team| team.team_id);+ let share_permission = SharePermissionV2::new_document_share_permission(+ file_type,+ owner_team.map(|team| team.default_link_share),+ );// Create the copy in the databaselet new_metadata = self@@ -1658,7 +1659,7 @@ impl<.copy_document(CopyDocumentRepoArgs {original_document: original_metadata.clone(),- user_id: user_id.clone(),+ owner,document_name,file_type,team_id: copy_team_id,@@ -1669,7 +1670,7 @@ impl<.map_err(|e| DocumentError::Internal(e.into()))?;let new_document_id = new_metadata.document_id.clone();- let new_owner = Owner::User(user_id.clone());+ let new_owner = &new_metadata.owner;// File-type-specific S3 operationslet copy_result = match file_type {@@ -1680,7 +1681,7 @@ impl<&original_metadata.document_id,);let dest_key =- build_docx_to_pdf_converted_document_key(&new_owner, &new_document_id);+ build_docx_to_pdf_converted_document_key(new_owner, &new_document_id);self.upload_url_service.copy_object(&source_key, &dest_key).await@@ -1717,7 +1718,7 @@ impl<source_version_id,);let dest_key = build_cloud_storage_bucket_document_key(- &new_owner,+ new_owner,&new_document_id,new_metadata.document_version_id,);@@ -1766,7 +1767,7 @@ impl<source_version_id,);let dest_key = build_cloud_storage_bucket_document_key(- &new_owner,+ new_owner,&new_document_id,new_metadata.document_version_id,);@@ -1820,6 +1821,7 @@ impl<let team_task_metadata = self.team_task_metadata_for_document(&new_document_id).await?;+ let attribution = Attribution::from(principal);self.publish_document_event(&DocumentMacroEvent::copied(new_document_id.clone(),@@ -1827,7 +1829,9 @@ impl<document_id: new_document_id.clone(),source_document_id: original_metadata.document_id.clone(),source_version_id: query_version_id,- owner: Owner::User(user_id.clone()),+ owner: new_owner.clone(),+ actor: Some(attribution.actor()),+ on_behalf_of: attribution.on_behalf_of(),document_name: new_metadata.document_name.clone(),file_type,project_id: new_metadata.project_id.clone(),@@ -1907,36 +1911,37 @@ impl<}/// Assigns the task properties to a document- #[tracing::instrument(skip(self, request, attribution), err)]+ #[tracing::instrument(skip(self, request), err)]async fn handle_task_properties(&self,- user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,document_id: &str,request: &CreateTaskRequest,- attribution: &Attribution,) -> Result<(), DocumentError> {// Use provided properties or assign default ones for tasklet properties = if let Some(properties) = request.property_values.as_ref() {properties} else {- &vec![- PropertyInput {+ &principal+ .user()+ .map(|user| PropertyInput {property_id: ASSIGNEES_PROPERTY_ID.to_string(),value: SetPropertyValue::MultiEntityReference {references: vec![EntityReference {- entity_id: user_id.as_ref().to_string(),+ entity_id: user.as_ref().to_string(),entity_type: models_properties::EntityType::User,specific_message_id: None,}],},- },- PropertyInput {+ })+ .into_iter()+ .chain([PropertyInput {property_id: STATUS_PROPERTY_ID.to_string(),value: SetPropertyValue::SelectOption {option_id: NOT_STARTED_STATUS_OPTION_ID,},- },- ]+ }])+ .collect::<Vec<_>>()};for property_input in properties {@@ -1948,11 +1953,10 @@ impl<let _ = self.task_properties_service.set_entity_property(- user_id.as_ref(),+ principal,document_id,property_uuid,Some(property_input.value.clone()),- attribution,).await.inspect_err(|e| {diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rsindex 1ceba46bca..e5b2f0cfb3 100644--- a/crates/documents/src/domain/service/tests.rs+++ b/crates/documents/src/domain/service/tests.rs@@ -9,12 +9,11 @@ use model::document::{DocumentMetadata, FileType};use std::sync::{Arc, Mutex};use crate::domain::models::{- EmailImportRepoOutcome, GithubPullRequest, ImportEmailAttachmentRepoArgs,+ EmailImportRepoOutcome, GithubPullRequest, ImportEmailAttachmentRepoArgs, OwnerTeam,};use crate::domain::ports::{DocumentContentEventService, MockDocumentRepo};use super::*;-use activity::{Actor, Attribution};mod sync_content;@@ -161,11 +160,10 @@ impl TaskPropertiesPort for TestTaskPropertiesPort {async fn set_entity_property(&self,- _user_id: &str,+ _principal: &CreationPrincipal,_entity_id: &str,_property_definition_id: uuid::Uuid,_value: Option<models_properties::api::requests::SetPropertyValue>,- _attribution: &activity::Attribution,) -> anyhow::Result<()> {Ok(())}@@ -2130,7 +2128,7 @@ async fn copy_document_best_effort_bumps_inherited_project_and_publishes_event()let mut copied_metadata = make_test_metadata();copied_metadata.document_id = "doc-2".to_string();copied_metadata.document_name = "copied doc".to_string();- repo.expect_get_team_default_link_share()+ repo.expect_get_owner_team().returning(|_| Box::pin(std::future::ready(Ok(None))));repo.expect_copy_document().returning(move |_, _| Box::pin(std::future::ready(Ok(copied_metadata.clone()))));@@ -2157,9 +2155,7 @@ async fn copy_document_best_effort_bumps_inherited_project_and_publishes_event().copy_document(authenticated_receipt("doc-1"),document_context,- macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),+ &CreationPrincipal::User(test_user()),"copied doc".to_string(),None,None,@@ -2180,6 +2176,130 @@ async fn copy_document_best_effort_bumps_inherited_project_and_publishes_event()assert_eq!(event.payload["metadata"]["owner"], "macro|[email protected]");}+#[derive(Clone, Default)]+struct RecordingUploadUrlPort {+ copies: Arc<Mutex<Vec<(String, String)>>>,+}++impl PresignedUploadUrlPort for RecordingUploadUrlPort {+ async fn put_document_storage_presigned_url(+ &self,+ _key: &str,+ _sha: &str,+ _content_type: ContentType,+ ) -> anyhow::Result<String> {+ Ok(String::new())+ }++ async fn put_docx_upload_presigned_url(+ &self,+ _key: &str,+ _sha: &str,+ _content_type: ContentType,+ ) -> anyhow::Result<String> {+ Ok(String::new())+ }++ async fn copy_object(&self, source_key: &str, destination_key: &str) -> anyhow::Result<()> {+ self.copies+ .lock()+ .unwrap()+ .push((source_key.to_string(), destination_key.to_string()));+ Ok(())+ }++ async fn get_snapshot(&self, _document_id: &str) -> anyhow::Result<Option<Vec<u8>>> {+ Ok(None)+ }++ async fn upload_snapshot(&self, _document_id: &str, _bytes: Vec<u8>) -> anyhow::Result<()> {+ Ok(())+ }+}++#[tokio::test]+async fn bot_owned_copy_reads_the_source_owner_key_and_writes_the_bot_key() {+ let principal = CreationPrincipal::TeamBot {+ bot: bot_id::NonSystemBotId::new(bot_id()).unwrap(),+ team: uuid::uuid!("00000000-0000-0000-0000-000000000456"),+ };++ for (file_type, source_key, destination_key) in [+ (+ "txt",+ "macro|[email protected]/doc-1/1",+ "bot|00000000-0000-0000-0000-000000000123/doc-2/3",+ ),+ (+ "docx",+ "macro|[email protected]/doc-1/converted.pdf",+ "bot|00000000-0000-0000-0000-000000000123/doc-2/converted.pdf",+ ),+ ] {+ let mut original = make_test_metadata();+ original.project_id = None;+ original.project_name = None;+ original.file_type = Some(file_type.to_string());+ original.document_bom = Some(serde_json::json!([]));+ let mut repo = make_mock_repo();+ repo.expect_get_document_metadata()+ .returning(move |_| Box::pin(std::future::ready(Ok(original.clone()))));+ repo.expect_get_owner_team()+ .returning(|_| Box::pin(std::future::ready(Ok(None))));+ repo.expect_copy_document().returning(|args, _| {+ let mut copied = make_test_metadata();+ copied.document_id = "doc-2".to_string();+ copied.document_version_id = 3;+ copied.owner = args.owner;+ copied.project_id = None;+ Box::pin(std::future::ready(Ok(copied)))+ });+ repo.expect_get_document_version_id()+ .returning(|_| Box::pin(std::future::ready(Ok((1, true)))));+ repo.expect_get_latest_document_version_id()+ .returning(|_| Box::pin(std::future::ready(Ok((1, true)))));+ repo.expect_set_document_content()+ .returning(|_, _| Box::pin(std::future::ready(Ok(()))));+ repo.expect_get_team_task_metadata()+ .returning(|_| Box::pin(std::future::ready(Ok(None))));+ let uploads = RecordingUploadUrlPort::default();+ let service = DocumentServiceImpl::new(+ repo,+ test_cloudfront_config(),+ sync_service_client::SyncServiceClient::new(+ "test-sync-key".to_string(),+ "http://sync-service.test".to_string(),+ ),+ uploads.clone(),+ TestTaskPropertiesPort,+ TestConnectionService::default(),+ TestEntityAccessManagementService::default(),+ TestForeignEntityService::default(),+ TestEventBroker::default(),+ );+ let mut context = task_document_context("doc-1");+ context.file_type = Some(file_type.to_string());+ context.sub_type = None;++ service+ .copy_document(+ bot_receipt("doc-1"),+ context,+ &principal,+ "copied doc".to_string(),+ None,+ None,+ )+ .await+ .unwrap();++ assert_eq!(+ *uploads.copies.lock().unwrap(),+ [(source_key.to_string(), destination_key.to_string())]+ );+ }+}+struct RejectUnexpectedFinalization;impl crate::domain::ports::markdown::MarkdownInitializationPort for RejectUnexpectedFinalization {@@ -2205,7 +2325,7 @@ impl crate::domain::ports::mentions::DocumentMentionTrackingPort for RejectUnexpasync fn track_document_mentions(&self,_: &str,- _: ¯o_user_id::user_id::MacroUserIdStr<'static>,+ _: Option<¯o_user_id::user_id::MacroUserIdStr<'static>>,_: &str,) -> anyhow::Result<()> {panic!("failed repository creation must not track mentions");@@ -2235,11 +2355,11 @@ async fn creator_forwards_explicit_consent_and_stops_after_repository_failure()),] {let mut repo = make_mock_repo();- repo.expect_get_team_default_link_share()+ repo.expect_get_owner_team().returning(|_| Box::pin(std::future::ready(Ok(None))));repo.expect_create_document().withf(move |args, permission| {- args.share_with_team == expected_share+ args.document.share_with_team == expected_share&& permission.team_share_access_level.is_none()}).times(1)@@ -2257,7 +2377,7 @@ async fn creator_forwards_explicit_consent_and_stops_after_repository_failure());let result = creator.create_markdown_text(- create_document_repo_args(FileType::Md).user_id,+ &CreationPrincipal::User(test_user()),NewMarkdownTextDocument {metadata: NewDocumentMetadata::new("test"),markdown: String::new(),@@ -2270,14 +2390,17 @@ async fn creator_forwards_explicit_consent_and_stops_after_repository_failure()}}-fn create_document_repo_args(file_type: FileType) -> CreateDocumentRepoArgs {- CreateDocumentRepoArgs {+fn test_user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned()+}++fn new_document(file_type: FileType) -> NewDocument {+ NewDocument {id: None,sha: "sha".to_string(),document_name: "doc".to_string(),- user_id: macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),file_type: Some(file_type),project_id: None,team_id: None,@@ -2285,11 +2408,38 @@ fn create_document_repo_args(file_type: FileType) -> CreateDocumentRepoArgs {created_at: None,sub_type: None,skip_history: false,- attribution: None,initial_link_share: InitialLinkShare::EntityDefault,}}+#[tokio::test]+async fn team_bot_task_rejects_a_different_numbering_team() {+ let mut repo = make_mock_repo();+ repo.expect_get_owner_team().times(0);+ repo.expect_create_document().times(0);+ let (service, broker) = make_test_service_with_event_broker(repo);+ let team = uuid::Uuid::from_u128(7);+ let principal = CreationPrincipal::TeamBot {+ bot: bot_id::NonSystemBotId::new(bot_id::BotId::TEST_A).unwrap(),+ team,+ };+ let mut document = new_document(FileType::Md);+ document.sub_type = Some(DocumentSubType::Task);+ document.team_id = Some(uuid::Uuid::from_u128(8));++ let error = crate::domain::ports::DocumentService::create_document(+ &service, &principal, document, None,+ )+ .await+ .unwrap_err();++ assert_eq!(+ error.to_string(),+ "bad request: task team does not match the creating bot's team"+ );+ assert!(broker.published().lock().unwrap().is_empty());+}+async fn create_document_with_team_default(team_default: Option<models_permissions::share_permission::TeamLinkShareDefault>,file_type: FileType,@@ -2297,9 +2447,16 @@ async fn create_document_with_team_default(expected_access_level: Option<models_permissions::share_permission::access_level::AccessLevel>,) {let mut repo = make_mock_repo();- repo.expect_get_team_default_link_share()- .withf(|user_id| user_id == "macro|[email protected]")- .returning(move |_| Box::pin(std::future::ready(Ok(team_default))));+ repo.expect_get_owner_team()+ .withf(|owner| *owner == Owner::User(test_user()))+ .returning(move |_| {+ Box::pin(std::future::ready(Ok(team_default.map(+ |default_link_share| OwnerTeam {+ team_id: uuid::Uuid::from_u128(1),+ default_link_share,+ },+ ))))+ });let created_metadata = make_test_metadata();repo.expect_create_document().withf(move |_, share_permission| {@@ -2317,10 +2474,8 @@ async fn create_document_with_team_default(crate::domain::ports::DocumentService::create_document(&service,- macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- create_document_repo_args(file_type),+ &CreationPrincipal::User(test_user()),+ new_document(file_type),None,).await@@ -2388,10 +2543,10 @@ async fn exact_initial_link_share_bypasses_md_public_edit_default() {] {let mut repo = make_mock_repo();let created_metadata = make_test_metadata();- repo.expect_get_team_default_link_share().times(0);+ repo.expect_get_owner_team().times(0);repo.expect_create_document().withf(move |args, share_permission| {- args.initial_link_share == InitialLinkShare::Exact(state)+ args.document.initial_link_share == InitialLinkShare::Exact(state)&& share_permission.link_share_state() == state&& share_permission.team_share_access_level.is_none()})@@ -2403,12 +2558,12 @@ async fn exact_initial_link_share_bypasses_md_public_edit_default() {.returning(|_| Box::pin(std::future::ready(Ok(None))));let (service, _event_broker) = make_test_service_with_event_broker(repo);- let mut args = create_document_repo_args(FileType::Md);- args.initial_link_share = InitialLinkShare::Exact(state);+ let mut document = new_document(FileType::Md);+ document.initial_link_share = InitialLinkShare::Exact(state);crate::domain::ports::DocumentService::create_document(&service,- args.user_id.clone(),- args,+ &CreationPrincipal::User(test_user()),+ document,None,).await@@ -2420,13 +2575,13 @@ async fn exact_initial_link_share_bypasses_md_public_edit_default() {async fn initiative_description_rejects_entity_default_link_share() {let repo = make_mock_repo();let (service, event_broker) = make_test_service_with_event_broker(repo);- let mut args = create_document_repo_args(FileType::Md);- args.sub_type = Some(document_sub_type::DocumentSubType::InitiativeDescription);+ let mut document = new_document(FileType::Md);+ document.sub_type = Some(document_sub_type::DocumentSubType::InitiativeDescription);let err = crate::domain::ports::DocumentService::create_document(&service,- args.user_id.clone(),- args,+ &CreationPrincipal::User(test_user()),+ document,None,).await@@ -2445,11 +2600,12 @@ async fn initiative_description_accepts_exact_link_share() {let mut repo = make_mock_repo();let created_metadata = make_test_metadata();- repo.expect_get_team_default_link_share().times(0);+ repo.expect_get_owner_team().times(0);repo.expect_create_document().withf(|args, share_permission| {- args.sub_type == Some(document_sub_type::DocumentSubType::InitiativeDescription)- && args.initial_link_share == InitialLinkShare::Exact(LinkShareState::Off)+ args.document.sub_type+ == Some(document_sub_type::DocumentSubType::InitiativeDescription)+ && args.document.initial_link_share == InitialLinkShare::Exact(LinkShareState::Off)&& share_permission.link_share_state() == LinkShareState::Off}).times(1)@@ -2460,13 +2616,13 @@ async fn initiative_description_accepts_exact_link_share() {.returning(|_| Box::pin(std::future::ready(Ok(None))));let (service, _event_broker) = make_test_service_with_event_broker(repo);- let mut args = create_document_repo_args(FileType::Md);- args.sub_type = Some(document_sub_type::DocumentSubType::InitiativeDescription);- args.initial_link_share = InitialLinkShare::Exact(LinkShareState::Off);+ let mut document = new_document(FileType::Md);+ document.sub_type = Some(document_sub_type::DocumentSubType::InitiativeDescription);+ document.initial_link_share = InitialLinkShare::Exact(LinkShareState::Off);crate::domain::ports::DocumentService::create_document(&service,- args.user_id.clone(),- args,+ &CreationPrincipal::User(test_user()),+ document,None,).await@@ -2474,9 +2630,73 @@ async fn initiative_description_accepts_exact_link_share() {}#[tokio::test]-async fn create_document_publishes_resolved_attribution() {+async fn create_document_publishes_the_principal_as_owner_and_actor() {+ let team_bot = CreationPrincipal::TeamBot {+ bot: bot_id::NonSystemBotId::new(bot_id::BotId::TEST_A).unwrap(),+ team: uuid::Uuid::from_u128(7),+ };+ for (principal, owner, actor, on_behalf_of) in [+ (+ CreationPrincipal::User(test_user()),+ "macro|[email protected]",+ "macro|[email protected]",+ None,+ ),+ (+ CreationPrincipal::BotForUser {+ bot: bot_id::MACRO_AI_BOT_ID,+ user: test_user(),+ },+ "macro|[email protected]",+ "bot|00000000-0000-0000-0000-00000000a1a1",+ Some("macro|[email protected]"),+ ),+ (+ team_bot,+ "bot|00000000-0000-0000-0000-00000000b07a",+ "bot|00000000-0000-0000-0000-00000000b07a",+ None,+ ),+ ] {+ let mut repo = make_mock_repo();+ repo.expect_get_owner_team()+ .returning(|_| Box::pin(std::future::ready(Ok(None))));+ repo.expect_create_document().returning(|args, _| {+ let mut metadata = make_test_metadata();+ metadata.owner = args.owner;+ Box::pin(std::future::ready(Ok(metadata)))+ });+ repo.expect_set_document_content()+ .returning(|_, _| Box::pin(std::future::ready(Ok(()))));+ repo.expect_get_team_task_metadata()+ .returning(|_| Box::pin(std::future::ready(Ok(None))));+ let (service, event_broker) = make_test_service_with_event_broker(repo);++ crate::domain::ports::DocumentService::create_document(+ &service,+ &principal,+ new_document(FileType::Txt),+ None,+ )+ .await+ .unwrap();++ let published = event_broker.published();+ let published = published.lock().unwrap();+ let metadata = &published[0].payload["metadata"];+ assert_eq!(metadata["owner"], owner);+ assert_eq!(metadata["actor"], actor);+ assert_eq!(+ metadata.get("on_behalf_of").and_then(|user| user.as_str()),+ on_behalf_of+ );+ }+}++#[tokio::test]+async fn email_import_is_attributed_to_the_system_bot() {let mut repo = make_mock_repo();- repo.expect_get_team_default_link_share()+ repo.expect_get_owner_team().returning(|_| Box::pin(std::future::ready(Ok(None))));let created_metadata = make_test_metadata();repo.expect_import_email_attachment_document()@@ -2493,18 +2713,13 @@ async fn create_document_publishes_resolved_attribution() {let (service, event_broker) = make_test_service_with_event_broker(repo);let args = ImportEmailAttachmentRepoArgs {email_attachment_id: uuid::Uuid::from_u128(7),- create: create_document_repo_args(FileType::Txt),+ owner: test_user(),+ document: new_document(FileType::Txt),};- crate::domain::ports::DocumentService::import_email_attachment(- &service,- macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- args,- )- .await- .unwrap();+ crate::domain::ports::DocumentService::import_email_attachment(&service, args)+ .await+ .unwrap();let published = event_broker.published();let published = published.lock().unwrap();@@ -2524,9 +2739,11 @@ async fn create_document_publishes_resolved_attribution() {);}+type PropertyWrite = (CreationPrincipal, uuid::Uuid, Option<SetPropertyValue>);+#[derive(Default, Clone)]struct RecordingTaskPropertiesPort {- writes: Arc<Mutex<Vec<(String, uuid::Uuid, Attribution)>>>,+ writes: Arc<Mutex<Vec<PropertyWrite>>>,}impl TaskPropertiesPort for RecordingTaskPropertiesPort {@@ -2540,17 +2757,15 @@ impl TaskPropertiesPort for RecordingTaskPropertiesPort {async fn set_entity_property(&self,- user_id: &str,+ principal: &CreationPrincipal,_entity_id: &str,property_definition_id: uuid::Uuid,- _value: Option<models_properties::api::requests::SetPropertyValue>,- attribution: &Attribution,+ value: Option<SetPropertyValue>,) -> anyhow::Result<()> {- self.writes.lock().unwrap().push((- user_id.to_string(),- property_definition_id,- attribution.clone(),- ));+ self.writes+ .lock()+ .unwrap()+ .push((principal.clone(), property_definition_id, value));Ok(())}@@ -2564,70 +2779,90 @@ impl TaskPropertiesPort for RecordingTaskPropertiesPort {}#[tokio::test]-async fn handle_task_properties_forwards_create_attribution() {- use crate::domain::models::{ASSIGNEES_PROPERTY_ID, CreateTaskRequest, STATUS_PROPERTY_ID};+async fn default_task_properties_assign_the_acting_user_and_never_a_team_bot() {+ let assignees = uuid::Uuid::parse_str(ASSIGNEES_PROPERTY_ID).unwrap();+ let status = uuid::Uuid::parse_str(STATUS_PROPERTY_ID).unwrap();+ let not_started = SetPropertyValue::SelectOption {+ option_id: NOT_STARTED_STATUS_OPTION_ID,+ };+ let assigned_to_user = SetPropertyValue::MultiEntityReference {+ references: vec![EntityReference {+ entity_id: "macro|[email protected]".to_string(),+ entity_type: models_properties::EntityType::User,+ specific_message_id: None,+ }],+ };+ let bot_for_user = CreationPrincipal::BotForUser {+ bot: bot_id::MACRO_SYSTEM_BOT_ID,+ user: test_user(),+ };+ let team_bot = CreationPrincipal::TeamBot {+ bot: bot_id::NonSystemBotId::new(bot_id::BotId::TEST_A).unwrap(),+ team: uuid::Uuid::from_u128(7),+ };- let task_properties = RecordingTaskPropertiesPort::default();- let service = DocumentServiceImpl::new(- make_mock_repo(),- test_cloudfront_config(),- sync_service_client::SyncServiceClient::new(- "test-sync-key".to_string(),- "http://sync-service.test".to_string(),+ for (principal, expected) in [+ (+ bot_for_user,+ vec![+ (assignees, Some(assigned_to_user)),+ (status, Some(not_started.clone())),+ ],),- TestUploadUrlPort,- task_properties.clone(),- TestConnectionService::default(),- TestEntityAccessManagementService::default(),- TestForeignEntityService::default(),- TestEventBroker::default(),- );- let user = macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned();- let attribution = Attribution::delegated(- Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID),- user.clone(),- );+ (team_bot, vec![(status, Some(not_started))]),+ ] {+ let task_properties = RecordingTaskPropertiesPort::default();+ let service = DocumentServiceImpl::new(+ make_mock_repo(),+ test_cloudfront_config(),+ sync_service_client::SyncServiceClient::new(+ "test-sync-key".to_string(),+ "http://sync-service.test".to_string(),+ ),+ TestUploadUrlPort,+ task_properties.clone(),+ TestConnectionService::default(),+ TestEntityAccessManagementService::default(),+ TestForeignEntityService::default(),+ TestEventBroker::default(),+ );- crate::domain::ports::DocumentService::handle_task_properties(- &service,- user.clone(),- "task-1",- &CreateTaskRequest {- task_name: "Intro to tasks".to_string(),- markdown: None,- project_id: None,- team_id: None,- property_values: None,- share_with_team: false,- },- &attribution,- )- .await- .unwrap();+ crate::domain::ports::DocumentService::handle_task_properties(+ &service,+ &principal,+ "task-1",+ &CreateTaskRequest {+ task_name: "Intro to tasks".to_string(),+ markdown: None,+ project_id: None,+ team_id: None,+ property_values: None,+ share_with_team: false,+ },+ )+ .await+ .unwrap();- let writes = task_properties.writes.lock().unwrap().clone();- assert_eq!(writes.len(), 2);- assert_eq!(- writes[0].1,- uuid::Uuid::parse_str(ASSIGNEES_PROPERTY_ID).unwrap()- );- assert_eq!(- writes[1].1,- uuid::Uuid::parse_str(STATUS_PROPERTY_ID).unwrap()- );- assert!(- writes- .iter()- .all(|(user_id, _, recorded)| user_id == user.as_ref() && recorded == &attribution)- );+ let writes = task_properties.writes.lock().unwrap().clone();+ assert!(+ writes+ .iter()+ .all(|(written_as, _, _)| *written_as == principal)+ );+ assert_eq!(+ writes+ .into_iter()+ .map(|(_, property, value)| (property, value))+ .collect::<Vec<_>>(),+ expected+ );+ }}#[tokio::test]async fn create_document_reuse_skips_content_url_and_created_event() {let mut repo = make_mock_repo();- repo.expect_get_team_default_link_share()+ repo.expect_get_owner_team().returning(|_| Box::pin(std::future::ready(Ok(None))));let created_metadata = make_test_metadata();repo.expect_import_email_attachment_document()@@ -2649,18 +2884,13 @@ async fn create_document_reuse_skips_content_url_and_created_event() {let (service, event_broker) = make_test_service_with_event_broker(repo);let args = ImportEmailAttachmentRepoArgs {email_attachment_id: uuid::Uuid::from_u128(9),- create: create_document_repo_args(FileType::Txt),+ owner: test_user(),+ document: new_document(FileType::Txt),};- let response = crate::domain::ports::DocumentService::import_email_attachment(- &service,- macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- args,- )- .await- .unwrap();+ let response = crate::domain::ports::DocumentService::import_email_attachment(&service, args)+ .await+ .unwrap();assert!(response.document_response.presigned_url.is_none());assert_eq!(@@ -2768,11 +2998,10 @@ fn spreadsheet_test_service()}-fn spreadsheet_create_args() -> CreateDocumentRepoArgs {- let mut args = create_document_repo_args(FileType::Spreadsheet);- args.user_id = MacroUserIdStr::try_from_email("[email protected]").unwrap();- args.sha = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".to_string();- args+fn spreadsheet_document() -> NewDocument {+ let mut document = new_document(FileType::Spreadsheet);+ document.sha = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".to_string();+ document}#[tokio::test]@@ -2780,7 +3009,7 @@ async fn spreadsheet_creation_is_ready_only_after_sync_initialization() {let mut repo = make_mock_repo();let mut sync = crate::domain::ports::sync::MockDocumentSyncPort::new();let mut sequence = mockall::Sequence::new();- repo.expect_get_team_default_link_share()+ repo.expect_get_owner_team().returning(|_| Box::pin(std::future::ready(Ok(None))));repo.expect_create_document().returning(|_, _| {let mut metadata = make_test_metadata();@@ -2809,10 +3038,14 @@ async fn spreadsheet_creation_is_ready_only_after_sync_initialization() {repo.expect_get_team_task_metadata().returning(|_| Box::pin(std::future::ready(Ok(None))));let service = spreadsheet_test_service(repo, sync);- let args = spreadsheet_create_args();- let result = DocumentService::create_document(&service, args.user_id.clone(), args, None)- .await- .unwrap();+ let result = DocumentService::create_document(+ &service,+ &CreationPrincipal::User(test_user()),+ spreadsheet_document(),+ None,+ )+ .await+ .unwrap();assert!(result.document_response.presigned_url.is_none());assert_eq!(result.document_response.document_metadata.content,@@ -2824,7 +3057,7 @@ async fn spreadsheet_creation_is_ready_only_after_sync_initialization() {async fn failed_spreadsheet_initialization_cleans_up_document_metadata() {let mut repo = make_mock_repo();let mut sync = crate::domain::ports::sync::MockDocumentSyncPort::new();- repo.expect_get_team_default_link_share()+ repo.expect_get_owner_team().returning(|_| Box::pin(std::future::ready(Ok(None))));repo.expect_create_document().returning(|_, _| Box::pin(std::future::ready(Ok(make_test_metadata()))));@@ -2840,11 +3073,15 @@ async fn failed_spreadsheet_initialization_cleans_up_document_metadata() {.times(1).returning(|_| Box::pin(std::future::ready(Ok(()))));let service = spreadsheet_test_service(repo, sync);- let args = spreadsheet_create_args();assert!(- DocumentService::create_document(&service, args.user_id.clone(), args, None)- .await- .is_err()+ DocumentService::create_document(+ &service,+ &CreationPrincipal::User(test_user()),+ spreadsheet_document(),+ None,+ )+ .await+ .is_err());}@@ -2885,7 +3122,7 @@ fn spreadsheet_uploads_are_rejected_instead_of_discarding_their_bytes() {.is_err());assert!(- validate_spreadsheet_creation(Some(FileType::Spreadsheet), &spreadsheet_create_args().sha)+ validate_spreadsheet_creation(Some(FileType::Spreadsheet), &spreadsheet_document().sha).is_ok());assert!(validate_spreadsheet_creation(Some(FileType::Csv), "uploaded-csv-sha").is_ok());diff --git a/crates/documents/src/inbound/axum_router.rs b/crates/documents/src/inbound/axum_router.rsindex 77c8489a41..c52bc72b1e 100644--- a/crates/documents/src/inbound/axum_router.rs+++ b/crates/documents/src/inbound/axum_router.rs@@ -28,6 +28,7 @@ pub mod create_skill;#[cfg(feature = "document_create")]pub mod create_snippet;pub mod create_task;+pub mod creation_principal;pub mod delete_document;pub mod edit_document;pub mod get_branch_name;@@ -55,6 +56,7 @@ use axum::{response::IntoResponse,};use entity_access::domain::ports::EntityAccessService;+use entity_registry::NonUserOwners;use lexical_client::LexicalClient;use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};use model_error_response::ErrorResponse;@@ -178,6 +180,8 @@ pub struct DocumentRouterState<T, Svc, Auth> {pub creator: DefaultDocumentCreator<T>,/// JWT secret for signing document permission tokens.pub document_permission_jwt_secret: String,+ /// Whether a team bot with no acting user may own what it creates.+ pub non_user_owners: NonUserOwners,}// Manual Clone impl so T, Svc, and Auth don't need to be Clone.@@ -193,6 +197,7 @@ impl<T, Svc, Auth> Clone for DocumentRouterState<T, Svc, Auth> {#[cfg(feature = "document_create_adapters")]creator: self.creator.clone(),document_permission_jwt_secret: self.document_permission_jwt_secret.clone(),+ non_user_owners: self.non_user_owners,}}}@@ -209,6 +214,12 @@ impl<T, Svc, Auth> FromRef<DocumentRouterState<T, Svc, Auth>> for MacroAuthoriza}}+impl<T, Svc, Auth> FromRef<DocumentRouterState<T, Svc, Auth>> for NonUserOwners {+ fn from_ref(state: &DocumentRouterState<T, Svc, Auth>) -> Self {+ state.non_user_owners+ }+}+/// Path parameters for document endpoints (document_id extraction).#[derive(Deserialize)]pub struct Params {diff --git a/crates/documents/src/inbound/axum_router/copy_document.rs b/crates/documents/src/inbound/axum_router/copy_document.rsindex 8a5cc86c45..8afb6bddd1 100644--- a/crates/documents/src/inbound/axum_router/copy_document.rs+++ b/crates/documents/src/inbound/axum_router/copy_document.rs@@ -6,10 +6,11 @@ use axum::{};use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::DocumentAccessExtractor;-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};+use macro_authorization::MacroAuthorizationService;use model::document::{DocumentBasic, FileTypeExt};use models_permissions::share_permission::access_level::ViewAccessLevel;+use super::creation_principal::CreationPrincipalExtractor;use super::{DocumentRouterState, Params};use crate::domain::models::{CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, DocumentError,@@ -38,15 +39,15 @@ use crate::domain::ports::DocumentService;(status = 500, body = model_error_response::ErrorResponse),))]-#[tracing::instrument(skip(state, access, user, document_context, req), fields(user_id=%user.authorization.user.macro_user_id, document_version_id=?params.version_id))]+#[tracing::instrument(skip(state, access, document_context, req), fields(document_version_id=?params.version_id))]pub async fn copy_document_handler<T: DocumentService,Svc: EntityAccessService,Auth: MacroAuthorizationService,>(+ CreationPrincipalExtractor { principal, .. }: CreationPrincipalExtractor<Auth>,access: DocumentAccessExtractor<ViewAccessLevel, Svc, Auth>,State(state): State<DocumentRouterState<T, Svc, Auth>>,- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,document_context: Extension<DocumentBasic>,Path(Params { document_id }): Path<Params>,Query(params): Query<CopyDocumentQueryParams>,@@ -61,7 +62,7 @@ pub async fn copy_document_handler<.copy_document(access.entity_access_receipt,document_context.0,- user.authorization.user.macro_user_id.clone(),+ &principal,req.document_name,params.version_id,req.version_id,diff --git a/crates/documents/src/inbound/axum_router/create_document.rs b/crates/documents/src/inbound/axum_router/create_document.rsindex 165051db29..71b670755f 100644--- a/crates/documents/src/inbound/axum_router/create_document.rs+++ b/crates/documents/src/inbound/axum_router/create_document.rs@@ -1,4 +1,4 @@-//! Handler for `POST /documents`.+//! Handlers for `POST /documents` and the internal `POST /internal/documents`.use std::str::FromStr;@@ -10,11 +10,13 @@ use macro_authorization::{};use model::document::response::CreateDocumentRequest;use model::document::{FileType, FileTypeExt};+use model_owner::CreationPrincipal;use models_permissions::share_permission::access_level::EditAccessLevel;use super::DocumentRouterState;+use super::creation_principal::CreationPrincipalExtractor;use crate::domain::models::{- CreateDocumentRepoArgs, DocumentError, ImportEmailAttachmentRepoArgs, InitialLinkShare,+ DocumentError, ImportEmailAttachmentRepoArgs, InitialLinkShare, NewDocument,};use crate::domain::ports::DocumentService;use crate::domain::response::CreateDocumentResponse;@@ -38,26 +40,80 @@ use crate::domain::response::CreateDocumentResponse;(status = 500, body = model_error_response::ErrorResponse),))]-#[tracing::instrument(skip(state, user, project), fields(user_id=?user.authorization.user.macro_user_id))]+#[tracing::instrument(skip(state, project))]pub async fn create_document_handler<T: DocumentService,Svc: EntityAccessService,Auth: MacroAuthorizationService,>(State(state): State<DocumentRouterState<T, Svc, Auth>>,- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ CreationPrincipalExtractor { principal, .. }: CreationPrincipalExtractor<Auth>,project: ProjectBodyAccessLevelExtractorV2<EditAccessLevel, CreateDocumentRequest, Svc, Auth>,) -> Result<Json<CreateDocumentResponse>, DocumentError> {let req = project.into_inner();- // Email linking is internal only- if req.email_attachment_id.is_some()- && user.authorization.caller != UserOrInternalCaller::Internal- {+ if req.email_attachment_id.is_some() {return Err(DocumentError::Unauthorized);}- // Parse file type from the request+ let job_id = req.job_id.clone();+ let response_data = state+ .service+ .create_document(&principal, new_document(req), job_id)+ .await?;++ Ok(Json(CreateDocumentResponse {+ error: false,+ data: response_data,+ }))+}++/// Handler for the internal `POST /internal/documents`.+///+/// Creates a document owned by the calling or acting user. Only an internal+/// caller may import an email attachment.+#[tracing::instrument(skip(state, caller, project), fields(user_id=?caller.authorization.user.macro_user_id))]+pub async fn create_document_internal_handler<+ T: DocumentService,+ Svc: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ State(state): State<DocumentRouterState<T, Svc, Auth>>,+ caller: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ project: ProjectBodyAccessLevelExtractorV2<EditAccessLevel, CreateDocumentRequest, Svc, Auth>,+) -> Result<Json<CreateDocumentResponse>, DocumentError> {+ let req = project.into_inner();+ let is_internal = caller.authorization.caller == UserOrInternalCaller::Internal;+ let user = caller.authorization.user.macro_user_id;++ let response_data = match req.email_attachment_id {+ Some(email_attachment_id) if is_internal => {+ state+ .service+ .import_email_attachment(ImportEmailAttachmentRepoArgs {+ email_attachment_id,+ owner: user,+ document: new_document(req),+ })+ .await?+ }+ Some(_) => return Err(DocumentError::Unauthorized),+ None => {+ let job_id = req.job_id.clone();+ state+ .service+ .create_document(&CreationPrincipal::User(user), new_document(req), job_id)+ .await?+ }+ };++ Ok(Json(CreateDocumentResponse {+ error: false,+ data: response_data,+ }))+}++fn new_document(req: CreateDocumentRequest) -> NewDocument {let user_provided_file_type: Option<FileType> = req.file_type.as_deref()@@ -88,47 +144,19 @@ pub async fn create_document_handler<);}- let team_id = req.team_id;-- let args = CreateDocumentRepoArgs {+ NewDocument {id: req.id,sha: req.sha,document_name,- user_id: user.authorization.user.macro_user_id.clone(),file_type,project_id: req.project_id,- team_id,+ team_id: req.team_id,share_with_team: false,created_at: req.created_at,sub_type: req.is_task.then_some(document_sub_type::DocumentSubType::Task),skip_history: req.skip_history,- attribution: None,initial_link_share: InitialLinkShare::EntityDefault,- };-- let user_id = user.authorization.user.macro_user_id.clone();- let response_data = if let Some(email_attachment_id) = req.email_attachment_id {- state- .service- .import_email_attachment(- user_id,- ImportEmailAttachmentRepoArgs {- email_attachment_id,- create: args,- },- )- .await?- } else {- state- .service- .create_document(user_id, args, req.job_id)- .await?- };-- Ok(Json(CreateDocumentResponse {- error: false,- data: response_data,- }))+ }}diff --git a/crates/documents/src/inbound/axum_router/create_markdown.rs b/crates/documents/src/inbound/axum_router/create_markdown.rsindex 4488157a03..faa557b537 100644--- a/crates/documents/src/inbound/axum_router/create_markdown.rs+++ b/crates/documents/src/inbound/axum_router/create_markdown.rs@@ -3,15 +3,16 @@use axum::{Json, extract::State};use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2;-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};+use macro_authorization::MacroAuthorizationService;use models_permissions::share_permission::access_level::{AccessLevel, EditAccessLevel};use super::DocumentRouterState;+use super::creation_principal::CreationPrincipalExtractor;use crate::domain::create::{MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument};use crate::domain::models::{CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, DocumentError,};-use crate::domain::permission_token::encode_permission_token;+use crate::domain::permission_token::encode_principal_permission_token;use crate::domain::ports::DocumentService;use crate::domain::ports::create::DocumentCreationService;@@ -29,14 +30,14 @@ use crate::domain::ports::create::DocumentCreationService;(status = 500, body = model_error_response::ErrorResponse),))]-#[tracing::instrument(skip(state, user, project), fields(user_id=?user.authorization.user.macro_user_id))]+#[tracing::instrument(skip(state, project))]pub async fn create_markdown_handler<T: DocumentService + DocumentCreationService,Svc: EntityAccessService,Auth: MacroAuthorizationService,>(State(state): State<DocumentRouterState<T, Svc, Auth>>,- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ CreationPrincipalExtractor { principal, .. }: CreationPrincipalExtractor<Auth>,project: ProjectBodyAccessLevelExtractorV2<EditAccessLevel,CreateMarkdownDocumentRequest,@@ -57,7 +58,7 @@ pub async fn create_markdown_handler<let created = state.creator.create_markdown_text(- user.authorization.user.macro_user_id.clone(),+ &principal,NewMarkdownTextDocument {metadata: metadata.build(),markdown: req.markdown.unwrap_or_default(),@@ -74,12 +75,11 @@ pub async fn create_markdown_handler<.metadata.clone();- let token = encode_permission_token(- Some(user.authorization.user.macro_user_id.as_ref().to_string()),+ let token = encode_principal_permission_token(+ &principal,document_id.clone(),AccessLevel::Edit,&state.document_permission_jwt_secret,- None,).map_err(|e| {tracing::error!(error=?e, "failed to encode permission token");diff --git a/crates/documents/src/inbound/axum_router/create_skill.rs b/crates/documents/src/inbound/axum_router/create_skill.rsindex b3b3ac3b28..04ffca0eca 100644--- a/crates/documents/src/inbound/axum_router/create_skill.rs+++ b/crates/documents/src/inbound/axum_router/create_skill.rs@@ -3,10 +3,11 @@use axum::{Json, extract::State};use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2;-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};+use macro_authorization::MacroAuthorizationService;use models_permissions::share_permission::access_level::EditAccessLevel;use super::DocumentRouterState;+use super::creation_principal::CreationPrincipalExtractor;use crate::domain::create::{MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument};use crate::domain::models::{CreateSkillRequest, CreateSkillResponse, DocumentError};use crate::domain::ports::DocumentService;@@ -28,14 +29,14 @@ use crate::domain::ports::create::DocumentCreationService;(status = 500, body = model_error_response::ErrorResponse),))]-#[tracing::instrument(skip(state, user, project), fields(user_id=?user.authorization.user.macro_user_id))]+#[tracing::instrument(skip(state, project))]pub async fn create_skill_handler<T: DocumentService + DocumentCreationService,Svc: EntityAccessService,Auth: MacroAuthorizationService,>(State(state): State<DocumentRouterState<T, Svc, Auth>>,- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ CreationPrincipalExtractor { principal, .. }: CreationPrincipalExtractor<Auth>,project: ProjectBodyAccessLevelExtractorV2<EditAccessLevel, CreateSkillRequest, Svc, Auth>,) -> Result<Json<CreateSkillResponse>, DocumentError> {let req = project.into_inner();@@ -48,7 +49,7 @@ pub async fn create_skill_handler<let created = state.creator.create_markdown_text(- user.authorization.user.macro_user_id.clone(),+ &principal,NewMarkdownTextDocument {metadata: metadata.build(),markdown: req.markdown.unwrap_or_default(),diff --git a/crates/documents/src/inbound/axum_router/create_snippet.rs b/crates/documents/src/inbound/axum_router/create_snippet.rsindex fc7477752a..54817a44b8 100644--- a/crates/documents/src/inbound/axum_router/create_snippet.rs+++ b/crates/documents/src/inbound/axum_router/create_snippet.rs@@ -3,10 +3,11 @@use axum::{Json, extract::State};use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2;-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};+use macro_authorization::MacroAuthorizationService;use models_permissions::share_permission::access_level::EditAccessLevel;use super::DocumentRouterState;+use super::creation_principal::CreationPrincipalExtractor;use crate::domain::create::{MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument};use crate::domain::models::{CreateSnippetRequest, CreateSnippetResponse, DocumentError};use crate::domain::ports::DocumentService;@@ -27,14 +28,14 @@ use crate::domain::ports::create::DocumentCreationService;(status = 500, body = model_error_response::ErrorResponse),))]-#[tracing::instrument(skip(state, user, project), fields(user_id=?user.authorization.user.macro_user_id))]+#[tracing::instrument(skip(state, project))]pub async fn create_snippet_handler<T: DocumentService + DocumentCreationService,Svc: EntityAccessService,Auth: MacroAuthorizationService,>(State(state): State<DocumentRouterState<T, Svc, Auth>>,- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ CreationPrincipalExtractor { principal, .. }: CreationPrincipalExtractor<Auth>,project: ProjectBodyAccessLevelExtractorV2<EditAccessLevel, CreateSnippetRequest, Svc, Auth>,) -> Result<Json<CreateSnippetResponse>, DocumentError> {let req = project.into_inner();@@ -47,7 +48,7 @@ pub async fn create_snippet_handler<let created = state.creator.create_markdown_text(- user.authorization.user.macro_user_id.clone(),+ &principal,NewMarkdownTextDocument {metadata: metadata.build(),markdown: req.markdown.unwrap_or_default(),diff --git a/crates/documents/src/inbound/axum_router/create_task.rs b/crates/documents/src/inbound/axum_router/create_task.rsindex 9ad1677544..d4b66dc8d6 100644--- a/crates/documents/src/inbound/axum_router/create_task.rs+++ b/crates/documents/src/inbound/axum_router/create_task.rs@@ -7,13 +7,14 @@ use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::{OptionalMacroUserTeamExtractorV2, ProjectBodyAccessLevelExtractorV2,};-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};+use macro_authorization::MacroAuthorizationService;use models_permissions::share_permission::access_level::{AccessLevel, EditAccessLevel};use super::DocumentRouterState;+use super::creation_principal::CreationPrincipalExtractor;use crate::domain::create::{MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument};use crate::domain::models::{CreateTaskRequest, CreateTaskResponse, DocumentError};-use crate::domain::permission_token::encode_permission_token;+use crate::domain::permission_token::encode_principal_permission_token;use crate::domain::ports::DocumentService;use crate::domain::ports::create::DocumentCreationService;use task_dedup::{EmbeddingMarkdown, NewTask};@@ -34,21 +35,20 @@ use super::task_duplicates::spawn_task_duplicate_detection;(status = 500, body = model_error_response::ErrorResponse),))]-#[tracing::instrument(skip(state, user, optional_team, project), fields(user_id=?user.authorization.user.macro_user_id))]+#[tracing::instrument(skip(state, optional_team, project))]pub async fn create_task_handler<T: DocumentService + DocumentCreationService,Svc: EntityAccessService,Auth: MacroAuthorizationService,>(State(state): State<DocumentRouterState<T, Svc, Auth>>,- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ CreationPrincipalExtractor { principal, .. }: CreationPrincipalExtractor<Auth>,optional_team: OptionalMacroUserTeamExtractorV2<MemberTeamRole, Svc, Auth>,project: ProjectBodyAccessLevelExtractorV2<EditAccessLevel, CreateTaskRequest, Svc, Auth>,) -> Result<Json<CreateTaskResponse>, DocumentError> {let req = project.into_inner();let task_name = req.task_name.clone();let markdown = req.markdown.clone().unwrap_or_default();- let owner = user.authorization.user.macro_user_id.as_ref().to_string();let mut metadata = NewDocumentMetadata::builder(task_name.clone());if let Some(project_id) = req.project_id {@@ -66,7 +66,7 @@ pub async fn create_task_handler<let created = state.creator.create_markdown_text(- user.authorization.user.macro_user_id.clone(),+ &principal,NewMarkdownTextDocument {metadata: metadata.build(),markdown,@@ -92,7 +92,7 @@ pub async fn create_task_handler<state.lexical_client.clone(),NewTask {document_id: document_id.clone(),- owner,+ owner: principal.owner().principal_id(),team_id: task_metadata.team_id,title: task_name,// Filled from lexical (embedding format) inside the spawn; defaults@@ -101,12 +101,11 @@ pub async fn create_task_handler<},);- let token = encode_permission_token(- Some(user.authorization.user.macro_user_id.as_ref().to_string()),+ let token = encode_principal_permission_token(+ &principal,document_id.clone(),AccessLevel::Edit,&state.document_permission_jwt_secret,- None,).map_err(|e| {tracing::error!(error=?e, "failed to encode permission token");diff --git a/crates/documents/src/inbound/axum_router/creation_principal.rs b/crates/documents/src/inbound/axum_router/creation_principal.rsnew file mode 100644index 0000000000..6cd78a0c6f--- /dev/null+++ b/crates/documents/src/inbound/axum_router/creation_principal.rs@@ -0,0 +1,53 @@+//! Resolves who a public document create request creates as.++use std::marker::PhantomData;++use axum::{+ extract::{FromRef, FromRequestParts},+ http::{StatusCode, request::Parts},+};+use entity_registry::{NonUserOwners, resolve_creation_principal};+use macro_authorization::{+ AnyPrincipal, MacroAuthorizationExtractor, MacroAuthorizationRejection,+ MacroAuthorizationService, MacroAuthorizationState,+};+use model_owner::CreationPrincipal;++/// The verified principal a public create request creates as.+///+/// A caller that cannot create is rejected with 403 before the request body+/// is read.+pub struct CreationPrincipalExtractor<Auth> {+ /// Who the request creates as.+ pub principal: CreationPrincipal,+ _auth: PhantomData<fn() -> Auth>,+}++impl<S, Auth> FromRequestParts<S> for CreationPrincipalExtractor<Auth>+where+ MacroAuthorizationState<Auth>: FromRef<S>,+ NonUserOwners: FromRef<S>,+ Auth: MacroAuthorizationService,+ S: Send + Sync + 'static,+{+ type Rejection = MacroAuthorizationRejection;++ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {+ let caller =+ MacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(parts, state)+ .await?;+ let principal =+ resolve_creation_principal(&caller.authorization, NonUserOwners::from_ref(state))+ .map_err(|error| {+ tracing::info!(%error, "caller cannot create documents");+ MacroAuthorizationRejection {+ status: StatusCode::FORBIDDEN,+ message: "forbidden".into(),+ }+ })?;+ Ok(Self {+ principal,+ _auth: PhantomData,+ })+ }+}diff --git a/crates/documents/src/inbound/axum_router/tests.rs b/crates/documents/src/inbound/axum_router/tests.rsindex a5ed7be916..242ddd1b84 100644--- a/crates/documents/src/inbound/axum_router/tests.rs+++ b/crates/documents/src/inbound/axum_router/tests.rs@@ -6,19 +6,24 @@ use axum::{body::Body,http::{Request, StatusCode, request::Builder},};+use bot_id::NonSystemBotId;use embedding::embedding_provider::openai::TextEmbedding3Small;use entity_access::domain::{models::{- AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityAccessReceipt,- EntityPermission, EntityType, MemberTeamRole, RequiredPermission, TeamRole, UserTeamInfo,+ AccessError, AccessLevel, BotAccessScope, BotId, BotReceiptScope, CallChannelInfo,+ EntityAccessReceipt, EntityPermission, EntityType, MemberTeamRole, RequiredPermission,+ TeamRole, UserTeamInfo,},ports::EntityAccessService,};+use entity_registry::NonUserOwners;use http_body_util::BodyExt;use lexical_client::LexicalClient;use macro_authorization::{- INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,- MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,+ BOT_FOR_MACRO_USER_ID_HEADER, BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims,+ BotAuthentication, BotScope, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,+ MacroAuthorizationState, MacroUserAuthentication,};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};use model::{@@ -26,7 +31,7 @@ use model::{sync_service::SyncServiceVersionID,};use model_entity::Entity;-use model_owner::Owner;+use model_owner::{CreationPrincipal, Owner};use model_user::UserContext;use rootcause::Report;use serde_json::{Value, json};@@ -43,7 +48,10 @@ use task_dedup::{use tower::ServiceExt;use uuid::Uuid;-use super::{DocumentRouterState, content_uploaded::content_uploaded_handler, documents_router};+use super::{+ DocumentRouterState, content_uploaded::content_uploaded_handler,+ create_document::create_document_internal_handler, documents_router,+};mod sync_content;use crate::{@@ -52,9 +60,9 @@ use crate::{create::DocumentCreator,events::InteractionReason,models::{- CreateDocumentRepoArgs, CreateTaskRequest, DocumentError, DocumentTeamShareResponse,- EditDocumentServiceArgs, GithubPullRequestsResponse, ImportEmailAttachmentRepoArgs,- LocationQueryParams, TaskBranchName,+ CreateTaskRequest, DocumentError, DocumentTeamShareResponse, EditDocumentServiceArgs,+ GithubPullRequestsResponse, ImportEmailAttachmentRepoArgs, LocationQueryParams,+ NewDocument, TaskBranchName,},ports::{DocumentContentEventService, DocumentService, create::DocumentCreationService},response::{@@ -79,10 +87,11 @@ const LEGACY_INTERNAL_USER_ID_HEADER: &str = "x-document-storage-service-user-idconst TEST_ORGANIZATION_ID: i32 = 42;const TEAM_ID: Uuid = Uuid::from_u128(0x82c6f359_691f_4ff3_965a_016a2970b1a2);const RESOLVED_DOCUMENT_ID: &str = "resolved-document";+const BOT_TOKEN: &str = "valid-bot-token";#[derive(Clone, Debug, Eq, PartialEq)]struct CreateDocumentCall {- user_id: String,+ principal: CreationPrincipal,}#[derive(Clone, Debug, Eq, PartialEq)]@@ -135,6 +144,7 @@ struct FakeDocumentService {team_slug_calls: Mutex<Vec<TeamSlugCall>>,team_slug_result: Mutex<Option<TeamSlugResult>>,get_document_calls: Mutex<Vec<String>>,+ copy_calls: Mutex<Vec<CreationPrincipal>>,}impl FakeDocumentService {@@ -145,6 +155,13 @@ impl FakeDocumentService {.clone()}+ fn copy_calls(&self) -> Vec<CreationPrincipal> {+ self.copy_calls+ .lock()+ .expect("copy calls lock poisoned")+ .clone()+ }+fn import_calls(&self) -> Vec<ImportEmailAttachmentCall> {self.import_calls.lock()@@ -291,34 +308,33 @@ impl DocumentService for FakeDocumentService {async fn create_document(&self,- user_id: MacroUserIdStr<'static>,- _args: CreateDocumentRepoArgs,+ principal: &CreationPrincipal,+ _document: NewDocument,_job_id: Option<String>,) -> Result<CreateDocumentResponseData, DocumentError> {self.create_calls.lock().expect("create calls lock poisoned").push(CreateDocumentCall {- user_id: user_id.as_ref().to_string(),+ principal: principal.clone(),});- Ok(create_document_response(user_id))+ Ok(create_document_response(principal.owner()))}async fn import_email_attachment(&self,- user_id: MacroUserIdStr<'static>,args: ImportEmailAttachmentRepoArgs,) -> Result<CreateDocumentResponseData, DocumentError> {self.import_calls.lock().expect("import calls lock poisoned").push(ImportEmailAttachmentCall {- user_id: user_id.as_ref().to_string(),+ user_id: args.owner.as_ref().to_string(),email_attachment_id: args.email_attachment_id,});- Ok(create_document_response(user_id))+ Ok(create_document_response(Owner::User(args.owner)))}async fn get_document_content(@@ -372,12 +388,17 @@ impl DocumentService for FakeDocumentService {&self,_entity_access_receipt: EntityAccessReceipt<entity_access::domain::models::ViewAccessLevel>,_document_context: DocumentBasic,- _user_id: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,_document_name: String,_query_version_id: Option<i64>,_sync_version_id: Option<SyncServiceVersionID>,) -> Result<DocumentResponse, DocumentError> {- panic!("unexpected copy_document call")+ self.copy_calls+ .lock()+ .expect("copy calls lock poisoned")+ .push(principal.clone());++ Ok(create_document_response(principal.owner()).document_response)}async fn get_project_name(&self, _project_id: &str) -> Result<String, DocumentError> {@@ -393,10 +414,9 @@ impl DocumentService for FakeDocumentService {async fn handle_task_properties(&self,- _user_id: MacroUserIdStr<'static>,+ _principal: &CreationPrincipal,_document_id: &str,_request: &CreateTaskRequest,- _attribution: &activity::Attribution,) -> Result<(), DocumentError> {panic!("unexpected handle_task_properties call")}@@ -477,19 +497,18 @@ impl DocumentContentEventService for FakeDocumentService {impl DocumentCreationService for FakeDocumentService {async fn create_document(&self,- user_id: MacroUserIdStr<'static>,- args: CreateDocumentRepoArgs,+ principal: &CreationPrincipal,+ document: NewDocument,job_id: Option<String>,) -> Result<CreateDocumentResponseData, DocumentError> {- DocumentService::create_document(self, user_id, args, job_id).await+ DocumentService::create_document(self, principal, document, job_id).await}async fn handle_task_properties(&self,- _user_id: MacroUserIdStr<'static>,+ _principal: &CreationPrincipal,_document_id: &str,_request: &CreateTaskRequest,- _attribution: &activity::Attribution,) -> Result<(), DocumentError> {panic!("unexpected creation handle_task_properties call")}@@ -511,14 +530,14 @@ impl DocumentCreationService for FakeDocumentService {}}-fn create_document_response(user_id: MacroUserIdStr<'static>) -> CreateDocumentResponseData {+fn create_document_response(owner: Owner) -> CreateDocumentResponseData {CreateDocumentResponseData {document_response: DocumentResponse {document_metadata: DocumentResponseMetadataWithContent::new(DocumentResponseMetadata {document_id: "created-document".to_string(),document_version_id: 1,- owner: Owner::User(user_id),+ owner,document_name: "test document".to_string(),file_type: Some("pdf".to_string()),sha: Some("test-sha".to_string()),@@ -656,21 +675,48 @@ impl EntityAccessService for FakeEntityAccessService {async fn generate_bot_entity_access_receipt<T: RequiredPermission>(&self,- _bot_id: BotId,- _scope: BotAccessScope,- _entity_id: &str,- _entity_type: EntityType,+ bot_id: BotId,+ scope: BotAccessScope,+ entity_id: &str,+ entity_type: EntityType,) -> Result<EntityAccessReceipt<T>, AccessError> {- panic!("unexpected generate_bot_entity_access_receipt call")+ let scope = match scope {+ BotAccessScope::User { user_id, .. } => BotReceiptScope::User {+ acting_user: user_id,+ },+ BotAccessScope::Team { team_id } => BotReceiptScope::Team { team_id },+ };+ EntityAccessReceipt::try_new_bot(+ bot_id.into_storage_id(),+ scope,+ entity_access::domain::models::Entity {+ entity_id: entity_id.to_string(),+ entity_type,+ },+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Owner,+ },+ )}async fn get_access_level(&self,- _user_id: Option<&MacroUserId<Lowercase<'_>>>,- _entity_id: &str,- _entity_type: EntityType,+ user_id: Option<&MacroUserId<Lowercase<'_>>>,+ entity_id: &str,+ entity_type: EntityType,) -> Result<Option<AccessLevel>, AccessError> {- panic!("unexpected get_access_level call")+ if let Some(user_id) = user_id {+ self.document_access_calls+ .lock()+ .expect("document access calls lock poisoned")+ .push(DocumentAccessCall {+ user_id: user_id.as_ref().to_string(),+ organization_id: None,+ entity_id: entity_id.to_string(),+ entity_type,+ });+ }+ Ok(Some(AccessLevel::Owner))}async fn check_access(@@ -794,6 +840,41 @@ impl MacroAuthorizationService for FakeAuthorizationService {Ok(claims.user_id.as_deref().map(user_context))}++ async fn authorize_bot(+ &self,+ bot_token: &str,+ bot_scope: BotScope,+ acting_user: Option<BotActingUserClaims>,+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {+ if bot_token != BOT_TOKEN {+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));+ }++ Ok(BotAuthentication {+ bot_id: BotId::TEST_A,+ token_id: Uuid::nil(),+ bot_scope,+ team_id: Some(TEAM_ID),+ acting_user: acting_user+ .and_then(|claims| claims.user_id)+ .map(|user_id| MacroUserAuthentication {+ macro_user_id: user(&user_id),+ user_context: user_context(&user_id),+ }),+ })+ }+}++fn user(user_id: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(user_id.to_string()).expect("test user id should be valid")+}++fn team_bot() -> CreationPrincipal {+ CreationPrincipal::TeamBot {+ bot: NonSystemBotId::new(BotId::TEST_A).expect("test bot is not a system bot"),+ team: TEAM_ID,+ }}fn user_context(user_id: &str) -> UserContext {@@ -828,6 +909,17 @@ fn test_router() -> (Arc<FakeDocumentService>,FakeEntityAccessService,FakeAuthorizationService,+) {+ test_router_with(NonUserOwners::Disabled)+}++fn test_router_with(+ non_user_owners: NonUserOwners,+) -> (+ Router,+ Arc<FakeDocumentService>,+ FakeEntityAccessService,+ FakeAuthorizationService,) {let pool = PgPoolOptions::new().connect_lazy("postgres://postgres:postgres@localhost/documents-router-test")@@ -868,6 +960,7 @@ fn test_router() -> (lexical_client,creator,document_permission_jwt_secret: "unused-jwt-secret".to_string(),+ non_user_owners,};let router = documents_router::<FakeDocumentService,@@ -895,6 +988,16 @@ fn test_router() -> (>,),)+ .route(+ "/internal",+ axum::routing::post(+ create_document_internal_handler::<+ FakeDocumentService,+ FakeEntityAccessService,+ FakeAuthorizationService,+ >,+ ),+ ).with_state(state);(@@ -909,6 +1012,65 @@ fn create_request() -> Builder {Request::post("/").header("content-type", "application/json")}+fn internal_create_request() -> Builder {+ Request::post("/internal").header("content-type", "application/json")+}++fn with_user_bot(builder: Builder) -> Builder {+ builder+ .header(BOT_TOKEN_HEADER, BOT_TOKEN)+ .header(BOT_SCOPE_HEADER, "user")+ .header(BOT_FOR_MACRO_USER_ID_HEADER, JWT_USER_ID)+}++fn with_team_bot(builder: Builder) -> Builder {+ builder+ .header(BOT_TOKEN_HEADER, BOT_TOKEN)+ .header(BOT_SCOPE_HEADER, "team")+}++fn with_user_bot_without_acting_user(builder: Builder) -> Builder {+ builder+ .header(BOT_TOKEN_HEADER, BOT_TOKEN)+ .header(BOT_SCOPE_HEADER, "user")+}++fn with_jwt(builder: Builder) -> Builder {+ builder.header("authorization", format!("Bearer {JWT_TOKEN}"))+}++fn with_internal_caller(builder: Builder) -> Builder {+ builder+ .header(INTERNAL_API_KEY_HEADER, STANDARD_INTERNAL_KEY)+ .header(INTERNAL_MACRO_USER_ID_HEADER, STANDARD_INTERNAL_USER_ID)+}++type Authenticate = fn(Builder) -> Builder;++fn creating_callers() -> [(Authenticate, NonUserOwners, CreationPrincipal); 4] {+ [+ (+ with_jwt,+ NonUserOwners::Disabled,+ CreationPrincipal::User(user(JWT_USER_ID)),+ ),+ (+ with_user_bot,+ NonUserOwners::Disabled,+ CreationPrincipal::BotForUser {+ bot: BotId::TEST_A,+ user: user(JWT_USER_ID),+ },+ ),+ (with_team_bot, NonUserOwners::Enabled, team_bot()),+ (+ with_internal_caller,+ NonUserOwners::Disabled,+ CreationPrincipal::User(user(STANDARD_INTERNAL_USER_ID)),+ ),+ ]+}+fn request_body(email_attachment_id: Option<Uuid>) -> Body {Body::from(serde_json::to_vec(&json!({@@ -1170,7 +1332,7 @@ async fn legacy_internal_headers_reach_the_internal_only_creation_path() {let email_attachment_id = Uuid::new_v4();let (router, document_service, _access_service, authorization_service) = test_router();let request = finish_request(- create_request()+ internal_create_request().header(LEGACY_INTERNAL_API_KEY_HEADER, LEGACY_INTERNAL_KEY).header(LEGACY_INTERNAL_USER_ID_HEADER, LEGACY_INTERNAL_USER_ID),Some(email_attachment_id),@@ -1199,7 +1361,7 @@ async fn legacy_internal_headers_reach_the_internal_only_creation_path() {async fn standard_internal_headers_reach_the_document_service() {let (router, document_service, _access_service, authorization_service) = test_router();let request = finish_request(- create_request()+ internal_create_request().header(INTERNAL_API_KEY_HEADER, STANDARD_INTERNAL_KEY).header(INTERNAL_MACRO_USER_ID_HEADER, STANDARD_INTERNAL_USER_ID),None,@@ -1211,7 +1373,7 @@ async fn standard_internal_headers_reach_the_document_service() {assert_eq!(document_service.create_calls(),[CreateDocumentCall {- user_id: STANDARD_INTERNAL_USER_ID.to_string(),+ principal: CreationPrincipal::User(user(STANDARD_INTERNAL_USER_ID)),}]);assert!(document_service.import_calls().is_empty());@@ -1227,7 +1389,7 @@ async fn standard_internal_headers_reach_the_document_service() {async fn standard_internal_headers_take_precedence_over_legacy_headers() {let (router, document_service, _access_service, authorization_service) = test_router();let request = finish_request(- create_request()+ internal_create_request().header(INTERNAL_API_KEY_HEADER, STANDARD_INTERNAL_KEY).header(INTERNAL_MACRO_USER_ID_HEADER, STANDARD_INTERNAL_USER_ID).header(LEGACY_INTERNAL_API_KEY_HEADER, LEGACY_INTERNAL_KEY)@@ -1241,7 +1403,7 @@ async fn standard_internal_headers_take_precedence_over_legacy_headers() {assert_eq!(document_service.create_calls(),[CreateDocumentCall {- user_id: STANDARD_INTERNAL_USER_ID.to_string(),+ principal: CreationPrincipal::User(user(STANDARD_INTERNAL_USER_ID)),}]);assert!(document_service.import_calls().is_empty());@@ -1274,3 +1436,163 @@ async fn jwt_user_cannot_create_a_document_for_an_email_attachment() {assert!(document_service.create_calls().is_empty());assert!(document_service.import_calls().is_empty());}++#[tokio::test]+async fn public_create_records_the_resolved_creation_principal() {+ for (authenticate, non_user_owners, principal) in creating_callers() {+ let (router, document_service, _access_service, _authorization_service) =+ test_router_with(non_user_owners);+ let request = finish_request(authenticate(create_request()), None);++ let (status, _body) = send(&router, request).await;++ assert_eq!(status, StatusCode::OK, "{principal:?}");+ assert_eq!(+ document_service.create_calls(),+ [CreateDocumentCall { principal }]+ );+ }+}++#[tokio::test]+async fn copy_records_the_resolved_creation_principal() {+ for (authenticate, non_user_owners, principal) in creating_callers() {+ let (router, document_service, _access_service, _authorization_service) =+ test_router_with(non_user_owners);+ let request = authenticate(+ Request::post("/copy-source/copy").header("content-type", "application/json"),+ )+ .body(Body::from(json!({ "documentName": "copy" }).to_string()))+ .expect("request should build");++ let (status, _body) = send(&router, request).await;++ assert_eq!(status, StatusCode::OK, "{principal:?}");+ assert_eq!(document_service.copy_calls(), [principal]);+ }+}++#[tokio::test]+async fn create_routes_reject_callers_that_cannot_create_before_reading_the_body() {+ let callers: [Authenticate; 2] = [with_team_bot, with_user_bot_without_acting_user];++ for path in [+ "/",+ "/create_markdown",+ "/create_task",+ "/create_snippet",+ "/create_skill",+ "/copy-source/copy",+ ] {+ for authenticate in callers {+ let (router, document_service, _access_service, _authorization_service) = test_router();+ let request =+ authenticate(Request::post(path).header("content-type", "application/json"))+ .body(Body::from("not json"))+ .expect("request should build");++ let (status, body) = send(&router, request).await;++ assert_eq!(+ (status, body),+ (StatusCode::FORBIDDEN, json!({ "message": "forbidden" })),+ "{path}"+ );+ assert!(document_service.create_calls().is_empty());+ assert!(document_service.copy_calls().is_empty());+ }+ }+}++#[tokio::test]+async fn internal_create_routes_reach_body_extraction() {+ for path in [+ "/",+ "/create_markdown",+ "/create_task",+ "/create_snippet",+ "/create_skill",+ "/copy-source/copy",+ ] {+ let (router, document_service, _access_service, _authorization_service) = test_router();+ let request =+ with_internal_caller(Request::post(path).header("content-type", "application/json"))+ .body(Body::from("not json"))+ .expect("request should build");++ assert_eq!(+ send_status(&router, request).await,+ StatusCode::BAD_REQUEST,+ "{path}"+ );+ assert!(document_service.create_calls().is_empty());+ assert!(document_service.copy_calls().is_empty());+ }+}++#[tokio::test]+async fn internal_create_makes_the_calling_user_the_owner() {+ let (router, document_service, _access_service, _authorization_service) = test_router();+ let request = finish_request(with_jwt(internal_create_request()), None);++ let (status, _body) = send(&router, request).await;++ assert_eq!(status, StatusCode::OK);+ assert_eq!(+ document_service.create_calls(),+ [CreateDocumentCall {+ principal: CreationPrincipal::User(user(JWT_USER_ID)),+ }]+ );+}++#[tokio::test]+async fn internal_create_imports_email_attachments_only_for_internal_callers() {+ let email_attachment_id = Uuid::new_v4();+ let (router, document_service, _access_service, _authorization_service) = test_router();++ let from_user = finish_request(+ with_jwt(internal_create_request()),+ Some(email_attachment_id),+ );+ assert_eq!(+ send(&router, from_user).await,+ (+ StatusCode::UNAUTHORIZED,+ json!({ "message": "unauthorized" })+ )+ );+ assert!(document_service.import_calls().is_empty());++ let from_internal = finish_request(+ with_internal_caller(internal_create_request()),+ Some(email_attachment_id),+ );+ let (status, _body) = send(&router, from_internal).await;++ assert_eq!(status, StatusCode::OK);+ assert_eq!(+ document_service.import_calls(),+ [ImportEmailAttachmentCall {+ user_id: STANDARD_INTERNAL_USER_ID.to_string(),+ email_attachment_id,+ }]+ );+ assert!(document_service.create_calls().is_empty());+}++#[tokio::test]+async fn internal_create_rejects_bots() {+ let (router, document_service, _access_service, _authorization_service) =+ test_router_with(NonUserOwners::Enabled);++ for authenticate in [with_user_bot as Authenticate, with_team_bot] {+ let request = finish_request(authenticate(internal_create_request()), None);++ assert_eq!(+ send(&router, request).await,+ (StatusCode::FORBIDDEN, json!({ "message": "forbidden" }))+ );+ }+ assert!(document_service.create_calls().is_empty());+}diff --git a/crates/documents/src/inbound/toolset.rs b/crates/documents/src/inbound/toolset.rsindex aa48614717..f6793f3576 100644--- a/crates/documents/src/inbound/toolset.rs+++ b/crates/documents/src/inbound/toolset.rs@@ -40,7 +40,6 @@ use crate::{lexical_comment_marks::LexicalCommentMarks, markdown_init::LexicalSyncMarkdownInitializer,},};-use activity::{Actor, Attribution};use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};use bot_id::BotId;use entity_access::domain::{@@ -50,6 +49,7 @@ use entity_access::domain::{use lexical_client::LexicalClient;use macro_user_id::user_id::MacroUserIdStr;use messages::domain::{api::MessageServiceApi, ports::MessageError, service::MessageWrite};+use model_owner::CreationPrincipal;use std::sync::Arc;use sync_service_client::SyncServiceClient;use uuid::Uuid;@@ -241,9 +241,12 @@ impl<.map_err(comment_access_error)}- /// Attribution for a write these tools make for `user`.- pub fn attribution(&self, user: MacroUserIdStr<'static>) -> Attribution {- Attribution::delegated(Actor::new_from_bot(self.actor), user)+ /// Who these tools create entities as when acting for `user`.+ pub fn creation_principal(&self, user: MacroUserIdStr<'static>) -> CreationPrincipal {+ CreationPrincipal::BotForUser {+ bot: self.actor,+ user,+ }}}diff --git a/crates/documents/src/inbound/toolset/create_document.rs b/crates/documents/src/inbound/toolset/create_document.rsindex 4b566a93bd..8f86107964 100644--- a/crates/documents/src/inbound/toolset/create_document.rs+++ b/crates/documents/src/inbound/toolset/create_document.rs@@ -135,8 +135,8 @@ whereNone};- let mut metadata_builder = NewDocumentMetadata::builder(self.document_name.clone())- .attribution(service_context.attribution(user_id.clone()));+ let principal = service_context.creation_principal(user_id);+ let mut metadata_builder = NewDocumentMetadata::builder(self.document_name.clone());if let Some(project_id) = self.project_id {metadata_builder = metadata_builder.project_id(project_id);}@@ -147,7 +147,7 @@ where"Create spreadsheets with empty fileContent and isTask false, then use ReadSpreadsheet and EditSpreadsheet to populate the workbook".to_string(),)));}- service_context.creator.create_spreadsheet(user_id, metadata_builder.build()).await+ service_context.creator.create_spreadsheet(&principal, metadata_builder.build()).await} else {let document = NewPlainTextDocument::builder(metadata_builder.build()).file_type(parsed_file_type)@@ -155,7 +155,7 @@ where.task_flag(self.is_task, maybe_team).build().map_err(failed_to_create_document)?;- service_context.creator.create_plain_text(user_id, document).await+ service_context.creator.create_plain_text(&principal, document).await}.map(|document| document.into_response()).map_err(failed_to_create_document)?;diff --git a/crates/documents/src/inbound/toolset/edit_document/test.rs b/crates/documents/src/inbound/toolset/edit_document/test.rsindex 00c6035824..af9b2269c2 100644--- a/crates/documents/src/inbound/toolset/edit_document/test.rs+++ b/crates/documents/src/inbound/toolset/edit_document/test.rs@@ -5,9 +5,9 @@ use std::sync::{Arc, Mutex};use crate::domain::content::DocumentContent;use crate::domain::events::InteractionReason;use crate::domain::models::{- CreateDocumentRepoArgs, CreateTaskRequest, DocumentError, DocumentTeamShareResponse,- EditDocumentServiceArgs, GithubPullRequestsResponse, ImportEmailAttachmentRepoArgs,- LocationQueryParams, TaskBranchName,+ CreateTaskRequest, DocumentError, DocumentTeamShareResponse, EditDocumentServiceArgs,+ GithubPullRequestsResponse, ImportEmailAttachmentRepoArgs, LocationQueryParams, NewDocument,+ TaskBranchName,};use crate::domain::permission_token::decode_permission_token;use crate::domain::ports::editing::{@@ -25,7 +25,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 model_owner::{CreationPrincipal, Owner};use sync_service_client::SyncServiceClient;use uuid::Uuid;@@ -118,8 +118,8 @@ impl DocumentService for FakeDocumentService {async fn create_document(&self,- _user_id: MacroUserIdStr<'static>,- _args: CreateDocumentRepoArgs,+ _principal: &CreationPrincipal,+ _document: NewDocument,_job_id: Option<String>,) -> Result<CreateDocumentResponseData, DocumentError> {panic!("unexpected create_document call")@@ -127,7 +127,6 @@ impl DocumentService for FakeDocumentService {async fn import_email_attachment(&self,- _user_id: MacroUserIdStr<'static>,_args: ImportEmailAttachmentRepoArgs,) -> Result<CreateDocumentResponseData, DocumentError> {panic!("unexpected import_email_attachment call")@@ -177,7 +176,7 @@ impl DocumentService for FakeDocumentService {&self,_entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,_document_context: DocumentBasic,- _user_id: MacroUserIdStr<'static>,+ _principal: &CreationPrincipal,_document_name: String,_query_version_id: Option<i64>,_sync_version_id: Option<SyncServiceVersionID>,@@ -198,10 +197,9 @@ impl DocumentService for FakeDocumentService {async fn handle_task_properties(&self,- _user_id: MacroUserIdStr<'static>,+ _principal: &CreationPrincipal,_document_id: &str,_request: &CreateTaskRequest,- _attribution: &activity::Attribution,) -> Result<(), DocumentError> {panic!("unexpected handle_task_properties call")}@@ -241,8 +239,8 @@ impl DocumentService for FakeDocumentService {impl DocumentCreationService for FakeDocumentService {async fn create_document(&self,- _user_id: MacroUserIdStr<'static>,- _args: CreateDocumentRepoArgs,+ _principal: &CreationPrincipal,+ _document: NewDocument,_job_id: Option<String>,) -> Result<CreateDocumentResponseData, DocumentError> {panic!("unexpected create_document call")@@ -250,10 +248,9 @@ impl DocumentCreationService for FakeDocumentService {async fn handle_task_properties(&self,- _user_id: MacroUserIdStr<'static>,+ _principal: &CreationPrincipal,_document_id: &str,_request: &CreateTaskRequest,- _attribution: &activity::Attribution,) -> Result<(), DocumentError> {panic!("unexpected handle_task_properties call")}@@ -813,23 +810,22 @@ fn editor_name_is_trimmed_and_never_blank() {}#[test]-fn tool_writes_are_delegated_from_the_context_actor_to_the_requesting_user() {+fn tool_creations_are_made_by_the_context_actor_for_the_requesting_user() {let user = MacroUserIdStr::try_from(TEST_USER_ID.to_string()).expect("valid user");let default_context =tool_context(FakeDocumentService::new("md"), FakeEditingWorker::default());assert_eq!(default_context.actor, bot_id::MACRO_AI_BOT_ID);- let attribution = default_context+ let principal = default_context.0.with_actor(BotId::TEST_A)- .attribution(user);+ .creation_principal(user.clone());assert_eq!(- attribution.actor().as_ref(),- BotId::TEST_A.into_storage_id().as_ref()- );- assert_eq!(- attribution.on_behalf_of().as_ref().map(|id| id.as_ref()),- Some(TEST_USER_ID)+ principal,+ CreationPrincipal::BotForUser {+ bot: BotId::TEST_A,+ user,+ });}diff --git a/crates/documents/src/inbound/toolset/upload_file.rs b/crates/documents/src/inbound/toolset/upload_file.rsindex 4b5cd13ad1..81435b5e9e 100644--- a/crates/documents/src/inbound/toolset/upload_file.rs+++ b/crates/documents/src/inbound/toolset/upload_file.rs@@ -133,12 +133,11 @@ wherelet created = service_context.creator.upload_file(- request_context.user_id.clone(),+ &service_context.creation_principal(request_context.user_id),NewFileUpload {file_name: self.file_name.clone(),bytes,project,- attribution: service_context.attribution(request_context.user_id),},).awaitdiff --git a/crates/documents/src/outbound/mention_tracker.rs b/crates/documents/src/outbound/mention_tracker.rsindex 1481064b1b..367eb101a8 100644--- a/crates/documents/src/outbound/mention_tracker.rs+++ b/crates/documents/src/outbound/mention_tracker.rs@@ -26,7 +26,7 @@ impl DocumentMentionTrackingPort for LexicalCommsMentionTracker {async fn track_document_mentions(&self,document_id: &str,- user_id: &MacroUserIdStr<'static>,+ user_id: Option<&MacroUserIdStr<'static>>,markdown: &str,) -> anyhow::Result<()> {if markdown.trim().is_empty() {@@ -52,7 +52,7 @@ impl DocumentMentionTrackingPort for LexicalCommsMentionTracker {&self.db,"document",document_id,- Some(user_id.as_ref()),+ user_id.map(|user| user.as_ref()),&mentions,).await?;diff --git a/crates/documents/src/outbound/pg_document_repo.rs b/crates/documents/src/outbound/pg_document_repo.rsindex 3724ec03bb..e24994bea5 100644--- a/crates/documents/src/outbound/pg_document_repo.rs+++ b/crates/documents/src/outbound/pg_document_repo.rs@@ -12,10 +12,12 @@ mod markdown_backfill;mod share;use document_sub_type::DocumentSubType;+use entity_registry::BotFacts;+use entity_registry_db_utils::{NewEntityRecord, OwnedEntityRegistrar, RegisteredEntityType};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 models_permissions::share_permission::{LinkShare, SharePermissionV2, TeamLinkShareDefault};use sqlx::PgPool;use model_entity::{Entity, EntityType};@@ -25,20 +27,26 @@ use crate::domain::content::{DocumentContent, DocumentContentState};use crate::domain::models::{BranchNameContext, CopyDocumentRepoArgs, CreateDocumentRepoArgs, DocumentError,DocumentTeamShare, EditDocumentRepoArgs, EmailImportRepoOutcome, ImportEmailAttachmentRepoArgs,- TeamTaskMetadata,+ OwnerTeam, TeamTaskMetadata,};use crate::domain::ports::DocumentRepo;+pub use markdown_backfill::PgMarkdownBackfillRepo;+/// PostgreSQL-backed document repository.#[derive(Clone)]-pub struct PgDocumentRepo {+pub struct PgDocumentRepo<B> {pool: PgPool,+ registrar: OwnedEntityRegistrar<B>,}-impl PgDocumentRepo {+impl<B: BotFacts + 'static> PgDocumentRepo<B> {/// Create a new repository backed by the given connection pool.- pub fn new(pool: PgPool) -> Self {- Self { pool }+ ///+ /// Created and copied documents register their owner grants through+ /// `registrar`.+ pub fn new(pool: PgPool, registrar: OwnedEntityRegistrar<B>) -> Self {+ Self { pool, registrar }}async fn reused_email_document(@@ -116,7 +124,7 @@ fn registry_protocol_error(sqlx::Error::Protocol(error.to_string())}-impl DocumentRepo for PgDocumentRepo {+impl<B: BotFacts + 'static> DocumentRepo for PgDocumentRepo<B> {type Err = sqlx::Error;#[tracing::instrument(err, skip(self))]@@ -467,11 +475,23 @@ impl DocumentRepo for PgDocumentRepo {}#[tracing::instrument(err, skip(self))]- async fn get_team_default_link_share(- &self,- user_id: &str,- ) -> Result<Option<TeamLinkShareDefault>, Self::Err> {- share_permission_db_utils::get_team_default_link_share(&self.pool, user_id).await+ async fn get_owner_team(&self, owner: &Owner) -> Result<Option<OwnerTeam>, Self::Err> {+ let row = sqlx::query!(+ r#"+ SELECT t.id AS "team_id!", t.default_link_share AS "default_link_share?: LinkShare"+ FROM owner_team($1) ot+ JOIN team t ON t.id = ot.team_id+ LIMIT 1+ "#,+ owner.principal_id(),+ )+ .fetch_optional(&self.pool)+ .await?;++ Ok(row.map(|row| OwnerTeam {+ team_id: row.team_id,+ default_link_share: TeamLinkShareDefault(row.default_link_share),+ }))}#[tracing::instrument(err, skip(self, args, share_permission))]@@ -482,7 +502,8 @@ impl DocumentRepo for PgDocumentRepo {) -> Result<DocumentMetadata, DocumentError> {let mut transaction = self.pool.begin().await?;let metadata =- create::insert_new_document(&mut transaction, args, &share_permission).await?;+ create::insert_new_document(&mut transaction, &self.registrar, args, &share_permission)+ .await?;transaction.commit().await?;Ok(metadata)}@@ -495,10 +516,11 @@ impl DocumentRepo for PgDocumentRepo {) -> Result<EmailImportRepoOutcome, DocumentError> {let ImportEmailAttachmentRepoArgs {email_attachment_id,- mut create,+ owner,+ mut document,} = args;// Imports do not carry task-creation consent, including reuse paths.- create.share_with_team = false;+ document.share_with_team = false;// Unlocked reuse: attachment already linked, or a live email doc with// this sha already exists. The advisory lock is only required when a@@ -509,8 +531,10 @@ impl DocumentRepo for PgDocumentRepo {return self.reused_email_document(existing_id).await;}+ let owner = Owner::User(owner);+ let owner_principal = owner.principal_id();if let Some(existing_id) = self- .find_reusable_email_document_by_sha(create.user_id.as_ref(), &create.sha)+ .find_reusable_email_document_by_sha(&owner_principal, &document.sha).await?{return self@@ -522,8 +546,8 @@ impl DocumentRepo for PgDocumentRepo {if let Some(existing_id) = create::reuse_email_document(&mut transaction,- create.user_id.as_ref(),- &create.sha,+ &owner_principal,+ &document.sha,email_attachment_id,).await?@@ -532,8 +556,13 @@ impl DocumentRepo for PgDocumentRepo {return self.reused_email_document(existing_id).await;}- let metadata =- create::insert_new_document(&mut transaction, create, &share_permission).await?;+ let metadata = create::insert_new_document(+ &mut transaction,+ &self.registrar,+ CreateDocumentRepoArgs { owner, document },+ &share_permission,+ )+ .await?;match create::link_document_email(&mut transaction,@@ -1086,7 +1115,7 @@ impl DocumentRepo for PgDocumentRepo {) -> Result<DocumentMetadata, Self::Err> {let CopyDocumentRepoArgs {original_document,- user_id,+ owner,document_name,file_type,team_id,@@ -1099,7 +1128,7 @@ impl DocumentRepo for PgDocumentRepo {copy::copy_docx_document(&mut transaction,&original_document,- user_id.clone(),+ &owner,&document_name,).await@@ -1108,7 +1137,7 @@ impl DocumentRepo for PgDocumentRepo {copy::copy_non_docx_document(&mut transaction,&original_document,- user_id.clone(),+ &owner,&document_name,).await@@ -1126,29 +1155,16 @@ impl DocumentRepo for PgDocumentRepo {create::set_share_permission(&mut transaction, &document_id, &share_permission).await?;- entity_access_db_utils::insert_entity_access_row(- &mut transaction,- &document_id,- entity_access_db_utils::EntityType::Document,- user_id.as_ref(),- entity_access_db_utils::EntityAccessSourceType::User,- entity_access_db_utils::AccessLevel::Owner,- )- .await?;-- entity_registry_db_utils::insert_entity(- &mut transaction,- entity_registry_db_utils::NewEntityRecord::new(- document_id,- entity_registry_db_utils::RegisteredEntityType::Document,- model_owner::Owner::User(user_id.clone()),- ),- )- .await- .map_err(registry_protocol_error)?;+ self.registrar+ .register_owned_entity(+ &mut transaction,+ NewEntityRecord::new(document_id, RegisteredEntityType::Document, owner.clone()),+ )+ .await+ .map_err(registry_protocol_error)?;let now = chrono::Utc::now();- create::insert_history(&mut transaction, &document_id, &user_id, &now).await?;+ create::insert_history(&mut transaction, &document_id, owner.as_user(), &now).await?;transaction.commit().await?;diff --git a/crates/documents/src/outbound/pg_document_repo/copy.rs b/crates/documents/src/outbound/pg_document_repo/copy.rsindex 7aae82f38c..bfb67a4aa7 100644--- a/crates/documents/src/outbound/pg_document_repo/copy.rs+++ b/crates/documents/src/outbound/pg_document_repo/copy.rs@@ -1,4 +1,3 @@-use macro_user_id::user_id::MacroUserIdStr;use model::document::{BomPart, DocumentMetadata, IDWithTimeStamps, SaveBomPart, VersionIDWithTimeStamps,VersionIDWithTimeStampsNoSha,@@ -11,7 +10,7 @@ use sqlx::{Postgres, Transaction};pub async fn copy_docx_document(transaction: &mut Transaction<'_, Postgres>,original_document: &DocumentMetadata,- user_id: MacroUserIdStr<'static>,+ owner: &Owner,new_document_name: &str,) -> Result<DocumentMetadata, sqlx::Error> {let original_document_id = &original_document.document_id;@@ -24,7 +23,7 @@ pub async fn copy_docx_document(VALUES ($1, $2, $3, $4, $5, $6, $7)RETURNING id, "createdAt"::timestamptz as created_at, "updatedAt"::timestamptz as updated_at;"#,- user_id.as_ref(),+ owner.principal_id(),new_document_name,original_document.file_type,original_document.document_family_id,@@ -34,10 +33,7 @@ pub async fn copy_docx_document().fetch_one(transaction.as_mut()).await- .map_err(|err| {- tracing::error!(error=?err, "unable to copy document");- map_insert_document_error(err)- })?;+ .map_err(insert_document_error)?;let document_bom = sqlx::query_as!(VersionIDWithTimeStampsNoSha,@@ -74,7 +70,7 @@ pub async fn copy_docx_document(Ok(DocumentMetadata {document_id: document.id.clone(),- owner: Owner::User(user_id),+ owner: owner.clone(),document_name: new_document_name.to_string(),file_type: original_document.file_type.clone(),sha: None,@@ -98,7 +94,7 @@ pub async fn copy_docx_document(pub async fn copy_non_docx_document(transaction: &mut Transaction<'_, Postgres>,original_document: &DocumentMetadata,- user_id: MacroUserIdStr<'static>,+ owner: &Owner,new_document_name: &str,) -> Result<DocumentMetadata, sqlx::Error> {let original_document_id = &original_document.document_id;@@ -116,7 +112,7 @@ pub async fn copy_non_docx_document(VALUES ($1, $2, $3, $4, $5, $6, $7)RETURNING id, "createdAt"::timestamptz as created_at, "updatedAt"::timestamptz as updated_at;"#,- user_id.as_ref(),+ owner.principal_id(),new_document_name,original_document.file_type,original_document.document_family_id,@@ -126,10 +122,7 @@ pub async fn copy_non_docx_document().fetch_one(transaction.as_mut()).await- .map_err(|err| {- tracing::error!(error=?err, "unable to copy document");- map_insert_document_error(err)- })?;+ .map_err(insert_document_error)?;let document_instance = sqlx::query_as!(VersionIDWithTimeStamps,@@ -189,7 +182,7 @@ pub async fn copy_non_docx_document(Ok(DocumentMetadata {document_id: document.id.clone(),- owner: Owner::User(user_id),+ owner: owner.clone(),document_name: new_document_name.to_string(),file_type: original_document.file_type.clone(),sha: Some(document_instance.sha),@@ -283,11 +276,7 @@ async fn create_bom_parts(Ok(saved_bom_parts)}-fn map_insert_document_error(err: sqlx::Error) -> sqlx::Error {- let no_user_found = "error returned from database: insert or update on table \"Document\" violates foreign key constraint \"Document_owner_fkey\"";- let err_string = err.to_string();- if err_string.contains(no_user_found) {- return sqlx::Error::Protocol("no user found".to_string());- }+fn insert_document_error(err: sqlx::Error) -> sqlx::Error {+ tracing::error!(error=?err, "unable to copy document");sqlx::Error::Protocol("unable to copy document".to_string())}diff --git a/crates/documents/src/outbound/pg_document_repo/create.rs b/crates/documents/src/outbound/pg_document_repo/create.rsindex 0702afc3cd..a245e6688d 100644--- a/crates/documents/src/outbound/pg_document_repo/create.rs+++ b/crates/documents/src/outbound/pg_document_repo/create.rs@@ -1,4 +1,6 @@use document_sub_type::DocumentSubType;+use entity_registry::BotFacts;+use entity_registry_db_utils::{NewEntityRecord, OwnedEntityRegistrar, RegisteredEntityType};use macro_user_id::user_id::MacroUserIdStr;use model::document::{DocumentMetadata, FileType, VersionIDWithTimeStamps};use model_owner::Owner;@@ -6,15 +8,15 @@ use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::team_share::TeamShareCreation;use share_permission_db_utils::team_share::{self, TeamShareError};-use crate::domain::models::{CreateDocumentRepoArgs, DocumentError};+use crate::domain::models::{CreateDocumentRepoArgs, DocumentError, NewDocument};/// Inserts a record into the document table/// Returns the document id#[tracing::instrument(skip(transaction), err)]-pub async fn insert_document_row<'a>(+pub async fn insert_document_row(transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,document_id: Option<&uuid::Uuid>,- user_id: &MacroUserIdStr<'a>,+ owner: &Owner,document_name: &str,file_type: Option<FileType>,project_id: Option<&uuid::Uuid>,@@ -31,7 +33,7 @@ pub async fn insert_document_row<'a>(VALUES ($1, $2, $3, $4, $5, $6, $6)"#,&document_id.to_string(),- user_id.as_ref(),+ owner.principal_id(),document_name,file_type.map(|ft| ft.as_str().to_string()),project_id.map(|s| s.to_string()),@@ -197,28 +199,30 @@ pub async fn set_share_permission(Ok(())}-/// Set user history+/// Records the document's last access, and `history_user`'s history when set.#[tracing::instrument(skip(transaction), err)]-pub async fn insert_history<'a>(+pub async fn insert_history(transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,document_id: &uuid::Uuid,- user_id: &MacroUserIdStr<'a>,+ history_user: Option<&MacroUserIdStr<'_>>,created_at: &chrono::DateTime<chrono::Utc>,) -> Result<(), sqlx::Error> {- sqlx::query!(- r#"+ if let Some(user_id) = history_user {+ sqlx::query!(+ r#"INSERT INTO "UserHistory" ("userId", "itemId", "itemType", "createdAt", "updatedAt")VALUES ($1, $2, $3, $4, $4)ON CONFLICT ("userId", "itemId", "itemType") DO UPDATESET "updatedAt" = $4"#,- user_id.as_ref(),- &document_id.to_string(),- "document",- created_at.naive_utc()- )- .execute(transaction.as_mut())- .await?;+ user_id.as_ref(),+ &document_id.to_string(),+ "document",+ created_at.naive_utc()+ )+ .execute(transaction.as_mut())+ .await?;+ }sqlx::query!(r#"@@ -381,17 +385,18 @@ pub async fn reuse_email_document(////// Does not link email attachments. Callers that need that belong on/// [`crate::domain::ports::DocumentRepo::import_email_attachment_document`].-#[tracing::instrument(skip(transaction, args, share_permission), err)]-pub async fn insert_new_document(+#[tracing::instrument(skip(transaction, registrar, args, share_permission), err)]+pub async fn insert_new_document<B: BotFacts>(transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ registrar: &OwnedEntityRegistrar<B>,args: CreateDocumentRepoArgs,share_permission: &SharePermissionV2,) -> Result<DocumentMetadata, DocumentError> {- let CreateDocumentRepoArgs {+ let CreateDocumentRepoArgs { owner, document } = args;+ let NewDocument {id,sha,document_name,- user_id,file_type,project_id,team_id,@@ -399,9 +404,8 @@ pub async fn insert_new_document(created_at: provided_created_at,sub_type: requested_sub_type,skip_history,- attribution: _,initial_link_share: _,- } = args;+ } = document;let now = chrono::Utc::now();let created_at = provided_created_at.as_ref().unwrap_or(&now);@@ -420,7 +424,7 @@ pub async fn insert_new_document(let document_id = insert_document_row(transaction,id.as_ref(),- &user_id,+ &owner,&document_name,file_type,project_id.as_ref(),@@ -443,29 +447,16 @@ pub async fn insert_new_document(set_share_permission(transaction, &document_id, share_permission).await?;if !skip_history {- insert_history(transaction, &document_id, &user_id, created_at).await?;+ insert_history(transaction, &document_id, owner.as_user(), created_at).await?;}- entity_access_db_utils::insert_entity_access_row(- transaction,- &document_id,- entity_access_db_utils::EntityType::Document,- user_id.as_ref(),- entity_access_db_utils::EntityAccessSourceType::User,- entity_access_db_utils::AccessLevel::Owner,- )- .await?;-- entity_registry_db_utils::insert_entity(- transaction,- entity_registry_db_utils::NewEntityRecord::new(- document_id,- entity_registry_db_utils::RegisteredEntityType::Document,- model_owner::Owner::User(user_id.clone()),- ),- )- .await- .map_err(|error| DocumentError::Internal(error.into()))?;+ registrar+ .register_owned_entity(+ transaction,+ NewEntityRecord::new(document_id, RegisteredEntityType::Document, owner.clone()),+ )+ .await+ .map_err(|error| DocumentError::Internal(error.into()))?;if share_with_team {let document_id_string = document_id.to_string();@@ -483,7 +474,7 @@ pub async fn insert_new_document(Ok(DocumentMetadata::new_document(&document_id.to_string(),document_version.id,- Owner::User(user_id),+ owner,&document_name,file_type,&document_version.sha,diff --git a/crates/documents/src/outbound/pg_document_repo/markdown_backfill.rs b/crates/documents/src/outbound/pg_document_repo/markdown_backfill.rsindex aeba23243b..2bb1f94971 100644--- a/crates/documents/src/outbound/pg_document_repo/markdown_backfill.rs+++ b/crates/documents/src/outbound/pg_document_repo/markdown_backfill.rs@@ -2,11 +2,24 @@use anyhow::Context as _;use model_owner::Owner;+use sqlx::PgPool;use crate::domain::markdown_backfill::{MarkdownBackfillCandidate, MarkdownBackfillRepo};-use crate::outbound::pg_document_repo::PgDocumentRepo;-impl MarkdownBackfillRepo for PgDocumentRepo {+/// PostgreSQL-backed markdown backfill repository.+#[derive(Clone)]+pub struct PgMarkdownBackfillRepo {+ pool: PgPool,+}++impl PgMarkdownBackfillRepo {+ /// Create a new repository backed by the given connection pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++impl MarkdownBackfillRepo for PgMarkdownBackfillRepo {#[tracing::instrument(err, skip(self))]#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]async fn fetch_markdown_backfill_candidates(diff --git a/crates/documents/src/outbound/pg_document_repo/tests.rs b/crates/documents/src/outbound/pg_document_repo/tests.rsindex 10981a58a1..e2a029a849 100644--- a/crates/documents/src/outbound/pg_document_repo/tests.rs+++ b/crates/documents/src/outbound/pg_document_repo/tests.rs@@ -1,3 +1,5 @@+use entity_registry::{BotFacts, EntityRegistryResult, OwnerGrantPolicy};+use entity_registry_db_utils::OwnedEntityRegistrar;use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::cowlike::CowLike;use model_entity::EntityType;@@ -14,7 +16,7 @@ use sqlx::{Pool, Postgres, Row};use crate::domain::models::{CopyDocumentRepoArgs, CreateDocumentRepoArgs, EditDocumentRepoArgs, EmailImportRepoOutcome,FileTypeUpdate, GithubPullRequest, GithubPullRequestsResponse, ImportEmailAttachmentRepoArgs,- InitialLinkShare,+ InitialLinkShare, NewDocument,};use crate::domain::ports::DocumentRepo;use crate::outbound::pg_document_repo::PgDocumentRepo;@@ -22,8 +24,43 @@ use models_permissions::share_permission::team_share::{TeamShareGrant, TeamShareLevel, TeamShareRequest, authorize_team_share,};+#[derive(Clone)]+struct SponsoredByOwner;++impl BotFacts for SponsoredByOwner {+ async fn sponsor(&self, _bot: bot_id::BotId) -> EntityRegistryResult<Option<Owner>> {+ Ok(Some(Owner::User(user_id(TEST_DOCUMENT_OWNER_ID))))+ }+}++type TestRepo = PgDocumentRepo<SponsoredByOwner>;++fn test_repo(pool: Pool<Postgres>) -> TestRepo {+ PgDocumentRepo::new(+ pool,+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(SponsoredByOwner)),+ )+}++#[derive(Clone)]+struct SponsoredByTeam(uuid::Uuid);++impl BotFacts for SponsoredByTeam {+ async fn sponsor(&self, _bot: bot_id::BotId) -> EntityRegistryResult<Option<Owner>> {+ Ok(Some(Owner::Team(self.0)))+ }+}++fn team_bot_repo(pool: Pool<Postgres>, team_id: uuid::Uuid) -> PgDocumentRepo<SponsoredByTeam> {+ let facts = SponsoredByTeam(team_id);+ PgDocumentRepo::new(+ pool,+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(facts)),+ )+}+async fn set_legacy_team_share(- repo: &PgDocumentRepo,+ repo: &TestRepo,document_id: &str,enabled: bool,) -> Result<crate::domain::models::DocumentTeamShare, crate::domain::models::DocumentError> {@@ -42,7 +79,7 @@ async fn set_legacy_team_share(repo.set_team_share(command).await}-async fn set_comment_share(repo: &PgDocumentRepo) {+async fn set_comment_share(repo: &TestRepo) {let facts = repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap();let command = authorize_team_share(facts.owner.as_user(),@@ -58,7 +95,7 @@ async fn set_comment_share(repo: &PgDocumentRepo) {repo.set_team_share(command).await.unwrap();}-async fn team_edit_args(repo: &PgDocumentRepo, level: Option<AccessLevel>) -> EditDocumentRepoArgs {+async fn team_edit_args(repo: &TestRepo, level: Option<AccessLevel>) -> EditDocumentRepoArgs {let facts = repo.get_team_share_facts(TEST_DOCUMENT_ID).await.unwrap();let command = authorize_team_share(facts.owner.as_user(),@@ -96,7 +133,7 @@ async fn team_edit_args(repo: &PgDocumentRepo, level: Option<AccessLevel>) -> Edfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn team_edit_exact_levels_omission_and_legacy_preservation(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let mut revision = 0;for level in [AccessLevel::Edit, AccessLevel::Comment, AccessLevel::View] {let args = team_edit_args(&repo, Some(level)).await;@@ -182,7 +219,7 @@ async fn team_edit_exact_levels_omission_and_legacy_preservation(pool: Pool<Postfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn team_edit_stale_command_rolls_back_accompanying_changes(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let args = team_edit_args(&repo, Some(AccessLevel::View)).await;set_legacy_team_share(&repo, TEST_DOCUMENT_ID, true).await@@ -218,7 +255,7 @@ async fn team_edit_stale_command_rolls_back_accompanying_changes(pool: Pool<Postfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn team_edit_channel_failure_rolls_back_metadata_permissions_and_grant(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());insert_non_owner_user_access(&pool).await;let args = team_edit_args(&repo, Some(AccessLevel::View)).await;let before = repo.get_basic_document(TEST_DOCUMENT_ID).await.unwrap();@@ -269,7 +306,7 @@ async fn team_edit_channel_failure_rolls_back_metadata_permissions_and_grant(poofixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn inherited_team_grant_does_not_enable_explicit_toggle(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());sqlx::query!(r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)VALUES ($1, 'document', $2, 'team', 'owner', $3)"#,@@ -308,14 +345,14 @@ async fn inherited_team_grant_does_not_enable_explicit_toggle(pool: Pool<Postgrefixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn creation_team_consent_is_explicit_and_uses_owner_membership(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());for subtype in [None,Some(document_sub_type::DocumentSubType::Task),Some(document_sub_type::DocumentSubType::Snippet),] {let mut args = create_document_args(TEST_DOCUMENT_OWNER_ID, false, None);- args.sub_type = subtype;+ args.document.sub_type = subtype;let document = repo.create_document(args, md_share_permission()).await@@ -330,7 +367,7 @@ async fn creation_team_consent_is_explicit_and_uses_owner_membership(pool: Pool<insert_second_team(&pool).await;let mut args = create_document_args(TEST_DOCUMENT_OWNER_ID, true, Some(SECOND_TEAM_ID));- args.share_with_team = true;+ args.document.share_with_team = true;let document = repo.create_document(args, md_share_permission()).await@@ -362,20 +399,71 @@ async fn creation_team_consent_is_explicit_and_uses_owner_membership(pool: Pool<assert_eq!(level, AccessLevel::Edit);}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn team_bot_task_does_not_manage_the_sponsor_owner_grant_as_a_share(pool: Pool<Postgres>) {+ sqlx::query!(+ r#"+ INSERT INTO bots (id, kind, team_id, name, handle)+ VALUES ($1, 'owned', $2, 'Task bot', 'task-bot-owner')+ "#,+ bot_id::BotId::TEST_A.as_uuid(),+ TEST_TEAM_ID,+ )+ .execute(&pool)+ .await+ .unwrap();+ let repo = team_bot_repo(pool.clone(), TEST_TEAM_ID);+ let mut args = create_document_args(TEST_DOCUMENT_OWNER_ID, true, Some(TEST_TEAM_ID));+ args.owner = Owner::Bot(bot_id::BotId::TEST_A);+ args.document.share_with_team = true;++ let document = repo+ .create_document(args, md_share_permission())+ .await+ .unwrap();+ let facts = repo+ .get_team_share_facts(&document.document_id)+ .await+ .unwrap();+ assert_eq!(facts.current, None);+ assert_eq!(facts.revision, 0);+ assert_eq!(+ sqlx::query_scalar!(+ r#"+ SELECT access_level AS "level: AccessLevel"+ FROM entity_access+ WHERE entity_id = $1+ AND source_type = 'team'+ AND source_id = $2+ AND granted_from_project_id IS NULL+ "#,+ uuid::Uuid::parse_str(&document.document_id).unwrap(),+ TEST_TEAM_ID.to_string(),+ )+ .fetch_one(&pool)+ .await+ .unwrap(),+ AccessLevel::Owner+ );+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn task_creation_failure_rolls_back_all_initialization(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let permissions_before = sqlx::query_scalar!(r#"SELECT COUNT(*) FROM "SharePermission""#).fetch_one(&pool).await.unwrap();let id = uuid::Uuid::new_v4();let mut args = create_document_args("macro|[email protected]", true, Some(TEST_TEAM_ID));- args.id = Some(id);- args.share_with_team = true;+ args.document.id = Some(id);+ args.document.share_with_team = true;assert!(repo.create_document(args, md_share_permission()).await@@ -414,8 +502,8 @@ async fn task_creation_failure_rolls_back_all_initialization(pool: Pool<Postgres.await.unwrap();let mut args = create_document_args(TEST_DOCUMENT_OWNER_ID, true, Some(TEST_TEAM_ID));- args.id = Some(id);- args.share_with_team = true;+ args.document.id = Some(id);+ args.document.share_with_team = true;assert!(repo.create_document(args, md_share_permission()).await@@ -481,19 +569,20 @@ fn create_document_args(team_id: Option<uuid::Uuid>,) -> CreateDocumentRepoArgs {CreateDocumentRepoArgs {- id: None,- sha: "sha".to_string(),- document_name: "task".to_string(),- user_id: self::user_id(user_id),- file_type: Some(model::document::FileType::Md),- project_id: None,- team_id,- share_with_team: false,- created_at: None,- sub_type: is_task.then_some(document_sub_type::DocumentSubType::Task),- skip_history: false,- attribution: None,- initial_link_share: InitialLinkShare::EntityDefault,+ owner: Owner::User(self::user_id(user_id)),+ document: NewDocument {+ id: None,+ sha: "sha".to_string(),+ document_name: "task".to_string(),+ file_type: Some(model::document::FileType::Md),+ project_id: None,+ team_id,+ share_with_team: false,+ created_at: None,+ sub_type: is_task.then_some(document_sub_type::DocumentSubType::Task),+ skip_history: false,+ initial_link_share: InitialLinkShare::EntityDefault,+ },}}@@ -543,7 +632,7 @@ fn md_share_permission() -> SharePermissionV2 {}async fn create_task_for_team(- repo: &PgDocumentRepo,+ repo: &TestRepo,user_id: &str,team_id: uuid::Uuid,) -> model::document::DocumentMetadata {@@ -722,7 +811,7 @@ async fn insert_second_team(pool: &Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_get_document_metadata(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);// Document existslet metadata = repo@@ -748,7 +837,7 @@ async fn test_get_document_metadata(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_get_basic_document(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);let basic = repo.get_basic_document("d0000000-0000-0000-0000-000000000001")@@ -799,7 +888,7 @@ async fn get_document_metadata_and_basic_document_decode_bot_and_team_owners(poo.await.unwrap();- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let metadata = repo.get_document_metadata(TEST_DOCUMENT_ID).await.unwrap();assert_eq!(metadata.owner,@@ -829,7 +918,7 @@ async fn get_document_metadata_and_basic_document_decode_bot_and_team_owners(poofixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_soft_delete_document(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let document_id = TEST_DOCUMENT_ID;let mut transaction = pool.begin().await.unwrap();entity_registry_db_utils::insert_entity(@@ -877,7 +966,7 @@ async fn test_update_document_modified(pool: Pool<Postgres>) {.await.unwrap();- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);let before = repo.get_document_metadata(document_id).await@@ -901,7 +990,7 @@ async fn test_update_document_modified(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_get_latest_document_version_id(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);let (version_id, _uploaded) = repo.get_latest_document_version_id("d0000000-0000-0000-0000-000000000001")@@ -915,7 +1004,7 @@ async fn test_get_latest_document_version_id(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_get_document_version_id(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);let (version_id, _uploaded) = repo.get_document_version_id("d0000000-0000-0000-0000-000000000001")@@ -929,7 +1018,7 @@ async fn test_get_document_version_id(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_get_user_view_location(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);// No view location existslet location = repo@@ -947,7 +1036,7 @@ async fn test_get_user_view_location(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_create_document_writes_link_share_fields(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let document = repo.create_document(create_document_args(TEST_DOCUMENT_OWNER_ID, false, None),@@ -967,7 +1056,7 @@ async fn test_create_document_writes_link_share_fields(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_create_document_persists_resolved_team_share_permission(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let document = repo.create_document(create_document_args(TEST_DOCUMENT_OWNER_ID, false, None),@@ -990,7 +1079,7 @@ async fn test_create_document_persists_resolved_team_share_permission(pool: Poolfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_edit_document_name(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());repo.edit_document(EditDocumentRepoArgs {team_share: None,@@ -1016,7 +1105,7 @@ async fn test_edit_document_name(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_edit_document_set_file_type(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());repo.edit_document(EditDocumentRepoArgs {document_id: "d0000000-0000-0000-0000-000000000001".to_string(),@@ -1042,7 +1131,7 @@ async fn test_edit_document_set_file_type(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_edit_document_clear_file_type(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());repo.edit_document(EditDocumentRepoArgs {document_id: "d0000000-0000-0000-0000-000000000001".to_string(),@@ -1068,7 +1157,7 @@ async fn test_edit_document_clear_file_type(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_edit_document_project(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());repo.edit_document(EditDocumentRepoArgs {team_share: None,@@ -1097,7 +1186,7 @@ async fn test_edit_document_project(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_edit_document_remove_project(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());// First set a projectrepo.edit_document(EditDocumentRepoArgs {@@ -1146,7 +1235,7 @@ async fn test_edit_document_remove_project(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_edit_document_public_to_null_revokes_non_owner_access(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());insert_non_owner_user_access(&pool).await;repo.edit_document(EditDocumentRepoArgs {@@ -1181,7 +1270,7 @@ async fn test_edit_document_public_to_null_revokes_non_owner_access(pool: Pool<Pfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_edit_document_public_to_team_revokes_non_owner_access(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());insert_non_owner_user_access(&pool).await;repo.edit_document(EditDocumentRepoArgs {@@ -1216,7 +1305,7 @@ async fn test_edit_document_public_to_team_revokes_non_owner_access(pool: Pool<Pfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_edit_document_omitted_link_share_does_not_revoke(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());insert_non_owner_user_access(&pool).await;repo.edit_document(EditDocumentRepoArgs {@@ -1275,7 +1364,7 @@ async fn test_edit_document_omitted_link_share_does_not_revoke(pool: Pool<Postgrfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_edit_document_name_and_project(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());insert_non_owner_user_access(&pool).await;repo.edit_document(EditDocumentRepoArgs {@@ -1320,7 +1409,7 @@ async fn test_edit_document_name_and_project(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_share_with_team_creates_access_for_team_members(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());set_comment_share(&repo).await;@@ -1361,7 +1450,7 @@ async fn test_share_with_team_creates_access_for_team_members(pool: Pool<Postgrefixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_get_team_ids_for_user_returns_empty_when_user_not_on_team(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);let team_ids = repo.get_team_ids_for_user("macro|[email protected]")@@ -1376,7 +1465,7 @@ async fn test_get_team_ids_for_user_returns_empty_when_user_not_on_team(pool: Pofixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_share_with_team_idempotent(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());// Repeated consent advances revision without duplicating grants.set_comment_share(&repo).await;@@ -1410,7 +1499,7 @@ async fn test_share_with_team_idempotent(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_team_share_roundtrip(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let document_id = "d0000000-0000-0000-0000-000000000001";// Unshared by default, but the owner's team resolves@@ -1494,7 +1583,7 @@ async fn direct_team_grant_levels(pool: &Pool<Postgres>) -> Vec<Option<String>>fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn historical_team_grant_is_adopted_as_explicit_consent(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());// A task shared before canonical state existed: a direct Comment grant, NULL level.insert_untracked_team_grant(&pool, AccessLevel::Comment).await;@@ -1554,7 +1643,7 @@ async fn historical_team_grant_is_adopted_as_explicit_consent(pool: Pool<Postgrefixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn untracked_grant_after_canonical_history_still_conflicts(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());set_comment_share(&repo).await;set_legacy_team_share(&repo, TEST_DOCUMENT_ID, false).await@@ -1588,7 +1677,7 @@ async fn untracked_grant_after_canonical_history_still_conflicts(pool: Pool<Postfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn owner_level_historical_grant_is_not_adopted(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());insert_untracked_team_grant(&pool, AccessLevel::Owner).await;// Owner is not a team-share level, so the row stays untracked and conflicts.@@ -1621,7 +1710,7 @@ async fn owner_level_historical_grant_is_not_adopted(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_team_share_no_team_owner(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());// Create a document owned by a user without a teamlet metadata = repo@@ -1654,7 +1743,7 @@ async fn test_team_share_no_team_owner(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_share_with_team_skips_user_with_existing_direct_access(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let doc_uuid = macro_uuid::string_to_uuid("d0000000-0000-0000-0000-000000000001").unwrap();@@ -1696,7 +1785,7 @@ async fn test_share_with_team_skips_user_with_existing_direct_access(pool: Pool<fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_share_with_owner_team(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());set_comment_share(&repo).await;@@ -1735,7 +1824,7 @@ async fn test_share_with_owner_team(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_create_first_task_assigns_team_task_id_one(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let metadata = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;let task_metadata = repo@@ -1754,7 +1843,7 @@ async fn test_create_first_task_assigns_team_task_id_one(pool: Pool<Postgres>) {)]async fn test_get_document_id_by_team_task_number(pool: Pool<Postgres>) {insert_second_team(&pool).await;- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);let first_team_task = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;let second_team_task =@@ -1785,7 +1874,7 @@ async fn test_get_document_id_by_team_task_number(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_create_multiple_tasks_same_team_assigns_sequence(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());for _ in 0..3 {create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;@@ -1800,7 +1889,7 @@ async fn test_create_multiple_tasks_same_team_assigns_sequence(pool: Pool<Postgr)]async fn test_create_tasks_different_teams_have_independent_sequences(pool: Pool<Postgres>) {insert_second_team(&pool).await;- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;@@ -1815,7 +1904,7 @@ async fn test_create_tasks_different_teams_have_independent_sequences(pool: Poolfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_concurrent_task_creates_same_team_get_unique_numbers(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let mut handles = Vec::new();for _ in 0..8 {@@ -1840,7 +1929,7 @@ async fn test_concurrent_task_creates_same_team_get_unique_numbers(pool: Pool<Pofixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_non_task_document_does_not_create_team_task_row(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);let metadata = repo.create_document(@@ -1863,7 +1952,7 @@ async fn test_non_task_document_does_not_create_team_task_row(pool: Pool<Postgrefixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_task_without_team_id_does_not_create_team_task_row(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);let metadata = repo.create_document(@@ -1886,7 +1975,7 @@ async fn test_task_without_team_id_does_not_create_team_task_row(pool: Pool<Postfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_deleting_document_cascades_team_task_row(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let metadata = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;repo.delete_document_by_id(&metadata.document_id)@@ -1915,7 +2004,7 @@ async fn test_deleting_document_cascades_team_task_row(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_delete_document_by_id_removes_entity_row(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let document_id = TEST_DOCUMENT_ID;let mut transaction = pool.begin().await.unwrap();entity_registry_db_utils::insert_entity(@@ -1940,14 +2029,14 @@ async fn test_delete_document_by_id_removes_entity_row(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_copying_task_allocates_new_team_task_number(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let original = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;let copied = repo.copy_document(CopyDocumentRepoArgs {original_document: original,- user_id: user_id("macro|[email protected]"),+ owner: Owner::User(user_id("macro|[email protected]")),document_name: "copied task".to_string(),file_type: Some(model::document::FileType::Md),team_id: Some(TEST_TEAM_ID),@@ -1972,7 +2061,7 @@ async fn test_copying_task_allocates_new_team_task_number(pool: Pool<Postgres>)fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_get_branch_name_context_prefers_github_and_team_task(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());sqlx::query!(r#"UPDATE team@@ -2014,7 +2103,7 @@ async fn test_get_branch_name_context_prefers_github_and_team_task(pool: Pool<Pofixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_get_branch_name_context_falls_back_for_unknown_user(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);let context = repo.get_branch_name_context(@@ -2035,7 +2124,7 @@ async fn test_get_branch_name_context_falls_back_for_unknown_user(pool: Pool<Posfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_get_github_pull_request_keys_orders_and_parses(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let task = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;let other_task = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;let task_short_id = short_id_for_document_id(&task.document_id);@@ -2140,7 +2229,7 @@ async fn test_get_github_pull_request_keys_orders_and_parses(pool: Pool<Postgresfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_edit_document_channel_share_creates_user_item_access(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let channel_id = "c0000000-0000-0000-0000-000000000001";repo.edit_document(EditDocumentRepoArgs {@@ -2215,7 +2304,7 @@ async fn test_edit_document_channel_share_creates_user_item_access(pool: Pool<Pofixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_edit_document_channel_share_idempotent(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let channel_id = "c0000000-0000-0000-0000-000000000001";let make_args = || EditDocumentRepoArgs {@@ -2268,7 +2357,7 @@ async fn test_edit_document_channel_share_idempotent(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_get_project_name(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);let name = repo.get_project_name("d0000000-0000-0000-0000-100000000001")@@ -2285,7 +2374,7 @@ async fn test_get_project_name(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_get_project_children(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);let children = repo.get_project_children("d0000000-0000-0000-0000-100000000001")@@ -2312,7 +2401,7 @@ async fn test_get_project_children(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_get_project_children_empty(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool);+ let repo = test_repo(pool);let children = repo.get_project_children("d0000000-0000-0000-0000-100000000002")@@ -2331,10 +2420,10 @@ fn pdf_share_permission() -> SharePermissionV2 {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn email_import_does_not_initialize_team_consent(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let attachments = insert_email_attachments(&pool, 1).await;let mut args = import_email_document_args(TEST_DOCUMENT_OWNER_ID, "import", attachments[0]);- args.create.share_with_team = true;+ args.document.share_with_team = true;let mut permission = pdf_share_permission();permission.team_share_access_level = Some(AccessLevel::Edit);let EmailImportRepoOutcome::Created(document) = repo@@ -2350,6 +2439,30 @@ async fn email_import_does_not_initialize_team_consent(pool: Pool<Postgres>) {.unwrap();assert_eq!(facts.current, None);assert_eq!(facts.revision, 0);+ assert_eq!(+ sqlx::query_scalar!(+ r#"SELECT COUNT(*) AS "count!" FROM "UserHistory" WHERE "itemId" = $1"#,+ document.document_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap(),+ 0+ );+ assert_eq!(+ sqlx::query_scalar!(+ r#"+ SELECT COUNT(*) AS "count!"+ FROM "ItemLastAccessed"+ WHERE item_id = $1 AND item_type = 'document'+ "#,+ document.document_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap(),+ 0+ );}fn import_email_document_args(@@ -2359,11 +2472,11 @@ fn import_email_document_args() -> ImportEmailAttachmentRepoArgs {ImportEmailAttachmentRepoArgs {email_attachment_id,- create: CreateDocumentRepoArgs {+ owner: user_id(owner),+ document: NewDocument {id: None,sha: sha.to_string(),document_name: "contract".to_string(),- user_id: user_id(owner),file_type: Some(model::document::FileType::Pdf),project_id: None,team_id: None,@@ -2371,7 +2484,6 @@ fn import_email_document_args(created_at: None,sub_type: None,skip_history: true,- attribution: None,initial_link_share: InitialLinkShare::EntityDefault,},}@@ -2477,7 +2589,7 @@ async fn document_email_rows(pool: &Pool<Postgres>, document_id: &str) -> Vec<uufixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_import_email_attachment_reuses_document_by_sha(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let attachments = insert_email_attachments(&pool, 2).await;let sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";@@ -2512,7 +2624,7 @@ async fn test_import_email_attachment_reuses_document_by_sha(pool: Pool<Postgresfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_import_email_attachment_same_attachment_id_reuses_document(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let attachments = insert_email_attachments(&pool, 1).await;let sha = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";@@ -2547,14 +2659,14 @@ async fn test_import_email_attachment_same_attachment_id_reuses_document(pool: Pasync fn test_import_email_attachment_does_not_reuse_non_email_document_by_sha(pool: Pool<Postgres>,) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let attachments = insert_email_attachments(&pool, 1).await;let sha = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";let mut uploaded = create_document_args(TEST_DOCUMENT_OWNER_ID, false, None);- uploaded.sha = sha.to_string();- uploaded.file_type = Some(model::document::FileType::Pdf);- uploaded.document_name = "manual-upload".to_string();+ uploaded.document.sha = sha.to_string();+ uploaded.document.file_type = Some(model::document::FileType::Pdf);+ uploaded.document.document_name = "manual-upload".to_string();let uploaded_doc = repo.create_document(uploaded, pdf_share_permission())@@ -2577,7 +2689,7 @@ async fn test_import_email_attachment_does_not_reuse_non_email_document_by_sha(fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_import_email_attachment_does_not_reuse_other_owner_sha(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let attachments = insert_email_attachments(&pool, 2).await;let sha = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd";@@ -2609,7 +2721,7 @@ async fn test_import_email_attachment_does_not_reuse_other_owner_sha(pool: Pool<fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_create_document_does_not_reuse_email_document_by_sha(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let attachments = insert_email_attachments(&pool, 1).await;let sha = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";@@ -2622,9 +2734,9 @@ async fn test_create_document_does_not_reuse_email_document_by_sha(pool: Pool<Po.unwrap();let mut created = create_document_args(TEST_DOCUMENT_OWNER_ID, false, None);- created.sha = sha.to_string();- created.file_type = Some(model::document::FileType::Pdf);- created.document_name = "same-sha-upload".to_string();+ created.document.sha = sha.to_string();+ created.document.file_type = Some(model::document::FileType::Pdf);+ created.document.document_name = "same-sha-upload".to_string();let created_doc = repo.create_document(created, pdf_share_permission())@@ -2640,7 +2752,7 @@ async fn test_create_document_does_not_reuse_email_document_by_sha(pool: Pool<Pofixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn test_import_email_attachment_only_reuses_latest_instance_sha(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let attachments = insert_email_attachments(&pool, 3).await;let old_sha = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";let new_sha = "1111111111111111111111111111111111111111111111111111111111111111";@@ -2693,7 +2805,7 @@ async fn test_import_email_attachment_only_reuses_latest_instance_sha(pool: Poolfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn create_document_registers_entity_row(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let document = repo.create_document(create_document_args(TEST_DOCUMENT_OWNER_ID, false, None),@@ -2718,14 +2830,14 @@ async fn create_document_registers_entity_row(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn copy_document_registers_distinct_entity_row(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let original = create_task_for_team(&repo, TEST_DOCUMENT_OWNER_ID, TEST_TEAM_ID).await;let copied = repo.copy_document(CopyDocumentRepoArgs {original_document: original.clone(),- user_id: user_id(TEST_DOCUMENT_OWNER_ID),+ owner: Owner::User(user_id(TEST_DOCUMENT_OWNER_ID)),document_name: "copied task".to_string(),file_type: Some(model::document::FileType::Md),team_id: Some(TEST_TEAM_ID),@@ -2762,7 +2874,7 @@ async fn copy_document_registers_distinct_entity_row(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn import_email_created_registers_one_entity_row(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let attachments = insert_email_attachments(&pool, 1).await;let sha = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";@@ -2789,7 +2901,7 @@ async fn import_email_created_registers_one_entity_row(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn import_email_reuse_keeps_one_entity_row_on_original(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let attachments = insert_email_attachments(&pool, 2).await;let sha = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";@@ -2829,7 +2941,7 @@ async fn import_email_reuse_keeps_one_entity_row_on_original(pool: Pool<Postgresfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn soft_delete_document_sets_entity_deleted_at(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let document = repo.create_document(create_document_args(TEST_DOCUMENT_OWNER_ID, false, None),@@ -2851,7 +2963,7 @@ async fn soft_delete_document_sets_entity_deleted_at(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn delete_document_by_id_removes_entity_row(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let document = repo.create_document(create_document_args(TEST_DOCUMENT_OWNER_ID, false, None),@@ -2875,7 +2987,7 @@ async fn delete_document_by_id_removes_entity_row(pool: Pool<Postgres>) {fixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn soft_delete_and_hard_delete_tolerate_missing_entity_row(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());repo.soft_delete_document(TEST_DOCUMENT_ID).await.unwrap();assert_eq!(count_entity_rows_for_id(&pool, TEST_DOCUMENT_ID).await, 0);@@ -2910,7 +3022,7 @@ async fn soft_delete_and_hard_delete_tolerate_missing_entity_row(pool: Pool<Postfixtures(path = "../../../fixtures", scripts("documents_test_data")))]async fn task_snippet_and_skill_register_one_document_entity_row(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let task = create_task_for_team(&repo, TEST_DOCUMENT_OWNER_ID, TEST_TEAM_ID).await;assert_eq!(count_entity_rows_for_id(&pool, &task.document_id).await, 1);assert_eq!(@@ -2927,7 +3039,7 @@ async fn task_snippet_and_skill_register_one_document_entity_row(pool: Pool<Postdocument_sub_type::DocumentSubType::Skill,] {let mut args = create_document_args(TEST_DOCUMENT_OWNER_ID, false, None);- args.sub_type = Some(sub_type);+ args.document.sub_type = Some(sub_type);let document = repo.create_document(args, md_share_permission()).await@@ -2945,3 +3057,232 @@ async fn task_snippet_and_skill_register_one_document_entity_row(pool: Pool<Post);}}++const TEST_BOT_ID: &str = "bot|00000000-0000-0000-0000-00000000b07a";++fn owned_document_args(owner: Owner) -> CreateDocumentRepoArgs {+ let mut args = create_document_args(TEST_DOCUMENT_OWNER_ID, false, None);+ args.owner = owner;+ args+}++fn copy_args(original: &model::document::DocumentMetadata, owner: Owner) -> CopyDocumentRepoArgs {+ CopyDocumentRepoArgs {+ original_document: original.clone(),+ owner,+ document_name: "copy".to_string(),+ file_type: Some(model::document::FileType::Md),+ team_id: None,+ }+}++fn principal(kind: &str, id: &str) -> (String, String) {+ (kind.to_string(), id.to_string())+}++#[derive(Debug, PartialEq)]+struct OwnershipRecords {+ owner: Owner,+ registered_owner: (String, String),+ owner_grants: Vec<(String, String)>,+ user_history_rows: i64,+}++async fn ownership_records(+ repo: &TestRepo,+ pool: &Pool<Postgres>,+ document_id: &str,+) -> OwnershipRecords {+ let entity = fetch_entity_row(pool, document_id).await;+ let owner_grants = sqlx::query!(+ r#"+ SELECT source_type::text AS "source_type!", source_id+ FROM entity_access+ WHERE entity_id = $1 AND access_level = 'owner'+ ORDER BY source_type::text+ "#,+ uuid::Uuid::parse_str(document_id).unwrap(),+ )+ .fetch_all(pool)+ .await+ .unwrap()+ .into_iter()+ .map(|row| (row.source_type, row.source_id))+ .collect();+ let user_history_rows = sqlx::query_scalar!(+ r#"SELECT COUNT(*) AS "count!" FROM "UserHistory" WHERE "itemId" = $1"#,+ document_id,+ )+ .fetch_one(pool)+ .await+ .unwrap();+ OwnershipRecords {+ owner: repo.get_document_metadata(document_id).await.unwrap().owner,+ registered_owner: (entity.owner_type, entity.owner_id),+ owner_grants,+ user_history_rows,+ }+}++fn ownership_cases() -> [(Owner, OwnershipRecords); 2] {+ [+ (+ Owner::User(user_id(TEST_DOCUMENT_OWNER_ID)),+ OwnershipRecords {+ owner: Owner::User(user_id(TEST_DOCUMENT_OWNER_ID)),+ registered_owner: principal("user", TEST_DOCUMENT_OWNER_ID),+ owner_grants: vec![principal("user", TEST_DOCUMENT_OWNER_ID)],+ user_history_rows: 1,+ },+ ),+ (+ Owner::Bot(bot_id::BotId::TEST_A),+ OwnershipRecords {+ owner: Owner::Bot(bot_id::BotId::TEST_A),+ registered_owner: principal("bot", TEST_BOT_ID),+ owner_grants: vec![+ principal("bot", TEST_BOT_ID),+ principal("user", TEST_DOCUMENT_OWNER_ID),+ ],+ user_history_rows: 0,+ },+ ),+ ]+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn create_records_the_owner_its_grants_and_user_only_history(pool: Pool<Postgres>) {+ let repo = test_repo(pool.clone());+ for (owner, expected) in ownership_cases() {+ let document = repo+ .create_document(owned_document_args(owner), md_share_permission())+ .await+ .unwrap();+ assert_eq!(+ ownership_records(&repo, &pool, &document.document_id).await,+ expected+ );+ }+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn copy_records_the_copy_owner_its_grants_and_user_only_history(pool: Pool<Postgres>) {+ let repo = test_repo(pool.clone());+ let original = repo+ .create_document(+ create_document_args(TEST_DOCUMENT_OWNER_ID, false, None),+ md_share_permission(),+ )+ .await+ .unwrap();+ for (owner, expected) in ownership_cases() {+ let copied = repo+ .copy_document(copy_args(&original, owner), md_share_permission())+ .await+ .unwrap();+ assert_eq!(+ ownership_records(&repo, &pool, &copied.document_id).await,+ expected+ );+ }+ assert_eq!(+ ownership_records(&repo, &pool, &original.document_id)+ .await+ .owner_grants,+ vec![principal("user", TEST_DOCUMENT_OWNER_ID)]+ );+}++#[derive(Debug, PartialEq)]+struct TestBotRows {+ documents: i64,+ entities: i64,+ grants: i64,+}++async fn test_bot_rows(pool: &Pool<Postgres>) -> TestBotRows {+ sqlx::query_as!(+ TestBotRows,+ r#"+ SELECT+ (SELECT COUNT(*) FROM "Document" WHERE owner = $1) AS "documents!",+ (SELECT COUNT(*) FROM entity WHERE owner_id = $1) AS "entities!",+ (SELECT COUNT(*) FROM entity_access WHERE source_id = $1) AS "grants!"+ "#,+ TEST_BOT_ID,+ )+ .fetch_one(pool)+ .await+ .unwrap()+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn failed_sponsor_grant_leaves_no_bot_owned_rows(pool: Pool<Postgres>) {+ let repo = test_repo(pool.clone());+ let original = repo+ .create_document(+ create_document_args(TEST_DOCUMENT_OWNER_ID, false, None),+ md_share_permission(),+ )+ .await+ .unwrap();+ let bot = Owner::Bot(bot_id::BotId::TEST_A);+ sqlx::raw_sql(+ r#"+ CREATE FUNCTION reject_sponsor_grant() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN RAISE EXCEPTION 'injected sponsor grant failure'; END $$;+ CREATE TRIGGER reject_sponsor_grant BEFORE INSERT ON entity_access+ FOR EACH ROW WHEN (NEW.source_type = 'user') EXECUTE FUNCTION reject_sponsor_grant();+ "#,+ )+ .execute(&pool)+ .await+ .unwrap();++ assert!(+ repo.create_document(owned_document_args(bot.clone()), md_share_permission())+ .await+ .is_err()+ );+ assert!(+ repo.copy_document(copy_args(&original, bot.clone()), md_share_permission())+ .await+ .is_err()+ );+ assert_eq!(+ test_bot_rows(&pool).await,+ TestBotRows {+ documents: 0,+ entities: 0,+ grants: 0,+ }+ );++ sqlx::raw_sql("DROP TRIGGER reject_sponsor_grant ON entity_access")+ .execute(&pool)+ .await+ .unwrap();+ repo.create_document(owned_document_args(bot.clone()), md_share_permission())+ .await+ .unwrap();+ repo.copy_document(copy_args(&original, bot), md_share_permission())+ .await+ .unwrap();+ assert_eq!(+ test_bot_rows(&pool).await,+ TestBotRows {+ documents: 2,+ entities: 2,+ grants: 2,+ }+ );+}diff --git a/crates/entity_registry/entity_registry/Cargo.toml b/crates/entity_registry/entity_registry/Cargo.tomlindex 6327fb5925..b14e5db9dc 100644--- a/crates/entity_registry/entity_registry/Cargo.toml+++ b/crates/entity_registry/entity_registry/Cargo.toml@@ -11,16 +11,20 @@ postgres = ["dep:sqlx", "model_owner/sqlx"][dependencies]bot_id = { path = "../../bot_id" }chrono = { workspace = true }+macro_authorization = { path = "../../macro_authorization", default-features = false }model-entity = { path = "../../model-entity" }model_owner = { path = "../../model_owner" }rootcause = { workspace = true }shared_entity_registry = { path = "../shared_entity_registry" }+thiserror = { workspace = true }tracing = { workspace = true }sqlx = { workspace = true, optional = true }uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../../workspace-hack" }[dev-dependencies]+harness_id = { path = "../../harness_id" }macro_db_migrator = { path = "../../macro_db_migrator" }+macro_user_id = { path = "../../macro_user_id" }tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }uuid = { workspace = true, features = ["v7"] }diff --git a/crates/entity_registry/entity_registry/src/domain.rs b/crates/entity_registry/entity_registry/src/domain.rsindex 57ac2dbc27..b414ded913 100644--- a/crates/entity_registry/entity_registry/src/domain.rs+++ b/crates/entity_registry/entity_registry/src/domain.rs@@ -1,5 +1,6 @@//! Domain models, ports, and the service implementation.+pub mod creation_principal;pub mod models;pub mod owner_grant_policy;pub mod ports;diff --git a/crates/entity_registry/entity_registry/src/domain/creation_principal.rs b/crates/entity_registry/entity_registry/src/domain/creation_principal.rsnew file mode 100644index 0000000000..3c0b2d4dcb--- /dev/null+++ b/crates/entity_registry/entity_registry/src/domain/creation_principal.rs@@ -0,0 +1,86 @@+//! Who an authenticated caller creates entities as.+//!+//! Resolving a creation principal decides the recorded owner. It does not+//! grant access; [`super::owner_grant_policy`] expands the owner into grants.++#[cfg(test)]+mod test;++use bot_id::NonSystemBotId;+use macro_authorization::{BotAuthentication, BotScope, MacroAuthorization};+use model_owner::CreationPrincipal;++/// Whether a creation may be owned by something other than a user.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum NonUserOwners {+ /// Every creation is owned by a user.+ Disabled,+ /// A team-scoped bot with no acting user owns what it creates.+ Enabled,+}++/// Why a caller cannot create entities.+#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]+pub enum CreationPrincipalError {+ /// A system bot has no sponsor, so it must act for a user.+ #[error("a system bot must act for a user")]+ SystemBotWithoutUser,+ /// A user-scoped bot must act for a user.+ #[error("a user-scoped bot must act for a user")]+ UserScopeWithoutUser,+ /// A team-scoped bot must belong to a verified team.+ #[error("a team-scoped bot has no verified team")]+ MissingTeam,+ /// Bot ownership is not enabled.+ #[error("non-user owners are disabled")]+ NonUserOwnersDisabled,+ /// An internal caller must act for a user.+ #[error("an internal caller must act for a user")]+ InternalWithoutUser,+ /// A harness cannot create entities.+ #[error("a harness cannot create entities")]+ Harness,+}++/// Resolve who `authorization` creates entities as.+///+/// A verified acting user always owns the result. Only a non-system bot in+/// team scope with a verified team and no acting user owns what it creates,+/// and only while `non_user_owners` is enabled.+pub fn resolve_creation_principal(+ authorization: &MacroAuthorization,+ non_user_owners: NonUserOwners,+) -> Result<CreationPrincipal, CreationPrincipalError> {+ match authorization {+ MacroAuthorization::User(user) | MacroAuthorization::Internal(Some(user)) => {+ Ok(CreationPrincipal::User(user.macro_user_id.clone()))+ }+ MacroAuthorization::Bot(bot) => resolve_bot(bot, non_user_owners),+ MacroAuthorization::Internal(None) => Err(CreationPrincipalError::InternalWithoutUser),+ MacroAuthorization::Harness(_) => Err(CreationPrincipalError::Harness),+ }+}++fn resolve_bot(+ bot: &BotAuthentication,+ non_user_owners: NonUserOwners,+) -> Result<CreationPrincipal, CreationPrincipalError> {+ if let Some(user) = &bot.acting_user {+ return Ok(CreationPrincipal::BotForUser {+ bot: bot.bot_id,+ user: user.macro_user_id.clone(),+ });+ }+ let owner =+ NonSystemBotId::new(bot.bot_id).ok_or(CreationPrincipalError::SystemBotWithoutUser)?;+ match (bot.bot_scope, bot.team_id, non_user_owners) {+ (BotScope::User, _, _) => Err(CreationPrincipalError::UserScopeWithoutUser),+ (BotScope::Team, None, _) => Err(CreationPrincipalError::MissingTeam),+ (BotScope::Team, Some(_), NonUserOwners::Disabled) => {+ Err(CreationPrincipalError::NonUserOwnersDisabled)+ }+ (BotScope::Team, Some(team), NonUserOwners::Enabled) => {+ Ok(CreationPrincipal::TeamBot { bot: owner, team })+ }+ }+}diff --git a/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rs b/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rsnew file mode 100644index 0000000000..21f42c0c33--- /dev/null+++ b/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rs@@ -0,0 +1,188 @@+use super::*;+use bot_id::{BotId, SYSTEM_BOTS};+use harness_id::HarnessId;+use macro_authorization::{+ HarnessAuthentication, HarnessAuthorizationOwner, MacroUserAuthentication,+};+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++const ROW_BOT: BotId = BotId::new_from_uuid(Uuid::from_u128(0xB07A));+const TEAM: Uuid = Uuid::from_u128(0x7EA3);+const GATES: [NonUserOwners; 2] = [NonUserOwners::Disabled, NonUserOwners::Enabled];++fn user_id() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()+}++fn user() -> MacroUserAuthentication {+ MacroUserAuthentication {+ macro_user_id: user_id(),+ user_context: Default::default(),+ }+}++fn bot(+ bot_id: BotId,+ bot_scope: BotScope,+ team_id: Option<Uuid>,+ acting_user: Option<MacroUserAuthentication>,+) -> MacroAuthorization {+ MacroAuthorization::Bot(BotAuthentication {+ bot_id,+ token_id: Uuid::from_u128(1),+ bot_scope,+ team_id,+ acting_user,+ })+}++fn harness() -> MacroAuthorization {+ MacroAuthorization::Harness(HarnessAuthentication {+ harness_id: HarnessId::new_from_uuid(Uuid::from_u128(2)),+ token_id: Uuid::from_u128(3),+ owner: HarnessAuthorizationOwner::Team { team_id: TEAM },+ acting_user: user(),+ })+}++fn resolve(+ authorization: MacroAuthorization,+ gate: NonUserOwners,+) -> Result<CreationPrincipal, CreationPrincipalError> {+ resolve_creation_principal(&authorization, gate)+}++#[test]+fn gate_independent_principals_resolve_the_same_either_way() {+ for gate in GATES {+ assert_eq!(+ resolve(MacroAuthorization::User(user()), gate),+ Ok(CreationPrincipal::User(user_id())),+ "user under {gate:?}"+ );+ assert_eq!(+ resolve(MacroAuthorization::Internal(Some(user())), gate),+ Ok(CreationPrincipal::User(user_id())),+ "internal for a user under {gate:?}"+ );+ assert_eq!(+ resolve(MacroAuthorization::Internal(None), gate),+ Err(CreationPrincipalError::InternalWithoutUser),+ "internal without a user under {gate:?}"+ );+ assert_eq!(+ resolve(harness(), gate),+ Err(CreationPrincipalError::Harness),+ "harness under {gate:?}"+ );+ }+}++#[test]+fn a_bot_with_an_acting_user_creates_for_that_user() {+ let bots = SYSTEM_BOTS.iter().map(|bot| bot.id).chain([ROW_BOT]);+ for bot_id in bots {+ for (scope, team) in [+ (BotScope::User, None),+ (BotScope::Team, Some(TEAM)),+ (BotScope::Team, None),+ ] {+ for gate in GATES {+ assert_eq!(+ resolve(bot(bot_id, scope, team, Some(user())), gate),+ Ok(CreationPrincipal::BotForUser {+ bot: bot_id,+ user: user_id(),+ }),+ "{bot_id} in {scope} scope under {gate:?}"+ );+ }+ }+ }+}++#[test]+fn a_system_bot_without_a_user_never_creates() {+ for system_bot in SYSTEM_BOTS {+ for (scope, team) in [+ (BotScope::User, None),+ (BotScope::User, Some(TEAM)),+ (BotScope::Team, None),+ (BotScope::Team, Some(TEAM)),+ ] {+ for gate in GATES {+ assert_eq!(+ resolve(bot(system_bot.id, scope, team, None), gate),+ Err(CreationPrincipalError::SystemBotWithoutUser),+ "{} in {scope} scope under {gate:?}",+ system_bot.handle+ );+ }+ }+ }+}++#[test]+fn a_row_bot_without_a_user_owns_only_in_verified_team_scope_behind_the_gate() {+ let cases = [+ (+ BotScope::User,+ None,+ NonUserOwners::Disabled,+ Err(CreationPrincipalError::UserScopeWithoutUser),+ ),+ (+ BotScope::User,+ None,+ NonUserOwners::Enabled,+ Err(CreationPrincipalError::UserScopeWithoutUser),+ ),+ (+ BotScope::User,+ Some(TEAM),+ NonUserOwners::Disabled,+ Err(CreationPrincipalError::UserScopeWithoutUser),+ ),+ (+ BotScope::User,+ Some(TEAM),+ NonUserOwners::Enabled,+ Err(CreationPrincipalError::UserScopeWithoutUser),+ ),+ (+ BotScope::Team,+ None,+ NonUserOwners::Disabled,+ Err(CreationPrincipalError::MissingTeam),+ ),+ (+ BotScope::Team,+ None,+ NonUserOwners::Enabled,+ Err(CreationPrincipalError::MissingTeam),+ ),+ (+ BotScope::Team,+ Some(TEAM),+ NonUserOwners::Disabled,+ Err(CreationPrincipalError::NonUserOwnersDisabled),+ ),+ (+ BotScope::Team,+ Some(TEAM),+ NonUserOwners::Enabled,+ Ok(CreationPrincipal::TeamBot {+ bot: NonSystemBotId::new(ROW_BOT).unwrap(),+ team: TEAM,+ }),+ ),+ ];+ for (scope, team, gate, expected) in cases {+ assert_eq!(+ resolve(bot(ROW_BOT, scope, team, None), gate),+ expected,+ "{scope} scope with team {team:?} under {gate:?}"+ );+ }+}diff --git a/crates/entity_registry/entity_registry/src/lib.rs b/crates/entity_registry/entity_registry/src/lib.rsindex 1c521a026b..b2c8fa8ff2 100644--- a/crates/entity_registry/entity_registry/src/lib.rs+++ b/crates/entity_registry/entity_registry/src/lib.rs@@ -28,6 +28,9 @@ pub mod domain;#[cfg(feature = "postgres")]pub mod outbound;+pub use domain::creation_principal::{+ CreationPrincipalError, NonUserOwners, resolve_creation_principal,+};pub use domain::models::{EntityRecord, EntityTypeCount};pub use domain::owner_grant_policy::OwnerGrantPolicy;pub use domain::ports::{BotFacts, EntityRegistryRepository, EntityRegistryService};diff --git a/crates/github/Cargo.toml b/crates/github/Cargo.tomlindex 2fd0941230..a54cd73490 100644--- a/crates/github/Cargo.toml+++ b/crates/github/Cargo.toml@@ -99,6 +99,7 @@ http-body-util = { workspace = true }macro_db_migrator = { path = "../macro_db_migrator" }mockall = { workspace = true }model = { path = "../model" }+model_owner = { path = "../model_owner" }model_user = { path = "../model_user" }models_permissions = { path = "../models_permissions" }rootcause = { workspace = true }diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rsindex c082bb0726..9920644bb7 100644--- a/crates/github/src/domain/service/sync/test.rs+++ b/crates/github/src/domain/service/sync/test.rs@@ -15,9 +15,7 @@ use document_sub_type::DocumentSubType;use documents::domain::models::EditDocumentServiceArgs;use documents::domain::{content::{DocumentContent, DocumentContentLocation},- models::{- CreateDocumentRepoArgs, DocumentError, ImportEmailAttachmentRepoArgs, LocationQueryParams,- },+ models::{DocumentError, ImportEmailAttachmentRepoArgs, LocationQueryParams, NewDocument},ports::DocumentService,response::{CreateDocumentResponseData, DocumentMetadataWithContent, DocumentResponse,@@ -37,6 +35,7 @@ use foreign_entity::domain::{use macro_user_id::user_id::MacroUserIdStr;use model::document::{DocumentBasic, DocumentMetadata};use model_entity::Entity;+use model_owner::CreationPrincipal;use models_permissions::share_permission::access_level::AccessLevel;use notification::domain::{models::{Notification, NotificationResult, SendNotificationRequest},@@ -211,8 +210,8 @@ impl DocumentService for StubDocumentService {}async fn create_document(&self,- _user_id: MacroUserIdStr<'static>,- _args: CreateDocumentRepoArgs,+ _principal: &CreationPrincipal,+ _document: NewDocument,_job_id: Option<String>,) -> Result<CreateDocumentResponseData, DocumentError> {unimplemented!()@@ -220,7 +219,6 @@ impl DocumentService for StubDocumentService {async fn import_email_attachment(&self,- _user_id: MacroUserIdStr<'static>,_args: ImportEmailAttachmentRepoArgs,) -> Result<CreateDocumentResponseData, DocumentError> {unimplemented!()@@ -272,7 +270,7 @@ impl DocumentService for StubDocumentService {&self,_entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,_document_context: DocumentBasic,- _user_id: MacroUserIdStr<'static>,+ _principal: &CreationPrincipal,_document_name: String,_query_version_id: Option<i64>,_sync_version_id: Option<model::sync_service::SyncServiceVersionID>,@@ -282,10 +280,9 @@ impl DocumentService for StubDocumentService {async fn handle_task_properties(&self,- _user_id: MacroUserIdStr<'static>,+ _principal: &CreationPrincipal,_document_id: &str,_request: &documents::domain::models::CreateTaskRequest,- _attribution: &activity::Attribution,) -> Result<(), DocumentError> {unimplemented!()}diff --git a/crates/initiative_documents/Cargo.toml b/crates/initiative_documents/Cargo.tomlindex a04740b23f..a7ad556181 100644--- a/crates/initiative_documents/Cargo.toml+++ b/crates/initiative_documents/Cargo.toml@@ -7,6 +7,7 @@ publish = false[dependencies]documents_hex = { package = "documents", path = "../documents", default-features = false, features = ["document_create"] }initiative = { path = "../initiative", default-features = false, features = ["ports"] }+model_owner = { path = "../model_owner" }rootcause = { workspace = true }tracing = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/crates/initiative_documents/src/lib.rs b/crates/initiative_documents/src/lib.rsindex 234a581cf5..a7e8a8a02e 100644--- a/crates/initiative_documents/src/lib.rs+++ b/crates/initiative_documents/src/lib.rs@@ -14,6 +14,7 @@ use documents_hex::domain::ports::mentions::DocumentMentionTrackingPort;use documents_hex::domain::purge::DocumentPurgeService;use initiative::domain::models::{DescriptionDocumentId, InitiativeError, NewDescriptionDocument};use initiative::domain::ports::InitiativeDescriptionDocuments;+use model_owner::CreationPrincipal;macro_rules! internal {($error:expr) => {@@ -68,7 +69,7 @@ wherelet created = self.creator.create_markdown_text(- owner,+ &CreationPrincipal::User(owner),NewMarkdownTextDocument {metadata,markdown: prefill_markdown,diff --git a/crates/macro_db_client/migrations/20260923183235_drop_owner_user_fks.down.sql b/crates/macro_db_client/migrations/20260923183235_drop_owner_user_fks.down.sqlnew file mode 100644index 0000000000..5ed4b224de--- /dev/null+++ b/crates/macro_db_client/migrations/20260923183235_drop_owner_user_fks.down.sql@@ -0,0 +1,16 @@+-- Intentionally validate existing rows: rollback must fail if any non-user owner exists.+ALTER TABLE "Document"+ ADD CONSTRAINT "Document_owner_fkey" FOREIGN KEY (owner)+ REFERENCES "User" (id) ON DELETE CASCADE ON UPDATE CASCADE;+ALTER TABLE "Project"+ ADD CONSTRAINT "Project_userId_fkey" FOREIGN KEY ("userId")+ REFERENCES "User" (id) ON DELETE CASCADE ON UPDATE CASCADE;+ALTER TABLE "Chat"+ ADD CONSTRAINT "Chat_userId_fkey" FOREIGN KEY ("userId")+ REFERENCES "User" (id) ON DELETE CASCADE ON UPDATE CASCADE;+ALTER TABLE agent_session+ ADD CONSTRAINT agent_session_owner_id_fkey FOREIGN KEY (owner_id)+ REFERENCES "User" (id) ON DELETE CASCADE;+ALTER TABLE scheduled_action+ ADD CONSTRAINT scheduled_action_owner_fkey FOREIGN KEY (owner)+ REFERENCES "User" (id) ON DELETE CASCADE;diff --git a/crates/macro_db_client/migrations/20260923183235_drop_owner_user_fks.up.sql b/crates/macro_db_client/migrations/20260923183235_drop_owner_user_fks.up.sqlnew file mode 100644index 0000000000..67faaff1f0--- /dev/null+++ b/crates/macro_db_client/migrations/20260923183235_drop_owner_user_fks.up.sql@@ -0,0 +1,7 @@+-- Deploy only after T4.2 is live; user deletion no longer relies on cascade for these tables.+-- Keep the NOT NULL owner columns as denormalized principal strings.+ALTER TABLE "Document" DROP CONSTRAINT "Document_owner_fkey";+ALTER TABLE "Project" DROP CONSTRAINT "Project_userId_fkey";+ALTER TABLE "Chat" DROP CONSTRAINT "Chat_userId_fkey";+ALTER TABLE agent_session DROP CONSTRAINT agent_session_owner_id_fkey;+ALTER TABLE scheduled_action DROP CONSTRAINT scheduled_action_owner_fkey;diff --git a/crates/macro_db_client/src/document/v2/create.rs b/crates/macro_db_client/src/document/v2/create.rsindex 35f8e9a1da..c4ef3c87f4 100644--- a/crates/macro_db_client/src/document/v2/create.rs+++ b/crates/macro_db_client/src/document/v2/create.rs@@ -329,6 +329,9 @@ async fn insert_document_with_id(}}+#[cfg(test)]+mod test;+#[cfg(test)]mod tests {#[allow(unused_imports)]@@ -498,38 +501,6 @@ mod tests {Ok(())}- #[sqlx::test(fixtures(path = "../../../fixtures", scripts("basic_user_with_documents")))]- async fn test_create_document_no_user(pool: Pool<Postgres>) {- // document exists- let document_metadata = create_document(- &pool,- CreateDocumentArgs {- id: None,- sha: "sha",- document_name: "document-name",- user_id: MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap(),- file_type: Some(FileType::Pdf),- project_id: None,- project_name: None,- share_permission: &SharePermissionV2::new_document_share_permission(- Some(FileType::Pdf),- None,- ),- skip_history: false,- email_attachment_id: None,- created_at: None,- is_task: false,- },- )- .await;-- assert!(document_metadata.is_err());- assert_eq!(- document_metadata.err().unwrap().to_string(),- "unable to create document: error returned from database: insert or update on table \"Document\" violates foreign key constraint \"Document_owner_fkey\"".to_string()- );- }// should return appropriate error if we try to insert a document with a duplicate ID#[sqlx::test(fixtures(path = "../../../fixtures", scripts("basic_user_with_documents")))]diff --git a/crates/macro_db_client/src/document/v2/create/test.rs b/crates/macro_db_client/src/document/v2/create/test.rsnew file mode 100644index 0000000000..5356147c65--- /dev/null+++ b/crates/macro_db_client/src/document/v2/create/test.rs@@ -0,0 +1,35 @@+use super::*;++// Only the denormalized owner column is relaxed. Full document creation still+// writes user-specific relations (such as history) that require a real user.+#[sqlx::test]+async fn document_row_does_not_require_a_user_owner(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let mut transaction = pool.begin().await?;+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let now = chrono::Utc::now();++ let document = insert_document_no_id(+ &mut transaction,+ owner.copied(),+ "document-name",+ Some(FileType::Pdf),+ None,+ &now,+ )+ .await?;+ assert!(!document.id.is_empty());++ insert_document_with_id(+ &mut transaction,+ ¯o_uuid::generate_uuid_v7().to_string(),+ owner,+ "document-with-id",+ Some(FileType::Pdf),+ None,+ &now,+ )+ .await?;++ transaction.rollback().await?;+ Ok(())+}diff --git a/crates/memory/Cargo.toml b/crates/memory/Cargo.tomlindex fa63adfee1..14d7238c28 100644--- a/crates/memory/Cargo.toml+++ b/crates/memory/Cargo.toml@@ -13,6 +13,7 @@ ai_tools = { path = "../ai_tools" }ai_toolset = { path = "../ai_toolset" }anyhow = { workspace = true }axum = { workspace = true }+bots = { path = "../bots", default-features = false, features = ["outbound"] }chrono = { workspace = true }call = { path = "../call", default-features = false, features = ["ai_tools", "outbound", "ports"] }futures = { workspace = true }@@ -42,6 +43,8 @@ email = { path = "../email" }email_service_client = { path = "../email_service_client" }entity_access = { path = "../entity_access" }entity_access_management = { path = "../entity_access_management" }+entity_registry = { path = "../entity_registry/entity_registry" }+entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils" }foreign_entity = { path = "../foreign_entity" }frecency = { path = "../frecency" }lexical_client = { path = "../lexical_client" }diff --git a/crates/memory/src/context.rs b/crates/memory/src/context.rsindex 64658a0910..5cdb368f4d 100644--- a/crates/memory/src/context.rs+++ b/crates/memory/src/context.rs@@ -2,6 +2,7 @@ use ai_tools::{NoOpConnectionService, NoOpSnsEndpointManager, ToolImportToolContext, ToolNotificationQueue,ToolServiceContext,};+use bots::outbound::pg_bots_repo::PgBotsRepo;use channels::{domain::list_service::ChannelListServiceImpl, outbound::pg_channels_repo::PgChannelsRepo,};@@ -15,6 +16,8 @@ use email::outbound::EmailPgRepo;use email_service_client::EmailServiceClientExternal;use entity_access::domain::service::EntityAccessServiceImpl;use entity_access::outbound::PgAccessRepository;+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use foreign_entity::{domain::service::ForeignEntityServiceImpl,outbound::pg_foreign_entity_repo::PgForeignEntityRepo,@@ -119,7 +122,10 @@ pub async fn build_tool_service_context(&config.document_storage_bucket,&config.docx_document_upload_bucket,);- let document_repo = PgDocumentRepo::new(pool.clone());+ let document_repo = PgDocumentRepo::new(+ pool.clone(),+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone()))),+ );let cloudfront_config = CloudFrontConfig {distribution_url: config.document_storage_service_cloudfront_distribution_urldiff --git a/crates/model_owner/Cargo.toml b/crates/model_owner/Cargo.tomlindex efd7b0ad12..4d420ecd4c 100644--- a/crates/model_owner/Cargo.toml+++ b/crates/model_owner/Cargo.toml@@ -16,4 +16,5 @@ thiserror = { workspace = true }uuid = { workspace = true }[dev-dependencies]+bot_id = { path = "../bot_id", features = ["test-utils"] }serde_json = { workspace = true }diff --git a/crates/model_owner/src/creation_principal.rs b/crates/model_owner/src/creation_principal.rsnew file mode 100644index 0000000000..7596be42fd--- /dev/null+++ b/crates/model_owner/src/creation_principal.rs@@ -0,0 +1,64 @@+//! The verified principal a new entity is created for.++use bot_id::{BotId, NonSystemBotId};+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++use crate::Owner;++#[cfg(test)]+mod test;++/// Who creates an entity, and so who owns it and who acts.+///+/// Owner, actor, and acting user all derive from this one value, so they+/// cannot disagree.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum CreationPrincipal {+ /// A user creating for themself.+ User(MacroUserIdStr<'static>),+ /// A bot acting for a verified user. The user owns the result.+ BotForUser {+ /// The acting bot.+ bot: BotId,+ /// The user the bot acts for.+ user: MacroUserIdStr<'static>,+ },+ /// A team-scoped bot with no acting user. The bot owns the result.+ TeamBot {+ /// The owning bot.+ bot: NonSystemBotId,+ /// The bot's verified team.+ team: Uuid,+ },+}++impl CreationPrincipal {+ /// Who owns the created entity.+ #[must_use]+ pub fn owner(&self) -> Owner {+ match self {+ Self::User(user) | Self::BotForUser { user, .. } => Owner::User(user.clone()),+ Self::TeamBot { bot, .. } => Owner::Bot(bot.get()),+ }+ }++ /// The user this creation acts as, or `None` for a team bot.+ #[must_use]+ pub fn user(&self) -> Option<&MacroUserIdStr<'static>> {+ match self {+ Self::User(user) | Self::BotForUser { user, .. } => Some(user),+ Self::TeamBot { .. } => None,+ }+ }++ /// The bot performing this creation, or `None` for a user.+ #[must_use]+ pub fn bot(&self) -> Option<BotId> {+ match self {+ Self::User(_) => None,+ Self::BotForUser { bot, .. } => Some(*bot),+ Self::TeamBot { bot, .. } => Some(bot.get()),+ }+ }+}diff --git a/crates/model_owner/src/creation_principal/test.rs b/crates/model_owner/src/creation_principal/test.rsnew file mode 100644index 0000000000..3418dc6ec6--- /dev/null+++ b/crates/model_owner/src/creation_principal/test.rs@@ -0,0 +1,45 @@+use super::*;++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()+}++fn row_bot() -> NonSystemBotId {+ NonSystemBotId::new(BotId::TEST_A).unwrap()+}++#[test]+fn user_owns_and_acts() {+ let principal = CreationPrincipal::User(user());++ assert_eq!(principal.owner().principal_id(), "macro|[email protected]");+ assert_eq!(principal.user(), Some(&user()));+ assert_eq!(principal.bot(), None);+}++#[test]+fn bot_for_user_is_owned_by_the_user() {+ let principal = CreationPrincipal::BotForUser {+ bot: BotId::TEST_A,+ user: user(),+ };++ assert_eq!(principal.owner().principal_id(), "macro|[email protected]");+ assert_eq!(principal.user(), Some(&user()));+ assert_eq!(principal.bot(), Some(BotId::TEST_A));+}++#[test]+fn team_bot_owns_without_a_user() {+ let principal = CreationPrincipal::TeamBot {+ bot: row_bot(),+ team: Uuid::from_u128(7),+ };++ assert_eq!(+ principal.owner().principal_id(),+ "bot|00000000-0000-0000-0000-00000000b07a"+ );+ assert_eq!(principal.user(), None);+ assert_eq!(principal.bot(), Some(BotId::TEST_A));+}diff --git a/crates/model_owner/src/lib.rs b/crates/model_owner/src/lib.rsindex 973cee6e7e..7bbec4ba9a 100644--- a/crates/model_owner/src/lib.rs+++ b/crates/model_owner/src/lib.rs@@ -24,8 +24,11 @@ use uuid::Uuid;#[cfg(test)]mod test;+pub mod creation_principal;pub mod team;+pub use creation_principal::CreationPrincipal;+const USER_PRINCIPAL_PREFIX: &str = "macro|";const BOT_PRINCIPAL_PREFIX: &str = "bot|";const TEAM_UUID_HYPHENATED_LEN: usize = 36;diff --git a/crates/projects/Cargo.toml b/crates/projects/Cargo.tomlindex d87ab2b17d..0d652b6f08 100644--- a/crates/projects/Cargo.toml+++ b/crates/projects/Cargo.toml@@ -29,6 +29,7 @@ outbound = ["dep:documents","dep:dynamodb_client","dep:entity_access_db_utils",+ "dep:entity_registry","dep:entity_registry_db_utils","dep:hex","dep:macro_sha_count_client",@@ -101,6 +102,7 @@ document_sub_type = { path = "../document_sub_type", optional = true }documents = { path = "../documents", default-features = false, optional = true }dynamodb_client = { path = "../dynamodb_client", optional = true }entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }+entity_registry = { path = "../entity_registry/entity_registry", optional = true }entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils", optional = true }hex = { workspace = true, optional = true }macro_sha_count_client = { path = "../macro_sha_count_client", optional = true }diff --git a/crates/projects/src/outbound/pg_project_repo.rs b/crates/projects/src/outbound/pg_project_repo.rsindex 32025247ab..71675c796a 100644--- a/crates/projects/src/outbound/pg_project_repo.rs+++ b/crates/projects/src/outbound/pg_project_repo.rs@@ -14,6 +14,8 @@ mod tests;use std::collections::HashMap;+use entity_registry::BotFacts;+use entity_registry_db_utils::OwnedEntityRegistrar;use model::project::{BasicProject, Project, ProjectPreviewData, ProjectPreviewV2, ProjectWithUploadRequest,WithProjectId,@@ -29,14 +31,16 @@ use crate::domain::ports::ProjectRepo;/// PostgreSQL-backed project repository.#[derive(Clone)]-pub struct PgProjectRepo {+pub struct PgProjectRepo<B> {pool: PgPool,+ registrar: OwnedEntityRegistrar<B>,}-impl PgProjectRepo {- /// Create a repository backed by the given connection pool.- pub fn new(pool: PgPool) -> Self {- Self { pool }+impl<B: BotFacts> PgProjectRepo<B> {+ /// Create a repository backed by `pool` that registers uploaded folder+ /// trees through `registrar`.+ pub fn new(pool: PgPool, registrar: OwnedEntityRegistrar<B>) -> Self {+ Self { pool, registrar }}}@@ -64,7 +68,7 @@ fn map_project(})}-impl ProjectRepo for PgProjectRepo {+impl<B: BotFacts + 'static> ProjectRepo for PgProjectRepo<B> {type Err = sqlx::Error;#[tracing::instrument(err, skip(self))]@@ -383,7 +387,7 @@ impl ProjectRepo for PgProjectRepo {args: UploadFolderRepoArgs,) -> Result<model::folder::UploadFolderWithIdsResponse, Self::Err> {let mut transaction = self.pool.begin().await?;- let result = upload_folder::upload_folder(&mut transaction, args).await?;+ let result = upload_folder::upload_folder(&mut transaction, &self.registrar, args).await?;transaction.commit().await?;Ok(result)}diff --git a/crates/projects/src/outbound/pg_project_repo/team_share/test.rs b/crates/projects/src/outbound/pg_project_repo/team_share/test.rsindex 59804e9ed8..39833c6650 100644--- a/crates/projects/src/outbound/pg_project_repo/team_share/test.rs+++ b/crates/projects/src/outbound/pg_project_repo/team_share/test.rs@@ -13,12 +13,12 @@ use uuid::Uuid;use crate::domain::models::{CreateProjectArgs, EditProjectArgs, ProjectError};use crate::domain::ports::ProjectRepo;-use crate::outbound::pg_project_repo::PgProjectRepo;+use crate::outbound::pg_project_repo::tests::{TestRepo, test_repo};const OWNER: &str = "macro|[email protected]";const TEAM_ID: Uuid = Uuid::from_u128(0xb2222222_2222_2222_2222_222222222222);-async fn create_project(repo: &PgProjectRepo, name: &str) -> String {+async fn create_project(repo: &TestRepo, name: &str) -> String {repo.create_project(CreateProjectArgs {user_id: OWNER.to_owned(),name: name.to_string(),@@ -54,7 +54,7 @@ fn command(facts: &TeamShareFacts, level: Option<AccessLevel>) -> AuthorizedTeam}async fn edit_team_share(- repo: &PgProjectRepo,+ repo: &TestRepo,project_id: &str,level: Option<AccessLevel>,) -> Result<(), ProjectError> {@@ -164,7 +164,7 @@ fn unshared() -> StoredTeamShare {fixtures(path = "../fixtures", scripts("users", "team")))]async fn get_team_share_facts_reads_owner_team_and_null_state(pool: PgPool) {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let project_id = create_project(&repo, "Facts").await;let facts = repo.get_team_share_facts(&project_id).await.unwrap();@@ -182,7 +182,7 @@ async fn get_team_share_facts_reads_owner_team_and_null_state(pool: PgPool) {fixtures(path = "../fixtures", scripts("users")))]async fn get_team_share_facts_without_team_has_no_owner_team(pool: PgPool) {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let project_id = create_project(&repo, "No team").await;let facts = repo.get_team_share_facts(&project_id).await.unwrap();@@ -196,7 +196,7 @@ async fn get_team_share_facts_without_team_has_no_owner_team(pool: PgPool) {fixtures(path = "../fixtures", scripts("users", "team")))]async fn edit_applies_team_share_command_and_inserts_direct_team_entity_access(pool: PgPool) {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let project_id = create_project(&repo, "Shared").await;edit_team_share(&repo, &project_id, Some(AccessLevel::Edit))@@ -243,7 +243,7 @@ async fn edit_applies_team_share_command_and_inserts_direct_team_entity_access(pfixtures(path = "../fixtures", scripts("users", "team")))]async fn edit_team_share_copies_and_clears_nested_document_grants(pool: PgPool) {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let project_id = create_project(&repo, "Folder").await;let document_id = Uuid::from_u128(0xc3333333_3333_3333_3333_333333333333);insert_folder_document(&pool, &project_id, document_id).await;@@ -301,7 +301,7 @@ async fn edit_team_share_copies_and_clears_nested_document_grants(pool: PgPool)fixtures(path = "../fixtures", scripts("users", "team")))]async fn edit_clear_command_removes_managed_team_entity_access_and_bumps_revision(pool: PgPool) {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let project_id = create_project(&repo, "Cleared").await;edit_team_share(&repo, &project_id, Some(AccessLevel::Comment)).await@@ -325,7 +325,7 @@ async fn edit_clear_command_removes_managed_team_entity_access_and_bumps_revisiofixtures(path = "../fixtures", scripts("users", "team")))]async fn edit_with_team_level_but_no_command_returns_unauthorized(pool: PgPool) {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let project_id = create_project(&repo, "Original").await;let result = repo@@ -357,7 +357,7 @@ async fn edit_with_team_level_but_no_command_returns_unauthorized(pool: PgPool)fixtures(path = "../fixtures", scripts("users", "team")))]async fn edit_rejects_command_for_other_project_or_mismatched_level(pool: PgPool) {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let project_id = create_project(&repo, "Target").await;let other_project_id = create_project(&repo, "Other").await;let facts = repo.get_team_share_facts(&project_id).await.unwrap();@@ -399,7 +399,7 @@ async fn edit_rejects_command_for_other_project_or_mismatched_level(pool: PgPoolfixtures(path = "../fixtures", scripts("users", "team")))]async fn edit_stale_command_returns_conflict(pool: PgPool) {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let project_id = create_project(&repo, "Stale").await;let facts = repo.get_team_share_facts(&project_id).await.unwrap();let stale = command(&facts, Some(AccessLevel::Edit));@@ -428,7 +428,7 @@ async fn edit_stale_command_returns_conflict(pool: PgPool) {fixtures(path = "../fixtures", scripts("users", "team")))]async fn edit_team_share_and_link_share_in_one_call_persists_both(pool: PgPool) {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let project_id = create_project(&repo, "Both").await;let facts = repo.get_team_share_facts(&project_id).await.unwrap();@@ -473,7 +473,7 @@ async fn edit_team_share_and_link_share_in_one_call_persists_both(pool: PgPool)fixtures(path = "../fixtures", scripts("users", "team")))]async fn get_project_share_permission_reads_team_share_access_level(pool: PgPool) {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let project_id = create_project(&repo, "Read").await;assert_eq!(repo.get_project_share_permission(&project_id)diff --git a/crates/projects/src/outbound/pg_project_repo/tests.rs b/crates/projects/src/outbound/pg_project_repo/tests.rsindex c99c2cc2e3..bbace6f9a9 100644--- a/crates/projects/src/outbound/pg_project_repo/tests.rs+++ b/crates/projects/src/outbound/pg_project_repo/tests.rs@@ -1,20 +1,41 @@use std::collections::HashMap;+use entity_registry::{BotFacts, EntityRegistryResult, OwnerGrantPolicy};+use entity_registry_db_utils::OwnedEntityRegistrar;use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model::document::FileType;use model::folder::{FileSystemNode, FileSystemNodeWithIds, FolderItem};use model::item::Item;use model::project::ProjectPreviewV2;+use model_owner::Owner;use models_permissions::share_permission::{LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2, access_level::AccessLevel,};-use sqlx::{Pool, Postgres, Row};+use sqlx::{PgPool, Pool, Postgres, Row};use super::PgProjectRepo;use crate::domain::models::{CreateProjectArgs, EditProjectArgs, UploadFolderRepoArgs};use crate::domain::ports::ProjectRepo;+#[derive(Clone)]+pub(super) struct NoBots;++impl BotFacts for NoBots {+ async fn sponsor(&self, _bot: bot_id::BotId) -> EntityRegistryResult<Option<Owner>> {+ Ok(None)+ }+}++pub(super) type TestRepo = PgProjectRepo<NoBots>;++pub(super) fn test_repo(pool: PgPool) -> TestRepo {+ PgProjectRepo::new(+ pool,+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(NoBots)),+ )+}+const ROOT_ID: &str = "10000000-0000-0000-0000-000000000001";const CHILD_ID: &str = "10000000-0000-0000-0000-000000000002";const DELETED_ID: &str = "10000000-0000-0000-0000-000000000009";@@ -112,7 +133,7 @@ async fn project_share_permission_columns(async fn history_listing_differs_from_owner_pending_listing(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool);+ let repo = test_repo(pool);let viewed = repo.get_projects_for_user("macro|[email protected]").await?;assert_eq!(@@ -154,7 +175,7 @@ async fn history_listing_differs_from_owner_pending_listing(async fn basic_lookup_includes_deleted_but_full_lookup_excludes_it(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool);+ let repo = test_repo(pool);let basic = repo.get_basic_project(DELETED_ID)@@ -174,7 +195,7 @@ async fn basic_lookup_includes_deleted_but_full_lookup_excludes_it(async fn children_are_depth_one_filtered_and_type_ordered(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool);+ let repo = test_repo(pool);let children = repo.get_project_children(ROOT_ID).await?;let children = children@@ -206,7 +227,7 @@ async fn children_are_depth_one_filtered_and_type_ordered(async fn preview_preserves_found_and_missing_input_entries(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool);+ let repo = test_repo(pool);let missing = "10000000-0000-0000-0000-000000000099".to_owned();let previews = repo.batch_get_project_preview(&[CHILD_ID.to_owned(), missing.clone()])@@ -233,7 +254,7 @@ async fn preview_preserves_found_and_missing_input_entries(async fn reads_share_permissions_and_bumps_modified_timestamp(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool);+ let repo = test_repo(pool);let permission = repo.get_project_share_permission(ROOT_ID).await?;assert_eq!(permission.id, "share-root");assert_eq!(permission.owner, "macro|[email protected]");@@ -264,7 +285,7 @@ async fn reads_share_permissions_and_bumps_modified_timestamp(fixtures(path = "../../../fixtures", scripts("projects_test_data")))]async fn create_is_atomic_and_inserts_all_metadata(pool: Pool<Postgres>) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let permission = SharePermissionV2::new_project_share_permission(None);let project = repo.create_project(CreateProjectArgs {@@ -345,7 +366,7 @@ async fn create_is_atomic_and_inserts_all_metadata(pool: Pool<Postgres>) -> anyhfixtures(path = "../../../fixtures", scripts("projects_test_data")))]async fn create_defaults_enabled_link_share_to_view(pool: Pool<Postgres>) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let mut permission = SharePermissionV2::new_project_share_permission(None);permission.link_share = Some(LinkShare::Team);@@ -376,7 +397,7 @@ async fn create_defaults_enabled_link_share_to_view(pool: Pool<Postgres>) -> anyfixtures(path = "../../../fixtures", scripts("projects_test_data")))]async fn edit_supports_parent_flags_and_sharing(pool: Pool<Postgres>) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let unchanged = repo.edit_project(EditProjectArgs {project_id: CHILD_ID.to_owned(),@@ -528,7 +549,7 @@ async fn edit_supports_parent_flags_and_sharing(pool: Pool<Postgres>) -> anyhow:fixtures(path = "../../../fixtures", scripts("projects_test_data")))]async fn recursive_detection_and_soft_delete_output(pool: Pool<Postgres>) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());assert!(repo.is_project_recursively_nested(ROOT_ID, ROOT_ID).await?);assert!(repo.is_project_recursively_nested(ROOT_ID, CHILD_ID)@@ -582,7 +603,7 @@ async fn recursive_detection_and_soft_delete_output(pool: Pool<Postgres>) -> anyasync fn revert_restores_subtree_and_handles_parent_state(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());sqlx::query!(r#"UPDATE "Project" SET "parentId" = $2 WHERE id = $1"#,ROOT_ID,@@ -626,7 +647,7 @@ async fn revert_restores_subtree_and_handles_parent_state(async fn purge_returns_outputs_and_removes_access_and_permissions(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let deleted = repo.soft_delete_project(ROOT_ID).await?;let document_id = &deleted.document_ids[0];let bom_id = sqlx::query_scalar!(@@ -684,7 +705,7 @@ async fn purge_returns_outputs_and_removes_access_and_permissions(fixtures(path = "../../../fixtures", scripts("projects_test_data")))]async fn purge_rolls_back_all_deletions(pool: Pool<Postgres>) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());repo.soft_delete_project(ROOT_ID).await?;let mut transaction = pool.begin().await?;@@ -711,14 +732,7 @@ async fn purge_rolls_back_all_deletions(pool: Pool<Postgres>) -> anyhow::Result<Ok(())}-#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../fixtures", scripts("projects_test_data"))-)]-async fn upload_folder_preserves_tree_metadata_and_compensates(- pool: Pool<Postgres>,-) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool.clone());+fn nested_upload_args() -> anyhow::Result<UploadFolderRepoArgs> {let file = FolderItem {name: "nested.pdf".to_owned(),full_name: "nested.pdf".to_owned(),@@ -738,16 +752,70 @@ async fn upload_folder_preserves_tree_metadata_and_compensates(]));let mut share_permission = SharePermissionV2::new_project_share_permission(None);share_permission.link_share = Some(LinkShare::Team);- let result = repo- .upload_folder(UploadFolderRepoArgs {- user_id: MacroUserIdStr::parse_from_str("macro|[email protected]")?.into_owned(),- share_permission,- root_folder,- root_folder_name: "Upload".to_owned(),- upload_request_id: "lambda-request-id".to_owned(),- parent_id: Some(ROOT_ID.to_owned()),- })- .await?;+ Ok(UploadFolderRepoArgs {+ user_id: MacroUserIdStr::parse_from_str("macro|[email protected]")?.into_owned(),+ share_permission,+ root_folder,+ root_folder_name: "Upload".to_owned(),+ upload_request_id: "lambda-request-id".to_owned(),+ parent_id: Some(ROOT_ID.to_owned()),+ })+}++async fn direct_grants(pool: &Pool<Postgres>, id: &str) -> Vec<(String, String, String)> {+ sqlx::query!(+ r#"+ SELECT source_type::text AS "source_type!", source_id,+ access_level::text AS "access_level!"+ FROM entity_access+ WHERE entity_id::text = $1 AND granted_from_project_id IS NULL+ ORDER BY source_type::text, source_id+ "#,+ id,+ )+ .fetch_all(pool)+ .await+ .unwrap()+ .into_iter()+ .map(|row| (row.source_type, row.source_id, row.access_level))+ .collect()+}++#[derive(Debug, PartialEq)]+struct UploaderRows {+ upload_projects: i64,+ documents: i64,+ entities: i64,+ grants: i64,+}++async fn uploader_rows(pool: &Pool<Postgres>) -> UploaderRows {+ sqlx::query_as!(+ UploaderRows,+ r#"+ SELECT+ (SELECT COUNT(*) FROM "Project" WHERE "uploadRequestId" = 'lambda-request-id')+ AS "upload_projects!",+ (SELECT COUNT(*) FROM "Document" WHERE owner = $1) AS "documents!",+ (SELECT COUNT(*) FROM entity WHERE owner_id = $1) AS "entities!",+ (SELECT COUNT(*) FROM entity_access WHERE source_id = $1) AS "grants!"+ "#,+ "macro|[email protected]",+ )+ .fetch_one(pool)+ .await+ .unwrap()+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn upload_folder_preserves_tree_metadata_and_compensates(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = test_repo(pool.clone());+ let result = repo.upload_folder(nested_upload_args()?).await?;assert_eq!(result.project_ids.len(), 3);assert_eq!(result.documents.len(), 1);@@ -798,16 +866,28 @@ async fn upload_folder_preserves_tree_metadata_and_compensates(.await?;assert_eq!(created_permissions, 4);+ let uploader_grant = || {+ (+ "user".to_owned(),+ "macro|[email protected]".to_owned(),+ "owner".to_owned(),+ )+ };for project_id in &result.project_ids {let entity = fetch_entity_row(&pool, project_id).await;assert_eq!(entity.owner_type, "user");assert_eq!(entity.owner_id, "macro|[email protected]");assert_eq!(entity.entity_type, "project");+ assert_eq!(direct_grants(&pool, project_id).await, [uploader_grant()]);}let document_entity = fetch_entity_row(&pool, &result.documents[0].document_id).await;assert_eq!(document_entity.owner_type, "user");assert_eq!(document_entity.owner_id, "macro|[email protected]");assert_eq!(document_entity.entity_type, "document");+ assert_eq!(+ direct_grants(&pool, &result.documents[0].document_id).await,+ [uploader_grant()]+ );repo.delete_uploaded_tree(&result.project_ids, &document_ids).await?;@@ -833,6 +913,45 @@ async fn upload_folder_preserves_tree_metadata_and_compensates(Ok(())}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn upload_folder_rolls_back_the_whole_tree_when_a_registration_fails(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = test_repo(pool.clone());+ let before = uploader_rows(&pool).await;+ sqlx::raw_sql(+ r#"+ CREATE FUNCTION reject_document_grant() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN RAISE EXCEPTION 'injected document grant failure'; END $$;+ CREATE TRIGGER reject_document_grant BEFORE INSERT ON entity_access+ FOR EACH ROW WHEN (NEW.entity_type = 'document') EXECUTE FUNCTION reject_document_grant();+ "#,+ )+ .execute(&pool)+ .await?;++ assert!(repo.upload_folder(nested_upload_args()?).await.is_err());+ assert_eq!(uploader_rows(&pool).await, before);++ sqlx::raw_sql("DROP TRIGGER reject_document_grant ON entity_access")+ .execute(&pool)+ .await?;+ repo.upload_folder(nested_upload_args()?).await?;+ assert_eq!(+ uploader_rows(&pool).await,+ UploaderRows {+ upload_projects: before.upload_projects + 3,+ documents: before.documents + 1,+ entities: before.entities + 4,+ grants: before.grants + 4,+ }+ );+ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("projects_test_data"))@@ -840,7 +959,7 @@ async fn upload_folder_preserves_tree_metadata_and_compensates(async fn mark_uploaded_is_recursive_and_rejects_missing_root(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool.clone());+ let repo = test_repo(pool.clone());let uploaded_tree = repo.mark_projects_uploaded("10000000-0000-0000-0000-000000000006").await?;diff --git a/crates/projects/src/outbound/pg_project_repo/upload_folder.rs b/crates/projects/src/outbound/pg_project_repo/upload_folder.rsindex 6afb7fb521..40707243f2 100644--- a/crates/projects/src/outbound/pg_project_repo/upload_folder.rs+++ b/crates/projects/src/outbound/pg_project_repo/upload_folder.rs@@ -4,10 +4,13 @@ use async_recursion::async_recursion;use entity_access_db_utils::{AccessLevel, EntityAccessSourceType, EntityType, insert_entity_access_row,};+use entity_registry::BotFacts;+use entity_registry_db_utils::{NewEntityRecord, OwnedEntityRegistrar, RegisteredEntityType};use macro_user_id::user_id::MacroUserIdStr;use model::document::{DocumentMetadata, FileType, FileTypeExt};use model::folder::{FileSystemNode, FileSystemNodeWithIds, UploadFolderWithIdsResponse};use model::project::Project;+use model_owner::Owner;use models_permissions::share_permission::SharePermissionV2;use sqlx::{Postgres, Transaction};@@ -15,8 +18,9 @@ use crate::domain::models::{MarkedUploadedTree, UploadFolderRepoArgs};use super::share;-pub(super) async fn upload_folder(+pub(super) async fn upload_folder<B: BotFacts>(transaction: &mut Transaction<'_, Postgres>,+ registrar: &OwnedEntityRegistrar<B>,args: UploadFolderRepoArgs,) -> Result<UploadFolderWithIdsResponse, sqlx::Error> {let root_project = create_pending_project(@@ -41,6 +45,7 @@ pub(super) async fn upload_folder(for (name, node) in root_content {let extended_node = traverse_with_ids(transaction,+ registrar,node,args.user_id.clone(),&args.share_permission,@@ -68,8 +73,9 @@ pub(super) async fn upload_folder(#[async_recursion]#[expect(clippy::too_many_arguments, reason = "recursive tree traversal state")]-async fn traverse_with_ids(+async fn traverse_with_ids<B>(transaction: &mut Transaction<'_, Postgres>,+ registrar: &OwnedEntityRegistrar<B>,node: &FileSystemNode,user_id: MacroUserIdStr<'static>,share_permission: &SharePermissionV2,@@ -78,12 +84,21 @@ async fn traverse_with_ids(upload_request_id: &str,project_ids: &mut Vec<String>,documents: &mut Vec<DocumentMetadata>,-) -> Result<FileSystemNodeWithIds, sqlx::Error> {+) -> Result<FileSystemNodeWithIds, sqlx::Error>+where+ B: BotFacts,+{match node {FileSystemNode::File(item) => {- let document =- create_empty_document(transaction, user_id, share_permission, item, parent_project)- .await?;+ let document = create_empty_document(+ transaction,+ registrar,+ user_id,+ share_permission,+ item,+ parent_project,+ )+ .await?;let document_id = document.document_id.clone();documents.push(document);Ok(FileSystemNodeWithIds::File {@@ -107,6 +122,7 @@ async fn traverse_with_ids(for (child_name, child) in content {let extended_node = traverse_with_ids(transaction,+ registrar,child,user_id.clone(),share_permission,@@ -182,10 +198,10 @@ async fn create_pending_project(.await?;entity_registry_db_utils::insert_entity(transaction,- entity_registry_db_utils::NewEntityRecord::new(+ NewEntityRecord::new(entity_id,- entity_registry_db_utils::RegisteredEntityType::Project,- model_owner::Owner::User(user_id.clone()),+ RegisteredEntityType::Project,+ Owner::User(user_id),),).await@@ -193,8 +209,28 @@ async fn create_pending_project(Ok(project)}-async fn create_empty_document(+async fn register_user_owned_document<B: BotFacts>(+ transaction: &mut Transaction<'_, Postgres>,+ registrar: &OwnedEntityRegistrar<B>,+ id: &str,+ user_id: MacroUserIdStr<'static>,+) -> Result<(), sqlx::Error> {+ let id = id+ .parse()+ .map_err(|error| sqlx::Error::Decode(Box::new(error)))?;+ registrar+ .register_owned_entity(+ transaction,+ NewEntityRecord::new(id, RegisteredEntityType::Document, Owner::User(user_id)),+ )+ .await+ .map_err(|error| sqlx::Error::Protocol(error.to_string()))?;+ Ok(())+}++async fn create_empty_document<B: BotFacts>(transaction: &mut Transaction<'_, Postgres>,+ registrar: &OwnedEntityRegistrar<B>,user_id: MacroUserIdStr<'static>,share_permission: &SharePermissionV2,item: &model::folder::FolderItem,@@ -245,34 +281,12 @@ async fn create_empty_document(};create_document_share_permission(transaction, &document.id, share_permission).await?;- let entity_id = document- .id- .parse()- .map_err(|error| sqlx::Error::Decode(Box::new(error)))?;- insert_entity_access_row(- transaction,- &entity_id,- EntityType::Document,- user_id.as_ref(),- EntityAccessSourceType::User,- AccessLevel::Owner,- )- .await?;- entity_registry_db_utils::insert_entity(- transaction,- entity_registry_db_utils::NewEntityRecord::new(- entity_id,- entity_registry_db_utils::RegisteredEntityType::Document,- model_owner::Owner::User(user_id.clone()),- ),- )- .await- .map_err(|error| sqlx::Error::Protocol(error.to_string()))?;+ register_user_owned_document(transaction, registrar, &document.id, user_id.clone()).await?;Ok(DocumentMetadata::new_document(&document.id,version_id,- model_owner::Owner::User(user_id),+ Owner::User(user_id),&document_name,item.file_type,&item.sha,diff --git a/crates/properties/src/domain/service_impl.rs b/crates/properties/src/domain/service_impl.rsindex 3e334f2728..a639cd9c8b 100644--- a/crates/properties/src/domain/service_impl.rs+++ b/crates/properties/src/domain/service_impl.rs@@ -75,13 +75,16 @@ fn published_event_actors(access: &EditReceipt) -> PublishedEventActors {on_behalf_of: Some(acting_user.clone()),actor_user_id: None,},- BotReceiptScope::Team { .. } | BotReceiptScope::Channel { .. } => {- PublishedEventActors {- actor: None,- on_behalf_of: None,- actor_user_id: None,- }- }+ BotReceiptScope::Team { .. } => PublishedEventActors {+ actor: Some(Actor::new_from_bot(bot.bot_id())),+ on_behalf_of: None,+ actor_user_id: None,+ },+ BotReceiptScope::Channel { .. } => PublishedEventActors {+ actor: None,+ on_behalf_of: None,+ actor_user_id: None,+ },},EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => PublishedEventActors {actor: None,diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rsindex 77972da201..4194a1ad1b 100644--- a/crates/properties/src/domain/test.rs+++ b/crates/properties/src/domain/test.rs@@ -1183,7 +1183,7 @@ async fn entity_property_event_set_failures_do_not_publish_before_commit() {}#[tokio::test]-async fn entity_property_event_actor_is_only_an_authenticated_user() {+async fn entity_property_event_attributes_team_bot_but_not_system_access() {let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"));let bot_access = EditReceipt::dangerously_assert_bot(bot_id.into_storage_id(),@@ -1207,7 +1207,11 @@ async fn entity_property_event_actor_is_only_an_authenticated_user() {let internal_access =EditReceipt::dangerously_assert_internal_user("doc1", AccessEntityType::Document);- for access in [bot_access, unauthenticated_access, internal_access] {+ for (access, expected_actor) in [+ (bot_access, Some(bot_id.into_storage_id().to_string())),+ (unauthenticated_access, None),+ (internal_access, None),+ ] {let property_definition_id = Uuid::from_u128(0xE704);let assignment = entity_property_for_event(Uuid::from_u128(0xE705),@@ -1245,7 +1249,12 @@ async fn entity_property_event_actor_is_only_an_authenticated_user() {published.envelope["metadata"]["actor_user_id"],serde_json::Value::Null);- assert!(published.envelope["metadata"]["actor"].is_null());+ assert_eq!(+ published.envelope["metadata"]["actor"],+ expected_actor+ .map(serde_json::Value::String)+ .unwrap_or(serde_json::Value::Null)+ );assert!(published.envelope["metadata"]["on_behalf_of"].is_null());}}diff --git a/crates/share_permission_db_utils/src/team_share.rs b/crates/share_permission_db_utils/src/team_share.rsindex e62d2aecb0..3939d455e8 100644--- a/crates/share_permission_db_utils/src/team_share.rs+++ b/crates/share_permission_db_utils/src/team_share.rs@@ -376,6 +376,20 @@ pub async fn initialize(if target.is_none() {return Ok(());}+ if let Some(target) = target+ && state.facts.owner_team_id == Some(target.team_id)+ && direct_level(+ transaction.as_mut(),+ &entity_uuid(entity)?,+ entity.entity_type,+ target.team_id,+ )+ .await+ .context(TeamShareError::Infrastructure)?+ == Some(AccessLevel::Owner)+ {+ return Ok(());+ }reject_untracked(transaction.as_mut(), &state.facts, target).await?;write_state(transaction, state, target, 1).await}diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rsindex d4170dcb11..43061f883d 100644--- a/crates/webhook/src/domain/ingestion/test.rs+++ b/crates/webhook/src/domain/ingestion/test.rs@@ -515,6 +515,8 @@ fn document_event_cases() -> Vec<EventCase> {source_document_id: DOCUMENT_ID.to_string(),source_version_id: None,owner: Owner::User(user_id("macro|[email protected]")),+ actor: None,+ on_behalf_of: None,document_name: "notes (copy)".to_string(),file_type: None,project_id: None,diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex b8a42a7322..f2983f680b 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -4611,6 +4611,10 @@ export type DocumentContentUploadedMetadata = {* Metadata for [`DocumentTopicEvent::Copied`].*/export type DocumentCopiedMetadata = {+ /**+ * Who mechanically created the copy.+ */+ actor?: string | null;/*** The id of the newly created copy.*/@@ -4620,6 +4624,7 @@ export type DocumentCopiedMetadata = {*/document_name: string;file_type?: null | FileType;+ on_behalf_of?: null | MacroUserIdStr;/*** The principal who owns the new copy.*/diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex cc29f6eb06..8257a38871 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -22030,6 +22030,10 @@"document_name"],"properties": {+ "actor": {+ "type": ["string", "null"],+ "description": "Who mechanically created the copy."+ },"document_id": {"type": "string","description": "The id of the newly created copy."@@ -22049,6 +22053,17 @@}]},+ "on_behalf_of": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "The user whose feed this copy belongs on, when different from the actor."+ }+ ]+ },"owner": {"type": "string","description": "The principal who owns the new copy."diff --git a/services/document_cognition_service/Cargo.toml b/services/document_cognition_service/Cargo.tomlindex 365c9a5edf..f84806e4ad 100644--- a/services/document_cognition_service/Cargo.toml+++ b/services/document_cognition_service/Cargo.toml@@ -37,6 +37,7 @@ ai_toolset = { path = "../../crates/ai_toolset" }anyhow = { workspace = true }async-openai = { workspace = true }async-stream = { workspace = true }+bots = { path = "../../crates/bots", default-features = false, features = ["outbound"] }async-trait = { workspace = true }aws-sdk-dynamodb = { workspace = true }aws-sdk-s3 = { workspace = true }@@ -59,6 +60,8 @@ email = { path = "../../crates/email", features = ["outbound", "attachment"] }email_service_client = { path = "../../crates/email_service_client" }entity_access = { path = "../../crates/entity_access" }entity_access_management = { path = "../../crates/entity_access_management" }+entity_registry = { path = "../../crates/entity_registry/entity_registry" }+entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }foreign_entity = { path = "../../crates/foreign_entity" }frecency = { path = "../../crates/frecency", features = ["outbound", "postgres"] }futures = { workspace = true }diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex a86b9da883..0d5a827fc0 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -233,7 +233,14 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar"test-bucket","test-docx-bucket",);- let document_repo = documents::outbound::pg_document_repo::PgDocumentRepo::new(pool.clone());+ let document_repo = documents::outbound::pg_document_repo::PgDocumentRepo::new(+ pool.clone(),+ entity_registry_db_utils::OwnedEntityRegistrar::new(+ entity_registry::OwnerGrantPolicy::new(bots::outbound::pg_bots_repo::PgBotsRepo::new(+ pool.clone(),+ )),+ ),+ );let cloudfront_config = documents::domain::models::CloudFrontConfig {distribution_url: "https://test.cloudfront.net".to_string(),signer_public_key_id: "test-key-id".to_string(),diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rsindex eaba53f00a..592beeda31 100644--- a/services/document_cognition_service/src/main.rs+++ b/services/document_cognition_service/src/main.rs@@ -2,6 +2,7 @@use crate::api::context::ApiContext;use ai_tools::{NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress};use anyhow::Context;+use bots::outbound::pg_bots_repo::PgBotsRepo;use call::domain::service::{CallRecordQueryServiceImpl, CallServiceImpl};use call::inbound::toolset::CallToolContext;use call::outbound::pg_call_repo::PgCallRepo;@@ -21,6 +22,8 @@ use email::domain::service::EmailServiceImpl;use email::outbound::EmailPgRepo;use email_service_client::{EmailServiceClient, EmailServiceClientExternal};use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use foreign_entity::{domain::service::ForeignEntityServiceImpl,outbound::pg_foreign_entity_repo::PgForeignEntityRepo,@@ -270,7 +273,10 @@ async fn main() -> anyhow::Result<()> {config.document_storage_bucket.to_string(),config.docx_document_upload_bucket.to_string(),);- let document_repo = PgDocumentRepo::new(db.clone());+ let document_repo = PgDocumentRepo::new(+ db.clone(),+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(db.clone()))),+ );let cloudfront_config = CloudFrontConfig {distribution_url: configdiff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.tomlindex 3c5392e694..547d5c1aa9 100644--- a/services/document_storage_service/Cargo.toml+++ b/services/document_storage_service/Cargo.toml@@ -104,6 +104,8 @@ entity_access = { path = "../../crates/entity_access", features = [] }entity_access_management = { path = "../../crates/entity_access_management" }entity_mutation = { path = "../../crates/entity_mutation" }+entity_registry = { path = "../../crates/entity_registry/entity_registry" }+entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }favorites = { path = "../../crates/favorites", features = ["inbound","postgres",diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex 8180773245..5e5eef970b 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -285,22 +285,16 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {async fn set_entity_property(&self,- user_id: &str,+ principal: &model_owner::CreationPrincipal,entity_id: &str,property_definition_id: uuid::Uuid,value: Option<models_properties::api::requests::SetPropertyValue>,- attribution: &activity::Attribution,) -> anyhow::Result<()> {use properties::PropertiesService as _;- let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)?;- let entity_access_receipt = task_property_edit_receipt(- self.entity_access_service.as_ref(),- &user_id,- attribution,- entity_id,- )- .await?;+ let entity_access_receipt =+ task_property_edit_receipt(self.entity_access_service.as_ref(), principal, entity_id)+ .await?;self.properties.set_entity_property(&entity_access_receipt, property_definition_id, value).await@@ -328,7 +322,7 @@ pub(crate) type EntityAccessManagementService =>;pub(crate) type DocumentService = DocumentServiceImpl<- PgDocumentRepo,+ PgDocumentRepo<PgBotsRepo>,S3UploadUrlAdapter,TaskPropertiesAdapter,ConnectionServiceImpl<EntityAccessService, ConnectionGatewayImpl>,@@ -347,7 +341,7 @@ pub(crate) type DocumentsState =/// Concrete project service wired into DSS.pub(crate) type ProjectService = ProjectServiceImpl<- PgProjectRepo,+ PgProjectRepo<PgBotsRepo>,S3ProjectUploadAdapter,DynamoBulkUploadAdapter,ShaCountAdapter,diff --git a/services/document_storage_service/src/api/documents/initialize_starter_docs.rs b/services/document_storage_service/src/api/documents/initialize_starter_docs.rsindex 2a69dc44ab..a84cf87635 100644--- a/services/document_storage_service/src/api/documents/initialize_starter_docs.rs+++ b/services/document_storage_service/src/api/documents/initialize_starter_docs.rs@@ -1,5 +1,4 @@use crate::api::context::{ApiContext, AuthorizationService};-use activity::{Actor, Attribution};use axum::{extract::State,response::{IntoResponse, Json, Response},@@ -22,6 +21,7 @@ use model::document_storage_service_internal::{};use model::response::GenericResponse;use model_entity::EntityType;+use model_owner::CreationPrincipal;use models_properties::api::{AddPropertyOptionRequest, AddStringOptionRequest, SetPropertyValue};use models_properties::service::property_option::PropertyOptionValue;use properties::{PropertiesService as _, domain::model::TagScope};@@ -172,10 +172,10 @@ pub async fn handler(tracing::info!("initialize starter docs");let user_id = &user_context.authorization.user.macro_user_id;- let system_for_user = Attribution::delegated(- Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID),- user_id.clone(),- );+ let system_for_user = &CreationPrincipal::BotForUser {+ bot: bot_id::MACRO_SYSTEM_BOT_ID,+ user: user_id.clone(),+ };// Resolve every starter document's deterministic id up front so the// templates can cross-link before any document has been created.@@ -257,10 +257,7 @@ pub async fn handler((id,NewMarkdownTextDocument {- metadata: NewDocumentMetadata::builder(task.name)- .id(id)- .attribution(system_for_user.clone())- .build(),+ metadata: NewDocumentMetadata::builder(task.name).id(id).build(),markdown: fill(task.template),subtype: MarkdownSubtype::Task {// Providing properties replaces the task defaults, so include@@ -303,7 +300,6 @@ pub async fn handler(NewMarkdownTextDocument {metadata: NewDocumentMetadata::builder(HOW_TO_GUIDE_NAME).id(guide_uuid)- .attribution(system_for_user.clone()).build(),markdown: fill(HOW_TO_GUIDE_TEMPLATE),subtype: MarkdownSubtype::Note,@@ -316,7 +312,7 @@ pub async fn handler(state_ref.documents_state.creator- .create_markdown_text(user_id.clone(), document)+ .create_markdown_text(system_for_user, document).await.map(|_| ())},diff --git a/services/document_storage_service/src/api/documents/permissions_token/create_permission_token.rs b/services/document_storage_service/src/api/documents/permissions_token/create_permission_token.rsindex 1590be0e20..00af7d0918 100644--- a/services/document_storage_service/src/api/documents/permissions_token/create_permission_token.rs+++ b/services/document_storage_service/src/api/documents/permissions_token/create_permission_token.rs@@ -1,4 +1,7 @@use crate::api::context::{AuthorizationService, EntityAccessService};+#[cfg(test)]+mod test;+use axum::{Json,extract::{Path, State},@@ -8,9 +11,7 @@ use axum::{use documents_hex::domain::permission_token::encode_permission_token;use entity_access::domain::models::EntityPermission;use entity_access::inbound::axum_extractors::DocumentAccessExtractor;-use macro_authorization::{- OptionalMacroAuthorizationExtractor, UserOrInternalService, UserOrInternalServiceAuthorization,-};+use macro_authorization::{AnyPrincipal, MacroAuthorization, OptionalMacroAuthorizationExtractor};use model::response::ErrorResponse;use models_permissions::share_permission::access_level::{AccessLevel, ViewAccessLevel};use serde::Deserialize;@@ -29,6 +30,26 @@ pub struct DocumentPermissionsTokenResponse {pub token: String,}+fn token_identity(+ authorization: Option<&MacroAuthorization>,+) -> Result<(Option<String>, Option<String>), ()> {+ match authorization {+ None => Ok((None, None)),+ Some(MacroAuthorization::User(user)) => Ok((Some(user.macro_user_id.to_string()), None)),+ Some(MacroAuthorization::Bot(bot)) => Ok((+ bot.acting_user+ .as_ref()+ .map(|user| user.macro_user_id.to_string()),+ Some(bot.bot_id.into_storage_id().to_string()),+ )),+ Some(MacroAuthorization::Internal(user)) => Ok((+ user.as_ref().map(|user| user.macro_user_id.to_string()),+ None,+ )),+ Some(MacroAuthorization::Harness(_)) => Err(()),+ }+}+/// Generates a document permissions token for a provided document id#[utoipa::path(tag = "document",@@ -51,7 +72,7 @@ pub struct DocumentPermissionsTokenResponse {)]pub async fn handler(State(state): State<ApiContext>,- user: OptionalMacroAuthorizationExtractor<AuthorizationService, UserOrInternalService>,+ user: OptionalMacroAuthorizationExtractor<AuthorizationService, AnyPrincipal>,users_access_level: DocumentAccessExtractor<ViewAccessLevel,EntityAccessService,@@ -62,11 +83,15 @@ pub async fn handler(if let Some(actor) = user.acting_entity() {tracing::Span::current().record("actor", tracing::field::display(actor));}- let user_id = user- .authorization- .as_ref()- .and_then(UserOrInternalServiceAuthorization::acting_user)- .map(|user| user.macro_user_id.to_string());+ let (user_id, actor) = token_identity(user.authorization.as_ref()).map_err(|()| {+ (+ StatusCode::FORBIDDEN,+ Json(ErrorResponse {+ message: "forbidden".into(),+ }),+ )+ .into_response()+ })?;let access_level = match users_access_level.entity_access_receipt.entity_permission() {EntityPermission::AccessLevel { access_level } => *access_level,@@ -78,7 +103,7 @@ pub async fn handler(document_id,access_level,state.config.document_permission_jwt.as_ref(),- None,+ actor,).map_err(|e| {tracing::error!(error=?e, "unable to encode jwt");diff --git a/services/document_storage_service/src/api/documents/permissions_token/create_permission_token/test.rs b/services/document_storage_service/src/api/documents/permissions_token/create_permission_token/test.rsnew file mode 100644index 0000000000..03e936d17e--- /dev/null+++ b/services/document_storage_service/src/api/documents/permissions_token/create_permission_token/test.rs@@ -0,0 +1,31 @@+use bot_id::BotId;+use macro_authorization::{BotAuthentication, BotScope, MacroAuthorization};+use uuid::Uuid;++use super::token_identity;++#[test]+fn bot_tokens_keep_the_actor_without_inventing_a_user() {+ let bot_id = BotId::new_from_uuid(Uuid::from_u128(42));+ let bot = BotAuthentication {+ bot_id,+ token_id: Uuid::nil(),+ bot_scope: BotScope::Team,+ team_id: Some(Uuid::from_u128(7)),+ acting_user: None,+ };++ assert_eq!(+ token_identity(Some(&MacroAuthorization::Bot(bot))),+ Ok((None, Some(bot_id.into_storage_id().to_string())))+ );+}++#[test]+fn anonymous_and_identityless_internal_tokens_have_no_identity_claims() {+ assert_eq!(token_identity(None), Ok((None, None)));+ assert_eq!(+ token_identity(Some(&MacroAuthorization::Internal(None))),+ Ok((None, None))+ );+}diff --git a/services/document_storage_service/src/api/instructions/create_instructions.rs b/services/document_storage_service/src/api/instructions/create_instructions.rsindex 631fb4be3a..fa558972d8 100644--- a/services/document_storage_service/src/api/instructions/create_instructions.rs+++ b/services/document_storage_service/src/api/instructions/create_instructions.rs@@ -12,6 +12,7 @@ use macro_db_client::instructions::create::{};use macro_db_client::instructions::get::get_instructions_document;use model::response::GenericErrorResponse;+use model_owner::CreationPrincipal;use models_dcs::constants::INSTRUCTIONS_FILE_NAME;/// Creates an instructions document for the current user@@ -46,7 +47,7 @@ pub async fn create_instructions_handler(.documents_state.creator.create_markdown_text(- user_id.clone(),+ &CreationPrincipal::User(user_id.clone()),NewMarkdownTextDocument::empty_note(NewDocumentMetadata::new(INSTRUCTIONS_FILE_NAME)),).await?;diff --git a/services/document_storage_service/src/api/internal.rs b/services/document_storage_service/src/api/internal.rsindex 9572360603..64cda00881 100644--- a/services/document_storage_service/src/api/internal.rs+++ b/services/document_storage_service/src/api/internal.rs@@ -103,7 +103,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {.route("/documents",post(- documents_hex::inbound::axum_router::create_document::create_document_handler::<+ documents_hex::inbound::axum_router::create_document::create_document_internal_handler::<DocumentService,EntityAccessService,AuthorizationService,diff --git a/services/document_storage_service/src/config.rs b/services/document_storage_service/src/config.rsindex 78f2e5fdc1..c9654965bb 100644--- a/services/document_storage_service/src/config.rs+++ b/services/document_storage_service/src/config.rs@@ -165,6 +165,12 @@ pub struct Config {#[macro_config_default(true)]pub legacy_comment_writes_enabled: bool,+ /// Lets a team-scoped bot with no acting user own the documents it+ /// creates. When `false` (the default) the document create routes answer+ /// those bots with 403, so every new document stays user-owned.+ #[macro_config_default(false)]+ pub enable_non_user_owners: bool,+/// The number of seconds a signed document or call recording URL is valid for.#[macro_config_default(DEFAULT_PRESIGNED_URL_EXPIRY_SECONDS)]pub document_storage_service_presigned_url_expiry_seconds: u64,diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex 8eb5ecac79..212f6d94d9 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -77,6 +77,8 @@ use email::{outbound::EmailPgRepo,};use embedding::embedding_provider::openai::TextEmbedding3Small;+use entity_registry::{NonUserOwners, OwnerGrantPolicy};+use entity_registry_db_utils::OwnedEntityRegistrar;use favorites::{domain::{mutation_service::FavoritesMutationServiceImpl, service::FavoritesServiceImpl},inbound::axum_router::FavoritesRouterState,@@ -467,7 +469,9 @@ async fn run() -> anyhow::Result<()> {));let system_properties_service = Arc::new(system_properties_service);- let document_repo = PgDocumentRepo::new(db.clone());+ let owned_entity_registrar =+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(db.clone())));+ let document_repo = PgDocumentRepo::new(db.clone(), owned_entity_registrar.clone());let cloudfront_config = CloudFrontConfig {distribution_url: config.document_storage_service_cloudfront_distribution_url@@ -513,7 +517,7 @@ async fn run() -> anyhow::Result<()> {));let project_service = Arc::new(ProjectServiceImpl::new(- PgProjectRepo::new(db.clone()),+ PgProjectRepo::new(db.clone(), owned_entity_registrar),S3ProjectUploadAdapter::new(macro_aws_config::s3_client().await,config.document_storage_bucket.as_ref(),@@ -1685,6 +1689,11 @@ async fn run() -> anyhow::Result<()> {lexical_client: lexical_client.clone(),creator: document_creator,document_permission_jwt_secret: config.document_permission_jwt.as_ref().to_string(),+ non_user_owners: if config.enable_non_user_owners {+ NonUserOwners::Enabled+ } else {+ NonUserOwners::Disabled+ },},config: Arc::new(config),channel_service: channels_service.clone(),diff --git a/services/document_upload_finalizer_handler/Cargo.toml b/services/document_upload_finalizer_handler/Cargo.tomlindex b76af80829..01db4abe12 100644--- a/services/document_upload_finalizer_handler/Cargo.toml+++ b/services/document_upload_finalizer_handler/Cargo.toml@@ -9,11 +9,14 @@ anyhow = { workspace = true }aws_lambda_events = { workspace = true, features = ["eventbridge"] }aws-sdk-s3 = { workspace = true }aws-sdk-sqs = { workspace = true }+bots = { path = "../../crates/bots", default-features = false, features = ["outbound"] }documents = { path = "../../crates/documents", default-features = false, features = ["markdown_init","outbound","ports",] }+entity_registry = { path = "../../crates/entity_registry/entity_registry" }+entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }lambda_runtime = { workspace = true }lexical_client = { path = "../../crates/lexical_client" }macro_aws_config = { path = "../../crates/macro_aws_config", features = ["s3"] }diff --git a/services/document_upload_finalizer_handler/src/outbound.rs b/services/document_upload_finalizer_handler/src/outbound.rsindex f7b6a6c02d..fc24ecab8e 100644--- a/services/document_upload_finalizer_handler/src/outbound.rs+++ b/services/document_upload_finalizer_handler/src/outbound.rs@@ -3,6 +3,7 @@ use documents::domain::models::DocumentError;use documents::domain::upload_finalize::{RepoUploadFinalizePort, UploadFinalizeDocumentPort};use documents::outbound::pg_document_repo::PgDocumentRepo;use documents::outbound::s3_utf8_object_reader::S3Utf8ObjectReader;+use entity_registry::BotFacts;use model::document::DocumentBasic;use crate::ports::{DocumentObjectReader, DocumentUploadMetadataPort};@@ -35,18 +36,18 @@ impl DocumentObjectReader for S3DocumentObjectReader {/// Postgres-backed document port for upload finalization.#[derive(Clone)]-pub struct PgDocumentUploadPort {- repo: PgDocumentRepo,+pub struct PgDocumentUploadPort<B> {+ repo: PgDocumentRepo<B>,}-impl PgDocumentUploadPort {+impl<B> PgDocumentUploadPort<B> {/// Construct a Postgres document upload port.- pub fn new(repo: PgDocumentRepo) -> Self {+ pub fn new(repo: PgDocumentRepo<B>) -> Self {Self { repo }}}-impl DocumentUploadMetadataPort for PgDocumentUploadPort {+impl<B: BotFacts + Clone + 'static> DocumentUploadMetadataPort for PgDocumentUploadPort<B> {async fn get_basic_document(&self,document_id: &str,@@ -61,7 +62,7 @@ impl DocumentUploadMetadataPort for PgDocumentUploadPort {}}-impl UploadFinalizeDocumentPort for PgDocumentUploadPort {+impl<B: BotFacts + Clone + 'static> UploadFinalizeDocumentPort for PgDocumentUploadPort<B> {async fn get_document_content(&self,document_context: &DocumentBasic,diff --git a/services/document_upload_finalizer_handler/src/runtime.rs b/services/document_upload_finalizer_handler/src/runtime.rsindex 23e25d73f6..0ec0f07482 100644--- a/services/document_upload_finalizer_handler/src/runtime.rs+++ b/services/document_upload_finalizer_handler/src/runtime.rs@@ -1,6 +1,9 @@use anyhow::Context as _;+use bots::outbound::pg_bots_repo::PgBotsRepo;use documents::outbound::markdown_init::LexicalSyncMarkdownInitializer;use documents::outbound::pg_document_repo::PgDocumentRepo;+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use lexical_client::LexicalClient;use macro_env_var::env_vars;use macro_service_urls::{LexicalServiceUrl, SyncServiceUrl};@@ -18,7 +21,7 @@ env_vars! {/// Concrete app context used by Lambda and local worker entrypoints.pub struct AppContext {- finalizer: DocumentUploadFinalizer<PgDocumentUploadPort, S3DocumentObjectReader>,+ finalizer: DocumentUploadFinalizer<PgDocumentUploadPort<PgBotsRepo>, S3DocumentObjectReader>,lexical_client: LexicalClient,sync_service_client: SyncServiceClient,}@@ -42,7 +45,9 @@ impl AppContext {.await.context("failed to connect to postgres")?;- let repo = PgDocumentRepo::new(db_pool);+ let registrar =+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(db_pool.clone())));+ let repo = PgDocumentRepo::new(db_pool, registrar);let document_port = PgDocumentUploadPort::new(repo);let object_reader = S3DocumentObjectReader::new(macro_aws_config::s3_client().await);let finalizer = DocumentUploadFinalizer::new(document_port, object_reader);diff --git a/services/mcp_service/Cargo.toml b/services/mcp_service/Cargo.tomlindex f36e010454..80ea229312 100644--- a/services/mcp_service/Cargo.toml+++ b/services/mcp_service/Cargo.toml@@ -23,6 +23,7 @@ attachment = { path = "../../crates/attachment" }aws-sdk-secretsmanager = { workspace = true }aws-sdk-sqs = { workspace = true }axum = { workspace = true, features = ["tower-log"] }+bots = { path = "../../crates/bots", default-features = false, features = ["outbound"] }call = { path = "../../crates/call", default-features = false, features = ["ports",] }@@ -37,6 +38,8 @@ email = { path = "../../crates/email", features = ["outbound"] }email_service_client = { path = "../../crates/email_service_client" }entity_access = { path = "../../crates/entity_access" }entity_access_management = { path = "../../crates/entity_access_management" }+entity_registry = { path = "../../crates/entity_registry/entity_registry" }+entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }foreign_entity = { path = "../../crates/foreign_entity" }frecency = { path = "../../crates/frecency", features = ["outbound",diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex 652fc7c1c4..64c8b1d54d 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -5,6 +5,7 @@ use ai_tools::{NoOpSnsEndpointManager, ToolImportToolContext, ToolNotificationQueue, ToolServiceContext,};use anyhow::Context;+use bots::outbound::pg_bots_repo::PgBotsRepo;use channels::{domain::list_service::ChannelListServiceImpl, outbound::pg_channels_repo::PgChannelsRepo,};@@ -21,6 +22,8 @@ use email::domain::service::EmailServiceImpl;use email::outbound::EmailPgRepo;use email_service_client::{EmailServiceClient, EmailServiceClientExternal};use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use foreign_entity::{domain::service::ForeignEntityServiceImpl,outbound::pg_foreign_entity_repo::PgForeignEntityRepo,@@ -209,7 +212,10 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Toconfig.document_storage_bucket.as_ref(),config.docx_document_upload_bucket.as_ref(),);- let document_repo = PgDocumentRepo::new(db.clone());+ let document_repo = PgDocumentRepo::new(+ db.clone(),+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(db.clone()))),+ );let cloudfront_private_key = LocalOrRemoteSecret::new_from_secret_manager(config.document_storage_service_cloudfront_signer_private_key_secret_namediff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rsindex ee29eae646..acf5a5da02 100644--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs@@ -951,6 +951,8 @@ fn document_event_cases() -> Vec<(DocumentTopicEvent, DocumentEventDescription)>source_document_id: SOURCE_DOCUMENT_ID.to_string(),source_version_id: Some(7),owner,+ actor: None,+ on_behalf_of: None,document_name: "Copied document".to_string(),file_type: Some(FileType::Pdf),project_id: Some(PROJECT_ID.to_string()),diff --git a/tooling/scripts/verify-document-creation-principal.sh b/tooling/scripts/verify-document-creation-principal.shnew file mode 100755index 0000000000..70be5a31f2--- /dev/null+++ b/tooling/scripts/verify-document-creation-principal.sh@@ -0,0 +1,43 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT_DIR="$(\cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+\cd "$ROOT_DIR"++export DATABASE_URL="${DATABASE_URL:-postgres://user:password@localhost:5432/macrodb}"+unset SQLX_OFFLINE++raw_owner_writes="$(rg -n --glob '!**/test.rs' --glob '!**/tests.rs' \+ 'insert_entity_access_row|insert_entity\(|INSERT INTO entity_access|INSERT INTO entity ' \+ crates/documents/src || true)"+if [[ -n "$raw_owner_writes" ]]; then+ echo "document owners must register through OwnedEntityRegistrar:" >&2+ echo "$raw_owner_writes" >&2+ exit 1+fi++python3 - <<'PY'+from pathlib import Path++path = Path("crates/projects/src/outbound/pg_project_repo/upload_folder.rs")+source = path.read_text()+document_create = source.split("async fn create_empty_document", 1)[1].split(+ "async fn create_document_share_permission", 1+)[0]+if "register_user_owned_document" not in document_create:+ raise SystemExit("folder-upload documents must use the owned entity registrar")+for forbidden in ("insert_entity_access_row", "insert_entity("):+ if forbidden in document_create:+ raise SystemExit(f"folder-upload documents contain raw owner write: {forbidden}")+PY++cargo test -p bot_id -p model_owner -p entity_registry --lib+cargo test -p activity --lib creation_principal+cargo test -p properties --lib entity_property_event+cargo test -p share_permission_db_utils --lib team_share+cargo test -p documents --lib+cargo test -p projects --lib pg_project_repo+cargo test -p document_storage_service bot_tokens_keep_the_actor_without_inventing_a_user+cargo test --no-run -p ai_tools -p memory -p github -p document_storage_service \+ -p document_cognition_service -p mcp_service -p document_upload_finalizer_handler \+ -p webhook -p search_processing_service