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): projects create with a typed owner (#7210)
Will Hutchinson400a7f5e7d0b
diff --git a/.sqlx/query-2036fd34035088aeafb99858f8b016fac6f818f326e4d0c148842ff711178f1c.json b/.sqlx/query-2036fd34035088aeafb99858f8b016fac6f818f326e4d0c148842ff711178f1c.jsonnew file mode 100644index 0000000000..9c1b257bd8--- /dev/null+++ b/.sqlx/query-2036fd34035088aeafb99858f8b016fac6f818f326e4d0c148842ff711178f1c.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT source_type::text AS \"source_type!\", source_id,\n access_level::text AS \"access_level!\", granted_from_project_id\n FROM entity_access\n WHERE entity_id = $1 AND entity_type = 'project'\n ORDER BY source_type::text, source_id, granted_from_project_id NULLS FIRST\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"+ },+ {+ "ordinal": 3,+ "name": "granted_from_project_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null,+ false,+ null,+ true+ ]+ },+ "hash": "2036fd34035088aeafb99858f8b016fac6f818f326e4d0c148842ff711178f1c"+}diff --git a/.sqlx/query-40af4bc51382276ca7165b935d1a9231fa2900cf771f3b7b28c1323c99dc883c.json b/.sqlx/query-40af4bc51382276ca7165b935d1a9231fa2900cf771f3b7b28c1323c99dc883c.jsonnew file mode 100644index 0000000000..4c5df83139--- /dev/null+++ b/.sqlx/query-40af4bc51382276ca7165b935d1a9231fa2900cf771f3b7b28c1323c99dc883c.json@@ -0,0 +1,32 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n (SELECT COUNT(*) FROM \"Project\") AS \"projects!\",\n (SELECT COUNT(*) FROM entity) AS \"entities!\",\n (SELECT COUNT(*) FROM entity_access) AS \"grants!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "projects!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "entities!",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "grants!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null,+ null,+ null+ ]+ },+ "hash": "40af4bc51382276ca7165b935d1a9231fa2900cf771f3b7b28c1323c99dc883c"+}diff --git a/.sqlx/query-46daa61a3a837c75426b48340931a5988793eee1696bfabacb989b458275fd44.json b/.sqlx/query-46daa61a3a837c75426b48340931a5988793eee1696bfabacb989b458275fd44.jsonnew file mode 100644index 0000000000..1cddc761cf--- /dev/null+++ b/.sqlx/query-46daa61a3a837c75426b48340931a5988793eee1696bfabacb989b458275fd44.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT owner_type::text AS \"owner_type!\", owner_id,\n (SELECT COUNT(*) FROM \"UserHistory\" WHERE \"itemId\" = $1) AS \"user_history_rows!\"\n FROM entity\n WHERE id::text = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner_type!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "user_history_rows!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null,+ false,+ null+ ]+ },+ "hash": "46daa61a3a837c75426b48340931a5988793eee1696bfabacb989b458275fd44"+}diff --git a/.sqlx/query-6b7cddc66bafd8797da9d38914f81b52cb654143cff1bbdf1858a13a75003cce.json b/.sqlx/query-6b7cddc66bafd8797da9d38914f81b52cb654143cff1bbdf1858a13a75003cce.jsonnew file mode 100644index 0000000000..25f0fe88ba--- /dev/null+++ b/.sqlx/query-6b7cddc66bafd8797da9d38914f81b52cb654143cff1bbdf1858a13a75003cce.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT 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": "default_link_share?: LinkShare",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "6b7cddc66bafd8797da9d38914f81b52cb654143cff1bbdf1858a13a75003cce"+}diff --git a/.sqlx/query-82b775238244a17a78e7a9a09a6bfd2a848fd68f789975adbeed938b4c60d393.json b/.sqlx/query-82b775238244a17a78e7a9a09a6bfd2a848fd68f789975adbeed938b4c60d393.jsonnew file mode 100644index 0000000000..6d6a559754--- /dev/null+++ b/.sqlx/query-82b775238244a17a78e7a9a09a6bfd2a848fd68f789975adbeed938b4c60d393.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"UserHistory\" (\"userId\", \"itemId\", \"itemType\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, 'project', NOW(), NOW())\n ON CONFLICT (\"userId\", \"itemId\", \"itemType\") DO UPDATE\n SET \"updatedAt\" = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "82b775238244a17a78e7a9a09a6bfd2a848fd68f789975adbeed938b4c60d393"+}diff --git a/.sqlx/query-c8f34fe33771813859b548d69d19f4b4d0b1b972d34c935de0919fbda84cce6c.json b/.sqlx/query-c8f34fe33771813859b548d69d19f4b4d0b1b972d34c935de0919fbda84cce6c.jsondeleted file mode 100644index 17ee804dd9..0000000000--- a/.sqlx/query-c8f34fe33771813859b548d69d19f4b4d0b1b972d34c935de0919fbda84cce6c.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO \"UserHistory\" (\"userId\", \"itemId\", \"itemType\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, 'project', NOW(), NOW())\n ON CONFLICT (\"userId\", \"itemId\", \"itemType\") DO UPDATE\n SET \"updatedAt\" = NOW()\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "c8f34fe33771813859b548d69d19f4b4d0b1b972d34c935de0919fbda84cce6c"-}diff --git a/Cargo.lock b/Cargo.lockindex 2db0d88d67..2f589a2424 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7000,6 +7000,7 @@ dependencies = [name = "entity_registry"version = "0.1.0"dependencies = [+ "axum","bot_id","chrono","harness_id",diff --git a/crates/documents/Cargo.toml b/crates/documents/Cargo.tomlindex 83e210f3c4..3cf44973d8 100644--- a/crates/documents/Cargo.toml+++ b/crates/documents/Cargo.toml@@ -45,6 +45,7 @@ axum = ["dep:task_dedup","dep:utoipa","entity_access/axum",+ "entity_registry/axum","schema",]backfill_binary = [diff --git a/crates/documents/src/inbound/axum_router.rs b/crates/documents/src/inbound/axum_router.rsindex c52bc72b1e..df17c046ea 100644--- a/crates/documents/src/inbound/axum_router.rs+++ b/crates/documents/src/inbound/axum_router.rs@@ -28,7 +28,6 @@ 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;diff --git a/crates/documents/src/inbound/axum_router/copy_document.rs b/crates/documents/src/inbound/axum_router/copy_document.rsindex 8afb6bddd1..c005cc5fe8 100644--- a/crates/documents/src/inbound/axum_router/copy_document.rs+++ b/crates/documents/src/inbound/axum_router/copy_document.rs@@ -6,11 +6,11 @@ use axum::{};use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::DocumentAccessExtractor;+use entity_registry::CreationPrincipalExtractor;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,diff --git a/crates/documents/src/inbound/axum_router/create_document.rs b/crates/documents/src/inbound/axum_router/create_document.rsindex 71b670755f..2d0573dc6a 100644--- a/crates/documents/src/inbound/axum_router/create_document.rs+++ b/crates/documents/src/inbound/axum_router/create_document.rs@@ -5,6 +5,7 @@ use std::str::FromStr;use axum::{Json, extract::State};use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2;+use entity_registry::CreationPrincipalExtractor;use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal, UserOrInternalCaller,};@@ -14,7 +15,6 @@ use model_owner::CreationPrincipal;use models_permissions::share_permission::access_level::EditAccessLevel;use super::DocumentRouterState;-use super::creation_principal::CreationPrincipalExtractor;use crate::domain::models::{DocumentError, ImportEmailAttachmentRepoArgs, InitialLinkShare, NewDocument,};diff --git a/crates/documents/src/inbound/axum_router/create_markdown.rs b/crates/documents/src/inbound/axum_router/create_markdown.rsindex faa557b537..68cc27b45e 100644--- a/crates/documents/src/inbound/axum_router/create_markdown.rs+++ b/crates/documents/src/inbound/axum_router/create_markdown.rs@@ -3,11 +3,11 @@use axum::{Json, extract::State};use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2;+use entity_registry::CreationPrincipalExtractor;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,diff --git a/crates/documents/src/inbound/axum_router/create_skill.rs b/crates/documents/src/inbound/axum_router/create_skill.rsindex 04ffca0eca..c53ca40e92 100644--- a/crates/documents/src/inbound/axum_router/create_skill.rs+++ b/crates/documents/src/inbound/axum_router/create_skill.rs@@ -3,11 +3,11 @@use axum::{Json, extract::State};use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2;+use entity_registry::CreationPrincipalExtractor;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;diff --git a/crates/documents/src/inbound/axum_router/create_snippet.rs b/crates/documents/src/inbound/axum_router/create_snippet.rsindex 54817a44b8..f18420c99f 100644--- a/crates/documents/src/inbound/axum_router/create_snippet.rs+++ b/crates/documents/src/inbound/axum_router/create_snippet.rs@@ -3,11 +3,11 @@use axum::{Json, extract::State};use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2;+use entity_registry::CreationPrincipalExtractor;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;diff --git a/crates/documents/src/inbound/axum_router/create_task.rs b/crates/documents/src/inbound/axum_router/create_task.rsindex d4b66dc8d6..8dde0cd790 100644--- a/crates/documents/src/inbound/axum_router/create_task.rs+++ b/crates/documents/src/inbound/axum_router/create_task.rs@@ -7,11 +7,11 @@ use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::{OptionalMacroUserTeamExtractorV2, ProjectBodyAccessLevelExtractorV2,};+use entity_registry::CreationPrincipalExtractor;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_principal_permission_token;diff --git a/crates/entity_access_management/fixtures/bot_owned_child_project_test_data.sql b/crates/entity_access_management/fixtures/bot_owned_child_project_test_data.sqlnew file mode 100644index 0000000000..270903446b--- /dev/null+++ b/crates/entity_access_management/fixtures/bot_owned_child_project_test_data.sql@@ -0,0 +1,14 @@+INSERT INTO public."Project" ("id", "name", "userId")+ VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'parent', 'macro|[email protected]');++INSERT INTO public."Project" ("id", "name", "userId", "parentId")+ VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'bot-child', 'bot|00000000-0000-0000-0000-00000000b07a', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');++INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'project', 'macro|[email protected]', 'user', 'owner'),+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'project', 'b2222222-2222-2222-2222-222222222222', 'team', 'comment');++-- A bot-owned project carries its bot's owner grant and its sponsor's owner grant.+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'project', 'bot|00000000-0000-0000-0000-00000000b07a', 'bot', 'owner'),+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'project', 'macro|[email protected]', 'user', 'owner');diff --git a/crates/entity_access_management/src/outbound/pg_repo/test.rs b/crates/entity_access_management/src/outbound/pg_repo/test.rsindex ae5219118d..a51dadfc48 100644--- a/crates/entity_access_management/src/outbound/pg_repo/test.rs+++ b/crates/entity_access_management/src/outbound/pg_repo/test.rs@@ -387,6 +387,71 @@ async fn add_entity_to_project_inserts_access_for_all_ancestor_shares(pool: Pool);}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../fixtures",+ scripts("bot_owned_child_project_test_data")+ )+)]+async fn add_bot_owned_child_project_keeps_its_owner_grants_and_inherits_the_parents(+ pool: Pool<Postgres>,+) {+ let repo = PgRepository::new(pool.clone());+ let parent = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();+ let child = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb").unwrap();++ repo.add_entity_to_project(&child, EntityType::Project, &parent)+ .await+ .unwrap();++ let rows = sqlx::query!(+ r#"+ SELECT source_type::text AS "source_type!", source_id,+ access_level::text AS "access_level!", granted_from_project_id+ FROM entity_access+ WHERE entity_id = $1 AND entity_type = 'project'+ ORDER BY source_type::text, source_id, granted_from_project_id NULLS FIRST+ "#,+ child,+ )+ .fetch_all(&pool)+ .await+ .unwrap();+ let parent_id = parent.to_string();+ assert_eq!(+ rows.iter()+ .map(|row| (+ row.source_type.as_str(),+ row.source_id.as_str(),+ row.access_level.as_str(),+ row.granted_from_project_id.as_deref(),+ ))+ .collect::<Vec<_>>(),+ [+ (+ "bot",+ "bot|00000000-0000-0000-0000-00000000b07a",+ "owner",+ None+ ),+ (+ "team",+ "b2222222-2222-2222-2222-222222222222",+ "comment",+ Some(parent_id.as_str()),+ ),+ ("user", "macro|[email protected]", "owner", None),+ (+ "user",+ "macro|[email protected]",+ "owner",+ Some(parent_id.as_str())+ ),+ ]+ );+}+/// Adds a document to PROJECT_C then removes it, verifying that all 6/// inherited access rows are deleted while the pre-existing project/// access rows remain untouched.diff --git a/crates/entity_registry/entity_registry/Cargo.toml b/crates/entity_registry/entity_registry/Cargo.tomlindex b14e5db9dc..c920c86222 100644--- a/crates/entity_registry/entity_registry/Cargo.toml+++ b/crates/entity_registry/entity_registry/Cargo.toml@@ -5,10 +5,12 @@ publish = falseversion = "0.1.0"[features]+axum = ["dep:axum", "macro_authorization/axum"]default = []postgres = ["dep:sqlx", "model_owner/sqlx"][dependencies]+axum = { workspace = true, optional = true }bot_id = { path = "../../bot_id" }chrono = { workspace = true }macro_authorization = { path = "../../macro_authorization", default-features = false }diff --git a/crates/documents/src/inbound/axum_router/creation_principal.rs b/crates/entity_registry/entity_registry/src/inbound.rssimilarity index 92%rename from crates/documents/src/inbound/axum_router/creation_principal.rsrename to crates/entity_registry/entity_registry/src/inbound.rsindex 6cd78a0c6f..1809f95b34 100644--- a/crates/documents/src/inbound/axum_router/creation_principal.rs+++ b/crates/entity_registry/entity_registry/src/inbound.rs@@ -1,4 +1,4 @@-//! Resolves who a public document create request creates as.+//! Axum adapter that resolves who a public create request creates as.use std::marker::PhantomData;@@ -6,13 +6,14 @@ 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;+use crate::{NonUserOwners, resolve_creation_principal};+/// The verified principal a public create request creates as.////// A caller that cannot create is rejected with 403 before the request body@@ -39,7 +40,7 @@ wherelet principal =resolve_creation_principal(&caller.authorization, NonUserOwners::from_ref(state)).map_err(|error| {- tracing::info!(%error, "caller cannot create documents");+ tracing::info!(%error, "caller cannot create entities");MacroAuthorizationRejection {status: StatusCode::FORBIDDEN,message: "forbidden".into(),diff --git a/crates/entity_registry/entity_registry/src/lib.rs b/crates/entity_registry/entity_registry/src/lib.rsindex b2c8fa8ff2..059f1a4a41 100644--- a/crates/entity_registry/entity_registry/src/lib.rs+++ b/crates/entity_registry/entity_registry/src/lib.rs@@ -25,6 +25,9 @@pub mod domain;+#[cfg(feature = "axum")]+pub mod inbound;+#[cfg(feature = "postgres")]pub mod outbound;@@ -40,5 +43,7 @@ pub use shared_entity_registry::{RegisteredEntityType, UnregisteredEntityType, WriteOutcome,};+#[cfg(feature = "axum")]+pub use inbound::CreationPrincipalExtractor;#[cfg(feature = "postgres")]pub use outbound::pg_entity_registry_repo::PgEntityRegistryRepository;diff --git a/crates/projects/Cargo.toml b/crates/projects/Cargo.tomlindex 0d652b6f08..4f5e464d82 100644--- a/crates/projects/Cargo.toml+++ b/crates/projects/Cargo.toml@@ -14,10 +14,12 @@ ai_tools = [axum = ["dep:axum","dep:axum-extra",+ "dep:entity_registry","dep:macro_authorization","dep:model-error-response","dep:utoipa","entity_access/axum",+ "entity_registry/axum",]default = ["axum", "inbound", "outbound", "ports", "service"]inbound = ["axum", "ports"]@@ -116,6 +118,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]aws-sdk-sqs = { workspace = true }+bot_id = { path = "../bot_id", features = ["test-utils"] }dotenvy = { workspace = true }http-body-util = { workspace = true }kafka_util = { path = "../kafka_util" }diff --git a/crates/projects/src/domain/models.rs b/crates/projects/src/domain/models.rsindex 1eebf1552b..15031243a6 100644--- a/crates/projects/src/domain/models.rs+++ b/crates/projects/src/domain/models.rs@@ -3,14 +3,15 @@use macro_user_id::user_id::MacroUserIdStr;use model::folder::FileSystemNode;use model::project::Project;+use model_owner::Owner;use models_permissions::share_permission::team_share::AuthorizedTeamShareCommand;use models_permissions::share_permission::{SharePermissionV2, UpdateSharePermissionRequestV2};/// Arguments for atomically creating a project and its access metadata.#[derive(Debug, Clone)]pub struct CreateProjectArgs {- /// Project owner.- pub user_id: String,+ /// Recorded project owner.+ pub owner: Owner,/// Project name.pub name: String,/// Optional parent project.diff --git a/crates/projects/src/domain/ports.rs b/crates/projects/src/domain/ports.rsindex c20c6cbab6..5061e8cbb0 100644--- a/crates/projects/src/domain/ports.rs+++ b/crates/projects/src/domain/ports.rs@@ -18,6 +18,7 @@ use model::project::{BasicProject, PendingProject, Project, ProjectPreview, ProjectPreviewV2,ProjectWithUploadRequest,};+use model_owner::{CreationPrincipal, Owner};use models_bulk_upload::{BulkUploadRequest, BulkUploadRequestDocuments, UploadExtractFolderRequest,UploadExtractFolderResponseData,@@ -91,11 +92,12 @@ pub trait ProjectRepo: Send + Sync + 'static {project_ids: &[String],) -> impl Future<Output = Result<Vec<ProjectPreviewV2>, Self::Err>> + Send;- /// Get the link-share preference of the user's team, or `None` when the- /// user is not on a team.+ /// Get the link-share preference of the team `owner` resolves to, per+ /// [`model_owner::team::owner_team`]. Bots resolve through their team or+ /// owning user; a teamless owner has no team default.fn get_team_default_link_share(&self,- user_id: &str,+ owner: &Owner,) -> impl Future<Output = Result<Option<TeamLinkShareDefault>, Self::Err>> + Send;/// Atomically create a project and its permission, history, and owner-access rows.@@ -369,10 +371,11 @@ pub trait ProjectService: Send + Sync + 'static {receipt: EntityAccessReceipt<ViewAccessLevel>,) -> impl Future<Output = Result<AccessLevel, ProjectError>> + Send;- /// Create a project, optionally beneath an authorized parent.+ /// Create a project owned by `principal`, optionally beneath an authorized+ /// parent.fn create_project(&self,- actor: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,args: CreateProjectRequest,) -> impl Future<Output = Result<Project, ProjectError>> + Send;diff --git a/crates/projects/src/domain/service.rs b/crates/projects/src/domain/service.rsindex 1c9ade222b..80f9122959 100644--- a/crates/projects/src/domain/service.rs+++ b/crates/projects/src/domain/service.rs@@ -18,7 +18,7 @@ use model::project::{BasicProject, PendingProject, Project, ProjectPreview, ProjectPreviewData, ProjectPreviewV2,WithProjectId,};-use model_owner::Owner;+use model_owner::{CreationPrincipal, Owner};use models_bulk_upload::{UploadExtractFolderRequest, UploadExtractFolderResponseData};use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::access_level::AccessLevel;@@ -345,16 +345,17 @@ whereasync fn create_project(&self,- actor: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,args: CreateProjectRequest,) -> Result<Project, ProjectError> {validate_project_name(&args.name)?;+ let owner = principal.owner();// The owner's team default link-share preference decides the initial// share permission; without a team, projects default to link sharing off.let team_default = self.repo- .get_team_default_link_share(actor.as_ref())+ .get_team_default_link_share(&owner).await.map_err(|error| internal_error(error, "unable to resolve team default link share"))?;@@ -362,7 +363,7 @@ wherelet project = self.repo.create_project(CreateProjectArgs {- user_id: actor.to_string(),+ owner: owner.clone(),name: args.name,parent_id: parent_id.clone(),share_permission: SharePermissionV2::new_project_share_permission(team_default),@@ -395,7 +396,7 @@ whereproject.id.clone(),ProjectCreatedMetadata {project_id: project.id.clone(),- owner: Owner::User(actor),+ owner,name: project.name.clone(),parent_project_id: project.parent_id.clone(),created_at: project.created_at,@@ -667,7 +668,7 @@ where// permission; without a team, link sharing defaults to off.let team_default = self.repo- .get_team_default_link_share(actor.as_ref())+ .get_team_default_link_share(&Owner::User(actor.clone())).await.map_err(|error| internal_error(error, "unable to resolve team default link share"))?;diff --git a/crates/projects/src/domain/service/tests.rs b/crates/projects/src/domain/service/tests.rsindex 3fa499ec2d..5c24414fd8 100644--- a/crates/projects/src/domain/service/tests.rs+++ b/crates/projects/src/domain/service/tests.rs@@ -1,5 +1,6 @@use std::sync::{Arc, Mutex};+use bot_id::{BotId, NonSystemBotId};use entity_access::domain::models::{EditAccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,OwnerAccessLevel, ViewAccessLevel,@@ -19,7 +20,7 @@ use model::project::request::{CreateProjectRequest, PatchProjectRequestV2};use model::project::{BasicProject, Project, ProjectPreviewData, ProjectPreviewV2, ProjectWithUploadRequest,};-use model_owner::Owner;+use model_owner::{CreationPrincipal, Owner};use models_bulk_upload::{BulkUploadRequest, BulkUploadRequestDocuments, ProjectDocumentStatus, UploadDocumentStatus,UploadExtractFolderRequest, UploadFolderStatus,@@ -690,7 +691,8 @@ async fn create_uses_grapheme_limit_and_orchestrates_parent_side_effects() {.returning(|_| Box::pin(async { Ok(None) }));repo.expect_create_project().withf(move |args| {- args.name == expected_name+ args.owner == owner("macro|[email protected]")+ && args.name == expected_name&& args.parent_id.as_deref() == Some(parent_id.to_string().as_str())&& args.share_permission.link_share.is_none()&& args.share_permission.link_share_access_level.is_none()@@ -713,7 +715,7 @@ async fn create_uses_grapheme_limit_and_orchestrates_parent_side_effects() {service.create_project(- user_id("macro|[email protected]"),+ &CreationPrincipal::User(user_id("macro|[email protected]")),CreateProjectRequest {name: accepted_name,project_parent_id: Some(parent_id),@@ -723,7 +725,7 @@ async fn create_uses_grapheme_limit_and_orchestrates_parent_side_effects() {.unwrap();let error = service.create_project(- user_id("macro|[email protected]"),+ &CreationPrincipal::User(user_id("macro|[email protected]")),CreateProjectRequest {name: "👨👩👧👦".repeat(101),project_parent_id: None,@@ -773,7 +775,7 @@ async fn create_project_publishes_repository_metadata_after_success() {let result = service.create_project(- user_id("macro|[email protected]"),+ &CreationPrincipal::User(user_id("macro|[email protected]")),CreateProjectRequest {name: "Requested name".to_string(),project_parent_id: Some(parent_id),@@ -813,7 +815,7 @@ async fn create_project_failures_publish_no_event() {let validation_error = service.create_project(- user_id("macro|[email protected]"),+ &CreationPrincipal::User(user_id("macro|[email protected]")),CreateProjectRequest {name: "x".repeat(101),project_parent_id: None,@@ -822,7 +824,7 @@ async fn create_project_failures_publish_no_event() {.await;let repository_error = service.create_project(- user_id("macro|[email protected]"),+ &CreationPrincipal::User(user_id("macro|[email protected]")),CreateProjectRequest {name: "Project".to_string(),project_parent_id: None,@@ -859,7 +861,7 @@ async fn create_project_succeeds_when_event_publication_fails() {let result = service.create_project(- user_id("macro|[email protected]"),+ &CreationPrincipal::User(user_id("macro|[email protected]")),CreateProjectRequest {name: "Project".to_string(),project_parent_id: None,@@ -879,7 +881,7 @@ async fn create_project_resolves_share_permission_from_team_default() {let project_id = Uuid::new_v4();let mut repo = MockProjectRepo::new();repo.expect_get_team_default_link_share()- .withf(|user_id| user_id == "macro|[email protected]")+ .withf(|owner| owner == &Owner::User(user_id("macro|[email protected]"))).returning(|_| Box::pin(async { Ok(Some(TeamLinkShareDefault(Some(LinkShare::Team)))) }));repo.expect_create_project().withf(|args| {@@ -899,7 +901,7 @@ async fn create_project_resolves_share_permission_from_team_default() {service.create_project(- user_id("macro|[email protected]"),+ &CreationPrincipal::User(user_id("macro|[email protected]")),CreateProjectRequest {name: "Project".to_string(),project_parent_id: None,@@ -909,6 +911,56 @@ async fn create_project_resolves_share_permission_from_team_default() {.unwrap();}+#[tokio::test]+async fn team_bot_creates_a_bot_owned_project_and_publishes_the_bot_owner() {+ let project_id = Uuid::new_v4();+ let mut repo = MockProjectRepo::new();+ repo.expect_get_team_default_link_share()+ .withf(|owner| owner == &Owner::Bot(BotId::TEST_A))+ .returning(|_| Box::pin(async { Ok(None) }));+ repo.expect_create_project()+ .withf(|args| args.owner == Owner::Bot(BotId::TEST_A) && args.name == "Bot project")+ .return_once(move |_| {+ Box::pin(async move {+ Ok(project(+ &project_id.to_string(),+ "bot|00000000-0000-0000-0000-00000000b07a",+ None,+ ))+ })+ });+ let event_broker = TestEventBroker::default();+ let published = event_broker.published();+ let service = mutation_service_with_event_broker(+ repo,+ RecordingEam::default(),+ RecordingIndexer::default(),+ event_broker,+ );++ service+ .create_project(+ &CreationPrincipal::TeamBot {+ bot: NonSystemBotId::new(BotId::TEST_A).unwrap(),+ team: Uuid::from_u128(0x7ea3),+ },+ CreateProjectRequest {+ name: "Bot project".to_string(),+ project_parent_id: None,+ },+ )+ .await+ .unwrap();++ let published = published.lock().unwrap();+ assert_eq!(published.len(), 1);+ assert_eq!(published[0].payload["event_type"], "project.created");+ assert_eq!(+ published[0].payload["metadata"]["owner"],+ "bot|00000000-0000-0000-0000-00000000b07a"+ );+}+#[tokio::test]async fn edit_project_publishes_requested_update_metadata() {struct Case {diff --git a/crates/projects/src/inbound/axum_router.rs b/crates/projects/src/inbound/axum_router.rsindex 800d031fa4..a9a2826d3f 100644--- a/crates/projects/src/inbound/axum_router.rs+++ b/crates/projects/src/inbound/axum_router.rs@@ -24,6 +24,7 @@ use axum::{response::IntoResponse,};use entity_access::domain::ports::EntityAccessService;+use entity_registry::NonUserOwners;use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};use model::response::GenericErrorResponse;use serde::Deserialize;@@ -49,6 +50,8 @@ pub struct ProjectRouterState<T, Svc, Auth> {pub access_service: Arc<Svc>,/// Request authorization state.pub authorization_state: MacroAuthorizationState<Auth>,+ /// Whether a team bot with no acting user may own what it creates.+ pub non_user_owners: NonUserOwners,}// A derived implementation would unnecessarily require all service types to be `Clone`.@@ -58,6 +61,7 @@ impl<T, Svc, Auth> Clone for ProjectRouterState<T, Svc, Auth> {service: self.service.clone(),access_service: self.access_service.clone(),authorization_state: self.authorization_state.clone(),+ non_user_owners: self.non_user_owners,}}}@@ -74,6 +78,12 @@ impl<T, Svc, Auth> FromRef<ProjectRouterState<T, Svc, Auth>> for MacroAuthorizat}}+impl<T, Svc, Auth> FromRef<ProjectRouterState<T, Svc, Auth>> for NonUserOwners {+ fn from_ref(state: &ProjectRouterState<T, Svc, Auth>) -> Self {+ state.non_user_owners+ }+}+/// Project path parameters.#[derive(Deserialize)]pub struct Params {diff --git a/crates/projects/src/inbound/axum_router/create_project.rs b/crates/projects/src/inbound/axum_router/create_project.rsindex dca4c51d8b..1d44fa8038 100644--- a/crates/projects/src/inbound/axum_router/create_project.rs+++ b/crates/projects/src/inbound/axum_router/create_project.rs@@ -5,7 +5,8 @@ use entity_access::{domain::{models::EditAccessLevel, ports::EntityAccessService},inbound::axum_extractors::ProjectBodyAccessLevelExtractorV2,};-use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};+use entity_registry::CreationPrincipalExtractor;+use macro_authorization::MacroAuthorizationService;use model::project::{request::CreateProjectRequest, response::CreateProjectResponse};use super::ProjectRouterState;@@ -23,14 +24,10 @@ use crate::domain::{models::ProjectError, ports::ProjectService};(status = 500, body = model::response::GenericErrorResponse),))]-#[tracing::instrument(- skip(state, user, project),- fields(user_id = ?user.authorization.user.macro_user_id),- err-)]+#[tracing::instrument(skip(state, project), err)]pub async fn create_project_handler<T, Svc, Auth>(State(state): State<ProjectRouterState<T, Svc, Auth>>,- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ CreationPrincipalExtractor { principal, .. }: CreationPrincipalExtractor<Auth>,project: ProjectBodyAccessLevelExtractorV2<EditAccessLevel, CreateProjectRequest, Svc, Auth>,) -> Result<Json<CreateProjectResponse>, ProjectError>where@@ -40,10 +37,7 @@ where{let data = state.service- .create_project(- user.authorization.user.macro_user_id.clone(),- project.into_inner(),- )+ .create_project(&principal, project.into_inner()).await?;Ok(Json(CreateProjectResponse { error: false, data }))diff --git a/crates/projects/src/inbound/axum_router/tests.rs b/crates/projects/src/inbound/axum_router/tests.rsindex 30c93c827b..ba89a30c85 100644--- a/crates/projects/src/inbound/axum_router/tests.rs+++ b/crates/projects/src/inbound/axum_router/tests.rs@@ -7,9 +7,10 @@ use std::{use axum::{Router,body::Body,- http::{Request, StatusCode},+ http::{Request, StatusCode, request::Builder},response::IntoResponse,};+use bot_id::NonSystemBotId;use entity_access::domain::{models::{AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityAccessReceipt,@@ -17,10 +18,12 @@ use entity_access::domain::{},ports::EntityAccessService,};+use entity_registry::NonUserOwners;use http_body_util::BodyExt;use macro_authorization::{- InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,- MacroAuthorizationState,+ BOT_FOR_MACRO_USER_ID_HEADER, BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims,+ BotAuthentication, BotScope, InternalIdentityClaims, MacroAuthorizationError,+ MacroAuthorizationService, MacroAuthorizationState, MacroUserAuthentication,};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};use model::{@@ -32,7 +35,7 @@ use model::{response::GetProjectResponseData,},};-use model_owner::Owner;+use model_owner::{CreationPrincipal, Owner};use model_user::UserContext;use models_bulk_upload::{UploadExtractFolderRequest, UploadExtractFolderResponseData};use models_permissions::share_permission::{@@ -51,8 +54,10 @@ use crate::domain::{const TOKEN: &str = "valid-token";const INTERNAL_KEY: &str = "internal-key";+const BOT_TOKEN: &str = "valid-bot-token";const USER_ID: &str = "macro|[email protected]";const PROJECT_ID: &str = "project-1";+const TEAM_ID: Uuid = Uuid::from_u128(0x7ea4);#[derive(Clone)]struct FakeProjectService {@@ -60,6 +65,7 @@ struct FakeProjectService {mutations: Arc<Mutex<Vec<&'static str>>>,permanently_deleted_projects: Arc<Mutex<Vec<BasicProject>>>,upload_internal_flags: Arc<Mutex<Vec<bool>>>,+ create_principals: Arc<Mutex<Vec<CreationPrincipal>>>,}impl FakeProjectService {@@ -75,6 +81,7 @@ impl FakeProjectService {mutations: Arc::new(Mutex::new(Vec::new())),permanently_deleted_projects: Arc::new(Mutex::new(Vec::new())),upload_internal_flags: Arc::new(Mutex::new(Vec::new())),+ create_principals: Arc::new(Mutex::new(Vec::new())),}}@@ -84,6 +91,7 @@ impl FakeProjectService {mutations: Arc::new(Mutex::new(Vec::new())),permanently_deleted_projects: Arc::new(Mutex::new(Vec::new())),upload_internal_flags: Arc::new(Mutex::new(Vec::new())),+ create_principals: Arc::new(Mutex::new(Vec::new())),}}}@@ -136,13 +144,17 @@ impl ProjectService for FakeProjectService {async fn create_project(&self,- _actor: MacroUserIdStr<'static>,+ principal: &CreationPrincipal,_args: CreateProjectRequest,) -> Result<Project, ProjectError> {self.mutations.lock().expect("mutation lock poisoned").push("create");+ self.create_principals+ .lock()+ .expect("create principal lock poisoned")+ .push(principal.clone());Ok(project())}@@ -394,18 +406,54 @@ impl MacroAuthorizationService for FakeAuthorizationService {}Ok(claims.user_id.map(|user_id| user_context(&user_id)))}++ 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 router(service: FakeProjectService, access_level: Option<AccessLevel>) -> Router {+ router_with(service, access_level, NonUserOwners::Disabled)+}++fn router_with(+ service: FakeProjectService,+ access_level: Option<AccessLevel>,+ non_user_owners: NonUserOwners,+) -> Router {projects_router::<FakeProjectService, FakeEntityAccessService, FakeAuthorizationService, ()>(ProjectRouterState {service: Arc::new(service),access_service: Arc::new(FakeEntityAccessService { access_level }),authorization_state: MacroAuthorizationState::new(Arc::new(FakeAuthorizationService)),+ non_user_owners,},)}+fn user(user_id: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(user_id.to_string()).expect("test user id should be valid")+}+fn user_context(value: &str) -> UserContext {UserContext {user_id: value.to_string(),@@ -466,6 +514,78 @@ fn internal_identity_json_request(method: &str, uri: &str, body: Value) -> Reque.expect("request should be valid")}+type Authenticate = fn(Builder) -> Builder;++fn with_jwt(builder: Builder) -> Builder {+ builder.header("authorization", format!("Bearer {TOKEN}"))+}++fn with_internal_user(builder: Builder) -> Builder {+ builder+ .header("x-internal-auth-key", INTERNAL_KEY)+ .header("x-internal-macro-user-id", USER_ID)+}++fn with_internal_service(builder: Builder) -> Builder {+ builder.header("x-internal-auth-key", INTERNAL_KEY)+}++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, USER_ID)+}++fn with_user_bot_without_acting_user(builder: Builder) -> Builder {+ builder+ .header(BOT_TOKEN_HEADER, BOT_TOKEN)+ .header(BOT_SCOPE_HEADER, "user")+}++fn with_team_bot(builder: Builder) -> Builder {+ builder+ .header(BOT_TOKEN_HEADER, BOT_TOKEN)+ .header(BOT_SCOPE_HEADER, "team")+}++fn creating_callers() -> [(Authenticate, NonUserOwners, CreationPrincipal); 4] {+ [+ (+ with_jwt,+ NonUserOwners::Disabled,+ CreationPrincipal::User(user(USER_ID)),+ ),+ (+ with_internal_user,+ NonUserOwners::Disabled,+ CreationPrincipal::User(user(USER_ID)),+ ),+ (+ with_user_bot,+ NonUserOwners::Disabled,+ CreationPrincipal::BotForUser {+ bot: BotId::TEST_A,+ user: user(USER_ID),+ },+ ),+ (+ with_team_bot,+ NonUserOwners::Enabled,+ CreationPrincipal::TeamBot {+ bot: NonSystemBotId::new(BotId::TEST_A).expect("test bot is not a system bot"),+ team: TEAM_ID,+ },+ ),+ ]+}++fn create_request(authenticate: Authenticate, body: impl Into<Body>) -> Request<Body> {+ authenticate(Request::post("/").header("content-type", "application/json"))+ .body(body.into())+ .expect("request should be valid")+}+async fn json_body(response: axum::response::Response) -> Value {let bytes = response.into_body()@@ -583,6 +703,70 @@ async fn create_returns_project_success_envelope() {);}+#[tokio::test]+async fn create_records_the_resolved_creation_principal() {+ for (authenticate, non_user_owners, principal) in creating_callers() {+ let service = FakeProjectService::with_project(USER_ID, false);+ let create_principals = service.create_principals.clone();++ let response = router_with(service, None, non_user_owners)+ .oneshot(create_request(+ authenticate,+ json!({ "name": "Created", "projectParentId": null }).to_string(),+ ))+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::OK, "{principal:?}");+ assert_eq!(+ *create_principals+ .lock()+ .expect("create principal lock poisoned"),+ [principal]+ );+ }+}++#[tokio::test]+async fn create_rejects_callers_that_cannot_create_before_reading_the_body() {+ let callers: [(&str, Authenticate, NonUserOwners); 3] = [+ ("team bot", with_team_bot, NonUserOwners::Disabled),+ (+ "user-scoped bot without an acting user",+ with_user_bot_without_acting_user,+ NonUserOwners::Enabled,+ ),+ (+ "internal caller without a user",+ with_internal_service,+ NonUserOwners::Enabled,+ ),+ ];++ for (caller, authenticate, non_user_owners) in callers {+ let service = FakeProjectService::with_project(USER_ID, false);+ let create_principals = service.create_principals.clone();++ let response = router_with(service, None, non_user_owners)+ .oneshot(create_request(authenticate, "not json"))+ .await+ .expect("router should respond");++ assert_eq!(+ (response.status(), json_body(response).await),+ (StatusCode::FORBIDDEN, json!({ "message": "forbidden" })),+ "{caller}"+ );+ assert!(+ create_principals+ .lock()+ .expect("create principal lock poisoned")+ .is_empty(),+ "{caller} must not reach the service"+ );+ }+}+#[tokio::test]async fn edit_permission_denial_prevents_mutation() {let response = router(@@ -884,6 +1068,7 @@ async fn mark_uploaded_preserves_exact_lambda_request_and_response_json() {service: Arc::new(FakeProjectService::with_project(USER_ID, false)),access_service: Arc::new(FakeEntityAccessService { access_level: None }),authorization_state: MacroAuthorizationState::new(Arc::new(FakeAuthorizationService)),+ non_user_owners: NonUserOwners::Disabled,};let router = Router::new().route(diff --git a/crates/projects/src/inbound/toolset/create_project.rs b/crates/projects/src/inbound/toolset/create_project.rsindex 66ee0f076c..3ffe6f37a6 100644--- a/crates/projects/src/inbound/toolset/create_project.rs+++ b/crates/projects/src/inbound/toolset/create_project.rs@@ -9,6 +9,7 @@ use entity_access::domain::ports::EntityAccessService;use entity_mutation::MoveEntity;use model::project::request::CreateProjectRequest;use model_entity::EntityType;+use model_owner::CreationPrincipal;use schemars::JsonSchema;use serde::{Deserialize, Serialize};@@ -109,7 +110,10 @@ wherelet project = service_context.service.create_project(- user_id,+ &CreationPrincipal::BotForUser {+ bot: service_context.actor,+ user: user_id,+ },CreateProjectRequest {name: self.project_name.clone(),project_parent_id: self.parent_project_id,diff --git a/crates/projects/src/outbound/pg_project_repo.rs b/crates/projects/src/outbound/pg_project_repo.rsindex 71675c796a..1a66df1333 100644--- a/crates/projects/src/outbound/pg_project_repo.rs+++ b/crates/projects/src/outbound/pg_project_repo.rs@@ -15,13 +15,14 @@ mod tests;use std::collections::HashMap;use entity_registry::BotFacts;-use entity_registry_db_utils::OwnedEntityRegistrar;+use entity_registry_db_utils::{NewEntityRecord, OwnedEntityRegistrar, RegisteredEntityType};use model::project::{BasicProject, Project, ProjectPreviewData, ProjectPreviewV2, ProjectWithUploadRequest,WithProjectId,};use model_owner::Owner;-use sqlx::PgPool;+use models_permissions::share_permission::{LinkShare, TeamLinkShareDefault};+use sqlx::{PgPool, Postgres, Transaction};use crate::domain::models::{CreateProjectArgs, EditProjectArgs, MarkedUploadedTree, ProjectError, PurgedProjectTree,@@ -37,8 +38,8 @@ pub struct PgProjectRepo<B> {}impl<B: BotFacts> PgProjectRepo<B> {- /// Create a repository backed by `pool` that registers uploaded folder- /// trees through `registrar`.+ /// Create a repository backed by `pool` that registers the owners of+ /// created projects and uploaded folder trees through `registrar`.pub fn new(pool: PgPool, registrar: OwnedEntityRegistrar<B>) -> Self {Self { pool, registrar }}@@ -48,6 +49,23 @@ fn decode_owner(value: &str) -> Result<Owner, sqlx::Error> {Owner::from_principal_str(value).map_err(|error| sqlx::Error::Decode(Box::new(error)))}+async fn register_owned<B: BotFacts>(+ transaction: &mut Transaction<'_, Postgres>,+ registrar: &OwnedEntityRegistrar<B>,+ id: &str,+ entity_type: RegisteredEntityType,+ owner: Owner,+) -> Result<(), sqlx::Error> {+ let id = id+ .parse()+ .map_err(|error| sqlx::Error::Decode(Box::new(error)))?;+ registrar+ .register_owned_entity(transaction, NewEntityRecord::new(id, entity_type, owner))+ .await+ .map_err(|error| sqlx::Error::Protocol(error.to_string()))?;+ Ok(())+}+fn map_project(id: String,name: String,@@ -74,9 +92,21 @@ impl<B: BotFacts + 'static> ProjectRepo for PgProjectRepo<B> {#[tracing::instrument(err, skip(self))]async fn get_team_default_link_share(&self,- user_id: &str,- ) -> Result<Option<models_permissions::share_permission::TeamLinkShareDefault>, Self::Err> {- share_permission_db_utils::get_team_default_link_share(&self.pool, user_id).await+ owner: &Owner,+ ) -> Result<Option<TeamLinkShareDefault>, Self::Err> {+ let row = sqlx::query!(+ r#"+ SELECT 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| TeamLinkShareDefault(row.default_link_share)))}#[tracing::instrument(err, skip(self))]@@ -313,7 +343,7 @@ impl<B: BotFacts + 'static> ProjectRepo for PgProjectRepo<B> {#[tracing::instrument(err, skip(self, args))]async fn create_project(&self, args: CreateProjectArgs) -> Result<Project, Self::Err> {let mut transaction = self.pool.begin().await?;- let project = create::create_project(&mut transaction, &args).await?;+ let project = create::create_project(&mut transaction, &self.registrar, &args).await?;transaction.commit().await?;Ok(project)}diff --git a/crates/projects/src/outbound/pg_project_repo/create.rs b/crates/projects/src/outbound/pg_project_repo/create.rsindex 3a5562c184..cfc50d2f75 100644--- a/crates/projects/src/outbound/pg_project_repo/create.rs+++ b/crates/projects/src/outbound/pg_project_repo/create.rs@@ -1,7 +1,5 @@-use entity_access_db_utils::{- AccessLevel, EntityAccessSourceType, EntityType, insert_entity_access_row,-};-use macro_user_id::user_id::MacroUserIdStr;+use entity_registry::BotFacts;+use entity_registry_db_utils::{OwnedEntityRegistrar, RegisteredEntityType};use model::project::Project;use sqlx::{Postgres, Transaction};@@ -9,8 +7,9 @@ use crate::domain::models::CreateProjectArgs;use super::share;-pub(super) async fn create_project(+pub(super) async fn create_project<B: BotFacts>(transaction: &mut Transaction<'_, Postgres>,+ registrar: &OwnedEntityRegistrar<B>,args: &CreateProjectArgs,) -> Result<Project, sqlx::Error> {let row = sqlx::query!(@@ -27,7 +26,7 @@ pub(super) async fn create_project("deletedAt"::timestamptz AS deleted_at"#,args.name,- args.user_id,+ args.owner.principal_id(),args.parent_id,).fetch_one(transaction.as_mut())@@ -45,46 +44,29 @@ pub(super) async fn create_project(share::create_project_share_permission(transaction, &project.id, &args.share_permission).await?;- sqlx::query!(- r#"- INSERT INTO "UserHistory" ("userId", "itemId", "itemType", "createdAt", "updatedAt")- VALUES ($1, $2, 'project', NOW(), NOW())- ON CONFLICT ("userId", "itemId", "itemType") DO UPDATE- SET "updatedAt" = NOW()- "#,- args.user_id,- project.id,- )- .execute(transaction.as_mut())- .await?;+ if let Some(user) = args.owner.as_user() {+ sqlx::query!(+ r#"+ INSERT INTO "UserHistory" ("userId", "itemId", "itemType", "createdAt", "updatedAt")+ VALUES ($1, $2, 'project', NOW(), NOW())+ ON CONFLICT ("userId", "itemId", "itemType") DO UPDATE+ SET "updatedAt" = NOW()+ "#,+ user.as_ref(),+ project.id,+ )+ .execute(transaction.as_mut())+ .await?;+ }- let project_id = project- .id- .parse()- .map_err(|error| sqlx::Error::Decode(Box::new(error)))?;- insert_entity_access_row(+ super::register_owned(transaction,- &project_id,- EntityType::Project,- &args.user_id,- EntityAccessSourceType::User,- AccessLevel::Owner,+ registrar,+ &project.id,+ RegisteredEntityType::Project,+ args.owner.clone(),).await?;- entity_registry_db_utils::insert_entity(- transaction,- entity_registry_db_utils::NewEntityRecord::new(- project_id,- entity_registry_db_utils::RegisteredEntityType::Project,- model_owner::Owner::User(- MacroUserIdStr::try_from(args.user_id.clone())- .map_err(|error| sqlx::Error::Decode(Box::new(error)))?,- ),- ),- )- .await- .map_err(|error| sqlx::Error::Protocol(error.to_string()))?;-Ok(project)}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 39833c6650..135606082c 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@@ -1,5 +1,10 @@+use bot_id::BotId;+use entity_access_management::domain::ports::EntityAccessManagementRepository;+use entity_access_management::outbound::PgRepository;use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserIdStr;use model_entity::EntityType;+use model_owner::Owner;use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::team_share::{AuthorizedTeamShareCommand, TeamShareFacts, TeamShareLevel, TeamShareRequest,@@ -13,14 +18,19 @@ use uuid::Uuid;use crate::domain::models::{CreateProjectArgs, EditProjectArgs, ProjectError};use crate::domain::ports::ProjectRepo;-use crate::outbound::pg_project_repo::tests::{TestRepo, test_repo};+use crate::outbound::pg_project_repo::tests::{SponsoredBy, TestRepo, test_repo, test_repo_with};const OWNER: &str = "macro|[email protected]";const TEAM_ID: Uuid = Uuid::from_u128(0xb2222222_2222_2222_2222_222222222222);+const BOT: &str = "bot|00000000-0000-0000-0000-00000000b07a";++fn owner() -> Owner {+ Owner::User(MacroUserIdStr::try_from(OWNER).unwrap())+}async fn create_project(repo: &TestRepo, name: &str) -> String {repo.create_project(CreateProjectArgs {- user_id: OWNER.to_owned(),+ owner: owner(),name: name.to_string(),parent_id: None,share_permission: SharePermissionV2::new_project_share_permission(None),@@ -159,6 +169,81 @@ fn unshared() -> StoredTeamShare {}}+type Grant = (String, String, String, Option<String>);++fn grant(source_type: &str, source_id: &str, level: &str, granted_from: Option<&str>) -> Grant {+ (+ source_type.to_string(),+ source_id.to_string(),+ level.to_string(),+ granted_from.map(str::to_string),+ )+}++async fn project_grants(pool: &Pool<Postgres>, project_id: &str) -> Vec<Grant> {+ sqlx::query!(+ r#"+ SELECT source_type::text AS "source_type!", source_id,+ access_level::text AS "access_level!", granted_from_project_id+ FROM entity_access+ WHERE entity_id = $1 AND entity_type = 'project'+ ORDER BY source_type::text, source_id, granted_from_project_id NULLS FIRST+ "#,+ Uuid::parse_str(project_id).unwrap(),+ )+ .fetch_all(pool)+ .await+ .unwrap()+ .into_iter()+ .map(|row| {+ (+ row.source_type,+ row.source_id,+ row.access_level,+ row.granted_from_project_id,+ )+ })+ .collect()+}++#[derive(Debug, PartialEq)]+struct OwnershipRecords {+ owner: Owner,+ registered_owner: (String, String),+ grants: Vec<Grant>,+ user_history_rows: i64,+}++async fn ownership_records(+ repo: &TestRepo,+ pool: &Pool<Postgres>,+ project_id: &str,+) -> OwnershipRecords {+ let registration = sqlx::query!(+ r#"+ SELECT owner_type::text AS "owner_type!", owner_id,+ (SELECT COUNT(*) FROM "UserHistory" WHERE "itemId" = $1) AS "user_history_rows!"+ FROM entity+ WHERE id::text = $1+ "#,+ project_id,+ )+ .fetch_one(pool)+ .await+ .unwrap();+ OwnershipRecords {+ owner: repo+ .get_project_by_id(project_id)+ .await+ .unwrap()+ .unwrap()+ .user_id,+ registered_owner: (registration.owner_type, registration.owner_id),+ grants: project_grants(pool, project_id).await,+ user_history_rows: registration.user_history_rows,+ }+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../fixtures", scripts("users", "team"))@@ -495,3 +580,56 @@ async fn get_project_share_permission_reads_team_share_access_level(pool: PgPoolSome(AccessLevel::Comment));}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("users", "team"))+)]+async fn bot_owned_child_under_team_shared_parent_inherits_and_keeps_its_own_grants(pool: PgPool) {+ let repo = test_repo(pool.clone());+ let parent_id = create_project(&repo, "Parent").await;+ edit_team_share(&repo, &parent_id, Some(AccessLevel::Comment))+ .await+ .unwrap();++ let child = test_repo_with(pool.clone(), SponsoredBy(owner()))+ .create_project(CreateProjectArgs {+ owner: Owner::Bot(BotId::TEST_A),+ name: "Bot child".to_string(),+ parent_id: Some(parent_id.clone()),+ share_permission: SharePermissionV2::new_project_share_permission(None),+ })+ .await+ .unwrap();+ assert_eq!(+ ownership_records(&repo, &pool, &child.id).await,+ OwnershipRecords {+ owner: Owner::Bot(BotId::TEST_A),+ registered_owner: ("bot".to_string(), BOT.to_string()),+ grants: vec![+ grant("bot", BOT, "owner", None),+ grant("user", OWNER, "owner", None),+ ],+ user_history_rows: 0,+ }+ );++ PgRepository::new(pool.clone())+ .add_entity_to_project(+ &Uuid::parse_str(&child.id).unwrap(),+ EntityType::Project,+ &Uuid::parse_str(&parent_id).unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(+ project_grants(&pool, &child.id).await,+ [+ grant("bot", BOT, "owner", None),+ grant("team", &TEAM_ID.to_string(), "comment", Some(&parent_id)),+ grant("user", OWNER, "owner", None),+ grant("user", OWNER, "owner", Some(&parent_id)),+ ]+ );+}diff --git a/crates/projects/src/outbound/pg_project_repo/tests.rs b/crates/projects/src/outbound/pg_project_repo/tests.rsindex bbace6f9a9..588f235dc6 100644--- a/crates/projects/src/outbound/pg_project_repo/tests.rs+++ b/crates/projects/src/outbound/pg_project_repo/tests.rs@@ -27,13 +27,23 @@ impl BotFacts for NoBots {}}+#[derive(Clone)]+pub(super) struct SponsoredBy(pub(super) Owner);++impl BotFacts for SponsoredBy {+ async fn sponsor(&self, _bot: bot_id::BotId) -> EntityRegistryResult<Option<Owner>> {+ Ok(Some(self.0.clone()))+ }+}+pub(super) type TestRepo = PgProjectRepo<NoBots>;+pub(super) fn test_repo_with<B: BotFacts>(pool: PgPool, bots: B) -> PgProjectRepo<B> {+ PgProjectRepo::new(pool, OwnedEntityRegistrar::new(OwnerGrantPolicy::new(bots)))+}+pub(super) fn test_repo(pool: PgPool) -> TestRepo {- PgProjectRepo::new(- pool,- OwnedEntityRegistrar::new(OwnerGrantPolicy::new(NoBots)),- )+ test_repo_with(pool, NoBots)}const ROOT_ID: &str = "10000000-0000-0000-0000-000000000001";@@ -44,6 +54,10 @@ const DELETED_DOCUMENT_ID: &str = "20000000-0000-0000-0000-000000000002";const CHAT_ID: &str = "30000000-0000-0000-0000-000000000001";const DELETED_CHAT_ID: &str = "30000000-0000-0000-0000-000000000002";+fn project_owner() -> Owner {+ Owner::User(MacroUserIdStr::try_from("macro|[email protected]").unwrap())+}+#[derive(Debug, Eq, PartialEq)]struct StoredSharePermission {link_share: Option<String>,@@ -289,7 +303,7 @@ async fn create_is_atomic_and_inserts_all_metadata(pool: Pool<Postgres>) -> anyhlet permission = SharePermissionV2::new_project_share_permission(None);let project = repo.create_project(CreateProjectArgs {- user_id: "macro|[email protected]".to_owned(),+ owner: project_owner(),name: "Created".to_owned(),parent_id: Some(ROOT_ID.to_owned()),share_permission: permission.clone(),@@ -329,7 +343,7 @@ async fn create_is_atomic_and_inserts_all_metadata(pool: Pool<Postgres>) -> anyhassert!(repo.create_project(CreateProjectArgs {- user_id: "macro|[email protected]".to_owned(),+ owner: project_owner(),name: "Must roll back".to_owned(),parent_id: Some("missing-parent".to_owned()),share_permission: permission,@@ -361,6 +375,63 @@ async fn create_is_atomic_and_inserts_all_metadata(pool: Pool<Postgres>) -> anyhOk(())}+#[derive(Debug, PartialEq)]+struct OwnershipRowCounts {+ projects: i64,+ entities: i64,+ grants: i64,+}++async fn ownership_row_counts(pool: &Pool<Postgres>) -> OwnershipRowCounts {+ sqlx::query_as!(+ OwnershipRowCounts,+ r#"+ SELECT+ (SELECT COUNT(*) FROM "Project") AS "projects!",+ (SELECT COUNT(*) FROM entity) AS "entities!",+ (SELECT COUNT(*) FROM entity_access) AS "grants!"+ "#,+ )+ .fetch_one(pool)+ .await+ .unwrap()+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn unsponsored_bot_owner_leaves_no_project_rows(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let bot_project = || CreateProjectArgs {+ owner: Owner::Bot(bot_id::BotId::TEST_A),+ name: "Bot project".to_owned(),+ parent_id: None,+ share_permission: SharePermissionV2::new_project_share_permission(None),+ };+ let before = ownership_row_counts(&pool).await;++ assert!(+ test_repo(pool.clone())+ .create_project(bot_project())+ .await+ .is_err()+ );+ assert_eq!(ownership_row_counts(&pool).await, before);++ test_repo_with(pool.clone(), SponsoredBy(project_owner()))+ .create_project(bot_project())+ .await?;+ assert_eq!(+ ownership_row_counts(&pool).await,+ OwnershipRowCounts {+ projects: before.projects + 1,+ entities: before.entities + 1,+ grants: before.grants + 2,+ }+ );+ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("projects_test_data"))@@ -372,7 +443,7 @@ async fn create_defaults_enabled_link_share_to_view(pool: Pool<Postgres>) -> anylet project = repo.create_project(CreateProjectArgs {- user_id: "macro|[email protected]".to_owned(),+ owner: project_owner(),name: "Team project".to_owned(),parent_id: None,share_permission: permission,diff --git a/crates/projects/src/outbound/pg_project_repo/upload_folder.rs b/crates/projects/src/outbound/pg_project_repo/upload_folder.rsindex 40707243f2..5c619296d2 100644--- a/crates/projects/src/outbound/pg_project_repo/upload_folder.rs+++ b/crates/projects/src/outbound/pg_project_repo/upload_folder.rs@@ -1,11 +1,8 @@use std::collections::HashMap;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 entity_registry_db_utils::{OwnedEntityRegistrar, RegisteredEntityType};use macro_user_id::user_id::MacroUserIdStr;use model::document::{DocumentMetadata, FileType, FileTypeExt};use model::folder::{FileSystemNode, FileSystemNodeWithIds, UploadFolderWithIdsResponse};@@ -25,6 +22,7 @@ pub(super) async fn upload_folder<B: BotFacts>() -> Result<UploadFolderWithIdsResponse, sqlx::Error> {let root_project = create_pending_project(transaction,+ registrar,args.user_id.clone(),&args.share_permission,&args.root_folder_name,@@ -109,6 +107,7 @@ whereFileSystemNode::Folder(content) => {let project = create_pending_project(transaction,+ registrar,user_id.clone(),share_permission,name,@@ -143,8 +142,9 @@ where}}-async fn create_pending_project(+async fn create_pending_project<B: BotFacts>(transaction: &mut Transaction<'_, Postgres>,+ registrar: &OwnedEntityRegistrar<B>,user_id: MacroUserIdStr<'static>,share_permission: &SharePermissionV2,name: &str,@@ -183,51 +183,17 @@ async fn create_pending_project()?;share::create_project_share_permission(transaction, &project.id, share_permission).await?;- let entity_id = project- .id- .parse()- .map_err(|error| sqlx::Error::Decode(Box::new(error)))?;- insert_entity_access_row(+ super::register_owned(transaction,- &entity_id,- EntityType::Project,- user_id.as_ref(),- EntityAccessSourceType::User,- AccessLevel::Owner,+ registrar,+ &project.id,+ RegisteredEntityType::Project,+ Owner::User(user_id),).await?;- entity_registry_db_utils::insert_entity(- transaction,- NewEntityRecord::new(- entity_id,- RegisteredEntityType::Project,- Owner::User(user_id),- ),- )- .await- .map_err(|error| sqlx::Error::Protocol(error.to_string()))?;Ok(project)}-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>,@@ -281,7 +247,14 @@ async fn create_empty_document<B: BotFacts>(};create_document_share_permission(transaction, &document.id, share_permission).await?;- register_user_owned_document(transaction, registrar, &document.id, user_id.clone()).await?;+ super::register_owned(+ transaction,+ registrar,+ &document.id,+ RegisteredEntityType::Document,+ Owner::User(user_id.clone()),+ )+ .await?;Ok(DocumentMetadata::new_document(&document.id,diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex 790d7df8e2..c924812ea2 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -1695,6 +1695,7 @@ async fn run() -> anyhow::Result<()> {service: project_service,access_service: entity_access_service.clone(),authorization_state: authorization_state.clone(),+ non_user_owners,},documents_state: DocumentRouterState {service: document_service,