Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(ownership): chat create with a typed owner (#7214)

Will Hutchinson38bd8da011c3
diff --git a/.sqlx/query-8438a27e49d8bc1b178b680c3c02166732a63e215b8f01b949211d1744ae5de9.json b/.sqlx/query-8438a27e49d8bc1b178b680c3c02166732a63e215b8f01b949211d1744ae5de9.json
new file mode 100644
index 0000000000..ddea3befd7
--- /dev/null
+++ b/.sqlx/query-8438a27e49d8bc1b178b680c3c02166732a63e215b8f01b949211d1744ae5de9.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": "8438a27e49d8bc1b178b680c3c02166732a63e215b8f01b949211d1744ae5de9"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 2f589a2424..1a1fd10194 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3838,6 +3838,7 @@ dependencies = [
"entity_access_db_utils",
"entity_access_management",
"entity_mutation",
+ "entity_registry",
"entity_registry_db_utils",
"futures",
"http-body-util",
@@ -15787,6 +15788,7 @@ dependencies = [
"aws-sdk-sqs",
"axum",
"bot_id",
+ "bots",
"channel_sender",
"channels",
"chat",
@@ -15798,6 +15800,7 @@ dependencies = [
"documents",
"doppler-config",
"entity_access",
+ "entity_registry",
"entity_registry_db_utils",
"futures",
"kafka_util",
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
index 0f0f603725..4d56788f3c 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
@@ -496,6 +496,11 @@ export type createChatResponse401 = {
status: 401;
};
+export type createChatResponse403 = {
+ data: string;
+ status: 403;
+};
+
export type createChatResponse500 = {
data: string;
status: 500;
@@ -506,6 +511,7 @@ export type createChatResponseSuccess = createChatResponse200 & {
};
export type createChatResponseError = (
| createChatResponse401
+ | createChatResponse403
| createChatResponse500
) & {
headers: Headers;
diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.json
index 5f89f1d533..0253b8d90c 100644
--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json
+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json
@@ -413,6 +413,16 @@
}
}
},
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 890740d7dd..0bc6204894 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -240,10 +240,9 @@ 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(),
- OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone()))),
- );
+ let owned_entity_registrar =
+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone())));
+ let document_repo = PgDocumentRepo::new(pool.clone(), owned_entity_registrar.clone());
let cloudfront_config = CloudFrontConfig {
distribution_url: env
.document_storage_service_cloudfront_distribution_url
@@ -383,7 +382,7 @@ pub async fn build_tool_service_context_from_env(
let notification_tool_context =
notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);
- let chat_repo = chat::outbound::postgres::PgChatRepo::new(pool.clone());
+ let chat_repo = chat::outbound::postgres::PgChatRepo::new(pool.clone(), owned_entity_registrar);
let chat_service = chat::domain::service::ChatServiceImpl::new(
chat_repo,
Arc::new(ai_toolset::AsyncToolCollection::new()),
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 7b067cc362..42897d8fb8 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1055,7 +1055,8 @@ pub fn build_reminders_tool_context(
/// Type alias for the chat service implementation used by AI tools.
/// Uses an empty toolset — the read-only tool never invokes tool execution.
-pub type ToolChatService = ChatServiceImpl<PgChatRepo, (), ToolEntityAccessManagementService>;
+pub type ToolChatService =
+ ChatServiceImpl<PgChatRepo<PgBotsRepo>, (), ToolEntityAccessManagementService>;
/// Type alias for the project service implementation used by AI tools.
/// Upload, content-hash, and search-cleanup ports are unwired — project
diff --git a/crates/chat/Cargo.toml b/crates/chat/Cargo.toml
index 89beaf0ed3..4049ace7d1 100644
--- a/crates/chat/Cargo.toml
+++ b/crates/chat/Cargo.toml
@@ -13,13 +13,16 @@ attachment = [
]
inbound = [
"dep:axum",
+ "dep:entity_registry",
"dep:macro_authorization",
"dep:roles_and_permissions",
"entity_access/inbound",
+ "entity_registry/axum",
"ports",
]
outbound = [
"dep:entity_access_db_utils",
+ "dep:entity_registry",
"dep:entity_registry_db_utils",
"dep:macro_uuid",
"dep:share_permission_db_utils",
@@ -39,6 +42,7 @@ attachment = { path = "../attachment" }
chrono = { workspace = true }
entity_access = { path = "../entity_access", default-features = false }
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 }
entity_access_management = { path = "../entity_access_management", default-features = false, features = [
"ports",
@@ -87,6 +91,7 @@ macro_uuid = { path = "../macro_uuid", optional = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+bot_id = { path = "../bot_id", features = ["test-utils"] }
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
serde_json = { workspace = true }
diff --git a/crates/chat/src/domain/ports/chat.rs b/crates/chat/src/domain/ports/chat.rs
index 32f3a84777..359086b331 100644
--- a/crates/chat/src/domain/ports/chat.rs
+++ b/crates/chat/src/domain/ports/chat.rs
@@ -10,6 +10,7 @@ use entity_access::domain::models::{
};
use macro_user_id::user_id::MacroUserIdStr;
use model::chat::Chat;
+use model_owner::Owner;
use models_permissions::share_permission::access_level::AccessLevel;
use models_permissions::share_permission::team_share::TeamShareFacts;
use models_permissions::share_permission::{SharePermissionV2, TeamLinkShareDefault};
@@ -22,16 +23,17 @@ pub trait ChatRepo: Send + Sync + 'static {
/// repository persists it verbatim and carries no share-policy of its own.
fn create(
&self,
- user_id: MacroUserIdStr<'static>,
+ owner: Owner,
args: CreateChatArgs,
share_permission: SharePermissionV2,
) -> impl std::future::Future<Output = Result<String>> + 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 owner's team, or `None` when the
+ /// owner has no team. The team is the one [`model_owner::team::owner_team`]
+ /// resolves, so a bot owner gets its team's default.
fn get_team_default_link_share(
&self,
- user_id: &str,
+ owner: &Owner,
) -> impl std::future::Future<Output = Result<Option<TeamLinkShareDefault>>> + Send;
/// Get the full chat response (metadata, messages, web citations).
@@ -57,7 +59,7 @@ pub trait ChatRepo: Send + Sync + 'static {
/// copy — the repository persists it verbatim.
fn copy_chat(
&self,
- user_id: MacroUserIdStr<'static>,
+ owner: Owner,
source_chat_id: &str,
args: CopyChatArgs,
share_permission: SharePermissionV2,
@@ -162,7 +164,7 @@ pub trait ChatService: Send + Sync + 'static {
/// Create a new chat, returning the chat ID.
fn create(
&self,
- user_id: MacroUserIdStr<'static>,
+ owner: Owner,
args: CreateChatArgs,
) -> impl std::future::Future<Output = Result<String>> + Send;
diff --git a/crates/chat/src/domain/service/chat.rs b/crates/chat/src/domain/service/chat.rs
index 2ba08e1519..d9528d378c 100644
--- a/crates/chat/src/domain/service/chat.rs
+++ b/crates/chat/src/domain/service/chat.rs
@@ -161,11 +161,7 @@ where
ToolSetContext: Clone + Send + Sync + 'static,
{
#[tracing::instrument(err, skip(self))]
- async fn create(
- &self,
- user_id: MacroUserIdStr<'static>,
- args: CreateChatArgs,
- ) -> Result<String> {
+ async fn create(&self, owner: Owner, args: CreateChatArgs) -> Result<String> {
if args.name.graphemes(true).count() > 100 {
return Err(ChatErr::BadRequest("name too long".to_string()));
}
@@ -175,15 +171,12 @@ where
// The owner's team default link-share preference decides the initial
// share permission; without a team the chat default (public/view) applies.
- let team_default = self
- .repo
- .get_team_default_link_share(user_id.as_ref())
- .await?;
+ let team_default = self.repo.get_team_default_link_share(&owner).await?;
let share_permission = SharePermissionV2::new_chat_share_permission(team_default);
let chat_id = self
.repo
- .create(user_id.clone(), args, share_permission)
+ .create(owner.clone(), args, share_permission)
.await?;
if let Some(project_id) = &project_id
@@ -205,7 +198,7 @@ where
self.publish_chat_event(&ChatMacroEvent::created(ChatCreatedMetadata {
chat_id: chat_id.clone(),
- owner: Owner::User(user_id),
+ owner,
name,
project_id,
}));
@@ -270,16 +263,14 @@ where
// The copier becomes the owner, so their team default decides the
// copy's initial share permission.
- let team_default = self
- .repo
- .get_team_default_link_share(user_id.as_ref())
- .await?;
+ let owner = Owner::User(user_id.to_owned());
+ let team_default = self.repo.get_team_default_link_share(&owner).await?;
let share_permission = SharePermissionV2::new_chat_share_permission(team_default);
let new_chat_id = self
.repo
.copy_chat(
- user_id.to_owned(),
+ owner,
chat_id,
CopyChatArgs {
name: name.clone(),
diff --git a/crates/chat/src/domain/service/chat/test.rs b/crates/chat/src/domain/service/chat/test.rs
index 511afb7cba..f4b3eb9465 100644
--- a/crates/chat/src/domain/service/chat/test.rs
+++ b/crates/chat/src/domain/service/chat/test.rs
@@ -42,6 +42,7 @@ struct StubChatRepo {
metadata_project_id: Option<String>,
message_persistence: Arc<Mutex<MessagePersistence>>,
team_default: Option<models_permissions::share_permission::TeamLinkShareDefault>,
+ received_owners: Arc<Mutex<Vec<Owner>>>,
received_share_permission: Arc<Mutex<Option<SharePermissionV2>>>,
/// Facts returned by `get_team_share_facts`; `None` uses the owner-with-team default.
team_share_facts: Option<TeamShareFacts>,
@@ -75,6 +76,10 @@ impl StubChatRepo {
*self.team_share_facts_loads.lock().unwrap()
}
+ fn received_owners(&self) -> Vec<Owner> {
+ self.received_owners.lock().unwrap().clone()
+ }
+
fn received_team_share(&self) -> Option<Option<AuthorizedTeamShareCommand>> {
self.received_patch
.lock()
@@ -111,21 +116,23 @@ impl StubChatRepo {
impl ChatRepo for StubChatRepo {
async fn create(
&self,
- _user_id: MacroUserIdStr<'static>,
+ owner: Owner,
_args: CreateChatArgs,
share_permission: SharePermissionV2,
) -> Result<String> {
if self.fail_create {
return Err(Self::repo_err());
}
+ self.received_owners.lock().unwrap().push(owner);
*self.received_share_permission.lock().unwrap() = Some(share_permission);
Ok(CHAT_ID.to_string())
}
async fn get_team_default_link_share(
&self,
- _user_id: &str,
+ owner: &Owner,
) -> Result<Option<models_permissions::share_permission::TeamLinkShareDefault>> {
+ self.received_owners.lock().unwrap().push(owner.clone());
Ok(self.team_default)
}
@@ -158,7 +165,7 @@ impl ChatRepo for StubChatRepo {
async fn copy_chat(
&self,
- _user_id: MacroUserIdStr<'static>,
+ owner: Owner,
_source_chat_id: &str,
_args: CopyChatArgs,
share_permission: SharePermissionV2,
@@ -166,6 +173,7 @@ impl ChatRepo for StubChatRepo {
if self.fail_copy_chat {
return Err(Self::repo_err());
}
+ self.received_owners.lock().unwrap().push(owner);
*self.received_share_permission.lock().unwrap() = Some(share_permission);
Ok(NEW_CHAT_ID.to_string())
}
@@ -536,7 +544,7 @@ async fn create_publishes_chat_created() {
let chat_id = service
.create(
- owner(),
+ Owner::User(owner()),
CreateChatArgs {
name: "New Chat".to_string(),
project_id: Some(PROJECT_ID.to_string()),
@@ -571,7 +579,7 @@ async fn create_resolves_share_permission_from_team_default() {
service
.create(
- owner(),
+ Owner::User(owner()),
CreateChatArgs {
name: "New Chat".to_string(),
project_id: None,
@@ -600,7 +608,7 @@ async fn create_uses_chat_default_without_team() {
service
.create(
- owner(),
+ Owner::User(owner()),
CreateChatArgs {
name: "New Chat".to_string(),
project_id: None,
@@ -631,7 +639,7 @@ async fn create_disables_link_share_when_team_turned_it_off() {
service
.create(
- owner(),
+ Owner::User(owner()),
CreateChatArgs {
name: "New Chat".to_string(),
project_id: None,
@@ -671,6 +679,10 @@ async fn copy_chat_resolves_share_permission_from_team_default() {
.unwrap();
assert_eq!(permission.link_share, Some(LinkShare::Team));
assert_eq!(permission.link_share_access_level, Some(AccessLevel::View));
+ assert_eq!(
+ repo.received_owners(),
+ vec![Owner::User(owner()), Owner::User(owner())]
+ );
}
#[tokio::test]
@@ -692,6 +704,56 @@ async fn copy_chat_publishes_chat_copied_keyed_by_new_chat() {
assert_eq!(metadata["name"], "Source Chat Copy");
}
+#[tokio::test]
+async fn create_publishes_bot_owner_event() {
+ let bot_owner = Owner::Bot(bot_id::BotId::TEST_A);
+ let repo = StubChatRepo::default();
+ let broker = RecordingEventBroker::default();
+ let service = build_service(repo.clone(), broker.clone());
+
+ service
+ .create(
+ bot_owner.clone(),
+ CreateChatArgs {
+ name: "Bot Chat".to_string(),
+ project_id: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(repo.received_owners(), vec![bot_owner.clone(), bot_owner]);
+ let events = broker.events();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].envelope["event_type"], "chat.created");
+ assert_eq!(
+ events[0].envelope["metadata"]["owner"],
+ "bot|00000000-0000-0000-0000-00000000b07a"
+ );
+}
+
+#[tokio::test]
+async fn copy_chat_by_bot_receipt_is_rejected() {
+ let repo = StubChatRepo::default();
+ let broker = RecordingEventBroker::default();
+ let service = build_service(repo.clone(), broker.clone());
+ let receipt = EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_bot(
+ bot_id::BotId::TEST_A.into_storage_id(),
+ entity_access::domain::models::BotReceiptScope::Team { team_id: TEAM_ID },
+ CHAT_ID,
+ EntityType::Chat,
+ );
+
+ let result = service.copy_chat(receipt).await;
+
+ assert!(matches!(
+ result,
+ Err(ChatErr::Access(AccessError::Unauthorized))
+ ));
+ assert!(repo.received_owners().is_empty());
+ assert!(broker.events().is_empty());
+}
+
#[tokio::test]
async fn delete_publishes_chat_deleted() {
let broker = RecordingEventBroker::default();
@@ -824,7 +886,7 @@ async fn failing_repo_calls_emit_no_events() {
assert!(
service
.create(
- owner(),
+ Owner::User(owner()),
CreateChatArgs {
name: "New Chat".to_string(),
project_id: None,
@@ -862,7 +924,7 @@ async fn broker_scheduling_failure_does_not_fail_the_call() {
assert!(
service
.create(
- owner(),
+ Owner::User(owner()),
CreateChatArgs {
name: "New Chat".to_string(),
project_id: None,
diff --git a/crates/chat/src/inbound/http/router.rs b/crates/chat/src/inbound/http/router.rs
index 5b5675c1f9..7a3d98fe75 100644
--- a/crates/chat/src/inbound/http/router.rs
+++ b/crates/chat/src/inbound/http/router.rs
@@ -12,9 +12,8 @@ use axum::{
use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAccessLevel};
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::ChatAccessLevelExtractor;
-use macro_authorization::{
- ActingUser, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
-};
+use entity_registry::{CreationPrincipalExtractor, NonUserOwners};
+use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
use model::response::StringIDResponse;
use models_permissions::share_permission::SharePermissionV2;
use roles_and_permissions::domain::port::UserRolesAndPermissionsService;
@@ -23,17 +22,20 @@ use utoipa::ToSchema;
use crate::domain::models::{CreateChatArgs, GetChatResponse, PatchChatArgs, Result};
use crate::domain::ports::ChatService;
-use crate::inbound::http::extractors::{ChatModelAccess, UserPermissionsState};
+use crate::inbound::http::extractors::UserPermissionsState;
/// Shared state for the chat router, wrapping a [`ChatService`] implementation,
/// an [`EntityAccessService`] for entity authorization, a
-/// [`MacroAuthorizationService`] for caller authentication, and a
-/// [`UserRolesAndPermissionsService`] for model-entitlement lookups.
+/// [`MacroAuthorizationService`] for caller authentication, a
+/// [`UserRolesAndPermissionsService`] for model-entitlement lookups, and the
+/// [`NonUserOwners`] gate deciding whether a team bot with no acting user may
+/// own the chats it creates.
pub struct ChatRouterState<S, Svc, Auth, P> {
inner: Arc<S>,
access_service: Arc<Svc>,
authorization_state: MacroAuthorizationState<Auth>,
permissions_state: UserPermissionsState<P>,
+ non_user_owners: NonUserOwners,
}
impl<S, Svc, Auth, P> Clone for ChatRouterState<S, Svc, Auth, P> {
@@ -43,6 +45,7 @@ impl<S, Svc, Auth, P> Clone for ChatRouterState<S, Svc, Auth, P> {
access_service: Arc::clone(&self.access_service),
authorization_state: self.authorization_state.clone(),
permissions_state: self.permissions_state.clone(),
+ non_user_owners: self.non_user_owners,
}
}
}
@@ -65,6 +68,12 @@ impl<S, Svc, Auth, P> FromRef<ChatRouterState<S, Svc, Auth, P>> for UserPermissi
}
}
+impl<S, Svc, Auth, P> FromRef<ChatRouterState<S, Svc, Auth, P>> for NonUserOwners {
+ fn from_ref(state: &ChatRouterState<S, Svc, Auth, P>) -> Self {
+ state.non_user_owners
+ }
+}
+
impl<
S: ChatService,
Svc: EntityAccessService,
@@ -73,18 +82,21 @@ impl<
> ChatRouterState<S, Svc, Auth, P>
{
/// Create a new [`ChatRouterState`] from a service, access service,
- /// authorization state, and roles-and-permissions service.
+ /// authorization state, roles-and-permissions service, and the gate for
+ /// chats owned by a team bot.
pub fn new(
service: S,
access_service: Svc,
authorization_state: MacroAuthorizationState<Auth>,
permissions_service: Arc<P>,
+ non_user_owners: NonUserOwners,
) -> Self {
Self {
inner: Arc::new(service),
access_service: Arc::new(access_service),
authorization_state,
permissions_state: UserPermissionsState(permissions_service),
+ non_user_owners,
}
}
}
@@ -201,15 +213,12 @@ pub struct CreateChatRequest {
responses(
(status = 200, body = StringIDResponse),
(status = 401, body = String),
+ (status = 403, body = String),
(status = 500, body = String),
)
)]
/// Create a new chat.
-#[tracing::instrument(
- skip(state, user, _access, req),
- fields(actor = %user.acting_entity()),
- err(Debug)
-)]
+#[tracing::instrument(skip(state, req), err(Debug))]
pub async fn create_chat_handler<
S: ChatService,
Svc: EntityAccessService,
@@ -217,17 +226,13 @@ pub async fn create_chat_handler<
P: UserRolesAndPermissionsService,
>(
State(state): State<ChatRouterState<S, Svc, Auth, P>>,
- user: MacroAuthorizationExtractor<Auth, ActingUser>,
- // 402 on no perms
- _access: ChatModelAccess<Auth, P>,
+ CreationPrincipalExtractor { principal, .. }: CreationPrincipalExtractor<Auth>,
Json(req): Json<CreateChatRequest>,
) -> Result<Json<StringIDResponse>> {
- let user = &user.authorization.user;
-
let id = state
.inner
.create(
- user.macro_user_id.clone(),
+ principal.owner(),
CreateChatArgs {
name: req.name.unwrap_or_else(|| "New Chat".to_string()),
project_id: req.project_id,
diff --git a/crates/chat/src/inbound/test.rs b/crates/chat/src/inbound/test.rs
index 46171f30ae..fedb498092 100644
--- a/crates/chat/src/inbound/test.rs
+++ b/crates/chat/src/inbound/test.rs
@@ -1,12 +1,16 @@
+mod create;
+
use axum::Extension;
use axum::Router;
use axum::body::Body;
use axum::http::{Request, StatusCode, header};
use entity_access::domain::models::TeamRole;
+use entity_registry::NonUserOwners;
use http_body_util::BodyExt;
use macro_authorization::{
- InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
- MacroAuthorizationState,
+ BotActingUserClaims, BotAuthentication, BotScope, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+ MacroUserAuthentication,
};
use macro_user_id::user_id::MacroUserIdStr;
use model::chat::ChatBasic;
@@ -14,8 +18,9 @@ use model::response::StringIDResponse;
use model::user::UserContext;
use model_owner::Owner;
use rootcause::Report;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
use tower::util::ServiceExt;
+use uuid::Uuid;
use crate::domain::models::{
ChatErr, ChatResponse, CreateChatArgs, GetChatResponse, PatchChatArgs, Result,
@@ -33,14 +38,26 @@ use entity_access::domain::ports::EntityAccessService;
use macro_user_id::lowercased::Lowercase;
use macro_user_id::user_id::MacroUserId;
-struct MockService;
+#[derive(Clone, Default)]
+struct MockService {
+ created_owners: Arc<Mutex<Vec<Owner>>>,
+}
+
+impl MockService {
+ fn created_owners(&self) -> Vec<Owner> {
+ self.created_owners
+ .lock()
+ .expect("created owners lock poisoned")
+ .clone()
+ }
+}
impl ChatService for MockService {
- async fn create(
- &self,
- _user_id: macro_user_id::user_id::MacroUserIdStr<'static>,
- _args: CreateChatArgs,
- ) -> Result<String> {
+ async fn create(&self, owner: Owner, _args: CreateChatArgs) -> Result<String> {
+ self.created_owners
+ .lock()
+ .expect("created owners lock poisoned")
+ .push(owner);
Ok("test-chat-id".to_string())
}
@@ -161,11 +178,7 @@ impl ChatService for MockService {
struct ErrorService;
impl ChatService for ErrorService {
- async fn create(
- &self,
- _user_id: macro_user_id::user_id::MacroUserIdStr<'static>,
- _args: CreateChatArgs,
- ) -> Result<String> {
+ async fn create(&self, _owner: Owner, _args: CreateChatArgs) -> Result<String> {
Err(ChatErr::Unknown(anyhow::anyhow!("db error")))
}
@@ -269,11 +282,7 @@ impl ChatService for ErrorService {
struct NotFoundService;
impl ChatService for NotFoundService {
- async fn create(
- &self,
- _user_id: macro_user_id::user_id::MacroUserIdStr<'static>,
- _args: CreateChatArgs,
- ) -> Result<String> {
+ async fn create(&self, _owner: Owner, _args: CreateChatArgs) -> Result<String> {
Err(ChatErr::Unknown(anyhow::anyhow!("db error")))
}
@@ -485,8 +494,9 @@ impl EntityAccessService for MockAccessService {
}
}
-/// Fake authorization service accepting the `valid` bearer token as the test
-/// user.
+const BOT_TOKEN: &str = "bot-valid";
+const TEAM_ID: Uuid = Uuid::from_u128(0x7EA3);
+
#[derive(Clone)]
struct FakeAuthorizationService;
@@ -514,6 +524,36 @@ impl MacroAuthorizationService for FakeAuthorizationService {
) -> std::result::Result<Option<UserContext>, Report<MacroAuthorizationError>> {
Err(Report::new(MacroAuthorizationError::InvalidCredentials))
}
+
+ async fn authorize_bot(
+ &self,
+ bot_token: &str,
+ bot_scope: BotScope,
+ acting_user: Option<BotActingUserClaims>,
+ ) -> std::result::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: MacroUserIdStr::try_from(user_id.clone())
+ .expect("test user id should be valid"),
+ user_context: UserContext {
+ user_id,
+ fusion_user_id: "1234".to_string(),
+ permissions: None,
+ organization_id: None,
+ },
+ }),
+ })
+ }
}
fn authorization_state() -> MacroAuthorizationState<FakeAuthorizationService> {
@@ -602,10 +642,11 @@ fn chat_basic_extension() -> Extension<ChatBasic> {
fn mock_id_router() -> Router {
let state = ChatRouterState::new(
- MockService,
+ MockService::default(),
MockAccessService,
authorization_state(),
permissions_service(),
+ NonUserOwners::Disabled,
);
chat_view_router(state.clone())
.merge(chat_id_router(state))
@@ -619,6 +660,7 @@ fn error_id_router() -> Router {
MockAccessService,
authorization_state(),
permissions_service(),
+ NonUserOwners::Disabled,
);
chat_view_router(state.clone())
.merge(chat_id_router(state))
@@ -632,6 +674,7 @@ fn not_found_id_router() -> Router {
MockAccessService,
authorization_state(),
permissions_service(),
+ NonUserOwners::Disabled,
);
chat_view_router(state.clone())
.merge(chat_id_router(state))
@@ -639,35 +682,6 @@ fn not_found_id_router() -> Router {
.layer(axum::middleware::map_request(attach_bearer))
}
-fn mock_create_router() -> Router {
- chat_create_router(ChatRouterState::new(
- MockService,
- MockAccessService,
- authorization_state(),
- permissions_service(),
- ))
- .layer(axum::middleware::map_request(attach_bearer))
-}
-
-// -- create_chat tests --
-
-#[tokio::test]
-async fn create_chat_returns_id() {
- let req = Request::builder()
- .method("POST")
- .uri("/")
- .header("content-type", "application/json")
- .body(Body::from(r#"{"name": "My Chat"}"#))
- .unwrap();
-
- let res = mock_create_router().oneshot(req).await.unwrap();
- assert_eq!(res.status(), StatusCode::OK);
-
- let body = res.into_body().collect().await.unwrap().to_bytes();
- let response: StringIDResponse = serde_json::from_slice(&body).unwrap();
- assert_eq!(response.id, "test-chat-id");
-}
-
// -- get_chat tests --
#[tokio::test]
diff --git a/crates/chat/src/inbound/test/create.rs b/crates/chat/src/inbound/test/create.rs
new file mode 100644
index 0000000000..008d0a5f44
--- /dev/null
+++ b/crates/chat/src/inbound/test/create.rs
@@ -0,0 +1,163 @@
+use axum::http::request::Builder;
+use macro_authorization::{BOT_FOR_MACRO_USER_ID_HEADER, BOT_SCOPE_HEADER, BOT_TOKEN_HEADER};
+use serde_json::{Value, json};
+
+use super::*;
+
+const ACTING_USER_ID: &str = "macro|[email protected]";
+
+fn create_router(non_user_owners: NonUserOwners) -> (Router, MockService) {
+ let service = MockService::default();
+ let router = chat_create_router(ChatRouterState::new(
+ service.clone(),
+ MockAccessService,
+ authorization_state(),
+ permissions_service(),
+ non_user_owners,
+ ));
+ (router, service)
+}
+
+fn mock_create_router() -> Router {
+ chat_create_router(ChatRouterState::new(
+ MockService::default(),
+ MockAccessService,
+ authorization_state(),
+ permissions_service(),
+ NonUserOwners::Disabled,
+ ))
+ .layer(axum::middleware::map_request(attach_bearer))
+}
+
+fn create_request() -> Builder {
+ Request::builder()
+ .method("POST")
+ .uri("/")
+ .header(header::CONTENT_TYPE, "application/json")
+}
+
+fn with_jwt(builder: Builder) -> Builder {
+ builder.header(header::AUTHORIZATION, "Bearer valid")
+}
+
+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, ACTING_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")
+}
+
+async fn send(router: Router, builder: Builder) -> (StatusCode, Value) {
+ let request = builder
+ .body(Body::from(json!({ "name": "My Chat" }).to_string()))
+ .expect("request should build");
+ let response = router
+ .oneshot(request)
+ .await
+ .expect("router should respond");
+ let status = response.status();
+ let body = response
+ .into_body()
+ .collect()
+ .await
+ .expect("body should be readable")
+ .to_bytes();
+ (
+ status,
+ serde_json::from_slice(&body).expect("body should be JSON"),
+ )
+}
+
+fn user_owner(user_id: &str) -> Owner {
+ Owner::User(
+ MacroUserIdStr::try_from(user_id.to_string()).expect("test user id should be valid"),
+ )
+}
+
+#[tokio::test]
+async fn create_chat_returns_id() {
+ let req = Request::builder()
+ .method("POST")
+ .uri("/")
+ .header("content-type", "application/json")
+ .body(Body::from(r#"{"name": "My Chat"}"#))
+ .unwrap();
+
+ let res = mock_create_router().oneshot(req).await.unwrap();
+ assert_eq!(res.status(), StatusCode::OK);
+
+ let body = res.into_body().collect().await.unwrap().to_bytes();
+ let response: StringIDResponse = serde_json::from_slice(&body).unwrap();
+ assert_eq!(response.id, "test-chat-id");
+}
+
+#[tokio::test]
+async fn create_chat_records_user_owner() {
+ let (router, service) = create_router(NonUserOwners::Disabled);
+
+ let response = send(router, with_jwt(create_request())).await;
+
+ assert_eq!(response, (StatusCode::OK, json!({ "id": "test-chat-id" })));
+ assert_eq!(
+ service.created_owners(),
+ vec![user_owner("macro|[email protected]")]
+ );
+}
+
+#[tokio::test]
+async fn create_chat_by_bot_acting_for_user_records_that_user() {
+ let (router, service) = create_router(NonUserOwners::Disabled);
+
+ let response = send(router, with_user_bot(create_request())).await;
+
+ assert_eq!(response, (StatusCode::OK, json!({ "id": "test-chat-id" })));
+ assert_eq!(service.created_owners(), vec![user_owner(ACTING_USER_ID)]);
+}
+
+#[tokio::test]
+async fn create_chat_by_team_bot_records_bot_owner_when_enabled() {
+ let (router, service) = create_router(NonUserOwners::Enabled);
+
+ let response = send(router, with_team_bot(create_request())).await;
+
+ assert_eq!(response, (StatusCode::OK, json!({ "id": "test-chat-id" })));
+ assert_eq!(service.created_owners(), vec![Owner::Bot(BotId::TEST_A)]);
+}
+
+#[tokio::test]
+async fn create_chat_by_team_bot_is_forbidden_when_disabled() {
+ let (router, service) = create_router(NonUserOwners::Disabled);
+
+ let response = send(router, with_team_bot(create_request())).await;
+
+ assert_eq!(
+ response,
+ (StatusCode::FORBIDDEN, json!({ "message": "forbidden" }))
+ );
+ assert_eq!(service.created_owners(), Vec::<Owner>::new());
+}
+
+#[tokio::test]
+async fn create_chat_by_user_bot_without_acting_user_is_forbidden() {
+ let (router, service) = create_router(NonUserOwners::Enabled);
+
+ let response = send(router, with_user_bot_without_acting_user(create_request())).await;
+
+ assert_eq!(
+ response,
+ (StatusCode::FORBIDDEN, json!({ "message": "forbidden" }))
+ );
+ assert_eq!(service.created_owners(), Vec::<Owner>::new());
+}
diff --git a/crates/chat/src/inbound/toolset/test.rs b/crates/chat/src/inbound/toolset/test.rs
index 15bf179955..2a3e26d4d7 100644
--- a/crates/chat/src/inbound/toolset/test.rs
+++ b/crates/chat/src/inbound/toolset/test.rs
@@ -43,7 +43,7 @@ mod self_read_guard {
impl ChatService for UnreachableChatService {
async fn create(
&self,
- _user_id: MacroUserIdStr<'static>,
+ _owner: model_owner::Owner,
_args: CreateChatArgs,
) -> Result<String> {
unreachable!("guard should short-circuit before calling the chat service")
@@ -280,7 +280,7 @@ mod self_read_guard {
impl ChatService for StubChatService {
async fn create(
&self,
- _user_id: MacroUserIdStr<'static>,
+ _owner: model_owner::Owner,
_args: CreateChatArgs,
) -> Result<String> {
Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
diff --git a/crates/chat/src/outbound/postgres.rs b/crates/chat/src/outbound/postgres.rs
index a8ba3ed2ea..ae90d65a8a 100644
--- a/crates/chat/src/outbound/postgres.rs
+++ b/crates/chat/src/outbound/postgres.rs
@@ -12,14 +12,18 @@ use crate::domain::models::{
use crate::domain::ports::{ChatRepo, MessageRepo};
use agent::types::ChatMessageContent;
use attachment::FormattedParts;
+use entity_registry::BotFacts;
+use entity_registry_db_utils::{NewEntityRecord, OwnedEntityRegistrar, RegisteredEntityType};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use model::chat::ChatMessageWithAttachments;
use model::chat::NewChatMessage;
+use model_owner::Owner;
use models_permissions::share_permission::access_level::AccessLevel;
use models_permissions::share_permission::team_share::TeamShareFacts;
use models_permissions::share_permission::{SharePermissionV2, TeamLinkShareDefault};
-use sqlx::PgPool;
+use sqlx::{PgPool, Postgres, Transaction};
+use uuid::Uuid;
/// Convert an [`anyhow::Error`] to a [`ChatErr`], detecting `sqlx::RowNotFound`.
fn to_chat_err(e: anyhow::Error) -> ChatErr {
@@ -32,16 +36,50 @@ fn to_chat_err(e: anyhow::Error) -> ChatErr {
}
}
+/// Insert a chat row for `owner` with its share permission and recency rows,
+/// returning the chat id and its registry uuid.
+async fn insert_owned_chat(
+ tx: &mut Transaction<'_, Postgres>,
+ owner: &Owner,
+ name: &str,
+ project_id: Option<&str>,
+ share_permission: &SharePermissionV2,
+) -> Result<(String, Uuid)> {
+ let chat_id = queries::insert_chat::insert_chat(tx, owner, name, project_id)
+ .await
+ .map_err(to_chat_err)?;
+
+ queries::create_chat_permission::create_chat_permission(tx, &chat_id, share_permission)
+ .await
+ .map_err(to_chat_err)?;
+
+ // `UserHistory."userId"` still references `"User"`, so only a user owner has history.
+ if let Some(user_id) = owner.as_user() {
+ queries::upsert_user_history::upsert_user_history(tx, user_id.copied(), &chat_id)
+ .await
+ .map_err(to_chat_err)?;
+ }
+
+ queries::upsert_item_last_accessed::upsert_item_last_accessed(tx, &chat_id)
+ .await
+ .map_err(to_chat_err)?;
+
+ let chat_uuid = macro_uuid::string_to_uuid(&chat_id).map_err(to_chat_err)?;
+ Ok((chat_id, chat_uuid))
+}
+
/// Postgres adapter for chat repository operations.
#[derive(Clone)]
-pub struct PgChatRepo {
+pub struct PgChatRepo<B> {
pool: PgPool,
+ registrar: OwnedEntityRegistrar<B>,
}
-impl PgChatRepo {
- /// Create a new [`PgChatRepo`] with the given connection pool.
- pub fn new(pool: PgPool) -> Self {
- Self { pool }
+impl<B: BotFacts + 'static> PgChatRepo<B> {
+ /// Create a new [`PgChatRepo`] with the given connection pool. Created and
+ /// copied chats register their owner grants through `registrar`.
+ pub fn new(pool: PgPool, registrar: OwnedEntityRegistrar<B>) -> Self {
+ Self { pool, registrar }
}
async fn get_messages(&self, chat_id: &str) -> anyhow::Result<Vec<ChatMessageWithAttachments>> {
@@ -76,11 +114,11 @@ impl PgChatRepo {
}
}
-impl ChatRepo for PgChatRepo {
+impl<B: BotFacts + 'static> ChatRepo for PgChatRepo<B> {
#[tracing::instrument(err, skip(self, share_permission))]
async fn create(
&self,
- user_id: MacroUserIdStr<'static>,
+ owner: Owner,
args: CreateChatArgs,
share_permission: SharePermissionV2,
) -> Result<String> {
@@ -90,53 +128,22 @@ impl ChatRepo for PgChatRepo {
.await
.map_err(|e| ChatErr::Unknown(e.into()))?;
- let chat_id = queries::insert_chat::insert_chat(
+ let (chat_id, chat_uuid) = insert_owned_chat(
&mut tx,
- &user_id,
+ &owner,
&args.name,
args.project_id.as_deref(),
- )
- .await
- .map_err(to_chat_err)?;
-
- queries::create_chat_permission::create_chat_permission(
- &mut tx,
- &chat_id,
&share_permission,
)
- .await
- .map_err(to_chat_err)?;
-
- queries::upsert_user_history::upsert_user_history(&mut tx, user_id.copied(), &chat_id)
- .await
- .map_err(to_chat_err)?;
+ .await?;
- queries::upsert_item_last_accessed::upsert_item_last_accessed(&mut tx, &chat_id)
+ self.registrar
+ .register_owned_entity(
+ &mut tx,
+ NewEntityRecord::new(chat_uuid, RegisteredEntityType::Chat, owner),
+ )
.await
- .map_err(to_chat_err)?;
-
- let chat_uuid = macro_uuid::string_to_uuid(&chat_id).map_err(to_chat_err)?;
- entity_access_db_utils::insert_entity_access_row(
- &mut tx,
- &chat_uuid,
- entity_access_db_utils::EntityType::Chat,
- user_id.as_ref(),
- entity_access_db_utils::EntityAccessSourceType::User,
- entity_access_db_utils::AccessLevel::Owner,
- )
- .await
- .map_err(|e| ChatErr::Unknown(e.into()))?;
-
- entity_registry_db_utils::insert_entity(
- &mut tx,
- entity_registry_db_utils::NewEntityRecord::new(
- chat_uuid,
- entity_registry_db_utils::RegisteredEntityType::Chat,
- model_owner::Owner::User(user_id),
- ),
- )
- .await
- .map_err(|e| ChatErr::Unknown(e.into()))?;
+ .map_err(|e| ChatErr::Unknown(e.into()))?;
tx.commit().await.map_err(|e| {
tracing::error!(error=?e, "create_chat transaction error");
@@ -149,11 +156,11 @@ impl ChatRepo for PgChatRepo {
#[tracing::instrument(err, skip(self))]
async fn get_team_default_link_share(
&self,
- user_id: &str,
+ owner: &Owner,
) -> Result<Option<TeamLinkShareDefault>> {
- share_permission_db_utils::get_team_default_link_share(&self.pool, user_id)
+ queries::owner_team_link_share::owner_team_link_share(&self.pool, owner)
.await
- .map_err(|e| ChatErr::Unknown(e.into()))
+ .map_err(to_chat_err)
}
#[tracing::instrument(err, skip(self))]
@@ -195,7 +202,7 @@ impl ChatRepo for PgChatRepo {
#[tracing::instrument(err, skip(self, share_permission))]
async fn copy_chat(
&self,
- user_id: MacroUserIdStr<'static>,
+ owner: Owner,
source_chat_id: &str,
args: CopyChatArgs,
share_permission: SharePermissionV2,
@@ -206,57 +213,26 @@ impl ChatRepo for PgChatRepo {
.await
.map_err(|e| ChatErr::Unknown(e.into()))?;
- let chat_id = queries::insert_chat::insert_chat(
+ let (chat_id, chat_uuid) = insert_owned_chat(
&mut tx,
- &user_id,
+ &owner,
&args.name,
args.project_id.as_deref(),
- )
- .await
- .map_err(to_chat_err)?;
-
- queries::create_chat_permission::create_chat_permission(
- &mut tx,
- &chat_id,
&share_permission,
)
- .await
- .map_err(to_chat_err)?;
-
- queries::upsert_user_history::upsert_user_history(&mut tx, user_id.copied(), &chat_id)
- .await
- .map_err(to_chat_err)?;
-
- queries::upsert_item_last_accessed::upsert_item_last_accessed(&mut tx, &chat_id)
- .await
- .map_err(to_chat_err)?;
-
- let chat_uuid = macro_uuid::string_to_uuid(&chat_id).map_err(to_chat_err)?;
- entity_access_db_utils::insert_entity_access_row(
- &mut tx,
- &chat_uuid,
- entity_access_db_utils::EntityType::Chat,
- user_id.as_ref(),
- entity_access_db_utils::EntityAccessSourceType::User,
- entity_access_db_utils::AccessLevel::Owner,
- )
- .await
- .map_err(|e| ChatErr::Unknown(e.into()))?;
+ .await?;
queries::copy_messages::copy_messages(&mut tx, source_chat_id, &chat_id)
.await
.map_err(to_chat_err)?;
- entity_registry_db_utils::insert_entity(
- &mut tx,
- entity_registry_db_utils::NewEntityRecord::new(
- chat_uuid,
- entity_registry_db_utils::RegisteredEntityType::Chat,
- model_owner::Owner::User(user_id),
- ),
- )
- .await
- .map_err(|e| ChatErr::Unknown(e.into()))?;
+ self.registrar
+ .register_owned_entity(
+ &mut tx,
+ NewEntityRecord::new(chat_uuid, RegisteredEntityType::Chat, owner),
+ )
+ .await
+ .map_err(|e| ChatErr::Unknown(e.into()))?;
tx.commit().await.map_err(|e| {
tracing::error!(error=?e, "copy_chat transaction error");
@@ -427,7 +403,7 @@ impl ChatRepo for PgChatRepo {
}
}
-impl MessageRepo for PgChatRepo {
+impl<B: BotFacts + 'static> MessageRepo for PgChatRepo<B> {
#[tracing::instrument(err, skip(self, message))]
async fn create(&self, chat_id: &str, message: NewChatMessage) -> Result<String> {
queries::create_message::create_message(&self.pool, chat_id, message)
diff --git a/crates/chat/src/outbound/postgres/queries/insert_chat.rs b/crates/chat/src/outbound/postgres/queries/insert_chat.rs
index 31b1e8e9f8..2dcfbbbe70 100644
--- a/crates/chat/src/outbound/postgres/queries/insert_chat.rs
+++ b/crates/chat/src/outbound/postgres/queries/insert_chat.rs
@@ -1,13 +1,13 @@
//! Insert a new chat row.
-use macro_user_id::user_id::MacroUserIdStr;
+use model_owner::Owner;
use sqlx::{Postgres, Transaction};
/// Insert a new chat and return the generated chat ID.
#[tracing::instrument(err, skip(tx))]
pub(crate) async fn insert_chat(
tx: &mut Transaction<'_, Postgres>,
- user_id: &MacroUserIdStr<'_>,
+ owner: &Owner,
name: &str,
project_id: Option<&str>,
) -> anyhow::Result<String> {
@@ -17,7 +17,7 @@ pub(crate) async fn insert_chat(
VALUES ($1, $2, $3)
RETURNING id
"#,
- user_id.as_ref(),
+ owner.principal_id(),
name,
project_id,
)
diff --git a/crates/chat/src/outbound/postgres/queries/mod.rs b/crates/chat/src/outbound/postgres/queries/mod.rs
index 579f07a27f..6bf9bd07fe 100644
--- a/crates/chat/src/outbound/postgres/queries/mod.rs
+++ b/crates/chat/src/outbound/postgres/queries/mod.rs
@@ -13,6 +13,7 @@ pub(crate) mod get_permissions;
pub(crate) mod get_resolved_message;
pub(crate) mod get_web_citations;
pub(crate) mod insert_chat;
+pub(crate) mod owner_team_link_share;
pub(crate) mod patch_chat;
pub(crate) mod permanently_delete_chat;
pub(crate) mod revert_delete_chat;
diff --git a/crates/chat/src/outbound/postgres/queries/owner_team_link_share.rs b/crates/chat/src/outbound/postgres/queries/owner_team_link_share.rs
new file mode 100644
index 0000000000..73cf9c1fe9
--- /dev/null
+++ b/crates/chat/src/outbound/postgres/queries/owner_team_link_share.rs
@@ -0,0 +1,26 @@
+//! Read the link-share preference of an owner's team.
+
+use model_owner::Owner;
+use models_permissions::share_permission::{LinkShare, TeamLinkShareDefault};
+
+/// Get the link-share preference of the team `owner` resolves to, or `None`
+/// when the owner has no team.
+#[tracing::instrument(err, skip(pool))]
+pub(crate) async fn owner_team_link_share(
+ pool: &sqlx::PgPool,
+ owner: &Owner,
+) -> anyhow::Result<Option<TeamLinkShareDefault>> {
+ 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(pool)
+ .await?;
+
+ Ok(row.map(|row| TeamLinkShareDefault(row.default_link_share)))
+}
diff --git a/crates/chat/src/outbound/postgres/team_share/test.rs b/crates/chat/src/outbound/postgres/team_share/test.rs
index 2c6725e9ff..6b9ff56c42 100644
--- a/crates/chat/src/outbound/postgres/team_share/test.rs
+++ b/crates/chat/src/outbound/postgres/team_share/test.rs
@@ -3,6 +3,7 @@ use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::cowlike::CowLike;
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,
@@ -16,7 +17,7 @@ use uuid::Uuid;
use crate::domain::models::{ChatErr, CreateChatArgs, PatchChatRepoArgs};
use crate::domain::ports::ChatRepo;
-use crate::outbound::postgres::PgChatRepo;
+use crate::outbound::postgres::test::{TestRepo, test_repo};
const OWNER: &str = "macro|[email protected]";
const TEAM_ID: Uuid = Uuid::from_u128(0xb2222222_2222_2222_2222_222222222222);
@@ -25,9 +26,9 @@ fn owner() -> MacroUserIdStr<'static> {
MacroUserIdStr::parse_from_str(OWNER).unwrap().into_owned()
}
-async fn create_chat(repo: &PgChatRepo, name: &str) -> String {
+async fn create_chat(repo: &TestRepo, name: &str) -> String {
repo.create(
- owner(),
+ Owner::User(owner()),
CreateChatArgs {
name: name.to_string(),
project_id: None,
@@ -63,7 +64,7 @@ fn command(facts: &TeamShareFacts, level: Option<AccessLevel>) -> AuthorizedTeam
}
async fn patch_team_share(
- repo: &PgChatRepo,
+ repo: &TestRepo,
chat_id: &str,
level: Option<AccessLevel>,
) -> Result<(), ChatErr> {
@@ -140,7 +141,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 = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_chat(&repo, "Facts").await;
let facts = repo.get_team_share_facts(&chat_id).await.unwrap();
@@ -158,7 +159,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 = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_chat(&repo, "No team").await;
let facts = repo.get_team_share_facts(&chat_id).await.unwrap();
@@ -172,7 +173,7 @@ async fn get_team_share_facts_without_team_has_no_owner_team(pool: PgPool) {
fixtures(path = "../fixtures", scripts("users", "team"))
)]
async fn patch_applies_team_share_command_and_inserts_direct_team_entity_access(pool: PgPool) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_chat(&repo, "Shared").await;
patch_team_share(&repo, &chat_id, Some(AccessLevel::Edit))
@@ -214,7 +215,7 @@ async fn patch_applies_team_share_command_and_inserts_direct_team_entity_access(
fixtures(path = "../fixtures", scripts("users", "team"))
)]
async fn patch_clear_command_removes_managed_team_entity_access_and_bumps_revision(pool: PgPool) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_chat(&repo, "Cleared").await;
patch_team_share(&repo, &chat_id, Some(AccessLevel::Comment))
.await
@@ -238,7 +239,7 @@ async fn patch_clear_command_removes_managed_team_entity_access_and_bumps_revisi
fixtures(path = "../fixtures", scripts("users", "team"))
)]
async fn patch_with_team_level_but_no_command_returns_unauthorized(pool: PgPool) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_chat(&repo, "Original").await;
let result = repo
@@ -269,7 +270,7 @@ async fn patch_with_team_level_but_no_command_returns_unauthorized(pool: PgPool)
fixtures(path = "../fixtures", scripts("users", "team"))
)]
async fn patch_rejects_command_for_other_chat_or_mismatched_level(pool: PgPool) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_chat(&repo, "Target").await;
let other_chat_id = create_chat(&repo, "Other").await;
let facts = repo.get_team_share_facts(&chat_id).await.unwrap();
@@ -312,7 +313,7 @@ async fn patch_rejects_command_for_other_chat_or_mismatched_level(pool: PgPool)
fixtures(path = "../fixtures", scripts("users", "team"))
)]
async fn patch_stale_command_returns_conflict(pool: PgPool) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_chat(&repo, "Stale").await;
let facts = repo.get_team_share_facts(&chat_id).await.unwrap();
let stale = command(&facts, Some(AccessLevel::Edit));
@@ -343,7 +344,7 @@ async fn patch_stale_command_returns_conflict(pool: PgPool) {
fixtures(path = "../fixtures", scripts("users", "team"))
)]
async fn patch_team_share_and_link_share_in_one_call_persists_both(pool: PgPool) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_chat(&repo, "Both").await;
let facts = repo.get_team_share_facts(&chat_id).await.unwrap();
@@ -380,7 +381,7 @@ async fn patch_team_share_and_link_share_in_one_call_persists_both(pool: PgPool)
fixtures(path = "../fixtures", scripts("users", "team"))
)]
async fn get_permissions_reads_team_share_access_level(pool: PgPool) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_chat(&repo, "Read").await;
assert_eq!(
repo.get_permissions(&chat_id)
diff --git a/crates/chat/src/outbound/postgres/test.rs b/crates/chat/src/outbound/postgres/test.rs
index 2b81b00833..3e0f51bd86 100644
--- a/crates/chat/src/outbound/postgres/test.rs
+++ b/crates/chat/src/outbound/postgres/test.rs
@@ -1,7 +1,11 @@
+mod owner;
+
use std::time::Duration;
use agent::types::{ChatMessageContent, Role};
use chrono::Utc;
+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 macro_user_id::user_id::MacroUserIdStr;
@@ -18,6 +22,29 @@ use super::PgChatRepo;
use crate::domain::models::{ChatErr, CopyChatArgs, CreateChatArgs, PatchChatRepoArgs};
use crate::domain::ports::ChatRepo;
+/// Sponsors every bot with the fixture user, so a bot owner also grants that user.
+#[derive(Clone)]
+pub(super) struct SponsoredByOwner;
+
+impl BotFacts for SponsoredByOwner {
+ async fn sponsor(&self, _bot: bot_id::BotId) -> EntityRegistryResult<Option<Owner>> {
+ Ok(Some(Owner::User(
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ )))
+ }
+}
+
+pub(super) type TestRepo = PgChatRepo<SponsoredByOwner>;
+
+pub(super) fn test_repo(pool: Pool<Postgres>) -> TestRepo {
+ PgChatRepo::new(
+ pool,
+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(SponsoredByOwner)),
+ )
+}
+
/// The no-team default permission for a chat — the repo persists whatever the
/// domain layer resolved, so tests pass it explicitly.
fn default_share_permission() -> SharePermissionV2 {
@@ -107,12 +134,12 @@ async fn get_stored_share_permission(
}
}
-async fn create_test_chat(repo: &PgChatRepo, name: &str) -> String {
+async fn create_test_chat(repo: &TestRepo, name: &str) -> String {
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
repo.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: name.to_string(),
project_id: None,
@@ -124,7 +151,7 @@ async fn create_test_chat(repo: &PgChatRepo, name: &str) -> String {
}
async fn patch_share_permission(
- repo: &PgChatRepo,
+ repo: &TestRepo,
chat_id: &str,
share_permission: UpdateSharePermissionRequestV2,
) {
@@ -145,13 +172,13 @@ async fn patch_share_permission(
.unwrap();
}
-async fn create_chat_with_message(repo: &PgChatRepo) -> (String, String) {
+async fn create_chat_with_message(repo: &TestRepo) -> (String, String) {
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Message update test".to_string(),
project_id: None,
@@ -185,14 +212,14 @@ async fn create_chat_with_message(repo: &PgChatRepo) -> (String, String) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn create_chat_returns_id(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Test Chat".to_string(),
project_id: None,
@@ -220,14 +247,14 @@ async fn create_chat_returns_id(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn create_message_updates_chat_timestamp_and_selected_model(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool);
+ let repo = test_repo(pool);
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Active Chat".to_string(),
project_id: None,
@@ -303,7 +330,7 @@ async fn create_message_updates_chat_timestamp_and_selected_model(pool: Pool<Pos
fixtures(path = "fixtures", scripts("users"))
)]
async fn delete_message_returns_parent_chat_id_and_removes_message(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool);
+ let repo = test_repo(pool);
let (chat_id, message_id) = create_chat_with_message(&repo).await;
let deleted_from_chat_id = crate::domain::ports::MessageRepo::delete(&repo, &message_id)
@@ -322,7 +349,7 @@ async fn delete_message_returns_parent_chat_id_and_removes_message(pool: Pool<Po
fixtures(path = "fixtures", scripts("users"))
)]
async fn update_message_content_bumps_chat_updated_at(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool);
+ let repo = test_repo(pool);
let (chat_id, message_id) = create_chat_with_message(&repo).await;
let original_updated_at = repo
.get_metadata(&chat_id)
@@ -354,7 +381,7 @@ async fn update_message_content_bumps_chat_updated_at(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn update_interim_message_content_does_not_bump_chat(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool);
+ let repo = test_repo(pool);
let (chat_id, message_id) = create_chat_with_message(&repo).await;
let original_updated_at = repo
.get_metadata(&chat_id)
@@ -386,7 +413,7 @@ async fn update_interim_message_content_does_not_bump_chat(pool: Pool<Postgres>)
fixtures(path = "fixtures", scripts("users"))
)]
async fn nonexistent_message_does_not_bump_chat(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool);
+ let repo = test_repo(pool);
let (chat_id, _) = create_chat_with_message(&repo).await;
let original_updated_at = repo
.get_metadata(&chat_id)
@@ -418,7 +445,7 @@ async fn nonexistent_message_does_not_bump_chat(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn create_chat_creates_public_view_permission(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_test_chat(&repo, "Perm Chat").await;
let permission = get_stored_share_permission(&pool, &chat_id).await;
@@ -432,14 +459,14 @@ async fn create_chat_creates_public_view_permission(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn create_chat_creates_user_item_access(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Access Chat".to_string(),
project_id: None,
@@ -491,14 +518,14 @@ async fn fetch_entity_row(pool: &Pool<Postgres>, chat_id: &str) -> PgRow {
fixtures(path = "fixtures", scripts("users"))
)]
async fn create_chat_registers_entity_row(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Entity Chat".to_string(),
project_id: None,
@@ -523,7 +550,7 @@ async fn create_chat_registers_entity_row(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn delete_chat_marks_entity_deleted(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_test_chat(&repo, "Entity Soft Delete").await;
repo.delete(&chat_id).await.unwrap();
@@ -540,7 +567,7 @@ async fn delete_chat_marks_entity_deleted(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn revert_delete_clears_entity_deleted_at(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_test_chat(&repo, "Entity Restore").await;
repo.delete(&chat_id).await.unwrap();
@@ -558,7 +585,7 @@ async fn revert_delete_clears_entity_deleted_at(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn permanently_delete_chat_removes_entity_row(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_test_chat(&repo, "Entity Perm Delete").await;
repo.permanently_delete(&chat_id).await.unwrap();
@@ -577,14 +604,14 @@ async fn permanently_delete_chat_removes_entity_row(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn copy_chat_registers_entity_row_for_source_and_copy(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let source_id = repo
.create(
- user_id.clone(),
+ Owner::User(user_id.clone()),
CreateChatArgs {
name: "Entity Source".to_string(),
project_id: None,
@@ -596,7 +623,7 @@ async fn copy_chat_registers_entity_row_for_source_and_copy(pool: Pool<Postgres>
let copied_id = repo
.copy_chat(
- user_id,
+ Owner::User(user_id),
&source_id,
CopyChatArgs {
name: "Entity Copy".to_string(),
@@ -630,7 +657,7 @@ async fn copy_chat_registers_entity_row_for_source_and_copy(pool: Pool<Postgres>
fixtures(path = "fixtures", scripts("users"))
)]
async fn delete_restore_and_purge_succeed_without_entity_row(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_test_chat(&repo, "Legacy Chat").await;
let chat_uuid = macro_uuid::string_to_uuid(&chat_id).unwrap();
@@ -664,14 +691,14 @@ async fn delete_restore_and_purge_succeed_without_entity_row(pool: Pool<Postgres
fixtures(path = "fixtures", scripts("users"))
)]
async fn create_chat_creates_user_history(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "History Chat".to_string(),
project_id: None,
@@ -701,14 +728,14 @@ async fn create_chat_creates_user_history(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn create_chat_with_project_id(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Project Chat".to_string(),
project_id: Some("project-123".to_string()),
@@ -735,14 +762,14 @@ async fn create_chat_with_project_id(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn get_chat_returns_chat(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Get Me".to_string(),
project_id: None,
@@ -770,7 +797,7 @@ async fn get_chat_returns_chat(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn get_chat_decodes_bot_and_team_owners(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_test_chat(&repo, "Owned Elsewhere").await;
insert_owner_principal(&pool, BOT_OWNER, "b1111111-1111-1111-1111-111111111111").await;
insert_owner_principal(&pool, TEAM_OWNER, "b2222222-2222-2222-2222-222222222222").await;
@@ -791,7 +818,7 @@ async fn get_chat_decodes_bot_and_team_owners(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn get_chat_not_found(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool);
+ let repo = test_repo(pool);
let result = repo.get_metadata("nonexistent-id").await;
assert!(matches!(result, Err(ChatErr::NotFound)));
@@ -802,14 +829,14 @@ async fn get_chat_not_found(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn soft_delete_chat_sets_deleted_at(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Delete Me".to_string(),
project_id: None,
@@ -836,14 +863,14 @@ async fn soft_delete_chat_sets_deleted_at(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn soft_delete_chat_removes_history(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "History Delete".to_string(),
project_id: None,
@@ -871,14 +898,14 @@ async fn soft_delete_chat_removes_history(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn permanently_delete_chat_removes_row(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Perm Delete".to_string(),
project_id: None,
@@ -904,14 +931,14 @@ async fn permanently_delete_chat_removes_row(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn permanently_delete_chat_removes_permissions(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Perm Delete Perms".to_string(),
project_id: None,
@@ -938,14 +965,14 @@ async fn permanently_delete_chat_removes_permissions(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn permanently_delete_chat_removes_user_item_access(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Perm Delete Access".to_string(),
project_id: None,
@@ -974,14 +1001,14 @@ async fn permanently_delete_chat_removes_user_item_access(pool: Pool<Postgres>)
fixtures(path = "fixtures", scripts("users"))
)]
async fn patch_chat_updates_name(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Original".to_string(),
project_id: None,
@@ -1016,14 +1043,14 @@ async fn patch_chat_updates_name(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn patch_chat_updates_project(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Project Chat".to_string(),
project_id: None,
@@ -1066,14 +1093,14 @@ async fn patch_chat_updates_project(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn patch_chat_clears_project(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Clear Project".to_string(),
project_id: Some("project-123".to_string()),
@@ -1113,14 +1140,14 @@ async fn patch_chat_clears_project(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn get_chat_returns_full_response(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Full Chat".to_string(),
project_id: None,
@@ -1147,7 +1174,7 @@ async fn get_chat_returns_full_response(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn get_chat_not_found_returns_error(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool);
+ let repo = test_repo(pool);
let result = repo.get_chat("nonexistent-id").await;
assert!(matches!(result, Err(ChatErr::NotFound)));
@@ -1158,14 +1185,14 @@ async fn get_chat_not_found_returns_error(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn copy_chat_creates_new_chat_with_same_messages(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let source_id = repo
.create(
- user_id.clone(),
+ Owner::User(user_id.clone()),
CreateChatArgs {
name: "Source Chat".to_string(),
project_id: None,
@@ -1189,7 +1216,7 @@ async fn copy_chat_creates_new_chat_with_same_messages(pool: Pool<Postgres>) {
let copied_id = repo
.copy_chat(
- user_id,
+ Owner::User(user_id),
&source_id,
CopyChatArgs {
name: "Copied Chat".to_string(),
@@ -1222,14 +1249,14 @@ async fn copy_chat_creates_new_chat_with_same_messages(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn revert_delete_restores_chat(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let chat_id = repo
.create(
- user_id,
+ Owner::User(user_id),
CreateChatArgs {
name: "Revert Me".to_string(),
project_id: None,
@@ -1268,7 +1295,7 @@ async fn revert_delete_restores_chat(pool: Pool<Postgres>) {
fixtures(path = "fixtures", scripts("users"))
)]
async fn revert_delete_skips_user_history_for_non_user_owner(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_test_chat(&repo, "Bot Chat").await;
insert_owner_principal(&pool, BOT_OWNER, "b1111111-1111-1111-1111-111111111111").await;
set_chat_owner(&pool, &chat_id, BOT_OWNER).await;
@@ -1294,7 +1321,7 @@ async fn revert_delete_skips_user_history_for_non_user_owner(pool: Pool<Postgres
fixtures(path = "fixtures", scripts("users"))
)]
async fn patch_chat_sets_team_share_and_defaults_explicit_null_level_to_view(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_test_chat(&repo, "Team Chat").await;
patch_share_permission(
@@ -1319,7 +1346,7 @@ async fn patch_chat_sets_team_share_and_defaults_explicit_null_level_to_view(poo
fixtures(path = "fixtures", scripts("users"))
)]
async fn patch_chat_defaults_explicit_null_level_for_existing_link_share(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_test_chat(&repo, "Default View Chat").await;
patch_share_permission(
@@ -1355,7 +1382,7 @@ async fn patch_chat_defaults_explicit_null_level_for_existing_link_share(pool: P
fixtures(path = "fixtures", scripts("users"))
)]
async fn patch_chat_disables_link_sharing_and_clears_both_levels(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_test_chat(&repo, "Private Chat").await;
patch_share_permission(
@@ -1380,7 +1407,7 @@ async fn patch_chat_disables_link_sharing_and_clears_both_levels(pool: Pool<Post
fixtures(path = "fixtures", scripts("users"))
)]
async fn get_permissions_reads_link_share_columns(pool: Pool<Postgres>) {
- let repo = PgChatRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let chat_id = create_test_chat(&repo, "Perms Chat").await;
let permission = repo.get_permissions(&chat_id).await.unwrap();
diff --git a/crates/chat/src/outbound/postgres/test/owner.rs b/crates/chat/src/outbound/postgres/test/owner.rs
new file mode 100644
index 0000000000..58d28c7516
--- /dev/null
+++ b/crates/chat/src/outbound/postgres/test/owner.rs
@@ -0,0 +1,168 @@
+use bot_id::BotId;
+use models_permissions::share_permission::TeamLinkShareDefault;
+
+use super::*;
+
+const TEST_BOT: &str = "bot|00000000-0000-0000-0000-00000000b07a";
+const SPONSOR: &str = "macro|[email protected]";
+
+#[derive(Debug, PartialEq, Eq)]
+struct ChatOwnership {
+ chat_user_id: String,
+ entity_owner: (String, String),
+ grants: Vec<(String, String, String)>,
+ user_history_rows: i64,
+ item_last_accessed_rows: i64,
+}
+
+async fn chat_ownership(pool: &Pool<Postgres>, chat_id: &str) -> ChatOwnership {
+ let chat_user_id: String = sqlx::query_scalar(r#"SELECT "userId" FROM "Chat" WHERE id = $1"#)
+ .bind(chat_id)
+ .fetch_one(pool)
+ .await
+ .unwrap();
+ let entity = fetch_entity_row(pool, chat_id).await;
+ let grants = sqlx::query_as(
+ r#"
+ SELECT source_type::text, source_id, access_level::text
+ FROM entity_access
+ WHERE entity_id = $1
+ ORDER BY source_type::text, source_id
+ "#,
+ )
+ .bind(macro_uuid::string_to_uuid(chat_id).unwrap())
+ .fetch_all(pool)
+ .await
+ .unwrap();
+ let item_last_accessed_rows: i64 = sqlx::query_scalar(
+ r#"SELECT COUNT(*) FROM "ItemLastAccessed" WHERE item_id = $1 AND item_type = 'chat'"#,
+ )
+ .bind(chat_id)
+ .fetch_one(pool)
+ .await
+ .unwrap();
+
+ ChatOwnership {
+ chat_user_id,
+ entity_owner: (entity.get("owner_type"), entity.get("owner_id")),
+ grants,
+ user_history_rows: chat_history_count(pool, chat_id).await,
+ item_last_accessed_rows,
+ }
+}
+
+fn test_bot_ownership() -> ChatOwnership {
+ ChatOwnership {
+ chat_user_id: TEST_BOT.to_owned(),
+ entity_owner: ("bot".to_owned(), TEST_BOT.to_owned()),
+ grants: vec![
+ ("bot".to_owned(), TEST_BOT.to_owned(), "owner".to_owned()),
+ ("user".to_owned(), SPONSOR.to_owned(), "owner".to_owned()),
+ ],
+ user_history_rows: 0,
+ item_last_accessed_rows: 1,
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("users"))
+)]
+async fn bot_owned_create_registers_owner_grants_without_user_history(pool: Pool<Postgres>) {
+ let repo = test_repo(pool.clone());
+
+ let chat_id = repo
+ .create(
+ Owner::Bot(BotId::TEST_A),
+ CreateChatArgs {
+ name: "Bot Chat".to_string(),
+ project_id: None,
+ },
+ default_share_permission(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(chat_ownership(&pool, &chat_id).await, test_bot_ownership());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("users"))
+)]
+async fn bot_owned_copy_copies_messages_and_registers_owner_grants(pool: Pool<Postgres>) {
+ let repo = test_repo(pool.clone());
+ let (source_id, _) = create_chat_with_message(&repo).await;
+
+ let copied_id = repo
+ .copy_chat(
+ Owner::Bot(BotId::TEST_A),
+ &source_id,
+ CopyChatArgs {
+ name: "Bot Copy".to_string(),
+ project_id: None,
+ },
+ default_share_permission(),
+ )
+ .await
+ .unwrap();
+
+ let copied_messages: i64 =
+ sqlx::query_scalar(r#"SELECT COUNT(*) FROM "ChatMessage" WHERE "chatId" = $1"#)
+ .bind(&copied_id)
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(copied_messages, 1);
+ assert_eq!(
+ chat_ownership(&pool, &copied_id).await,
+ test_bot_ownership()
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../fixtures", scripts("users"))
+)]
+async fn bot_owner_team_default_link_share_comes_from_owner_team(pool: Pool<Postgres>) {
+ let team_id = uuid::Uuid::from_u128(0x7ea3);
+ sqlx::query(
+ r#"
+ INSERT INTO team (id, name, owner_id, default_link_share)
+ VALUES ($1, 'Bot Team', $2, 'PUBLIC')
+ "#,
+ )
+ .bind(team_id)
+ .bind(SPONSOR)
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query(
+ r#"
+ INSERT INTO bots (id, kind, team_id, name, handle)
+ VALUES ($1, 'owned', $2, 'Chat bot', 'chat-bot-owner')
+ "#,
+ )
+ .bind(BotId::TEST_A.as_uuid())
+ .bind(team_id)
+ .execute(&pool)
+ .await
+ .unwrap();
+ let repo = test_repo(pool);
+ let teamless_user = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+
+ assert_eq!(
+ repo.get_team_default_link_share(&Owner::Bot(BotId::TEST_A))
+ .await
+ .unwrap(),
+ Some(TeamLinkShareDefault(Some(LinkShare::Public)))
+ );
+ assert_eq!(
+ repo.get_team_default_link_share(&Owner::User(teamless_user))
+ .await
+ .unwrap(),
+ None
+ );
+}
diff --git a/crates/entity_registry/entity_registry/src/domain/creation_principal.rs b/crates/entity_registry/entity_registry/src/domain/creation_principal.rs
index 3c0b2d4dcb..9997019dda 100644
--- a/crates/entity_registry/entity_registry/src/domain/creation_principal.rs
+++ b/crates/entity_registry/entity_registry/src/domain/creation_principal.rs
@@ -6,6 +6,8 @@
#[cfg(test)]
mod test;
+use std::str::ParseBoolError;
+
use bot_id::NonSystemBotId;
use macro_authorization::{BotAuthentication, BotScope, MacroAuthorization};
use model_owner::CreationPrincipal;
@@ -19,6 +21,21 @@ pub enum NonUserOwners {
Enabled,
}
+impl NonUserOwners {
+ /// Parse the gate from a config value the caller already loaded.
+ ///
+ /// `"true"` enables non-user owners. `"false"` or a missing value disables
+ /// them. Any other value is an error. This never reads the environment.
+ pub fn from_config_value(value: Option<&str>) -> Result<Self, ParseBoolError> {
+ let enabled = value.unwrap_or("false").parse::<bool>()?;
+ Ok(if enabled {
+ Self::Enabled
+ } else {
+ Self::Disabled
+ })
+ }
+}
+
/// Why a caller cannot create entities.
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum CreationPrincipalError {
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.rs
index 21f42c0c33..c645bcf7be 100644
--- a/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rs
+++ b/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rs
@@ -186,3 +186,31 @@ fn a_row_bot_without_a_user_owns_only_in_verified_team_scope_behind_the_gate() {
);
}
}
+
+#[test]
+fn missing_or_false_gate_disables_non_user_owners() {
+ assert_eq!(
+ NonUserOwners::from_config_value(None),
+ Ok(NonUserOwners::Disabled)
+ );
+ assert_eq!(
+ NonUserOwners::from_config_value(Some("false")),
+ Ok(NonUserOwners::Disabled)
+ );
+}
+
+#[test]
+fn true_gate_enables_non_user_owners() {
+ assert_eq!(
+ NonUserOwners::from_config_value(Some("true")),
+ Ok(NonUserOwners::Enabled)
+ );
+}
+
+#[test]
+fn invalid_gate_value_is_rejected() {
+ assert_eq!(
+ NonUserOwners::from_config_value(Some("yes")).map_err(|error| error.to_string()),
+ Err("provided string was not `true` or `false`".to_owned())
+ );
+}
diff --git a/crates/memory/src/context.rs b/crates/memory/src/context.rs
index 1abf5f005b..a6cfd95cd5 100644
--- a/crates/memory/src/context.rs
+++ b/crates/memory/src/context.rs
@@ -122,10 +122,9 @@ pub async fn build_tool_service_context(
&config.document_storage_bucket,
&config.docx_document_upload_bucket,
);
- let document_repo = PgDocumentRepo::new(
- pool.clone(),
- OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone()))),
- );
+ let owned_entity_registrar =
+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone())));
+ let document_repo = PgDocumentRepo::new(pool.clone(), owned_entity_registrar.clone());
let cloudfront_config = CloudFrontConfig {
distribution_url: config
.document_storage_service_cloudfront_distribution_url
@@ -224,7 +223,7 @@ pub async fn build_tool_service_context(
let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
chat::domain::service::ChatServiceImpl::new(
- chat::outbound::postgres::PgChatRepo::new(pool.clone()),
+ chat::outbound::postgres::PgChatRepo::new(pool.clone(), owned_entity_registrar),
Arc::new(ai_toolset::AsyncToolCollection::new()),
(),
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.ts
index 4d616e5b0c..7417b3bae7 100644
--- a/packages/sdk/generated/cognition/types.gen.ts
+++ b/packages/sdk/generated/cognition/types.gen.ts
@@ -1877,6 +1877,7 @@ export type CreateChatData = {
export type CreateChatErrors = {
401: string;
+ 403: string;
500: string;
};
diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.json
index 5f89f1d533..0253b8d90c 100644
--- a/packages/sdk/specs/cognition.json
+++ b/packages/sdk/specs/cognition.json
@@ -413,6 +413,16 @@
}
}
},
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
diff --git a/services/document_cognition_service/src/api/chats.rs b/services/document_cognition_service/src/api/chats.rs
index 3631fa282f..cac59ff048 100644
--- a/services/document_cognition_service/src/api/chats.rs
+++ b/services/document_cognition_service/src/api/chats.rs
@@ -9,6 +9,7 @@ use axum::{
response::Response,
routing::{get, post},
};
+use bots::outbound::pg_bots_repo::PgBotsRepo;
use chat::domain::service::ChatServiceImpl;
use chat::inbound::http::router::{
ChatRouterState, chat_create_router, chat_id_router, chat_view_router,
@@ -16,6 +17,8 @@ use chat::inbound::http::router::{
use chat::outbound::postgres::PgChatRepo;
use entity_access::domain::service::EntityAccessServiceImpl;
use entity_access::outbound::PgAccessRepository;
+use entity_registry::OwnerGrantPolicy;
+use entity_registry_db_utils::OwnedEntityRegistrar;
use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use tower::ServiceBuilder;
@@ -40,7 +43,10 @@ async fn require_authenticated_user(
pub fn router(state: ApiContext) -> Router<ApiContext> {
let access_repo = PgAccessRepository::new(state.db.clone());
let access_service = EntityAccessServiceImpl::new(access_repo);
- let chat_repo = PgChatRepo::new(state.db.clone());
+ let chat_repo = PgChatRepo::new(
+ state.db.clone(),
+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(state.db.clone()))),
+ );
let chat_service = ChatServiceImpl::new(
chat_repo,
@@ -56,6 +62,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
access_service,
state.authorization_state.clone(),
state.user_permissions_service.clone(),
+ state.non_user_owners,
);
let ensure_chat_exists = axum::middleware::from_fn_with_state(
diff --git a/services/document_cognition_service/src/api/context.rs b/services/document_cognition_service/src/api/context.rs
index 1354ab8a09..2d60aa90e3 100644
--- a/services/document_cognition_service/src/api/context.rs
+++ b/services/document_cognition_service/src/api/context.rs
@@ -7,6 +7,7 @@ use ai_tools::{
};
use attachment::provider::AttachmentProvider;
use axum::extract::FromRef;
+use bots::outbound::pg_bots_repo::PgBotsRepo;
use channels::inbound::attachment::ChannelAttachmentService;
use channels::outbound::pg_channels_repo::PgChannelsRepo;
use chat::domain::service::MessageServiceImpl;
@@ -17,6 +18,7 @@ use document_storage_service_client::DocumentStorageServiceClient;
use documents::inbound::attachment::DocumentAttachmentService;
use email::inbound::attachment::EmailAttachmentService;
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
+use entity_registry::NonUserOwners;
use macro_auth::InternalApiKey;
use macro_authorization::{
MacroAuthJwtValidator, MacroAuthorizationServiceImpl, MacroAuthorizationState,
@@ -67,7 +69,7 @@ pub type DcsChatModelAccess = chat::inbound::http::extractors::ChatModelAccess<
pub type DcsAttachmentProvider = AttachmentProvider<
DocumentAttachmentService<ToolDocumentService, ToolEntityAccessService>,
EmailAttachmentService<ToolEmailService, ToolEntityAccessService>,
- ChatAttachmentService<PgChatRepo, ToolEntityAccessService>,
+ ChatAttachmentService<PgChatRepo<PgBotsRepo>, ToolEntityAccessService>,
ChannelAttachmentService<PgChannelsRepo, ToolEntityAccessService>,
StaticFileAttachmentService<CdnStaticFileRepo>,
>;
@@ -79,7 +81,8 @@ pub type DcsEventBroker = macro_event_broker::MacroEventBrokerService<
>;
/// Type alias for the message service wired to concrete DCS services.
-pub type DcsMessageService = MessageServiceImpl<PgChatRepo, DcsAttachmentProvider, DcsEventBroker>;
+pub type DcsMessageService =
+ MessageServiceImpl<PgChatRepo<PgBotsRepo>, DcsAttachmentProvider, DcsEventBroker>;
#[cfg(test)]
mod test;
@@ -145,6 +148,8 @@ pub struct ApiContext {
pub email_service_client_external: Arc<email_service_client::EmailServiceClientExternal>,
pub authorization_state: MacroAuthorizationState<DcsAuthorizationService>,
pub user_permissions_service: Arc<DcsUserPermissionsService>,
+ /// Whether a team bot with no acting user may own what it creates.
+ pub non_user_owners: NonUserOwners,
/// Plan allowance gate for AI requests.
pub ai_billing: Arc<DcsAiBillingService>,
pub config: Arc<Config>,
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 806be2b65b..bf7ffad5fd 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -233,13 +233,14 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
"test-bucket",
"test-docx-bucket",
);
+ let owned_entity_registrar = entity_registry_db_utils::OwnedEntityRegistrar::new(
+ entity_registry::OwnerGrantPolicy::new(bots::outbound::pg_bots_repo::PgBotsRepo::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(),
- )),
- ),
+ owned_entity_registrar.clone(),
);
let cloudfront_config = documents::domain::models::CloudFrontConfig {
distribution_url: "https://test.cloudfront.net".to_string(),
@@ -346,7 +347,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
chat::domain::service::ChatServiceImpl::new(
- chat::outbound::postgres::PgChatRepo::new(pool.clone()),
+ chat::outbound::postgres::PgChatRepo::new(pool.clone(), owned_entity_registrar.clone()),
Arc::new(ai_toolset::AsyncToolCollection::new()),
(),
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
@@ -548,6 +549,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
macro_env::Environment::Local,
)),
user_permissions_service,
+ non_user_owners: NonUserOwners::Disabled,
config: Arc::new(Config::new_empty_for_test()),
internal_api_key: InternalApiKey::Comptime("testing"),
notification_ingress_service,
@@ -574,7 +576,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
entity_access_service: entity_access_service.clone(),
message_service: Arc::new(
chat::domain::service::MessageServiceImpl::new(
- chat::outbound::postgres::PgChatRepo::new(pool.clone()),
+ chat::outbound::postgres::PgChatRepo::new(
+ pool.clone(),
+ owned_entity_registrar.clone(),
+ ),
attachment::provider::AttachmentProvider {
document: documents::inbound::attachment::DocumentAttachmentService::new(
document_tool_context.service.clone(),
@@ -586,7 +591,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
entity_access_service.clone(),
),
chat: chat::inbound::attachment::ChatAttachmentService::new(
- Arc::new(chat::outbound::postgres::PgChatRepo::new(pool.clone())),
+ Arc::new(chat::outbound::postgres::PgChatRepo::new(
+ pool.clone(),
+ owned_entity_registrar.clone(),
+ )),
entity_access_service.clone(),
),
channel: channels::inbound::attachment::ChannelAttachmentService::new(
diff --git a/services/document_cognition_service/src/config.rs b/services/document_cognition_service/src/config.rs
index e9d34e469a..fffbcfaabf 100644
--- a/services/document_cognition_service/src/config.rs
+++ b/services/document_cognition_service/src/config.rs
@@ -1,4 +1,5 @@
use anyhow::Context;
+use entity_registry::NonUserOwners;
use macro_auth::InternalApiKey;
pub use macro_env::Environment;
use macro_env_var::{env_vars, maybe_env_vars};
@@ -30,6 +31,8 @@ env_vars!(
maybe_env_vars!(
pub struct DocumentBatchLimit;
+ /// Rollout gate for entities owned by bots or teams.
+ pub struct EnableNonUserOwners;
/// OAuth client ID for the Pipedream API (Pipedream project settings).
/// When unset (along with the other Pipedream credentials), the
/// Pipedream MCP endpoints answer 501 and its toolsets come up empty.
@@ -130,6 +133,8 @@ pub struct Config {
pub document_permission_jwt: DocumentPermissionJwt,
/// Comma-separated Kafka bootstrap servers for the macro event broker.
pub kafka_brokers: KafkaBrokers,
+ /// Lets a team-scoped bot with no acting user own the chats it creates.
+ pub enable_non_user_owners: EnableNonUserOwners,
}
fn default_mcp_public_url(environment: Environment) -> &'static str {
@@ -146,6 +151,11 @@ impl Config {
macro_config::ConfigLoader::load::<Config>().context("failed to load config")
}
+ pub fn non_user_owners(&self) -> anyhow::Result<NonUserOwners> {
+ NonUserOwners::from_config_value(self.enable_non_user_owners.value())
+ .context("ENABLE_NON_USER_OWNERS must be `true` or `false`")
+ }
+
#[cfg(test)]
pub fn new_empty_for_test() -> Self {
Config {
@@ -197,6 +207,7 @@ impl Config {
mcp_public_url: default_mcp_public_url(Environment::Local).to_string(),
document_permission_jwt: DocumentPermissionJwt::Comptime("DOCUMENT_PERMISSION_JWT"),
kafka_brokers: KafkaBrokers::Comptime("localhost:9092"),
+ enable_non_user_owners: EnableNonUserOwners::Unset,
}
}
}
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index b071e14e89..2b4c1d255f 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -77,6 +77,7 @@ async fn main() -> anyhow::Result<()> {
.resolve_remote_secrets(Environment::new_or_prod(), &secretsmanager_client)
.await
.context("expected to be able to resolve config secrets")?;
+ let non_user_owners = config.non_user_owners()?;
tracing::info!("initialized config");
@@ -273,10 +274,9 @@ 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(),
- OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::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
@@ -372,7 +372,10 @@ async fn main() -> anyhow::Result<()> {
entity_access_service.clone(),
),
chat: chat::inbound::attachment::ChatAttachmentService::new(
- Arc::new(chat::outbound::postgres::PgChatRepo::new(db.clone())),
+ Arc::new(chat::outbound::postgres::PgChatRepo::new(
+ db.clone(),
+ owned_entity_registrar.clone(),
+ )),
entity_access_service.clone(),
),
channel: channels::inbound::attachment::ChannelAttachmentService::new(
@@ -385,7 +388,7 @@ async fn main() -> anyhow::Result<()> {
};
let message_service = Arc::new(
chat::domain::service::MessageServiceImpl::new(
- chat::outbound::postgres::PgChatRepo::new(db.clone()),
+ chat::outbound::postgres::PgChatRepo::new(db.clone(), owned_entity_registrar.clone()),
attachment_provider,
)
.with_event_broker(macro_event_broker.clone()),
@@ -445,7 +448,7 @@ async fn main() -> anyhow::Result<()> {
let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
chat::domain::service::ChatServiceImpl::new(
- chat::outbound::postgres::PgChatRepo::new(db.clone()),
+ chat::outbound::postgres::PgChatRepo::new(db.clone(), owned_entity_registrar.clone()),
Arc::new(ai_toolset::AsyncToolCollection::new()),
(),
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
@@ -840,6 +843,7 @@ async fn main() -> anyhow::Result<()> {
search_service_client,
authorization_state,
user_permissions_service,
+ non_user_owners,
ai_billing,
internal_api_key: config.internal_api_key.clone(),
config: Arc::new(config),
diff --git a/services/document_cognition_service/src/service/chat_renamer.rs b/services/document_cognition_service/src/service/chat_renamer.rs
index caffa87bf4..b282159296 100644
--- a/services/document_cognition_service/src/service/chat_renamer.rs
+++ b/services/document_cognition_service/src/service/chat_renamer.rs
@@ -1,8 +1,11 @@
use crate::api::context::ApiContext;
use agent::PredefinedModel;
+use bots::outbound::pg_bots_repo::PgBotsRepo;
use chat::domain::models::PatchChatRepoArgs;
use chat::domain::ports::ChatRepo;
use chat::outbound::postgres::PgChatRepo;
+use entity_registry::OwnerGrantPolicy;
+use entity_registry_db_utils::OwnedEntityRegistrar;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
use std::sync::Arc;
@@ -67,19 +70,22 @@ async fn rename_initial_chat(
}
let user_id_string = user_id.as_ref().to_string();
- PgChatRepo::new(ctx.db.clone())
- .patch(
- user_id,
- &chat_id,
- PatchChatRepoArgs {
- name: Some(name.clone()),
- project_id: None,
- share_permission: None,
- team_share: None,
- },
- )
- .await
- .map_err(anyhow::Error::from)?;
+ PgChatRepo::new(
+ ctx.db.clone(),
+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(ctx.db.clone()))),
+ )
+ .patch(
+ user_id,
+ &chat_id,
+ PatchChatRepoArgs {
+ name: Some(name.clone()),
+ project_id: None,
+ share_permission: None,
+ team_share: None,
+ },
+ )
+ .await
+ .map_err(anyhow::Error::from)?;
ctx.connection_gateway_client
.batch_send_to_entities(
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 3a4e8be3e4..8c3eaf0696 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -445,7 +445,7 @@ pub(crate) type DssCallInternalState = InternalCallRouterState<DssCallService>;
/// Chat service used by the unified entity mutation adapter.
pub(crate) type DssChatMutationService = chat::domain::service::ChatServiceImpl<
- chat::outbound::postgres::PgChatRepo,
+ chat::outbound::postgres::PgChatRepo<PgBotsRepo>,
(),
EntityAccessManagementService,
>;
diff --git a/services/document_storage_service/src/config.rs b/services/document_storage_service/src/config.rs
index a78c1f6ca5..ba988d1e39 100644
--- a/services/document_storage_service/src/config.rs
+++ b/services/document_storage_service/src/config.rs
@@ -6,9 +6,6 @@ pub use macro_env::Environment;
use macro_env_var::{env_vars, maybe_env_vars};
use secretsmanager_client::LocalOrRemoteSecret;
-#[cfg(test)]
-mod test;
-
pub const DEFAULT_PRESIGNED_URL_EXPIRY_SECONDS: u64 = 900; // 15 minutes
/// Allow long recordings to play and seek without the signed URL expiring mid-session.
pub const CALL_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS: u64 = 6 * 60 * 60;
@@ -203,18 +200,7 @@ impl Config {
}
pub fn non_user_owners(&self) -> anyhow::Result<NonUserOwners> {
- parse_non_user_owners(self.enable_non_user_owners.value())
+ NonUserOwners::from_config_value(self.enable_non_user_owners.value())
+ .context("ENABLE_NON_USER_OWNERS must be `true` or `false`")
}
}
-
-fn parse_non_user_owners(value: Option<&str>) -> anyhow::Result<NonUserOwners> {
- let enabled = value
- .unwrap_or("false")
- .parse::<bool>()
- .context("ENABLE_NON_USER_OWNERS must be `true` or `false`")?;
- Ok(if enabled {
- NonUserOwners::Enabled
- } else {
- NonUserOwners::Disabled
- })
-}
diff --git a/services/document_storage_service/src/config/test.rs b/services/document_storage_service/src/config/test.rs
deleted file mode 100644
index 793e68ad1d..0000000000
--- a/services/document_storage_service/src/config/test.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-use super::*;
-
-#[test]
-fn missing_or_false_gate_disables_non_user_owners() {
- assert_eq!(
- parse_non_user_owners(None).unwrap(),
- NonUserOwners::Disabled
- );
- assert_eq!(
- parse_non_user_owners(Some("false")).unwrap(),
- NonUserOwners::Disabled
- );
-}
-
-#[test]
-fn true_gate_enables_non_user_owners() {
- assert_eq!(
- parse_non_user_owners(Some("true")).unwrap(),
- NonUserOwners::Enabled
- );
-}
-
-#[test]
-fn invalid_gate_value_is_rejected() {
- let error = parse_non_user_owners(Some("yes")).unwrap_err();
-
- assert_eq!(
- error.to_string(),
- "ENABLE_NON_USER_OWNERS must be `true` or `false`"
- );
-}
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index c924812ea2..2421e4935c 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -516,7 +516,7 @@ async fn run() -> anyhow::Result<()> {
let chat_mutation_service =
Arc::new(chat::domain::service::ChatServiceImpl::new_without_tools(
- chat::outbound::postgres::PgChatRepo::new(db.clone()),
+ chat::outbound::postgres::PgChatRepo::new(db.clone(), owned_entity_registrar.clone()),
entity_access_management_service.clone(),
));
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index a2f33cbb47..1501eaeb28 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -212,10 +212,9 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
config.document_storage_bucket.as_ref(),
config.docx_document_upload_bucket.as_ref(),
);
- let document_repo = PgDocumentRepo::new(
- db.clone(),
- OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::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_private_key = LocalOrRemoteSecret::new_from_secret_manager(
config
.document_storage_service_cloudfront_signer_private_key_secret_name
@@ -355,7 +354,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
chat::domain::service::ChatServiceImpl::new(
- chat::outbound::postgres::PgChatRepo::new(db.clone()),
+ chat::outbound::postgres::PgChatRepo::new(db.clone(), owned_entity_registrar),
Arc::new(ai_toolset::AsyncToolCollection::new()),
(),
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
diff --git a/services/scheduled_action/Cargo.toml b/services/scheduled_action/Cargo.toml
index 4188e02b0d..6b45e65aab 100644
--- a/services/scheduled_action/Cargo.toml
+++ b/services/scheduled_action/Cargo.toml
@@ -25,6 +25,7 @@ activity = { path = "../../crates/activity", default-features = false }
agent_runtime_protocol = { path = "../../crates/agent_runtime_protocol", default-features = false }
agent_session = { path = "../../crates/agent_session", default-features = false }
bot_id = { path = "../../crates/bot_id" }
+bots = { path = "../../crates/bots", default-features = false, features = ["outbound"] }
channel_sender = { path = "../../crates/channel_sender" }
channels = { path = "../../crates/channels", default-features = false }
documents = { path = "../../crates/documents", default-features = false }
@@ -72,6 +73,7 @@ memory = { path = "../../crates/memory" }
model = { path = "../../crates/model" }
model-entity = { path = "../../crates/model-entity" }
model_owner = { path = "../../crates/model_owner" }
+entity_registry = { path = "../../crates/entity_registry/entity_registry" }
entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }
model_notifications = { path = "../../crates/model_notifications" }
notification = { path = "../../crates/notification" }
diff --git a/services/scheduled_action/src/bins/service.rs b/services/scheduled_action/src/bins/service.rs
index 42e850d66c..e064dcc6fb 100644
--- a/services/scheduled_action/src/bins/service.rs
+++ b/services/scheduled_action/src/bins/service.rs
@@ -4,9 +4,12 @@ use std::{future::Future, sync::Arc, time::Duration};
use ai_tools::{AiHost, build_tool_service_context_from_env, tools_for};
use anyhow::{Context, Result};
use axum::Router;
+use bots::outbound::pg_bots_repo::PgBotsRepo;
use chat::outbound::postgres::PgChatRepo;
use connection_gateway_client::client::ConnectionGatewayClient;
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
+use entity_registry::OwnerGrantPolicy;
+use entity_registry_db_utils::OwnedEntityRegistrar;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_authorization::{
InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,
@@ -113,7 +116,10 @@ async fn main() -> Result<()> {
);
let runner = Arc::new(AgentTaskRunner::new(
Arc::clone(&tool_context.chat_tool_context.service),
- PgChatRepo::new(db.clone()),
+ PgChatRepo::new(
+ db.clone(),
+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(db.clone()))),
+ ),
memory,
tool_context,
notification_ingress,
diff --git a/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs b/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
index 3fc324f719..aeb8a6ed80 100644
--- a/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
+++ b/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
@@ -13,6 +13,7 @@ use futures::{Stream, StreamExt};
use macro_user_id::user_id::MacroUserIdStr;
use memory::domain::MemoryService;
use model::chat::NewChatMessage;
+use model_owner::Owner;
use notification::domain::service::NotificationIngress;
use crate::domain::event_trigger::EventReference;
@@ -68,7 +69,7 @@ where
let chat_id = self
.chats
.create(
- action.owner_user()?.clone(),
+ Owner::User(action.owner_user()?.clone()),
CreateChatArgs {
name: action.name.clone(),
project_id: None,