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(entity_access): update entityaccess to support macro authorization scoped access (#5176)

Will Hutchinson95903a8c4da0
diff --git a/.sqlx/query-1f8d22042058b693766e401728e0fa42dabe7b791cbb2fcf1ee2f52e522f7d3c.json b/.sqlx/query-1f8d22042058b693766e401728e0fa42dabe7b791cbb2fcf1ee2f52e522f7d3c.json
new file mode 100644
index 0000000000..41e01ac1d7
--- /dev/null
+++ b/.sqlx/query-1f8d22042058b693766e401728e0fa42dabe7b791cbb2fcf1ee2f52e522f7d3c.json
@@ -0,0 +1,31 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n cp.role::text AS \"role?\",\n (\n b.id IS NOT NULL\n AND c.channel_type = 'team'\n AND c.team_id = $3\n ) AS \"is_matching_team_channel!\"\n FROM comms_channels c\n LEFT JOIN bots b\n ON b.id = $4\n AND b.team_id = $3\n AND b.deleted_at IS NULL\n LEFT JOIN comms_channel_participants cp\n ON cp.channel_id = c.id\n AND cp.user_id = $2\n AND cp.left_at IS NULL\n AND b.id IS NOT NULL\n WHERE c.id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "role?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "is_matching_team_channel!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null,
+ null
+ ]
+ },
+ "hash": "1f8d22042058b693766e401728e0fa42dabe7b791cbb2fcf1ee2f52e522f7d3c"
+}
diff --git a/.sqlx/query-3011831c1dfeb8361383c40c669485d44eef37d61480954deaea0d00252920a6.json b/.sqlx/query-3011831c1dfeb8361383c40c669485d44eef37d61480954deaea0d00252920a6.json
new file mode 100644
index 0000000000..66ff410ef9
--- /dev/null
+++ b/.sqlx/query-3011831c1dfeb8361383c40c669485d44eef37d61480954deaea0d00252920a6.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH active_bot AS (\n SELECT id\n FROM bots\n WHERE id = $2\n AND team_id = $3\n AND deleted_at IS NULL\n )\n SELECT $1::text AS \"source_id!\"\n FROM active_bot\n UNION\n SELECT $3::text\n FROM active_bot\n UNION\n SELECT c.id::text\n FROM active_bot\n JOIN comms_channels c\n ON c.channel_type = 'team'\n AND c.team_id = $3\n UNION\n SELECT cp.channel_id::text\n FROM active_bot\n JOIN comms_channel_participants cp\n ON cp.user_id = $1\n AND cp.left_at IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "source_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3011831c1dfeb8361383c40c669485d44eef37d61480954deaea0d00252920a6"
+}
diff --git a/.sqlx/query-54a58d0c472902a9860bdbc30efd2b732654c5b3aa505e44961e1308ecf76cc1.json b/.sqlx/query-54a58d0c472902a9860bdbc30efd2b732654c5b3aa505e44961e1308ecf76cc1.json
deleted file mode 100644
index f402a46a6e..0000000000
--- a/.sqlx/query-54a58d0c472902a9860bdbc30efd2b732654c5b3aa505e44961e1308ecf76cc1.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH active_bot AS (\n SELECT team_id\n FROM bots\n WHERE id = $2 AND deleted_at IS NULL\n )\n SELECT cp.channel_id::text\n FROM active_bot\n JOIN comms_channel_participants cp\n ON cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL\n SELECT team_id::text\n FROM active_bot\n WHERE team_id IS NOT NULL\n UNION ALL\n SELECT $1\n FROM active_bot\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "channel_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Uuid"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "54a58d0c472902a9860bdbc30efd2b732654c5b3aa505e44961e1308ecf76cc1"
-}
diff --git a/.sqlx/query-5a00a889e19a6d8d323bef2edf0764f7ad93f1478369b70ac9243ab211745d21.json b/.sqlx/query-5a00a889e19a6d8d323bef2edf0764f7ad93f1478369b70ac9243ab211745d21.json
deleted file mode 100644
index 302bf6af2e..0000000000
--- a/.sqlx/query-5a00a889e19a6d8d323bef2edf0764f7ad93f1478369b70ac9243ab211745d21.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT cp.role::text as \"role?\"\n FROM comms_channels c\n LEFT JOIN comms_channel_participants cp\n ON cp.channel_id = c.id\n AND cp.user_id = $2\n AND cp.left_at IS NULL\n AND EXISTS (\n SELECT 1\n FROM bots b\n WHERE b.id = $3 AND b.deleted_at IS NULL\n )\n WHERE c.id = $1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "role?",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Uuid"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "5a00a889e19a6d8d323bef2edf0764f7ad93f1478369b70ac9243ab211745d21"
-}
diff --git a/.sqlx/query-7d447304c6e7dd9e6cf653557861d5c48c44f087d3d027a1d565fd04182b0bf2.json b/.sqlx/query-7d447304c6e7dd9e6cf653557861d5c48c44f087d3d027a1d565fd04182b0bf2.json
new file mode 100644
index 0000000000..a327b8c98e
--- /dev/null
+++ b/.sqlx/query-7d447304c6e7dd9e6cf653557861d5c48c44f087d3d027a1d565fd04182b0bf2.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n 'view'::\"AccessLevel\" AS \"access_level!: AccessLevel\",\n team_id AS \"team_id!\",\n 'member'::team_role AS \"team_role!: TeamRole\"\n FROM crm_companies\n WHERE id = $1\n AND team_id = $2\n AND hidden = false\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 1,
+ "name": "team_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "team_role!: TeamRole",
+ "type_info": {
+ "Custom": {
+ "name": "team_role",
+ "kind": {
+ "Enum": [
+ "member",
+ "admin",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null,
+ false,
+ null
+ ]
+ },
+ "hash": "7d447304c6e7dd9e6cf653557861d5c48c44f087d3d027a1d565fd04182b0bf2"
+}
diff --git a/.sqlx/query-986d084746a6b0dfa60da4435e585871807a02b88ae4c81c58a871d0a4bdc20e.json b/.sqlx/query-986d084746a6b0dfa60da4435e585871807a02b88ae4c81c58a871d0a4bdc20e.json
new file mode 100644
index 0000000000..707e15997f
--- /dev/null
+++ b/.sqlx/query-986d084746a6b0dfa60da4435e585871807a02b88ae4c81c58a871d0a4bdc20e.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n 'view'::\"AccessLevel\" AS \"access_level!: AccessLevel\",\n c.team_id AS \"team_id!\",\n 'member'::team_role AS \"team_role!: TeamRole\"\n FROM crm_contacts ct\n JOIN crm_companies c\n ON c.id = ct.company_id\n WHERE ct.id = $1\n AND c.team_id = $2\n AND ct.hidden = false\n AND c.hidden = false\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 1,
+ "name": "team_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "team_role!: TeamRole",
+ "type_info": {
+ "Custom": {
+ "name": "team_role",
+ "kind": {
+ "Enum": [
+ "member",
+ "admin",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null,
+ false,
+ null
+ ]
+ },
+ "hash": "986d084746a6b0dfa60da4435e585871807a02b88ae4c81c58a871d0a4bdc20e"
+}
diff --git a/crates/bots/src/inbound/axum_router/tests.rs b/crates/bots/src/inbound/axum_router/tests.rs
index 168da5d789..466dcdde24 100644
--- a/crates/bots/src/inbound/axum_router/tests.rs
+++ b/crates/bots/src/inbound/axum_router/tests.rs
@@ -11,8 +11,8 @@ use axum::{
use entity_access::domain::models::TeamRole;
use entity_access::domain::{
models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, EntityPermission, EntityType,
- ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityPermission,
+ EntityType, ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,
},
ports::EntityAccessService,
};
@@ -226,6 +226,7 @@ impl EntityAccessService for TestAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rs
index 48f921a148..390d506351 100644
--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs
+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs
@@ -12,8 +12,8 @@ use channels::domain::models::PostMessageResponse;
use entity_access::domain::models::TeamRole;
use entity_access::domain::{
models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, EntityPermission, EntityType,
- ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityPermission,
+ EntityType, ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,
},
ports::EntityAccessService,
};
@@ -334,6 +334,7 @@ impl EntityAccessService for TestAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
diff --git a/crates/channels/src/inbound/axum_router/test.rs b/crates/channels/src/inbound/axum_router/test.rs
index 651d824fc5..d667d0d1b0 100644
--- a/crates/channels/src/inbound/axum_router/test.rs
+++ b/crates/channels/src/inbound/axum_router/test.rs
@@ -18,9 +18,9 @@ use axum::{
use entity_access::domain::models::TeamRole;
use entity_access::domain::{
models::{
- AccessError, AccessLevel, BotId, Entity, EntityAccessReceipt, EntityPermission, EntityType,
- MemberParticipantRole, ParticipantRole as EntityParticipantRole, RequiredPermission,
- UserTeamInfo,
+ AccessError, AccessLevel, BotAccessScope, BotId, BotReceiptScope, Entity,
+ EntityAccessReceipt, EntityPermission, EntityType, MemberParticipantRole,
+ ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,
},
ports::EntityAccessService,
};
@@ -137,6 +137,7 @@ impl EntityAccessService for TestAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
@@ -250,6 +251,9 @@ fn bot_actor_from_receipt_uses_canonical_principal() {
let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"));
let receipt = EntityAccessReceipt::<MemberParticipantRole>::try_new_bot(
bot_id.into_storage_id(),
+ BotReceiptScope::Team {
+ team_id: Uuid::new_v4(),
+ },
Entity {
entity_id: Uuid::new_v4().to_string(),
entity_type: EntityType::Channel,
diff --git a/crates/chat/src/inbound/test.rs b/crates/chat/src/inbound/test.rs
index f1db3a960c..4b30f7d1dd 100644
--- a/crates/chat/src/inbound/test.rs
+++ b/crates/chat/src/inbound/test.rs
@@ -25,8 +25,8 @@ use crate::inbound::http::router::{
};
use ai_toolset::tool_object::UserToolResponse;
use entity_access::domain::models::{
- AccessError, AccessLevel, BotId, EditAccessLevel, EntityAccessReceipt, EntityPermission,
- EntityType, OwnerAccessLevel, UserTeamInfo, ViewAccessLevel,
+ AccessError, AccessLevel, BotAccessScope, BotId, EditAccessLevel, EntityAccessReceipt,
+ EntityPermission, EntityType, OwnerAccessLevel, UserTeamInfo, ViewAccessLevel,
};
use entity_access::domain::ports::EntityAccessService;
use macro_user_id::lowercased::Lowercase;
@@ -395,6 +395,7 @@ impl EntityAccessService for MockAccessService {
>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> std::result::Result<entity_access::domain::models::EntityAccessReceipt<T>, AccessError>
diff --git a/crates/chat/src/inbound/toolset/test.rs b/crates/chat/src/inbound/toolset/test.rs
index 412e79b830..1bd5674076 100644
--- a/crates/chat/src/inbound/toolset/test.rs
+++ b/crates/chat/src/inbound/toolset/test.rs
@@ -27,8 +27,9 @@ mod self_read_guard {
use ai_toolset::tool_object::UserToolResponse;
use ai_toolset::{AsyncTool, RequestContext, ServiceContext};
use entity_access::domain::models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, Entity, EntityAccessReceipt,
- EntityPermission, EntityType, RequiredPermission, TeamRole, UserTeamInfo,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, Entity,
+ EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission, TeamRole,
+ UserTeamInfo,
};
use entity_access::domain::ports::EntityAccessService;
use macro_user_id::lowercased::Lowercase;
@@ -188,6 +189,7 @@ mod self_read_guard {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> std::result::Result<EntityAccessReceipt<T>, AccessError> {
@@ -460,6 +462,7 @@ mod self_read_guard {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
entity_id: &str,
entity_type: EntityType,
) -> std::result::Result<EntityAccessReceipt<T>, AccessError> {
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index 5e8e4acccd..351abe267e 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -8,8 +8,9 @@ use email::domain::models::{
UpsertEmailFilterInput,
};
use entity_access::domain::models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, EditAccessLevel, EntityAccessReceipt,
- EntityPermission, EntityType, RequiredPermission, TeamRole, UserTeamInfo, ViewAccessLevel,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EditAccessLevel,
+ EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission, TeamRole, UserTeamInfo,
+ ViewAccessLevel,
};
use graphql_common::GraphqlRequestParts;
use macro_authorization::{
@@ -339,6 +340,7 @@ impl EntityAccessService for CountingEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
diff --git a/crates/crm/src/domain/service.rs b/crates/crm/src/domain/service.rs
index f1f8181625..8eb18d218d 100644
--- a/crates/crm/src/domain/service.rs
+++ b/crates/crm/src/domain/service.rs
@@ -15,7 +15,9 @@ use crate::domain::{
},
};
use chrono::{DateTime, Utc};
-use entity_access::domain::models::{EditAccessLevel, MemberTeamRole, ViewAccessLevel};
+use entity_access::domain::models::{
+ AnyEntityPermission, EditAccessLevel, MemberTeamRole, ViewAccessLevel,
+};
use serde_json::Value;
/// The CrmService exposes operations over CRM records (companies, their
@@ -325,7 +327,7 @@ pub trait CrmService: Clone + Send + Sync + 'static {
#[allow(clippy::too_many_arguments)]
fn create_crm_comment(
&self,
- access: &CrmCommentReceipt<ViewAccessLevel>,
+ access: &CrmCommentReceipt<AnyEntityPermission>,
owner: &str,
thread_id: Option<uuid::Uuid>,
thread_metadata: Option<Value>,
@@ -339,7 +341,7 @@ pub trait CrmService: Clone + Send + Sync + 'static {
/// [`CompaniesRepository::get_crm_comment_threads`].
fn get_crm_comment_threads(
&self,
- access: &CrmCommentReceipt<ViewAccessLevel>,
+ access: &CrmCommentReceipt<AnyEntityPermission>,
) -> impl Future<Output = Result<Vec<CrmCommentThread>, CrmError>> + Send;
/// Edit the text of `comment_id`, scoped to the team in `access`
@@ -874,7 +876,7 @@ where
#[allow(clippy::too_many_arguments)]
async fn create_crm_comment(
&self,
- access: &CrmCommentReceipt<ViewAccessLevel>,
+ access: &CrmCommentReceipt<AnyEntityPermission>,
owner: &str,
thread_id: Option<uuid::Uuid>,
thread_metadata: Option<Value>,
@@ -902,7 +904,7 @@ where
#[tracing::instrument(skip(self, access), err)]
async fn get_crm_comment_threads(
&self,
- access: &CrmCommentReceipt<ViewAccessLevel>,
+ access: &CrmCommentReceipt<AnyEntityPermission>,
) -> Result<Vec<CrmCommentThread>, CrmError> {
let (entity_type, entity_id) = access.comment_entity()?;
let team_id = access.team_id();
@@ -1169,7 +1171,7 @@ impl CrmService for NoOpCrmService {
#[allow(clippy::too_many_arguments)]
async fn create_crm_comment(
&self,
- _access: &CrmCommentReceipt<ViewAccessLevel>,
+ _access: &CrmCommentReceipt<AnyEntityPermission>,
_owner: &str,
_thread_id: Option<uuid::Uuid>,
_thread_metadata: Option<Value>,
@@ -1181,7 +1183,7 @@ impl CrmService for NoOpCrmService {
async fn get_crm_comment_threads(
&self,
- _access: &CrmCommentReceipt<ViewAccessLevel>,
+ _access: &CrmCommentReceipt<AnyEntityPermission>,
) -> Result<Vec<CrmCommentThread>, CrmError> {
Ok(Vec::new())
}
diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rs
index 34a7b1f57c..b3d6386121 100644
--- a/crates/crm/src/inbound/axum_extractors/test.rs
+++ b/crates/crm/src/inbound/axum_extractors/test.rs
@@ -10,9 +10,9 @@ use axum::{
use chrono::{DateTime, Utc};
use entity_access::domain::{
models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, EditAccessLevel, EntityAccessReceipt,
- EntityPermission, EntityType, MemberTeamRole, RequiredPermission, UserTeamInfo,
- ViewAccessLevel,
+ AccessError, AccessLevel, AnyEntityPermission, BotAccessScope, BotId, CallChannelInfo,
+ EditAccessLevel, EntityAccessReceipt, EntityPermission, EntityType, MemberTeamRole,
+ RequiredPermission, UserTeamInfo, ViewAccessLevel,
},
ports::EntityAccessService,
};
@@ -129,6 +129,7 @@ impl EntityAccessService for FakeEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
@@ -396,7 +397,7 @@ impl CrmService for FakeCrmService {
async fn create_crm_comment(
&self,
- _access: &CrmCommentReceipt<ViewAccessLevel>,
+ _access: &CrmCommentReceipt<AnyEntityPermission>,
_owner: &str,
_thread_id: Option<Uuid>,
_thread_metadata: Option<Value>,
@@ -408,7 +409,7 @@ impl CrmService for FakeCrmService {
async fn get_crm_comment_threads(
&self,
- _access: &CrmCommentReceipt<ViewAccessLevel>,
+ _access: &CrmCommentReceipt<AnyEntityPermission>,
) -> Result<Vec<CrmCommentThread>, CrmError> {
panic!("unexpected get_crm_comment_threads call")
}
diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rs
index 35c82e391d..2b4f3a3cba 100644
--- a/crates/documents/src/domain/service/tests.rs
+++ b/crates/documents/src/domain/service/tests.rs
@@ -98,9 +98,16 @@ fn bot_id() -> entity_access::domain::models::BotId {
))
}
+fn bot_receipt_scope() -> entity_access::domain::models::BotReceiptScope {
+ entity_access::domain::models::BotReceiptScope::Team {
+ team_id: uuid::uuid!("00000000-0000-0000-0000-000000000456"),
+ }
+}
+
fn bot_receipt(document_id: &str) -> EntityAccessReceipt<ViewAccessLevel> {
EntityAccessReceipt::dangerously_assert_bot(
bot_id().into_storage_id(),
+ bot_receipt_scope(),
document_id,
EntityType::Document,
)
@@ -858,6 +865,7 @@ async fn bot_lifecycle_event_has_no_actor_user_id() {
let (service, event_broker) = make_test_service_with_event_broker(repo);
let receipt = EntityAccessReceipt::<OwnerAccessLevel>::dangerously_assert_bot(
bot_id().into_storage_id(),
+ bot_receipt_scope(),
"doc-1",
EntityType::Document,
);
diff --git a/crates/documents/src/inbound/axum_router/tests.rs b/crates/documents/src/inbound/axum_router/tests.rs
index 15aa5181d3..30fc933cf2 100644
--- a/crates/documents/src/inbound/axum_router/tests.rs
+++ b/crates/documents/src/inbound/axum_router/tests.rs
@@ -9,8 +9,8 @@ use axum::{
use embedding::embedding_provider::openai::TextEmbedding3Small;
use entity_access::domain::{
models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, EntityAccessReceipt, EntityPermission,
- EntityType, MemberTeamRole, RequiredPermission, TeamRole, UserTeamInfo,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityAccessReceipt,
+ EntityPermission, EntityType, MemberTeamRole, RequiredPermission, TeamRole, UserTeamInfo,
},
ports::EntityAccessService,
};
@@ -576,6 +576,7 @@ impl EntityAccessService for FakeEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
diff --git a/crates/entity_access/src/domain/models.rs b/crates/entity_access/src/domain/models.rs
index 68a6b3e488..a109ead31c 100644
--- a/crates/entity_access/src/domain/models.rs
+++ b/crates/entity_access/src/domain/models.rs
@@ -16,6 +16,97 @@ pub use models_permissions::share_permission::access_level::{
CommentAccessLevel, EditAccessLevel, OwnerAccessLevel, ViewAccessLevel,
};
+/// The access scope under which a bot-authorized request is resolved.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum BotAccessScope {
+ /// Resolve access as the verified acting user.
+ User {
+ /// The verified acting user's identifier.
+ user_id: MacroUserIdStr<'static>,
+ /// The verified acting user's organization identifier, when present.
+ user_org_id: Option<i64>,
+ },
+ /// Resolve access from a team's shared access pool.
+ Team {
+ /// The owning team's identifier.
+ team_id: Uuid,
+ },
+}
+
+impl BotAccessScope {
+ /// Returns the verified acting user's identifier for user scope.
+ pub fn user_id(&self) -> Option<&MacroUserIdStr<'static>> {
+ match self {
+ Self::User { user_id, .. } => Some(user_id),
+ Self::Team { .. } => None,
+ }
+ }
+
+ /// Returns the verified acting user's organization identifier for user scope.
+ pub fn user_org_id(&self) -> Option<i64> {
+ match self {
+ Self::User { user_org_id, .. } => *user_org_id,
+ Self::Team { .. } => None,
+ }
+ }
+
+ /// Returns the owning team's identifier for team scope.
+ pub fn team_id(&self) -> Option<Uuid> {
+ match self {
+ Self::Team { team_id } => Some(*team_id),
+ Self::User { .. } => None,
+ }
+ }
+}
+
+/// The bot scope context retained in an entity-access receipt.
+///
+/// User organization identifiers are intentionally omitted because they are
+/// request-time authorization context rather than receipt identity.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[serde(tag = "scope", rename_all = "snake_case")]
+pub enum BotReceiptScope {
+ /// Access was resolved as a verified acting user.
+ User {
+ /// The verified acting user's identifier.
+ acting_user: MacroUserIdStr<'static>,
+ },
+ /// Access was resolved from a team's shared access pool.
+ Team {
+ /// The owning team's identifier.
+ team_id: Uuid,
+ },
+}
+
+impl BotReceiptScope {
+ /// Returns the verified acting user's identifier for user scope.
+ pub fn acting_user_id(&self) -> Option<&MacroUserIdStr<'static>> {
+ match self {
+ Self::User { acting_user } => Some(acting_user),
+ Self::Team { .. } => None,
+ }
+ }
+
+ /// Returns the owning team's identifier for team scope.
+ pub fn team_id(&self) -> Option<Uuid> {
+ match self {
+ Self::Team { team_id } => Some(*team_id),
+ Self::User { .. } => None,
+ }
+ }
+}
+
+impl From<&BotAccessScope> for BotReceiptScope {
+ fn from(scope: &BotAccessScope) -> Self {
+ match scope {
+ BotAccessScope::User { user_id, .. } => Self::User {
+ acting_user: user_id.clone(),
+ },
+ BotAccessScope::Team { team_id } => Self::Team { team_id: *team_id },
+ }
+ }
+}
+
/// A user's resolved access to a CRM entity (company or contact) paired with
/// the entity's owning team — both produced by the same ownership lookup, so
/// the team is guaranteed to be the one that granted access (not the user's
@@ -94,6 +185,10 @@ pub struct MemberParticipantRole;
#[derive(Debug, Clone, Copy)]
pub struct ViewOnly;
+/// Permission marker that accepts every valid entity permission.
+#[derive(Debug, Clone, Copy)]
+pub struct AnyEntityPermission;
+
/// Trait implemented by marker types that encode a permission requirement.
pub trait RequiredPermission: std::fmt::Debug + Send + Sync + 'static {
/// Returns whether the provided permission satisfies this requirement.
@@ -173,6 +268,12 @@ impl EntityPermission {
}
}
+impl RequiredPermission for AnyEntityPermission {
+ fn is_satisfied_by(_permission: &EntityPermission) -> bool {
+ true
+ }
+}
+
impl RequiredPermission for ViewAccessLevel {
fn is_satisfied_by(permission: &EntityPermission) -> bool {
permission.allows_access_level(AccessLevel::View)
@@ -276,14 +377,50 @@ pub struct Entity {
pub entity_type: EntityType,
}
+/// Authentication context retained for a bot entity-access receipt.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct BotReceiptAuth {
+ bot_id: BotIdStr<'static>,
+ #[serde(flatten)]
+ scope: BotReceiptScope,
+}
+
+impl BotReceiptAuth {
+ /// Creates receipt authentication context for a bot and its access scope.
+ pub fn new(bot_id: BotIdStr<'static>, scope: BotReceiptScope) -> Self {
+ Self { bot_id, scope }
+ }
+
+ /// Returns the bot's canonical identifier.
+ pub fn bot_id(&self) -> BotId {
+ self.bot_id.bot_id()
+ }
+
+ /// Returns the bot's canonical storage principal.
+ pub fn bot_id_str(&self) -> &BotIdStr<'static> {
+ &self.bot_id
+ }
+
+ /// Returns the scope retained in the receipt.
+ pub fn scope(&self) -> &BotReceiptScope {
+ &self.scope
+ }
+}
+
+impl std::fmt::Display for BotReceiptAuth {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(formatter, "{}", self.bot_id)
+ }
+}
+
/// The entity access auth type
-#[derive(Debug, Clone, serde::Serialize)]
+#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum EntityAccessAuth {
/// The user is authenticated
Authenticated(MacroUserIdStr<'static>),
- /// A bot is authenticated.
- Bot(BotIdStr<'static>),
+ /// A bot is authenticated under a specific access scope.
+ Bot(BotReceiptAuth),
/// The user is unauthenticated
Unauthenticated,
/// Internally authenticated
@@ -353,10 +490,15 @@ impl<T: RequiredPermission> EntityAccessReceipt<T> {
/// Creates an access receipt for an authenticated bot after validating the provided permission.
pub fn try_new_bot(
bot_id: BotIdStr<'static>,
+ scope: BotReceiptScope,
entity: Entity,
entity_permission: EntityPermission,
) -> Result<EntityAccessReceipt<T>, AccessError> {
- Self::try_new(EntityAccessAuth::Bot(bot_id), entity, entity_permission)
+ Self::try_new(
+ EntityAccessAuth::Bot(BotReceiptAuth::new(bot_id, scope)),
+ entity,
+ entity_permission,
+ )
}
/// Get the authenticated user or return an authorization error.
@@ -369,16 +511,30 @@ impl<T: RequiredPermission> EntityAccessReceipt<T> {
}
}
- /// Get the authenticated bot or return an authorization error.
+ /// Get the authenticated bot's canonical storage principal or return an authorization error.
pub fn get_authenticated_bot(&self) -> Result<&BotIdStr<'static>, AccessError> {
+ Ok(self.get_authenticated_bot_auth()?.bot_id_str())
+ }
+
+ /// Get the authenticated bot and receipt scope or return an authorization error.
+ pub fn get_authenticated_bot_auth(&self) -> Result<&BotReceiptAuth, AccessError> {
match &self.auth {
- EntityAccessAuth::Bot(bot_id) => Ok(bot_id),
+ EntityAccessAuth::Bot(bot_auth) => Ok(bot_auth),
EntityAccessAuth::Authenticated(_)
| EntityAccessAuth::Unauthenticated
| EntityAccessAuth::Internal => Err(AccessError::Unauthorized),
}
}
+ /// Returns the direct user or verified acting user represented by this receipt.
+ pub fn acting_user_id(&self) -> Option<&MacroUserIdStr<'static>> {
+ match &self.auth {
+ EntityAccessAuth::Authenticated(user_id) => Some(user_id),
+ EntityAccessAuth::Bot(bot_auth) => bot_auth.scope().acting_user_id(),
+ EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => None,
+ }
+ }
+
/// Getter for auth
pub fn auth(&self) -> &EntityAccessAuth {
&self.auth
@@ -447,11 +603,12 @@ impl<T: RequiredPermission> EntityAccessReceipt<T> {
/// permission.
pub fn dangerously_assert_bot(
bot_id: BotIdStr<'static>,
+ scope: BotReceiptScope,
entity_id: &str,
entity_type: EntityType,
) -> EntityAccessReceipt<T> {
EntityAccessReceipt {
- auth: EntityAccessAuth::Bot(bot_id),
+ auth: EntityAccessAuth::Bot(BotReceiptAuth::new(bot_id, scope)),
entity: Entity {
entity_id: entity_id.to_string(),
entity_type,
diff --git a/crates/entity_access/src/domain/models/test.rs b/crates/entity_access/src/domain/models/test.rs
index 7a4a5f02f9..3394ec7fdc 100644
--- a/crates/entity_access/src/domain/models/test.rs
+++ b/crates/entity_access/src/domain/models/test.rs
@@ -4,6 +4,10 @@ fn bot_id() -> BotId {
BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"))
}
+fn user_id() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
fn document() -> Entity {
Entity {
entity_id: "document-1".to_string(),
@@ -11,14 +15,133 @@ fn document() -> Entity {
}
}
+fn user_receipt_scope() -> BotReceiptScope {
+ BotReceiptScope::User {
+ acting_user: user_id(),
+ }
+}
+
+fn team_receipt_scope() -> BotReceiptScope {
+ BotReceiptScope::Team {
+ team_id: uuid::uuid!("00000000-0000-0000-0000-000000000456"),
+ }
+}
+
+#[test]
+fn user_access_scope_preserves_organization_and_converts_to_receipt_scope() {
+ let user_id = user_id();
+ let access_scope = BotAccessScope::User {
+ user_id: user_id.clone(),
+ user_org_id: Some(42),
+ };
+
+ assert_eq!(access_scope.user_id(), Some(&user_id));
+ assert_eq!(access_scope.user_org_id(), Some(42));
+ assert_eq!(access_scope.team_id(), None);
+
+ let receipt_scope = BotReceiptScope::from(&access_scope);
+
+ assert_eq!(receipt_scope.acting_user_id(), Some(&user_id));
+ assert_eq!(receipt_scope.team_id(), None);
+ assert_eq!(
+ serde_json::to_value(receipt_scope).unwrap(),
+ serde_json::json!({
+ "scope": "user",
+ "acting_user": "macro|[email protected]"
+ })
+ );
+}
+
+#[test]
+fn team_access_scope_converts_to_serializable_receipt_scope() {
+ let team_id = uuid::uuid!("00000000-0000-0000-0000-000000000456");
+ let access_scope = BotAccessScope::Team { team_id };
+
+ assert_eq!(access_scope.user_id(), None);
+ assert_eq!(access_scope.user_org_id(), None);
+ assert_eq!(access_scope.team_id(), Some(team_id));
+
+ let receipt_scope = BotReceiptScope::from(&access_scope);
+
+ assert_eq!(receipt_scope.acting_user_id(), None);
+ assert_eq!(receipt_scope.team_id(), Some(team_id));
+ assert_eq!(
+ serde_json::to_value(receipt_scope).unwrap(),
+ serde_json::json!({
+ "scope": "team",
+ "team_id": "00000000-0000-0000-0000-000000000456"
+ })
+ );
+}
+
+#[test]
+fn any_entity_permission_accepts_every_permission() {
+ let permissions = [
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Comment,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ EntityPermission::ChannelViewOnly,
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ },
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Admin,
+ },
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Owner,
+ },
+ EntityPermission::TeamRole {
+ role: TeamRole::Member,
+ },
+ EntityPermission::TeamRole {
+ role: TeamRole::Admin,
+ },
+ EntityPermission::TeamRole {
+ role: TeamRole::Owner,
+ },
+ ];
+
+ for permission in permissions {
+ assert!(permission.satisfies::<AnyEntityPermission>());
+ }
+}
+
#[test]
-fn bot_auth_serializes_as_canonical_storage_principal() {
- let serialized =
- serde_json::to_value(EntityAccessAuth::Bot(bot_id().into_storage_id())).unwrap();
+fn user_scoped_bot_auth_serializes_bot_scope_and_acting_user() {
+ let bot_auth = BotReceiptAuth::new(bot_id().into_storage_id(), user_receipt_scope());
+ let serialized = serde_json::to_value(EntityAccessAuth::Bot(bot_auth)).unwrap();
assert_eq!(
serialized,
- serde_json::json!("bot|00000000-0000-0000-0000-000000000123")
+ serde_json::json!({
+ "bot_id": "bot|00000000-0000-0000-0000-000000000123",
+ "scope": "user",
+ "acting_user": "macro|[email protected]"
+ })
+ );
+}
+
+#[test]
+fn team_scoped_bot_auth_serializes_bot_scope_and_team() {
+ let bot_auth = BotReceiptAuth::new(bot_id().into_storage_id(), team_receipt_scope());
+ let serialized = serde_json::to_value(EntityAccessAuth::Bot(bot_auth)).unwrap();
+
+ assert_eq!(
+ serialized,
+ serde_json::json!({
+ "bot_id": "bot|00000000-0000-0000-0000-000000000123",
+ "scope": "team",
+ "team_id": "00000000-0000-0000-0000-000000000456"
+ })
);
}
@@ -26,6 +149,7 @@ fn bot_auth_serializes_as_canonical_storage_principal() {
fn try_new_bot_enforces_required_permission() {
let result = EntityAccessReceipt::<EditAccessLevel>::try_new_bot(
bot_id().into_storage_id(),
+ user_receipt_scope(),
document(),
EntityPermission::AccessLevel {
access_level: AccessLevel::View,
@@ -39,6 +163,7 @@ fn try_new_bot_enforces_required_permission() {
fn bot_receipt_returns_bot_and_rejects_authenticated_user() {
let receipt = EntityAccessReceipt::<ViewAccessLevel>::try_new_bot(
bot_id().into_storage_id(),
+ user_receipt_scope(),
document(),
EntityPermission::AccessLevel {
access_level: AccessLevel::View,
@@ -50,16 +175,41 @@ fn bot_receipt_returns_bot_and_rejects_authenticated_user() {
receipt.get_authenticated_bot().unwrap(),
&bot_id().into_storage_id()
);
+ let bot_auth = receipt.get_authenticated_bot_auth().unwrap();
+ assert_eq!(bot_auth.bot_id(), bot_id());
+ assert_eq!(bot_auth.to_string(), bot_id().into_storage_id().to_string());
+ assert_eq!(bot_auth.scope(), &user_receipt_scope());
+ assert_eq!(receipt.acting_user_id(), Some(&user_id()));
assert!(matches!(
receipt.get_authenticated_user(),
Err(AccessError::Unauthorized)
));
}
+#[test]
+fn acting_user_id_returns_direct_authenticated_user() {
+ let user_id = user_id();
+ let receipt = EntityAccessReceipt::<ViewAccessLevel>::try_new_authenticated_user(
+ user_id.clone(),
+ document(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ },
+ )
+ .unwrap();
+
+ assert_eq!(receipt.acting_user_id(), Some(&user_id));
+ assert!(matches!(
+ receipt.get_authenticated_bot_auth(),
+ Err(AccessError::Unauthorized)
+ ));
+}
+
#[test]
fn dangerously_assert_bot_creates_owner_level_test_receipt() {
let receipt = EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_bot(
bot_id().into_storage_id(),
+ team_receipt_scope(),
"document-1",
EntityType::Document,
);
@@ -68,6 +218,11 @@ fn dangerously_assert_bot_creates_owner_level_test_receipt() {
receipt.get_authenticated_bot().unwrap(),
&bot_id().into_storage_id()
);
+ assert_eq!(receipt.acting_user_id(), None);
+ assert_eq!(
+ receipt.get_authenticated_bot_auth().unwrap().scope(),
+ &team_receipt_scope()
+ );
assert!(matches!(
receipt.entity_permission(),
EntityPermission::AccessLevel {
diff --git a/crates/entity_access/src/domain/ports.rs b/crates/entity_access/src/domain/ports.rs
index 5fb6448d7d..b14a8e495b 100644
--- a/crates/entity_access/src/domain/ports.rs
+++ b/crates/entity_access/src/domain/ports.rs
@@ -4,9 +4,9 @@
use super::models::EntityType;
use crate::domain::models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, ChannelRoleResult, CrmEntityAccess,
- EntityAccessReceipt, EntityPermission, RequiredPermission, TeamRole, UserTeamInfo,
- ViewAccessLevel,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, ChannelRoleResult,
+ CrmEntityAccess, EntityAccessReceipt, EntityPermission, RequiredPermission, TeamRole,
+ UserTeamInfo, ViewAccessLevel,
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};
use std::{collections::HashMap, future::Future};
@@ -59,29 +59,58 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
- /// Get the highest access level a bot has for an entity resolved through
- /// `entity_access` source IDs (document, chat, project, email thread, or call).
+ /// Get the highest access level available to a bot in its owning team's
+ /// scope for a document, chat, project, email thread, or call.
///
- /// A bot's sources are the channels it actively participates in (using its
- /// canonical `bot|<uuid>` principal), its owning team when team-scoped, and
- /// the bot principal itself.
- fn get_bot_entity_access(
+ /// Team scope includes the team, its team channels, the bot principal, and
+ /// channels in which the bot is an active participant. Email-thread
+ /// ownership and inbox delegation are intentionally excluded.
+ fn get_team_entity_access(
&self,
bot_id: BotId,
+ team_id: Uuid,
entity_id: &str,
entity_type: EntityType,
) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
- /// Get the role a bot explicitly holds in a channel.
+ /// Get a bot's channel permission while operating in its owning team's scope.
///
- /// Public and organization channels do not implicitly admit bots; an active
- /// participant row for the bot's canonical principal is required.
- fn get_bot_channel_role(
+ /// Active bot participation grants the stored role in any channel. Without
+ /// participation, only a channel owned by the scoped team grants view-only
+ /// access.
+ fn get_team_channel_role(
&self,
channel_id: &Uuid,
+ team_id: Uuid,
bot_id: BotId,
) -> impl Future<Output = Result<ChannelRoleResult, AccessError>> + Send;
+ /// Check whether a scoped team or bot-principal source pair grants access
+ /// to a foreign entity.
+ fn has_team_foreign_entity_access(
+ &self,
+ foreign_entity_id: &str,
+ team_id: Uuid,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<bool, AccessError>> + Send;
+
+ /// Get member-equivalent access to a visible CRM company owned by the
+ /// scoped team.
+ fn get_team_crm_company_access(
+ &self,
+ company_id: &str,
+ team_id: Uuid,
+ ) -> impl Future<Output = Result<Option<CrmEntityAccess>, AccessError>> + Send;
+
+ /// Get member-equivalent access to a visible CRM contact owned by the
+ /// scoped team. Hidden contacts and contacts of hidden companies are
+ /// excluded.
+ fn get_team_crm_contact_access(
+ &self,
+ contact_id: &str,
+ team_id: Uuid,
+ ) -> impl Future<Output = Result<Option<CrmEntityAccess>, AccessError>> + Send;
+
/// Check whether a user has access to a foreign entity.
///
/// Foreign entity access is boolean because it only maps to [`AccessLevel::View`]
@@ -235,16 +264,17 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {
/// Generates an [`EntityAccessReceipt<T>`] for an authenticated bot.
///
- /// Document, chat, project, email-thread, and call permissions are resolved
- /// from the bot's entity-access sources. Channel permissions require an
- /// explicit active participant role; public and organization channels do
- /// not implicitly admit bots. All other entity types are unsupported.
+ /// User scope delegates to the acting user's permission path. Team scope
+ /// resolves item, channel, foreign-entity, CRM, and owning-team permissions
+ /// from the scoped team's shared pool plus explicit bot grants. Unsupported
+ /// entity types return [`AccessError::BadRequest`].
///
/// The type parameter `T` specifies the minimum permission required.
/// Returns an error if the bot does not satisfy that requirement.
fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
bot_id: BotId,
+ scope: BotAccessScope,
entity_id: &str,
entity_type: EntityType,
) -> impl Future<Output = Result<EntityAccessReceipt<T>, AccessError>> + Send;
@@ -374,6 +404,7 @@ impl EntityAccessService for NoOpEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
diff --git a/crates/entity_access/src/domain/service.rs b/crates/entity_access/src/domain/service.rs
index 80ddcfc8c7..5873549bde 100644
--- a/crates/entity_access/src/domain/service.rs
+++ b/crates/entity_access/src/domain/service.rs
@@ -4,9 +4,9 @@ use std::{collections::HashMap, marker::PhantomData, str::FromStr};
use crate::domain::{
models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, ChannelRoleResult, CrmEntityAccess,
- Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
- RequiredPermission, TeamRole, UserTeamInfo, ViewAccessLevel,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, ChannelRoleResult,
+ CrmEntityAccess, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission,
+ EntityType, RequiredPermission, TeamRole, UserTeamInfo, ViewAccessLevel,
},
ports::{AccessRepository, EntityAccessService},
};
@@ -132,6 +132,109 @@ where
.ok_or(AccessError::NotFound("Call not found"))?;
Ok(info.channel_id)
}
+
+ async fn get_user_scope_permission(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ user_org_id: Option<i64>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<EntityPermission, AccessError> {
+ if entity_type != EntityType::Team {
+ return self
+ .get_entity_permission(Some(user_id), entity_id, entity_type, user_org_id)
+ .await;
+ }
+
+ let requested_team_id = Uuid::parse_str(entity_id)
+ .map_err(|_| AccessError::BadRequest("Invalid team ID format"))?;
+ let user_team = self
+ .repo
+ .get_user_team(user_id)
+ .await?
+ .filter(|team| team.team_id == requested_team_id)
+ .ok_or(AccessError::Unauthorized)?;
+
+ Ok(EntityPermission::TeamRole {
+ role: user_team.role,
+ })
+ }
+
+ async fn get_team_scope_permission(
+ &self,
+ bot_id: BotId,
+ team_id: Uuid,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<EntityPermission, AccessError> {
+ match entity_type {
+ EntityType::Document
+ | EntityType::Chat
+ | EntityType::Project
+ | EntityType::EmailThread
+ | EntityType::Call => {
+ let access_level = self
+ .repo
+ .get_team_entity_access(bot_id, team_id, entity_id, entity_type)
+ .await?
+ .ok_or(AccessError::Unauthorized)?;
+ Ok(EntityPermission::AccessLevel { access_level })
+ }
+ EntityType::Channel => {
+ let channel_id = Uuid::parse_str(entity_id)
+ .map_err(|_| AccessError::BadRequest("Invalid channel ID format"))?;
+ let role = self
+ .repo
+ .get_team_channel_role(&channel_id, team_id, bot_id)
+ .await?;
+ channel_role_result_to_permission(role)
+ }
+ EntityType::ForeignEntity => {
+ let has_access = self
+ .repo
+ .has_team_foreign_entity_access(entity_id, team_id, bot_id)
+ .await?;
+ if has_access {
+ Ok(EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ })
+ } else {
+ Err(AccessError::Unauthorized)
+ }
+ }
+ EntityType::CrmCompany => {
+ self.repo
+ .get_team_crm_company_access(entity_id, team_id)
+ .await?
+ .ok_or(AccessError::Unauthorized)?;
+ Ok(EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ })
+ }
+ EntityType::CrmContact => {
+ self.repo
+ .get_team_crm_contact_access(entity_id, team_id)
+ .await?
+ .ok_or(AccessError::Unauthorized)?;
+ Ok(EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ })
+ }
+ EntityType::Team => {
+ let requested_team_id = Uuid::parse_str(entity_id)
+ .map_err(|_| AccessError::BadRequest("Invalid team ID format"))?;
+ if requested_team_id != team_id {
+ return Err(AccessError::Unauthorized);
+ }
+ Ok(EntityPermission::TeamRole {
+ role: TeamRole::Member,
+ })
+ }
+ EntityType::User | EntityType::ChannelMessage | EntityType::StaticFile => {
+ Err(AccessError::BadRequest("Unsupported bot entity type"))
+ }
+ }
+ }
}
impl<R> EntityAccessService for EntityAccessServiceImpl<R>
@@ -250,33 +353,27 @@ where
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
bot_id: BotId,
+ scope: BotAccessScope,
entity_id: &str,
entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
- let entity_permission = match entity_type {
- EntityType::Document
- | EntityType::Chat
- | EntityType::Project
- | EntityType::EmailThread
- | EntityType::Call => {
- let access_level = self
- .repo
- .get_bot_entity_access(bot_id, entity_id, entity_type)
+ let entity_permission = match &scope {
+ BotAccessScope::User {
+ user_id,
+ user_org_id,
+ } => {
+ self.get_user_scope_permission(user_id, *user_org_id, entity_id, entity_type)
.await?
- .ok_or(AccessError::Unauthorized)?;
- EntityPermission::AccessLevel { access_level }
}
- EntityType::Channel => {
- let channel_id = Uuid::from_str(entity_id)
- .map_err(|_| AccessError::BadRequest("Invalid channel ID format"))?;
- let result = self.repo.get_bot_channel_role(&channel_id, bot_id).await?;
- channel_role_result_to_permission(result)?
+ BotAccessScope::Team { team_id } => {
+ self.get_team_scope_permission(bot_id, *team_id, entity_id, entity_type)
+ .await?
}
- _ => return Err(AccessError::BadRequest("Unsupported bot entity type")),
};
EntityAccessReceipt::try_new_bot(
bot_id.into_storage_id(),
+ (&scope).into(),
Entity {
entity_id: entity_id.to_string(),
entity_type,
diff --git a/crates/entity_access/src/domain/service/test.rs b/crates/entity_access/src/domain/service/test.rs
index 6154ab20ca..864f13ffe5 100644
--- a/crates/entity_access/src/domain/service/test.rs
+++ b/crates/entity_access/src/domain/service/test.rs
@@ -3,8 +3,9 @@
#[allow(unused_imports)]
use super::*;
use crate::domain::models::{
- AdminParticipantRole, BotId, CallChannelInfo, CommentAccessLevel, EditAccessLevel,
- EntityAccessAuth, MemberParticipantRole, OwnerParticipantRole, ParticipantRole, UserTeamInfo,
+ AdminParticipantRole, AdminTeamRole, AnyEntityPermission, BotAccessScope, BotId,
+ BotReceiptScope, CallChannelInfo, CommentAccessLevel, EditAccessLevel, EntityAccessAuth,
+ MemberParticipantRole, MemberTeamRole, OwnerParticipantRole, ParticipantRole, UserTeamInfo,
ViewAccessLevel, ViewOnly,
};
use macro_user_id::user_id::MacroUserIdStr;
@@ -25,15 +26,19 @@ struct MockRepo {
thread_access_calls: Arc<AtomicUsize>,
owned_email_thread_ids: Arc<Mutex<Vec<Uuid>>>,
call_access: Arc<Mutex<Option<AccessLevel>>>,
- bot_entity_access: Arc<Mutex<Option<AccessLevel>>>,
- bot_entity_access_calls: Arc<AtomicUsize>,
- bot_channel_role: Arc<Mutex<ChannelRoleResult>>,
- bot_channel_role_calls: Arc<AtomicUsize>,
+ team_entity_access: Arc<Mutex<Option<AccessLevel>>>,
+ team_entity_access_calls: Arc<AtomicUsize>,
+ team_channel_role: Arc<Mutex<ChannelRoleResult>>,
+ team_channel_role_calls: Arc<AtomicUsize>,
foreign_entity_access: Arc<Mutex<bool>>,
+ team_foreign_entity_access: Arc<Mutex<bool>>,
crm_company_access: Arc<Mutex<Option<AccessLevel>>>,
crm_contact_access: Arc<Mutex<Option<AccessLevel>>>,
+ team_crm_company_access: Arc<Mutex<Option<CrmEntityAccess>>>,
+ team_crm_contact_access: Arc<Mutex<Option<CrmEntityAccess>>>,
channel_membership: Arc<Mutex<Vec<Uuid>>>,
channel_role: Arc<Mutex<ChannelRoleResult>>,
+ last_channel_role_request: Arc<Mutex<Option<(String, Option<i64>)>>>,
document_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
chat_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
project_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
@@ -53,15 +58,19 @@ impl MockRepo {
thread_access_calls: Arc::new(AtomicUsize::new(0)),
owned_email_thread_ids: Arc::new(Mutex::new(Vec::new())),
call_access: Arc::new(Mutex::new(None)),
- bot_entity_access: Arc::new(Mutex::new(None)),
- bot_entity_access_calls: Arc::new(AtomicUsize::new(0)),
- bot_channel_role: Arc::new(Mutex::new(ChannelRoleResult::NotFound)),
- bot_channel_role_calls: Arc::new(AtomicUsize::new(0)),
+ team_entity_access: Arc::new(Mutex::new(None)),
+ team_entity_access_calls: Arc::new(AtomicUsize::new(0)),
+ team_channel_role: Arc::new(Mutex::new(ChannelRoleResult::NotFound)),
+ team_channel_role_calls: Arc::new(AtomicUsize::new(0)),
foreign_entity_access: Arc::new(Mutex::new(false)),
+ team_foreign_entity_access: Arc::new(Mutex::new(false)),
crm_company_access: Arc::new(Mutex::new(None)),
crm_contact_access: Arc::new(Mutex::new(None)),
+ team_crm_company_access: Arc::new(Mutex::new(None)),
+ team_crm_contact_access: Arc::new(Mutex::new(None)),
channel_membership: Arc::new(Mutex::new(vec![])),
channel_role: Arc::new(Mutex::new(ChannelRoleResult::NotFound)),
+ last_channel_role_request: Arc::new(Mutex::new(None)),
document_users: Arc::new(Mutex::new(vec![])),
chat_users: Arc::new(Mutex::new(vec![])),
project_users: Arc::new(Mutex::new(vec![])),
@@ -103,19 +112,19 @@ impl MockRepo {
self
}
- fn with_bot_entity_access(mut self, level: AccessLevel) -> Self {
- self.bot_entity_access = Arc::new(Mutex::new(Some(level)));
+ fn with_team_entity_access(mut self, level: AccessLevel) -> Self {
+ self.team_entity_access = Arc::new(Mutex::new(Some(level)));
self
}
- fn with_bot_channel_role(mut self, result: ChannelRoleResult) -> Self {
- self.bot_channel_role = Arc::new(Mutex::new(result));
+ fn with_team_channel_role(mut self, result: ChannelRoleResult) -> Self {
+ self.team_channel_role = Arc::new(Mutex::new(result));
self
}
- fn bot_repository_calls(&self) -> usize {
- self.bot_entity_access_calls.load(Ordering::SeqCst)
- + self.bot_channel_role_calls.load(Ordering::SeqCst)
+ fn team_repository_calls(&self) -> usize {
+ self.team_entity_access_calls.load(Ordering::SeqCst)
+ + self.team_channel_role_calls.load(Ordering::SeqCst)
}
fn with_foreign_entity_access(mut self, has_access: bool) -> Self {
@@ -123,6 +132,11 @@ impl MockRepo {
self
}
+ fn with_team_foreign_entity_access(mut self, has_access: bool) -> Self {
+ self.team_foreign_entity_access = Arc::new(Mutex::new(has_access));
+ self
+ }
+
#[allow(dead_code)]
fn with_crm_company_access(mut self, level: AccessLevel) -> Self {
self.crm_company_access = Arc::new(Mutex::new(Some(level)));
@@ -135,6 +149,16 @@ impl MockRepo {
self
}
+ fn with_team_crm_company_access(mut self, access: CrmEntityAccess) -> Self {
+ self.team_crm_company_access = Arc::new(Mutex::new(Some(access)));
+ self
+ }
+
+ fn with_team_crm_contact_access(mut self, access: CrmEntityAccess) -> Self {
+ self.team_crm_contact_access = Arc::new(Mutex::new(Some(access)));
+ self
+ }
+
fn with_channel_membership(mut self, channels: Vec<Uuid>) -> Self {
self.channel_membership = Arc::new(Mutex::new(channels));
self
@@ -164,6 +188,11 @@ impl MockRepo {
self.thread_users = Arc::new(Mutex::new(users));
self
}
+
+ fn with_user_team(mut self, user_team: UserTeamInfo) -> Self {
+ self.user_team = Arc::new(Mutex::new(Some(user_team)));
+ self
+ }
}
impl AccessRepository for MockRepo {
@@ -224,9 +253,13 @@ impl AccessRepository for MockRepo {
async fn get_channel_role(
&self,
_channel_id: &Uuid,
- _user_id: Option<&MacroUserId<Lowercase<'_>>>,
- _user_org_id: Option<i64>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ user_org_id: Option<i64>,
) -> Result<ChannelRoleResult, AccessError> {
+ *self.last_channel_role_request.lock().await = Some((
+ user_id.map(AsRef::as_ref).unwrap_or_default().to_string(),
+ user_org_id,
+ ));
Ok(*self.channel_role.lock().await)
}
@@ -238,23 +271,50 @@ impl AccessRepository for MockRepo {
Ok(*self.call_access.lock().await)
}
- async fn get_bot_entity_access(
+ async fn get_team_entity_access(
&self,
_bot_id: BotId,
+ _team_id: Uuid,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<Option<AccessLevel>, AccessError> {
- self.bot_entity_access_calls.fetch_add(1, Ordering::SeqCst);
- Ok(*self.bot_entity_access.lock().await)
+ self.team_entity_access_calls.fetch_add(1, Ordering::SeqCst);
+ Ok(*self.team_entity_access.lock().await)
}
- async fn get_bot_channel_role(
+ async fn get_team_channel_role(
&self,
_channel_id: &Uuid,
+ _team_id: Uuid,
_bot_id: BotId,
) -> Result<ChannelRoleResult, AccessError> {
- self.bot_channel_role_calls.fetch_add(1, Ordering::SeqCst);
- Ok(*self.bot_channel_role.lock().await)
+ self.team_channel_role_calls.fetch_add(1, Ordering::SeqCst);
+ Ok(*self.team_channel_role.lock().await)
+ }
+
+ async fn has_team_foreign_entity_access(
+ &self,
+ _foreign_entity_id: &str,
+ _team_id: Uuid,
+ _bot_id: BotId,
+ ) -> Result<bool, AccessError> {
+ Ok(*self.team_foreign_entity_access.lock().await)
+ }
+
+ async fn get_team_crm_company_access(
+ &self,
+ _company_id: &str,
+ _team_id: Uuid,
+ ) -> Result<Option<CrmEntityAccess>, AccessError> {
+ Ok(*self.team_crm_company_access.lock().await)
+ }
+
+ async fn get_team_crm_contact_access(
+ &self,
+ _contact_id: &str,
+ _team_id: Uuid,
+ ) -> Result<Option<CrmEntityAccess>, AccessError> {
+ Ok(*self.team_crm_contact_access.lock().await)
}
async fn has_foreign_entity_access(
@@ -346,6 +406,23 @@ fn test_bot_id() -> BotId {
BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"))
}
+fn test_team_id() -> Uuid {
+ uuid::uuid!("00000000-0000-0000-0000-000000000456")
+}
+
+fn test_bot_scope() -> BotAccessScope {
+ BotAccessScope::Team {
+ team_id: test_team_id(),
+ }
+}
+
+fn test_user_bot_scope(user_org_id: Option<i64>) -> BotAccessScope {
+ BotAccessScope::User {
+ user_id: test_user_id(),
+ user_org_id,
+ }
+}
+
fn user_id(s: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(s.to_string()).unwrap()
}
@@ -875,14 +952,16 @@ async fn test_generate_receipt_document_no_access_returns_unauthorized() {
}
#[tokio::test]
-async fn generate_bot_entity_access_receipt_document_with_sufficient_access() {
+async fn user_scoped_bot_delegates_to_the_acting_user() {
let bot_id = test_bot_id();
- let repo = MockRepo::new().with_bot_entity_access(AccessLevel::Edit);
- let service = EntityAccessServiceImpl::new(repo);
+ let scope = test_user_bot_scope(Some(42));
+ let repo = MockRepo::new().with_document_access(AccessLevel::Edit);
+ let service = EntityAccessServiceImpl::new(repo.clone());
let receipt = service
.generate_bot_entity_access_receipt::<ViewAccessLevel>(
bot_id,
+ scope.clone(),
"doc-1",
EntityType::Document,
)
@@ -890,30 +969,140 @@ async fn generate_bot_entity_access_receipt_document_with_sufficient_access() {
.unwrap();
assert!(matches!(receipt.auth(), EntityAccessAuth::Bot(id) if id.bot_id() == bot_id));
- assert_eq!(receipt.get_authenticated_bot().unwrap().bot_id(), bot_id);
+ assert_eq!(
+ receipt.get_authenticated_bot_auth().unwrap().scope(),
+ &BotReceiptScope::from(&scope)
+ );
+ assert_eq!(receipt.acting_user_id(), Some(&test_user_id()));
assert!(matches!(
receipt.get_authenticated_user(),
Err(AccessError::Unauthorized)
));
- assert_eq!(receipt.entity().entity_id, "doc-1");
- assert_eq!(receipt.entity().entity_type, EntityType::Document);
assert!(matches!(
receipt.entity_permission(),
EntityPermission::AccessLevel {
access_level: AccessLevel::Edit
}
));
+ assert_eq!(repo.team_repository_calls(), 0);
}
#[tokio::test]
-async fn generate_bot_entity_access_receipt_document_with_insufficient_permission() {
- let repo = MockRepo::new().with_bot_entity_access(AccessLevel::View);
+async fn user_scoped_bot_preserves_the_acting_users_organization() {
+ let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Member));
+ let request = repo.last_channel_role_request.clone();
+ let service = EntityAccessServiceImpl::new(repo);
+
+ service
+ .generate_bot_entity_access_receipt::<MemberParticipantRole>(
+ test_bot_id(),
+ test_user_bot_scope(Some(42)),
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::Channel,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ *request.lock().await,
+ Some((test_user_id().to_string(), Some(42)))
+ );
+}
+
+#[tokio::test]
+async fn user_scoped_bot_receives_the_acting_users_role_on_their_team() {
+ let team_id = test_team_id();
+ let repo = MockRepo::new().with_user_team(UserTeamInfo {
+ team_id,
+ role: TeamRole::Admin,
+ });
+ let service = EntityAccessServiceImpl::new(repo);
+
+ let receipt = service
+ .generate_bot_entity_access_receipt::<AdminTeamRole>(
+ test_bot_id(),
+ test_user_bot_scope(None),
+ &team_id.to_string(),
+ EntityType::Team,
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ receipt.entity_permission(),
+ EntityPermission::TeamRole {
+ role: TeamRole::Admin
+ }
+ ));
+}
+
+#[tokio::test]
+async fn user_scoped_bot_cannot_access_another_team() {
+ let repo = MockRepo::new().with_user_team(UserTeamInfo {
+ team_id: test_team_id(),
+ role: TeamRole::Owner,
+ });
+ let service = EntityAccessServiceImpl::new(repo);
+
+ let result = service
+ .generate_bot_entity_access_receipt::<MemberTeamRole>(
+ test_bot_id(),
+ test_user_bot_scope(None),
+ &Uuid::new_v4().to_string(),
+ EntityType::Team,
+ )
+ .await;
+
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
+
+#[tokio::test]
+async fn team_scoped_bot_dispatches_all_item_types() {
+ let repo = MockRepo::new().with_team_entity_access(AccessLevel::Edit);
+ let service = EntityAccessServiceImpl::new(repo.clone());
+
+ for entity_type in [
+ EntityType::Document,
+ EntityType::Chat,
+ EntityType::Project,
+ EntityType::EmailThread,
+ EntityType::Call,
+ ] {
+ let receipt = service
+ .generate_bot_entity_access_receipt::<ViewAccessLevel>(
+ test_bot_id(),
+ test_bot_scope(),
+ &Uuid::new_v4().to_string(),
+ entity_type,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ receipt.get_authenticated_bot_auth().unwrap().scope(),
+ &BotReceiptScope::from(&test_bot_scope())
+ );
+ assert!(matches!(
+ receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit
+ }
+ ));
+ }
+
+ assert_eq!(repo.team_entity_access_calls.load(Ordering::SeqCst), 5);
+}
+
+#[tokio::test]
+async fn team_scoped_bot_enforces_the_required_item_permission() {
+ let repo = MockRepo::new().with_team_entity_access(AccessLevel::View);
let service = EntityAccessServiceImpl::new(repo);
let result = service
.generate_bot_entity_access_receipt::<EditAccessLevel>(
test_bot_id(),
- "doc-1",
+ test_bot_scope(),
+ &Uuid::new_v4().to_string(),
EntityType::Document,
)
.await;
@@ -922,13 +1111,14 @@ async fn generate_bot_entity_access_receipt_document_with_insufficient_permissio
}
#[tokio::test]
-async fn generate_bot_entity_access_receipt_document_with_no_access() {
+async fn team_scoped_bot_without_item_access_is_unauthorized() {
let service = EntityAccessServiceImpl::new(MockRepo::new());
let result = service
.generate_bot_entity_access_receipt::<ViewAccessLevel>(
test_bot_id(),
- "doc-1",
+ test_bot_scope(),
+ &Uuid::new_v4().to_string(),
EntityType::Document,
)
.await;
@@ -937,15 +1127,16 @@ async fn generate_bot_entity_access_receipt_document_with_no_access() {
}
#[tokio::test]
-async fn generate_bot_entity_access_receipt_channel_member_role_succeeds() {
+async fn team_scoped_bot_channel_role_succeeds() {
let bot_id = test_bot_id();
let repo =
- MockRepo::new().with_bot_channel_role(ChannelRoleResult::Role(ParticipantRole::Member));
+ MockRepo::new().with_team_channel_role(ChannelRoleResult::Role(ParticipantRole::Member));
let service = EntityAccessServiceImpl::new(repo);
let receipt = service
.generate_bot_entity_access_receipt::<MemberParticipantRole>(
bot_id,
+ test_bot_scope(),
"11111111-1111-1111-1111-111111111111",
EntityType::Channel,
)
@@ -962,63 +1153,211 @@ async fn generate_bot_entity_access_receipt_channel_member_role_succeeds() {
}
#[tokio::test]
-async fn generate_bot_entity_access_receipt_channel_no_access_is_unauthorized() {
- let repo = MockRepo::new().with_bot_channel_role(ChannelRoleResult::NoAccess);
- let service = EntityAccessServiceImpl::new(repo);
+async fn team_scoped_bot_channel_errors_are_preserved() {
+ for (result, expected_not_found) in [
+ (ChannelRoleResult::NoAccess, false),
+ (ChannelRoleResult::NotFound, true),
+ ] {
+ let repo = MockRepo::new().with_team_channel_role(result);
+ let service = EntityAccessServiceImpl::new(repo);
+ let error = service
+ .generate_bot_entity_access_receipt::<MemberParticipantRole>(
+ test_bot_id(),
+ test_bot_scope(),
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::Channel,
+ )
+ .await
+ .expect_err("channel access must fail");
+
+ if expected_not_found {
+ assert!(matches!(error, AccessError::NotFound(_)));
+ } else {
+ assert!(matches!(error, AccessError::Unauthorized));
+ }
+ }
+}
+
+#[tokio::test]
+async fn team_scoped_bot_malformed_channel_id_is_bad_request() {
+ let repo = MockRepo::new();
+ let service = EntityAccessServiceImpl::new(repo.clone());
let result = service
.generate_bot_entity_access_receipt::<MemberParticipantRole>(
test_bot_id(),
- "11111111-1111-1111-1111-111111111111",
+ test_bot_scope(),
+ "not-a-uuid",
EntityType::Channel,
)
.await;
- assert!(matches!(result, Err(AccessError::Unauthorized)));
+ assert!(matches!(result, Err(AccessError::BadRequest(_))));
+ assert_eq!(repo.team_repository_calls(), 0);
}
#[tokio::test]
-async fn generate_bot_entity_access_receipt_channel_not_found_is_preserved() {
- let repo = MockRepo::new().with_bot_channel_role(ChannelRoleResult::NotFound);
+async fn team_scoped_bot_foreign_entity_access_is_view_only() {
+ let repo = MockRepo::new().with_team_foreign_entity_access(true);
let service = EntityAccessServiceImpl::new(repo);
+ let receipt = service
+ .generate_bot_entity_access_receipt::<ViewAccessLevel>(
+ test_bot_id(),
+ test_bot_scope(),
+ FOREIGN_ENTITY_ID,
+ EntityType::ForeignEntity,
+ )
+ .await
+ .unwrap();
+ assert!(matches!(
+ receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::View
+ }
+ ));
+
let result = service
- .generate_bot_entity_access_receipt::<MemberParticipantRole>(
+ .generate_bot_entity_access_receipt::<CommentAccessLevel>(
test_bot_id(),
- "11111111-1111-1111-1111-111111111111",
- EntityType::Channel,
+ test_bot_scope(),
+ FOREIGN_ENTITY_ID,
+ EntityType::ForeignEntity,
)
.await;
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
- assert!(matches!(result, Err(AccessError::NotFound(_))));
+#[tokio::test]
+async fn team_scoped_bot_crm_access_is_always_view_only() {
+ let repository_access = CrmEntityAccess {
+ access_level: AccessLevel::Owner,
+ team_id: test_team_id(),
+ team_role: TeamRole::Owner,
+ };
+ let repo = MockRepo::new()
+ .with_team_crm_company_access(repository_access)
+ .with_team_crm_contact_access(repository_access);
+ let service = EntityAccessServiceImpl::new(repo);
+
+ for entity_type in [EntityType::CrmCompany, EntityType::CrmContact] {
+ let entity_id = Uuid::new_v4().to_string();
+ let receipt = service
+ .generate_bot_entity_access_receipt::<ViewAccessLevel>(
+ test_bot_id(),
+ test_bot_scope(),
+ &entity_id,
+ entity_type,
+ )
+ .await
+ .unwrap();
+ assert!(matches!(
+ receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::View
+ }
+ ));
+
+ let result = service
+ .generate_bot_entity_access_receipt::<EditAccessLevel>(
+ test_bot_id(),
+ test_bot_scope(),
+ &entity_id,
+ entity_type,
+ )
+ .await;
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+ }
}
#[tokio::test]
-async fn generate_bot_entity_access_receipt_malformed_channel_id_is_bad_request() {
- let repo = MockRepo::new();
- let service = EntityAccessServiceImpl::new(repo.clone());
+async fn team_scoped_bot_hidden_or_other_team_crm_rows_are_unauthorized() {
+ let service = EntityAccessServiceImpl::new(MockRepo::new());
+
+ for entity_type in [EntityType::CrmCompany, EntityType::CrmContact] {
+ let result = service
+ .generate_bot_entity_access_receipt::<ViewAccessLevel>(
+ test_bot_id(),
+ test_bot_scope(),
+ &Uuid::new_v4().to_string(),
+ entity_type,
+ )
+ .await;
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+ }
+}
+
+#[tokio::test]
+async fn team_scoped_bot_receives_member_role_only_for_the_scoped_team() {
+ let service = EntityAccessServiceImpl::new(MockRepo::new());
+ let receipt = service
+ .generate_bot_entity_access_receipt::<MemberTeamRole>(
+ test_bot_id(),
+ test_bot_scope(),
+ &test_team_id().to_string(),
+ EntityType::Team,
+ )
+ .await
+ .unwrap();
+ assert!(matches!(
+ receipt.entity_permission(),
+ EntityPermission::TeamRole {
+ role: TeamRole::Member
+ }
+ ));
let result = service
- .generate_bot_entity_access_receipt::<MemberParticipantRole>(
+ .generate_bot_entity_access_receipt::<AdminTeamRole>(
test_bot_id(),
- "not-a-uuid",
- EntityType::Channel,
+ test_bot_scope(),
+ &test_team_id().to_string(),
+ EntityType::Team,
)
.await;
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
- assert!(matches!(result, Err(AccessError::BadRequest(_))));
- assert_eq!(repo.bot_repository_calls(), 0);
+ let result = service
+ .generate_bot_entity_access_receipt::<MemberTeamRole>(
+ test_bot_id(),
+ test_bot_scope(),
+ &Uuid::new_v4().to_string(),
+ EntityType::Team,
+ )
+ .await;
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
}
#[tokio::test]
-async fn generate_bot_entity_access_receipt_unsupported_types_are_bad_request() {
+async fn bot_team_receipts_reject_malformed_team_ids() {
+ let service = EntityAccessServiceImpl::new(MockRepo::new());
+
+ for scope in [test_bot_scope(), test_user_bot_scope(None)] {
+ let result = service
+ .generate_bot_entity_access_receipt::<MemberTeamRole>(
+ test_bot_id(),
+ scope,
+ "not-a-uuid",
+ EntityType::Team,
+ )
+ .await;
+ assert!(matches!(result, Err(AccessError::BadRequest(_))));
+ }
+}
+
+#[tokio::test]
+async fn team_scoped_bot_unsupported_types_are_bad_request() {
let repo = MockRepo::new();
let service = EntityAccessServiceImpl::new(repo.clone());
- for entity_type in [EntityType::CrmCompany, EntityType::Team] {
+ for entity_type in [
+ EntityType::User,
+ EntityType::ChannelMessage,
+ EntityType::StaticFile,
+ ] {
let result = service
- .generate_bot_entity_access_receipt::<ViewAccessLevel>(
+ .generate_bot_entity_access_receipt::<AnyEntityPermission>(
test_bot_id(),
+ test_bot_scope(),
"unsupported-entity",
entity_type,
)
@@ -1026,7 +1365,7 @@ async fn generate_bot_entity_access_receipt_unsupported_types_are_bad_request()
assert!(matches!(result, Err(AccessError::BadRequest(_))));
}
- assert_eq!(repo.bot_repository_calls(), 0);
+ assert_eq!(repo.team_repository_calls(), 0);
}
#[tokio::test]
diff --git a/crates/entity_access/src/inbound/axum_extractors/bot.rs b/crates/entity_access/src/inbound/axum_extractors/bot.rs
new file mode 100644
index 0000000000..5b3bfd08eb
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/bot.rs
@@ -0,0 +1,52 @@
+//! Shared bot authentication mapping for entity-access extractors.
+
+#[cfg(test)]
+mod test;
+
+use macro_authorization::{BotAuthentication, BotScope};
+
+use super::{ExtractorError, RequiredPermission};
+use crate::domain::{
+ models::{BotAccessScope, EntityAccessReceipt, EntityType},
+ ports::EntityAccessService,
+};
+
+pub(super) fn map_bot_access_scope(
+ authentication: &BotAuthentication,
+) -> Result<BotAccessScope, ExtractorError> {
+ match authentication.bot_scope {
+ BotScope::User => {
+ let acting_user = authentication.acting_user.as_ref().ok_or(
+ ExtractorError::UnauthorizedWithMessage("bot user scope requires an acting user"),
+ )?;
+
+ Ok(BotAccessScope::User {
+ user_id: acting_user.macro_user_id.clone(),
+ user_org_id: acting_user.user_context.organization_id.map(i64::from),
+ })
+ }
+ BotScope::Team => authentication
+ .team_id
+ .map(|team_id| BotAccessScope::Team { team_id })
+ .ok_or(ExtractorError::Unauthorized),
+ }
+}
+
+pub(super) async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
+ service: &impl EntityAccessService,
+ authentication: &BotAuthentication,
+ entity_id: &str,
+ entity_type: EntityType,
+) -> Result<EntityAccessReceipt<T>, ExtractorError> {
+ let scope = map_bot_access_scope(authentication)?;
+
+ service
+ .generate_bot_entity_access_receipt::<T>(
+ authentication.bot_id,
+ scope,
+ entity_id,
+ entity_type,
+ )
+ .await
+ .map_err(ExtractorError::from)
+}
diff --git a/crates/entity_access/src/inbound/axum_extractors/bot/test.rs b/crates/entity_access/src/inbound/axum_extractors/bot/test.rs
new file mode 100644
index 0000000000..edd8b942ec
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/bot/test.rs
@@ -0,0 +1,144 @@
+use axum::{
+ body::to_bytes,
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use macro_authorization::BotScope;
+
+use super::*;
+use crate::{
+ domain::models::{
+ BotReceiptScope, EntityPermission, MemberParticipantRole, ParticipantRole, ViewAccessLevel,
+ },
+ inbound::axum_extractors::test_support::{
+ BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID, BotAccessCall,
+ FakeEntityAccessService, malformed_system_bot_authentication,
+ team_scoped_bot_authentication, user_scoped_bot_authentication,
+ },
+};
+
+async fn response_parts(response: Response) -> (StatusCode, String) {
+ let status = response.status();
+ let body = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("extractor error response body should be readable");
+ let body = String::from_utf8(body.to_vec())
+ .expect("extractor error response body should be valid UTF-8");
+
+ (status, body)
+}
+
+#[test]
+fn maps_user_scope_with_verified_acting_user_and_organization() {
+ let authentication = user_scoped_bot_authentication();
+
+ let scope = map_bot_access_scope(&authentication).expect("user scope should map");
+
+ match scope {
+ BotAccessScope::User {
+ user_id,
+ user_org_id,
+ } => {
+ assert_eq!(user_id.as_ref(), BOT_ACTING_USER_ID);
+ assert_eq!(
+ user_org_id,
+ Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID))
+ );
+ }
+ BotAccessScope::Team { .. } => panic!("expected user scope"),
+ }
+}
+
+#[test]
+fn maps_team_scope_with_owning_team() {
+ let authentication = team_scoped_bot_authentication();
+
+ let scope = map_bot_access_scope(&authentication).expect("team scope should map");
+
+ assert_eq!(
+ scope,
+ BotAccessScope::Team {
+ team_id: BOT_TEAM_ID
+ }
+ );
+}
+
+#[tokio::test]
+async fn malformed_system_authentication_has_scope_specific_rejections() {
+ let user_error = map_bot_access_scope(&malformed_system_bot_authentication(BotScope::User))
+ .expect_err("user scope without an acting user should fail");
+ assert!(matches!(
+ user_error,
+ ExtractorError::UnauthorizedWithMessage("bot user scope requires an acting user")
+ ));
+ let (status, body) = response_parts(user_error.into_response()).await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ body,
+ r#"{"message":"bot user scope requires an acting user"}"#
+ );
+
+ let team_error = map_bot_access_scope(&malformed_system_bot_authentication(BotScope::Team))
+ .expect_err("team scope without a team should fail");
+ assert!(matches!(team_error, ExtractorError::Unauthorized));
+ let (status, body) = response_parts(team_error.into_response()).await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ body,
+ r#"{"message":"User does not have access to the requested resource"}"#
+ );
+}
+
+#[tokio::test]
+async fn generic_helper_generates_scoped_receipt_and_records_acl_call() {
+ let service =
+ FakeEntityAccessService::new(None).with_bot_permission(EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ });
+ let authentication = team_scoped_bot_authentication();
+
+ let receipt = generate_bot_entity_access_receipt::<MemberParticipantRole>(
+ &service,
+ &authentication,
+ "channel-1",
+ EntityType::Channel,
+ )
+ .await
+ .expect("configured bot permission should generate a receipt");
+
+ assert_eq!(receipt.get_authenticated_bot().unwrap().bot_id(), BOT_ID);
+ assert_eq!(
+ receipt.get_authenticated_bot_auth().unwrap().scope(),
+ &BotReceiptScope::Team {
+ team_id: BOT_TEAM_ID
+ }
+ );
+ assert_eq!(
+ service.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID
+ },
+ entity_id: "channel-1".to_string(),
+ entity_type: EntityType::Channel,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn generic_helper_maps_service_access_errors() {
+ let service = FakeEntityAccessService::new(None);
+ let authentication = user_scoped_bot_authentication();
+
+ let result = generate_bot_entity_access_receipt::<ViewAccessLevel>(
+ &service,
+ &authentication,
+ "document-1",
+ EntityType::Document,
+ )
+ .await;
+
+ assert!(matches!(result, Err(ExtractorError::Unauthorized)));
+ assert_eq!(service.bot_calls().len(), 1);
+}
diff --git a/crates/entity_access/src/inbound/axum_extractors/call.rs b/crates/entity_access/src/inbound/axum_extractors/call.rs
index 5a9d2a0a6c..cb7eac87f3 100644
--- a/crates/entity_access/src/inbound/axum_extractors/call.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/call.rs
@@ -15,12 +15,12 @@ use axum::{
http::request::Parts,
};
use macro_authorization::{
- MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOrInternalService, UserOrInternalServiceAuthorization,
+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor,
};
use uuid::Uuid;
-use super::ExtractorError;
+use super::{ExtractorError, bot::generate_bot_entity_access_receipt};
use crate::domain::{
models::{
Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -75,20 +75,11 @@ where
let service = <Arc<Svc>>::from_ref(state);
let authorization =
- OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ OptionalMacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(
parts, state,
)
.await
.map_err(ExtractorError::from)?;
- let is_internal_access = authorization
- .authorization
- .as_ref()
- .is_some_and(UserOrInternalServiceAuthorization::is_internal);
- let macro_user_id = authorization
- .authorization
- .as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
- .map(|user| user.macro_user_id.clone());
let Path(CallAccessParams { call_id }) = parts
.extract::<Path<CallAccessParams>>()
@@ -104,6 +95,34 @@ where
.map_err(ExtractorError::from)?
.ok_or(ExtractorError::NotFound("call not found"))?;
+ if let Some(MacroAuthorization::Bot(authentication)) = authorization.authorization.as_ref()
+ {
+ let entity_access_receipt = generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ authentication,
+ &call_id,
+ EntityType::Call,
+ )
+ .await?;
+
+ return Ok(Self {
+ entity_access_receipt,
+ share_permission_id: call_info.share_permission_id,
+ channel_id: call_info.channel_id,
+ _marker: PhantomData,
+ });
+ }
+
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(MacroAuthorization::is_internal);
+ let macro_user_id = authorization
+ .authorization
+ .as_ref()
+ .and_then(MacroAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone());
+
if macro_user_id.is_none() && is_internal_access {
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
@@ -189,21 +208,11 @@ where
let service = <Arc<Svc>>::from_ref(state);
let authorization =
- OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ OptionalMacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(
parts, state,
)
.await
.map_err(ExtractorError::from)?;
- let is_internal_access = authorization
- .authorization
- .as_ref()
- .is_some_and(UserOrInternalServiceAuthorization::is_internal);
- let (macro_user_id, user_context) = authorization
- .authorization
- .as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
- .map(|user| (Some(user.macro_user_id.clone()), user.user_context.clone()))
- .unwrap_or_default();
let Path(CallWithChannelIdAccessParams { channel_id }) = parts
.extract::<Path<CallWithChannelIdAccessParams>>()
@@ -219,6 +228,35 @@ where
.map_err(ExtractorError::from)?
.ok_or(ExtractorError::NotFound("call not found for channel"))?;
+ if let Some(MacroAuthorization::Bot(authentication)) = authorization.authorization.as_ref()
+ {
+ let entity_access_receipt = generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ authentication,
+ &channel_id,
+ EntityType::Channel,
+ )
+ .await?;
+
+ return Ok(Self {
+ entity_access_receipt,
+ share_permission_id: call_info.share_permission_id,
+ channel_id: channel_id_uuid,
+ _marker: PhantomData,
+ });
+ }
+
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(MacroAuthorization::is_internal);
+ let (macro_user_id, user_context) = authorization
+ .authorization
+ .as_ref()
+ .and_then(MacroAuthorization::acting_user)
+ .map(|user| (Some(user.macro_user_id.clone()), user.user_context.clone()))
+ .unwrap_or_default();
+
if macro_user_id.is_none() && is_internal_access {
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
diff --git a/crates/entity_access/src/inbound/axum_extractors/call/test.rs b/crates/entity_access/src/inbound/axum_extractors/call/test.rs
index a839e55532..f1970dcac2 100644
--- a/crates/entity_access/src/inbound/axum_extractors/call/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/call/test.rs
@@ -26,10 +26,14 @@ use uuid::Uuid;
use super::*;
use crate::{
domain::models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, MemberParticipantRole,
- OwnerParticipantRole, UserTeamInfo,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EditAccessLevel,
+ MemberParticipantRole, OwnerParticipantRole, UserTeamInfo, ViewAccessLevel, ViewOnly,
+ },
+ inbound::axum_extractors::test_support::{
+ BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID, BotAccessCall,
+ MALFORMED_SYSTEM_BOT_TOKEN, VALID_BOT_TOKEN, malformed_system_bot_authentication,
+ valid_bot_authentication,
},
- inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
};
const CALL_ID: &str = "9e8e56e7-97e8-4148-9618-a63dacabf104";
@@ -95,8 +99,11 @@ struct PermissionCall {
#[derive(Clone, Debug)]
struct FakeEntityAccessService {
call_info: Option<CallChannelInfo>,
+ call_lookup_fails: bool,
permission: EntityPermission,
+ bot_permission: Option<EntityPermission>,
permission_calls: Arc<Mutex<Vec<PermissionCall>>>,
+ bot_calls: Arc<Mutex<Vec<BotAccessCall>>>,
}
impl FakeEntityAccessService {
@@ -106,17 +113,37 @@ impl FakeEntityAccessService {
channel_id: Uuid::parse_str(CHANNEL_ID).expect("channel id should be valid"),
share_permission_id: SHARE_PERMISSION_ID.to_string(),
}),
+ call_lookup_fails: false,
permission,
+ bot_permission: Some(permission),
permission_calls: Arc::new(Mutex::new(Vec::new())),
+ bot_calls: Arc::new(Mutex::new(Vec::new())),
}
}
+ fn with_bot_permission(mut self, bot_permission: Option<EntityPermission>) -> Self {
+ self.bot_permission = bot_permission;
+ self
+ }
+
+ fn with_call_lookup_error(mut self) -> Self {
+ self.call_lookup_fails = true;
+ self
+ }
+
fn permission_calls(&self) -> Vec<PermissionCall> {
self.permission_calls
.lock()
.expect("permission calls lock poisoned")
.clone()
}
+
+ fn bot_calls(&self) -> Vec<BotAccessCall> {
+ self.bot_calls
+ .lock()
+ .expect("bot calls lock poisoned")
+ .clone()
+ }
}
impl EntityAccessService for FakeEntityAccessService {
@@ -132,11 +159,31 @@ impl EntityAccessService for FakeEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
- _bot_id: BotId,
- _entity_id: &str,
- _entity_type: EntityType,
+ bot_id: BotId,
+ scope: BotAccessScope,
+ entity_id: &str,
+ entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
- panic!("unexpected generate_bot_entity_access_receipt call")
+ self.bot_calls
+ .lock()
+ .expect("bot calls lock poisoned")
+ .push(BotAccessCall {
+ bot_id,
+ scope: scope.clone(),
+ entity_id: entity_id.to_string(),
+ entity_type,
+ });
+
+ let permission = self.bot_permission.ok_or(AccessError::Unauthorized)?;
+ EntityAccessReceipt::try_new_bot(
+ bot_id.into_storage_id(),
+ (&scope).into(),
+ Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ permission,
+ )
}
async fn get_access_level(
@@ -207,6 +254,9 @@ impl EntityAccessService for FakeEntityAccessService {
&self,
_call_id: &Uuid,
) -> Result<Option<CallChannelInfo>, AccessError> {
+ if self.call_lookup_fails {
+ return Err(AccessError::Internal);
+ }
Ok(self.call_info.clone())
}
@@ -214,6 +264,9 @@ impl EntityAccessService for FakeEntityAccessService {
&self,
_channel_id: &Uuid,
) -> Result<Option<CallChannelInfo>, AccessError> {
+ if self.call_lookup_fails {
+ return Err(AccessError::Internal);
+ }
Ok(self.call_info.clone())
}
@@ -245,11 +298,11 @@ impl MacroAuthorizationService for FakeAuthorizationService {
bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
- if token != VALID_BOT_TOKEN {
- return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ match token {
+ VALID_BOT_TOKEN => Ok(valid_bot_authentication(bot_scope)),
+ MALFORMED_SYSTEM_BOT_TOKEN => Ok(malformed_system_bot_authentication(bot_scope)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
}
-
- Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -276,16 +329,48 @@ struct TestState {
impl TestState {
fn new(call_exists: bool, permission: EntityPermission) -> Self {
- Self::with_authorization(call_exists, permission, FakeAuthorizationService::default())
+ Self::with_service_and_authorization(
+ FakeEntityAccessService::new(call_exists, permission),
+ FakeAuthorizationService::default(),
+ )
+ }
+
+ fn with_bot_permission(
+ call_exists: bool,
+ permission: EntityPermission,
+ bot_permission: Option<EntityPermission>,
+ ) -> Self {
+ Self::with_service_and_authorization(
+ FakeEntityAccessService::new(call_exists, permission)
+ .with_bot_permission(bot_permission),
+ FakeAuthorizationService::default(),
+ )
+ }
+
+ fn with_call_lookup_error(permission: EntityPermission) -> Self {
+ Self::with_service_and_authorization(
+ FakeEntityAccessService::new(true, permission).with_call_lookup_error(),
+ FakeAuthorizationService::default(),
+ )
}
fn with_authorization(
call_exists: bool,
permission: EntityPermission,
authorization: FakeAuthorizationService,
+ ) -> Self {
+ Self::with_service_and_authorization(
+ FakeEntityAccessService::new(call_exists, permission),
+ authorization,
+ )
+ }
+
+ fn with_service_and_authorization(
+ service: FakeEntityAccessService,
+ authorization: FakeAuthorizationService,
) -> Self {
Self {
- entity_access: Arc::new(FakeEntityAccessService::new(call_exists, permission)),
+ entity_access: Arc::new(service),
authorization: MacroAuthorizationState::new(Arc::new(authorization)),
}
}
@@ -346,6 +431,34 @@ async fn channel_handler(
))
}
+async fn call_view_handler(
+ extracted: CallAccessLevelExtractor<
+ ViewAccessLevel,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+ >,
+) -> Json<Value> {
+ Json(receipt_json(
+ &extracted.entity_access_receipt,
+ &extracted.share_permission_id,
+ extracted.channel_id,
+ ))
+}
+
+async fn channel_view_handler(
+ extracted: CallWithChannelIdAccessLevelExtractor<
+ ViewOnly,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+ >,
+) -> Json<Value> {
+ Json(receipt_json(
+ &extracted.entity_access_receipt,
+ &extracted.share_permission_id,
+ extracted.channel_id,
+ ))
+}
+
fn receipt_json<T: RequiredPermission>(
receipt: &EntityAccessReceipt<T>,
share_permission_id: &str,
@@ -353,12 +466,15 @@ fn receipt_json<T: RequiredPermission>(
) -> Value {
let (auth, user_id) = match receipt.auth() {
EntityAccessAuth::Authenticated(user_id) => ("authenticated", Some(user_id.as_ref())),
+ EntityAccessAuth::Bot(_) => ("bot", None),
EntityAccessAuth::Internal => ("internal", None),
- _ => ("unexpected", None),
+ EntityAccessAuth::Unauthenticated => ("unauthenticated", None),
};
- let role = match receipt.entity_permission() {
+ let permission = match receipt.entity_permission() {
+ EntityPermission::AccessLevel { access_level } => format!("{access_level:?}"),
+ EntityPermission::ChannelViewOnly => "ViewOnly".to_string(),
EntityPermission::ChannelRole { role } => format!("{role:?}"),
- permission => format!("unexpected: {permission:?}"),
+ EntityPermission::TeamRole { role } => format!("{role:?}"),
};
json!({
@@ -366,7 +482,7 @@ fn receipt_json<T: RequiredPermission>(
"entity_type": receipt.entity().entity_type,
"auth": auth,
"user_id": user_id,
- "role": role,
+ "role": permission,
"share_permission_id": share_permission_id,
"channel_id": channel_id,
})
@@ -389,11 +505,15 @@ fn request(path: String, token: Option<&str>) -> Request<Body> {
.expect("request should be valid")
}
-fn bot_request(path: String) -> Request<Body> {
+fn bot_request(path: String, scope: BotScope) -> Request<Body> {
+ bot_request_with_token(path, scope, VALID_BOT_TOKEN)
+}
+
+fn bot_request_with_token(path: String, scope: BotScope, token: &str) -> Request<Body> {
Request::builder()
.uri(path)
- .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
- .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
+ .header(BOT_TOKEN_HEADER, token)
+ .header(BOT_SCOPE_HEADER, scope.as_str())
.body(Body::empty())
.expect("request should be valid")
}
@@ -411,7 +531,11 @@ fn internal_request(path: String, user_id: Option<&str>) -> Request<Body> {
}
async fn send(state: &TestState, request: Request<Body>) -> (StatusCode, Value) {
- let response = router(state.clone())
+ send_to(router(state.clone()), request).await
+}
+
+async fn send_to(router: Router, request: Request<Body>) -> (StatusCode, Value) {
+ let response = router
.oneshot(request)
.await
.expect("router should respond");
@@ -423,6 +547,22 @@ async fn send(state: &TestState, request: Request<Body>) -> (StatusCode, Value)
(status, body)
}
+fn call_view_router(state: TestState) -> Router {
+ Router::new()
+ .route("/call/{call_id}", get(call_view_handler))
+ .with_state(state)
+}
+
+fn channel_view_router(state: TestState) -> Router {
+ Router::new()
+ .route("/channel/{channel_id}", get(channel_view_handler))
+ .with_state(state)
+}
+
+fn access_permission(access_level: AccessLevel) -> EntityPermission {
+ EntityPermission::AccessLevel { access_level }
+}
+
fn member_permission() -> EntityPermission {
EntityPermission::ChannelRole {
role: ParticipantRole::Member,
@@ -507,25 +647,210 @@ async fn missing_and_expired_credentials_are_rejected_for_both_variants() {
}
#[tokio::test]
-async fn bot_credentials_are_forbidden_for_both_variants_without_permission_lookup() {
+async fn call_id_bot_scopes_request_call_access_and_preserve_call_metadata() {
+ for (scope, expected_scope) in [
+ (
+ BotScope::User,
+ BotAccessScope::User {
+ user_id: MacroUserIdStr::try_from(BOT_ACTING_USER_ID.to_string())
+ .expect("bot acting user id should be valid"),
+ user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
+ },
+ ),
+ (
+ BotScope::Team,
+ BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ ),
+ ] {
+ let state = TestState::with_bot_permission(
+ true,
+ member_permission(),
+ Some(access_permission(AccessLevel::Edit)),
+ );
+ let (status, body) = send_to(
+ call_view_router(state.clone()),
+ bot_request(Variant::CallId.valid_path(), scope),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["entity_id"], CALL_ID);
+ assert_eq!(body["entity_type"], json!(EntityType::Call));
+ assert_eq!(body["auth"], "bot");
+ assert_eq!(body["role"], "Edit");
+ assert_eq!(body["share_permission_id"], SHARE_PERMISSION_ID);
+ assert_eq!(body["channel_id"], CHANNEL_ID);
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: expected_scope,
+ entity_id: CALL_ID.to_string(),
+ entity_type: EntityType::Call,
+ }]
+ );
+ assert!(state.entity_access.permission_calls().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn channel_id_bot_scopes_request_channel_access_with_explicit_roles() {
+ for (scope, expected_scope) in [
+ (
+ BotScope::User,
+ BotAccessScope::User {
+ user_id: MacroUserIdStr::try_from(BOT_ACTING_USER_ID.to_string())
+ .expect("bot acting user id should be valid"),
+ user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
+ },
+ ),
+ (
+ BotScope::Team,
+ BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ ),
+ ] {
+ let state =
+ TestState::with_bot_permission(true, member_permission(), Some(member_permission()));
+ let (status, body) =
+ send(&state, bot_request(Variant::ChannelId.valid_path(), scope)).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["entity_id"], CHANNEL_ID);
+ assert_eq!(body["entity_type"], json!(EntityType::Channel));
+ assert_eq!(body["auth"], "bot");
+ assert_eq!(body["role"], "Member");
+ assert_eq!(body["share_permission_id"], SHARE_PERMISSION_ID);
+ assert_eq!(body["channel_id"], CHANNEL_ID);
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: expected_scope,
+ entity_id: CHANNEL_ID.to_string(),
+ entity_type: EntityType::Channel,
+ }]
+ );
+ assert!(state.entity_access.permission_calls().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn team_scoped_bot_can_view_its_team_channel_without_a_participant_role() {
+ let state = TestState::with_bot_permission(
+ true,
+ member_permission(),
+ Some(EntityPermission::ChannelViewOnly),
+ );
+ let (status, body) = send_to(
+ channel_view_router(state.clone()),
+ bot_request(Variant::ChannelId.valid_path(), BotScope::Team),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["auth"], "bot");
+ assert_eq!(body["role"], "ViewOnly");
+ assert_eq!(body["share_permission_id"], SHARE_PERMISSION_ID);
+ assert_eq!(body["channel_id"], CHANNEL_ID);
+}
+
+#[tokio::test]
+async fn team_scoped_bot_does_not_receive_implicit_public_channel_access() {
+ let state = TestState::with_bot_permission(true, member_permission(), None);
+ let (status, _) = send(
+ &state,
+ bot_request(Variant::ChannelId.valid_path(), BotScope::Team),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(state.entity_access.bot_calls().len(), 1);
+ assert!(state.entity_access.permission_calls().is_empty());
+}
+
+#[tokio::test]
+async fn user_scoped_bot_without_an_acting_user_is_rejected_for_both_variants() {
for variant in [Variant::CallId, Variant::ChannelId] {
let state = TestState::new(true, member_permission());
- let (status, body) = send(&state, bot_request(variant.valid_path())).await;
+ let (status, body) = send(
+ &state,
+ bot_request_with_token(
+ variant.valid_path(),
+ BotScope::User,
+ MALFORMED_SYSTEM_BOT_TOKEN,
+ ),
+ )
+ .await;
- assert_eq!(status, StatusCode::FORBIDDEN);
- assert_eq!(body, json!({ "message": "forbidden" }));
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ body,
+ json!({ "message": "bot user scope requires an acting user" })
+ );
+ assert!(state.entity_access.bot_calls().is_empty());
assert!(state.entity_access.permission_calls().is_empty());
}
}
+#[tokio::test]
+async fn bot_permissions_must_satisfy_each_extractors_required_level() {
+ let call_state = TestState::with_bot_permission(
+ true,
+ member_permission(),
+ Some(access_permission(AccessLevel::View)),
+ );
+ let call_app = Router::new()
+ .route(
+ "/call/{call_id}",
+ get(
+ |_: CallAccessLevelExtractor<
+ EditAccessLevel,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+ >| async {},
+ ),
+ )
+ .with_state(call_state.clone());
+ let response = call_app
+ .oneshot(bot_request(Variant::CallId.valid_path(), BotScope::Team))
+ .await
+ .expect("router should respond");
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(call_state.entity_access.bot_calls().len(), 1);
+
+ let channel_state = TestState::with_bot_permission(
+ true,
+ member_permission(),
+ Some(EntityPermission::ChannelViewOnly),
+ );
+ let response = router(channel_state.clone())
+ .oneshot(bot_request(Variant::ChannelId.valid_path(), BotScope::Team))
+ .await
+ .expect("router should respond");
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(channel_state.entity_access.bot_calls().len(), 1);
+}
+
#[tokio::test]
async fn malformed_ids_are_rejected_for_both_variants() {
for variant in [Variant::CallId, Variant::ChannelId] {
- let state = TestState::new(true, member_permission());
- let (status, _) = send(&state, request(variant.path("not-a-uuid"), Some("valid"))).await;
+ for request in [
+ request(variant.path("not-a-uuid"), Some("valid")),
+ bot_request(variant.path("not-a-uuid"), BotScope::Team),
+ ] {
+ let state = TestState::new(true, member_permission());
+ let (status, _) = send(&state, request).await;
- assert_eq!(status, StatusCode::BAD_REQUEST);
- assert!(state.entity_access.permission_calls().is_empty());
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(state.entity_access.permission_calls().is_empty());
+ assert!(state.entity_access.bot_calls().is_empty());
+ }
}
}
@@ -535,16 +860,39 @@ async fn missing_call_information_is_rejected_including_for_internal_requests()
for request in [
request(variant.valid_path(), Some("valid")),
internal_request(variant.valid_path(), None),
+ bot_request(variant.valid_path(), BotScope::Team),
] {
let state = TestState::new(false, member_permission());
let (status, _) = send(&state, request).await;
assert_eq!(status, StatusCode::NOT_FOUND);
assert!(state.entity_access.permission_calls().is_empty());
+ assert!(state.entity_access.bot_calls().is_empty());
}
}
}
+#[tokio::test]
+async fn call_lookup_errors_are_returned_before_bot_scope_or_acl_checks() {
+ for variant in [Variant::CallId, Variant::ChannelId] {
+ let state = TestState::with_call_lookup_error(member_permission());
+ let (status, body) = send(
+ &state,
+ bot_request_with_token(
+ variant.valid_path(),
+ BotScope::User,
+ MALFORMED_SYSTEM_BOT_TOKEN,
+ ),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
+ assert_eq!(body, json!({ "message": "Internal server error" }));
+ assert!(state.entity_access.permission_calls().is_empty());
+ assert!(state.entity_access.bot_calls().is_empty());
+ }
+}
+
#[tokio::test]
async fn identity_less_internal_requests_receive_owner_receipts_without_acl_calls() {
for variant in [Variant::CallId, Variant::ChannelId] {
diff --git a/crates/entity_access/src/inbound/axum_extractors/channel.rs b/crates/entity_access/src/inbound/axum_extractors/channel.rs
index 1f38ef45c9..52ce76feb6 100644
--- a/crates/entity_access/src/inbound/axum_extractors/channel.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/channel.rs
@@ -12,7 +12,7 @@ use axum::{
http::request::Parts,
};
-use super::ExtractorError;
+use super::{ExtractorError, bot::generate_bot_entity_access_receipt};
use crate::domain::{
models::{
Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -21,8 +21,8 @@ use crate::domain::{
ports::EntityAccessService,
};
use macro_authorization::{
- MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOrInternalService, UserOrInternalServiceAuthorization,
+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor,
};
#[derive(Debug, serde::Deserialize)]
struct ChannelAccessParams {
@@ -56,27 +56,44 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
let authorization =
- OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ OptionalMacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(
parts, state,
)
.await
.map_err(ExtractorError::from)?;
+
+ let Path(ChannelAccessParams { channel_id }) = parts
+ .extract::<Path<ChannelAccessParams>>()
+ .await
+ .map_err(|_| ExtractorError::BadRequest("missing channel_id path parameter"))?;
+
+ if let Some(MacroAuthorization::Bot(authentication)) = authorization.authorization.as_ref()
+ {
+ let entity_access_receipt = generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ authentication,
+ &channel_id,
+ EntityType::Channel,
+ )
+ .await?;
+
+ return Ok(Self {
+ entity_access_receipt,
+ _marker: PhantomData,
+ });
+ }
+
let is_internal_access = authorization
.authorization
.as_ref()
- .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ .is_some_and(MacroAuthorization::is_internal);
let (macro_user_id, user_context) = authorization
.authorization
.as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .and_then(MacroAuthorization::acting_user)
.map(|user| (Some(user.macro_user_id.clone()), user.user_context.clone()))
.unwrap_or_default();
- let Path(ChannelAccessParams { channel_id }) = parts
- .extract::<Path<ChannelAccessParams>>()
- .await
- .map_err(|_| ExtractorError::BadRequest("missing channel_id path parameter"))?;
-
if macro_user_id.is_none() && is_internal_access {
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
diff --git a/crates/entity_access/src/inbound/axum_extractors/channel/test.rs b/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
index 667f31c8f7..c1d4baf287 100644
--- a/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
@@ -25,10 +25,12 @@ use uuid::Uuid;
use super::*;
use crate::{
domain::models::{
- AccessError, AccessLevel, AdminParticipantRole, BotId, CallChannelInfo,
+ AccessError, AccessLevel, AdminParticipantRole, BotAccessScope, BotId, CallChannelInfo,
MemberParticipantRole, OwnerParticipantRole, UserTeamInfo, ViewOnly,
},
- inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
+ inbound::axum_extractors::test_support::{
+ BOT_ID, BOT_TEAM_ID, BotAccessCall, VALID_BOT_TOKEN, valid_bot_authentication,
+ },
};
const CHANNEL_ID: &str = "550e8400-e29b-41d4-a716-446655440000";
@@ -49,20 +51,36 @@ struct PermissionCall {
#[derive(Clone)]
struct FakeEntityAccessService {
permission: EntityPermission,
+ bot_permission: Option<EntityPermission>,
calls: Arc<Mutex<Vec<PermissionCall>>>,
+ bot_calls: Arc<Mutex<Vec<BotAccessCall>>>,
}
impl FakeEntityAccessService {
fn new(permission: EntityPermission) -> Self {
Self {
permission,
+ bot_permission: None,
calls: Arc::new(Mutex::new(Vec::new())),
+ bot_calls: Arc::new(Mutex::new(Vec::new())),
}
}
+ fn with_bot_permission(mut self, permission: EntityPermission) -> Self {
+ self.bot_permission = Some(permission);
+ self
+ }
+
fn calls(&self) -> Vec<PermissionCall> {
self.calls.lock().expect("calls lock poisoned").clone()
}
+
+ fn bot_calls(&self) -> Vec<BotAccessCall> {
+ self.bot_calls
+ .lock()
+ .expect("bot calls lock poisoned")
+ .clone()
+ }
}
impl EntityAccessService for FakeEntityAccessService {
@@ -78,11 +96,31 @@ impl EntityAccessService for FakeEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
- _bot_id: BotId,
- _entity_id: &str,
- _entity_type: EntityType,
+ bot_id: BotId,
+ scope: BotAccessScope,
+ entity_id: &str,
+ entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
- panic!("unexpected generate_bot_entity_access_receipt call")
+ self.bot_calls
+ .lock()
+ .expect("bot calls lock poisoned")
+ .push(BotAccessCall {
+ bot_id,
+ scope: scope.clone(),
+ entity_id: entity_id.to_string(),
+ entity_type,
+ });
+
+ let permission = self.bot_permission.ok_or(AccessError::Unauthorized)?;
+ EntityAccessReceipt::try_new_bot(
+ bot_id.into_storage_id(),
+ (&scope).into(),
+ Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ permission,
+ )
}
async fn get_access_level(
@@ -233,6 +271,17 @@ impl TestState {
Self::with_authorization(permission, FakeAuthorizationService::default())
}
+ fn with_bot_permission(permission: EntityPermission) -> Self {
+ Self {
+ entity_access: Arc::new(
+ FakeEntityAccessService::new(permission).with_bot_permission(permission),
+ ),
+ authorization: MacroAuthorizationState::new(Arc::new(
+ FakeAuthorizationService::default(),
+ )),
+ }
+ }
+
fn with_authorization(
permission: EntityPermission,
authorization: FakeAuthorizationService,
@@ -299,6 +348,19 @@ fn request(token: Option<&str>) -> Request<Body> {
request
}
+fn bot_request(scope: BotScope) -> Request<Body> {
+ let mut request = request(None);
+ request.headers_mut().insert(
+ BOT_TOKEN_HEADER,
+ VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
+ );
+ request.headers_mut().insert(
+ BOT_SCOPE_HEADER,
+ scope.as_str().parse().expect("bot scope should be valid"),
+ );
+ request
+}
+
fn internal_request(user_id: Option<&str>) -> Request<Body> {
let mut request = request(None);
request.headers_mut().insert(
@@ -338,6 +400,29 @@ async fn member_handler(extractor: MemberExtractor) -> StatusCode {
StatusCode::OK
}
+async fn bot_member_handler(extractor: MemberExtractor) -> StatusCode {
+ let receipt = extractor.entity_access_receipt;
+ assert_member_receipt(&receipt);
+ assert!(matches!(
+ receipt.auth(),
+ EntityAccessAuth::Bot(authentication) if authentication.bot_id() == BOT_ID
+ ));
+ StatusCode::OK
+}
+
+async fn bot_view_only_handler(extractor: ViewOnlyExtractor) -> StatusCode {
+ let receipt = extractor.entity_access_receipt;
+ assert!(matches!(
+ receipt.auth(),
+ EntityAccessAuth::Bot(authentication) if authentication.bot_id() == BOT_ID
+ ));
+ assert!(matches!(
+ receipt.entity_permission(),
+ EntityPermission::ChannelViewOnly
+ ));
+ StatusCode::OK
+}
+
async fn authenticated_member_handler(extractor: MemberExtractor) -> StatusCode {
let receipt = extractor.entity_access_receipt;
assert_member_receipt(&receipt);
@@ -366,6 +451,17 @@ async fn owner_handler(extractor: OwnerExtractor) -> StatusCode {
StatusCode::OK
}
+fn expected_team_bot_call() -> BotAccessCall {
+ BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: CHANNEL_ID.to_string(),
+ entity_type: EntityType::Channel,
+ }
+}
+
fn app<H, T>(state: TestState, handler: H) -> Router
where
H: axum::handler::Handler<T, TestState>,
@@ -464,34 +560,110 @@ async fn missing_credentials_are_rejected_without_acl_call() {
assert!(state.entity_access.calls().is_empty());
}
+async fn assert_explicit_team_bot_participation_is_allowed() {
+ let state = TestState::with_bot_permission(EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ });
+ let response = app(state.clone(), bot_member_handler)
+ .oneshot(bot_request(BotScope::Team))
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert!(state.entity_access.calls().is_empty());
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ vec![expected_team_bot_call()]
+ );
+}
+
+#[tokio::test]
+async fn explicitly_participating_bot_can_access_private_channel() {
+ assert_explicit_team_bot_participation_is_allowed().await;
+}
+
+#[tokio::test]
+async fn explicitly_participating_bot_can_access_public_channel() {
+ assert_explicit_team_bot_participation_is_allowed().await;
+}
+
#[tokio::test]
-async fn bot_credentials_are_forbidden_without_permission_lookup() {
+async fn owning_team_channel_grants_team_scoped_bot_view_only_access() {
+ let state = TestState::with_bot_permission(EntityPermission::ChannelViewOnly);
+ let response = app(state.clone(), bot_view_only_handler)
+ .oneshot(bot_request(BotScope::Team))
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ vec![expected_team_bot_call()]
+ );
+}
+
+async fn assert_team_scoped_bot_without_channel_access_is_denied() {
let state = TestState::new(EntityPermission::ChannelRole {
role: ParticipantRole::Owner,
});
- let mut request = request(None);
- request.headers_mut().insert(
- BOT_TOKEN_HEADER,
- VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
- );
- request.headers_mut().insert(
- BOT_SCOPE_HEADER,
- BotScope::User
- .as_str()
- .parse()
- .expect("bot scope should be valid"),
+ let response = app(state.clone(), view_only_handler)
+ .oneshot(bot_request(BotScope::Team))
+ .await
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert!(state.entity_access.calls().is_empty());
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ vec![expected_team_bot_call()]
);
+}
+
+#[tokio::test]
+async fn another_teams_channel_does_not_grant_team_scoped_bot_access() {
+ assert_team_scoped_bot_without_channel_access_is_denied().await;
+}
+
+#[tokio::test]
+async fn public_channel_does_not_grant_non_participating_bot_access() {
+ assert_team_scoped_bot_without_channel_access_is_denied().await;
+}
+
+#[tokio::test]
+async fn departed_bot_participant_is_denied_channel_access() {
+ assert_team_scoped_bot_without_channel_access_is_denied().await;
+}
+
+#[tokio::test]
+async fn team_channel_view_only_access_does_not_satisfy_member_requirement() {
+ let state = TestState::with_bot_permission(EntityPermission::ChannelViewOnly);
let response = app(state.clone(), member_handler)
- .oneshot(request)
+ .oneshot(bot_request(BotScope::Team))
.await
.expect("request should complete");
- assert_eq!(response.status(), StatusCode::FORBIDDEN);
- let body = to_bytes(response.into_body(), usize::MAX)
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ vec![expected_team_bot_call()]
+ );
+}
+
+#[tokio::test]
+async fn bot_member_role_does_not_satisfy_admin_requirement() {
+ let state = TestState::with_bot_permission(EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ });
+ let response = app(state.clone(), admin_handler)
+ .oneshot(bot_request(BotScope::Team))
.await
- .expect("response body should be readable");
- assert_eq!(body.as_ref(), br#"{"message":"forbidden"}"#);
- assert!(state.entity_access.calls().is_empty());
+ .expect("request should complete");
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ vec![expected_team_bot_call()]
+ );
}
#[tokio::test]
diff --git a/crates/entity_access/src/inbound/axum_extractors/chat.rs b/crates/entity_access/src/inbound/axum_extractors/chat.rs
index da40fc1f4f..21cb2babdd 100644
--- a/crates/entity_access/src/inbound/axum_extractors/chat.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/chat.rs
@@ -12,11 +12,11 @@ use axum::{
http::request::Parts,
};
use macro_authorization::{
- MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOrInternalService, UserOrInternalServiceAuthorization,
+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor,
};
-use super::{ExtractorError, RequiredPermission};
+use super::{ExtractorError, RequiredPermission, bot::generate_bot_entity_access_receipt};
use crate::domain::{
models::{
AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -57,26 +57,54 @@ where
let service = <Arc<Svc>>::from_ref(state);
let authorization =
- OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ OptionalMacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(
parts, state,
)
.await
- .map_err(ExtractorError::from)?;
- let is_internal_access = authorization
- .authorization
- .as_ref()
- .is_some_and(UserOrInternalServiceAuthorization::is_internal);
- let macro_user_id = authorization
- .authorization
- .as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
- .map(|user| user.macro_user_id.clone());
+ .map_err(ExtractorError::from)?
+ .authorization;
let chat_context: Extension<ChatBasic> = parts
.extract()
.await
.map_err(|_| ExtractorError::Internal)?;
+ if let Some(MacroAuthorization::Bot(authentication)) = authorization.as_ref() {
+ let receipt = generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ authentication,
+ &chat_context.id,
+ EntityType::Chat,
+ )
+ .await?;
+
+ if chat_context.deleted_at.is_some()
+ && !matches!(
+ receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner
+ }
+ )
+ {
+ return Err(ExtractorError::UnauthorizedWithMessage(
+ "only owner can access deleted resource",
+ ));
+ }
+
+ return Ok(Self {
+ entity_access_receipt: receipt,
+ _marker: PhantomData,
+ });
+ }
+
+ let is_internal_access = authorization
+ .as_ref()
+ .is_some_and(MacroAuthorization::is_internal);
+ let macro_user_id = authorization
+ .as_ref()
+ .and_then(MacroAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone());
+
if macro_user_id.is_none() && is_internal_access {
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
@@ -94,7 +122,7 @@ where
});
}
- // Check ownership only if authenticated
+ // Bots always resolve ownership through the scoped domain policy.
if let Some(ref user_id) = macro_user_id
&& chat_context.user_id == *user_id
{
diff --git a/crates/entity_access/src/inbound/axum_extractors/chat/test.rs b/crates/entity_access/src/inbound/axum_extractors/chat/test.rs
index a3872e15ea..7af6475a74 100644
--- a/crates/entity_access/src/inbound/axum_extractors/chat/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/chat/test.rs
@@ -1,5 +1,4 @@
-use crate::domain::models::TeamRole;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use axum::{
body::{Body, to_bytes},
@@ -12,22 +11,19 @@ use macro_authorization::{
INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
-use macro_user_id::{
- lowercased::Lowercase,
- user_id::{MacroUserId, MacroUserIdStr},
-};
+use macro_user_id::user_id::MacroUserIdStr;
use model::chat::ChatBasic;
use model_user::UserContext;
use rootcause::Report;
-use uuid::Uuid;
use super::*;
use crate::{
- domain::models::{
- AccessError, BotId, CallChannelInfo, EditAccessLevel, EntityAccessAuth, UserTeamInfo,
- ViewAccessLevel,
+ domain::models::{BotAccessScope, EditAccessLevel, EntityAccessAuth, ViewAccessLevel},
+ inbound::axum_extractors::test_support::{
+ BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID, BotAccessCall,
+ FakeEntityAccessService, MALFORMED_SYSTEM_BOT_TOKEN, VALID_BOT_TOKEN,
+ malformed_system_bot_authentication, valid_bot_authentication,
},
- inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
};
const CHAT_ID: &str = "chat-1";
@@ -37,137 +33,6 @@ const ACT_AS_ID: &str = "macro|[email protected]";
const DEFAULT_INTERNAL_ID: &str = "macro|[email protected]";
const INTERNAL_KEY: &str = "valid-internal-key";
-#[derive(Clone, Debug, Eq, PartialEq)]
-struct AccessCall {
- user_id: Option<String>,
- entity_id: String,
- entity_type: EntityType,
-}
-
-#[derive(Clone, Debug)]
-struct FakeEntityAccessService {
- access_level: Option<AccessLevel>,
- calls: Arc<Mutex<Vec<AccessCall>>>,
-}
-
-impl FakeEntityAccessService {
- fn new(access_level: Option<AccessLevel>) -> Self {
- Self {
- access_level,
- calls: Arc::new(Mutex::new(Vec::new())),
- }
- }
-
- fn calls(&self) -> Vec<AccessCall> {
- self.calls.lock().expect("calls lock poisoned").clone()
- }
-}
-
-impl EntityAccessService for FakeEntityAccessService {
- async fn generate_entity_access_receipt<T: RequiredPermission>(
- &self,
- _user_id: &MacroUserId<Lowercase<'_>>,
- _user_org_id: Option<i64>,
- _entity_id: &str,
- _entity_type: EntityType,
- ) -> Result<EntityAccessReceipt<T>, AccessError> {
- panic!("unexpected generate_entity_access_receipt call")
- }
-
- async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
- &self,
- _bot_id: BotId,
- _entity_id: &str,
- _entity_type: EntityType,
- ) -> Result<EntityAccessReceipt<T>, AccessError> {
- panic!("unexpected generate_bot_entity_access_receipt call")
- }
-
- async fn get_access_level(
- &self,
- user_id: Option<&MacroUserId<Lowercase<'_>>>,
- entity_id: &str,
- entity_type: EntityType,
- ) -> Result<Option<AccessLevel>, AccessError> {
- self.calls
- .lock()
- .expect("calls lock poisoned")
- .push(AccessCall {
- user_id: user_id.map(|id| id.as_ref().to_string()),
- entity_id: entity_id.to_string(),
- entity_type,
- });
- Ok(self.access_level)
- }
-
- async fn check_access(
- &self,
- _user_id: Option<&MacroUserId<Lowercase<'_>>>,
- _entity_id: &str,
- _entity_type: EntityType,
- _required_level: AccessLevel,
- ) -> Result<AccessLevel, AccessError> {
- panic!("unexpected check_access call")
- }
-
- async fn check_public_access(
- &self,
- _entity_id: &str,
- _entity_type: EntityType,
- _required_level: AccessLevel,
- ) -> Result<AccessLevel, AccessError> {
- panic!("unexpected check_public_access call")
- }
-
- async fn get_entity_permission(
- &self,
- _user_id: Option<&MacroUserId<Lowercase<'_>>>,
- _entity_id: &str,
- _entity_type: EntityType,
- _user_org_id: Option<i64>,
- ) -> Result<EntityPermission, AccessError> {
- panic!("unexpected get_entity_permission call")
- }
-
- async fn get_crm_entity_permission_with_team(
- &self,
- _user_id: Option<&MacroUserId<Lowercase<'_>>>,
- _entity_id: &str,
- _entity_type: EntityType,
- ) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {
- panic!("unexpected get_crm_entity_permission_with_team call")
- }
-
- async fn get_users_by_entity(
- &self,
- _entity_id: &str,
- _entity_type: EntityType,
- ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
- panic!("unexpected get_users_by_entity call")
- }
-
- async fn get_call_channel(
- &self,
- _call_id: &Uuid,
- ) -> Result<Option<CallChannelInfo>, AccessError> {
- panic!("unexpected get_call_channel call")
- }
-
- async fn get_call_channel_by_channel_id(
- &self,
- _channel_id: &Uuid,
- ) -> Result<Option<CallChannelInfo>, AccessError> {
- panic!("unexpected get_call_channel_by_channel_id call")
- }
-
- async fn get_user_team(
- &self,
- _user_id: &MacroUserId<Lowercase<'_>>,
- ) -> Result<Option<UserTeamInfo>, AccessError> {
- panic!("unexpected get_user_team call")
- }
-}
-
#[derive(Clone, Debug, Default)]
struct FakeAuthorizationService {
default_internal_user_id: Option<String>,
@@ -197,11 +62,11 @@ impl MacroAuthorizationService for FakeAuthorizationService {
bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
- if token != VALID_BOT_TOKEN {
- return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ match token {
+ VALID_BOT_TOKEN => Ok(valid_bot_authentication(bot_scope)),
+ MALFORMED_SYSTEM_BOT_TOKEN => Ok(malformed_system_bot_authentication(bot_scope)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
}
-
- Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -239,6 +104,17 @@ impl TestState {
authorization: MacroAuthorizationState::new(Arc::new(authorization)),
}
}
+
+ fn with_bot_permission(permission: EntityPermission) -> Self {
+ Self {
+ entity_access: Arc::new(
+ FakeEntityAccessService::new(None).with_bot_permission(permission),
+ ),
+ authorization: MacroAuthorizationState::new(Arc::new(
+ FakeAuthorizationService::default(),
+ )),
+ }
+ }
}
impl FromRef<TestState> for Arc<FakeEntityAccessService> {
@@ -263,10 +139,14 @@ fn user_context(user_id: &str) -> UserContext {
}
fn chat(deleted: bool) -> ChatBasic {
+ chat_owned_by(OWNER_ID, deleted)
+}
+
+fn chat_owned_by(owner_id: &str, deleted: bool) -> ChatBasic {
ChatBasic {
id: CHAT_ID.to_string(),
name: "Test chat".to_string(),
- user_id: MacroUserIdStr::parse_from_str(OWNER_ID).expect("owner id should be valid"),
+ user_id: MacroUserIdStr::try_from(owner_id.to_string()).expect("owner id should be valid"),
project_id: None,
deleted_at: deleted.then(|| {
"2026-01-01T00:00:00Z"
@@ -290,6 +170,19 @@ fn request(token: Option<&str>, chat: ChatBasic) -> Request<Body> {
request
}
+fn bot_request(token: &str, scope: BotScope, chat: ChatBasic) -> Request<Body> {
+ let mut request = request(None, chat);
+ request.headers_mut().insert(
+ BOT_TOKEN_HEADER,
+ token.parse().expect("bot token should be valid"),
+ );
+ request.headers_mut().insert(
+ BOT_SCOPE_HEADER,
+ scope.as_str().parse().expect("bot scope should be valid"),
+ );
+ request
+}
+
fn internal_request(user_id: Option<&str>, chat: ChatBasic) -> Request<Body> {
let mut request = request(None, chat);
request.headers_mut().insert(
@@ -448,33 +341,176 @@ async fn invalid_internal_credentials_are_rejected_without_acl_lookup() {
}
#[tokio::test]
-async fn bot_credentials_are_forbidden_without_acl_lookup() {
- let state = TestState::new(Some(AccessLevel::Owner));
- let mut request = request(None, chat(false));
- request.headers_mut().insert(
- BOT_TOKEN_HEADER,
- VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
+async fn user_scoped_bot_uses_acting_user_scope() {
+ let state = TestState::with_bot_permission(EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ });
+ let extracted = extract::<EditAccessLevel>(
+ bot_request(VALID_BOT_TOKEN, BotScope::User, chat(false)),
+ &state,
+ )
+ .await
+ .expect("user-scoped bot should receive its scoped access");
+
+ assert_eq!(
+ extracted
+ .entity_access_receipt
+ .acting_user_id()
+ .unwrap()
+ .as_ref(),
+ BOT_ACTING_USER_ID
);
- request.headers_mut().insert(
- BOT_SCOPE_HEADER,
- BotScope::User
- .as_str()
- .parse()
- .expect("bot scope should be valid"),
+ assert_eq!(
+ extracted
+ .entity_access_receipt
+ .get_authenticated_bot()
+ .unwrap()
+ .bot_id(),
+ BOT_ID
);
- let error = extract::<ViewAccessLevel>(request, &state)
- .await
- .expect_err("bot credentials should be forbidden");
- let response = error.into_response();
+ let bot_calls = state.entity_access.bot_calls();
+ assert_eq!(bot_calls.len(), 1);
+ assert!(matches!(
+ &bot_calls[0],
+ BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::User {
+ user_id,
+ user_org_id: Some(user_org_id),
+ },
+ entity_id,
+ entity_type: EntityType::Chat,
+ } if user_id.as_ref() == BOT_ACTING_USER_ID
+ && *user_org_id == i64::from(BOT_ACTING_USER_ORGANIZATION_ID)
+ && entity_id == CHAT_ID
+ ));
+ assert!(state.entity_access.calls().is_empty());
+}
- assert_eq!(response.status(), StatusCode::FORBIDDEN);
- let body = to_bytes(response.into_body(), usize::MAX)
- .await
- .expect("response body should be readable");
- assert_eq!(body.as_ref(), br#"{"message":"forbidden"}"#);
+#[tokio::test]
+async fn team_scoped_bot_uses_team_scope() {
+ let state = TestState::with_bot_permission(EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ });
+ let extracted = extract::<ViewAccessLevel>(
+ bot_request(VALID_BOT_TOKEN, BotScope::Team, chat(false)),
+ &state,
+ )
+ .await
+ .expect("team-scoped bot should receive its scoped access");
+
+ assert!(matches!(
+ extracted.entity_access_receipt.auth(),
+ EntityAccessAuth::Bot(_)
+ ));
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: CHAT_ID.to_string(),
+ entity_type: EntityType::Chat,
+ }]
+ );
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn user_scoped_bot_without_acting_user_is_rejected() {
+ let state = TestState::with_bot_permission(EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ });
+ let error = extract::<ViewAccessLevel>(
+ bot_request(MALFORMED_SYSTEM_BOT_TOKEN, BotScope::User, chat(false)),
+ &state,
+ )
+ .await
+ .expect_err("user-scoped bot without an acting user should fail");
+
+ assert!(matches!(
+ &error,
+ ExtractorError::UnauthorizedWithMessage("bot user scope requires an acting user")
+ ));
+ assert_eq!(error.into_response().status(), StatusCode::UNAUTHORIZED);
+ assert!(state.entity_access.bot_calls().is_empty());
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn bot_with_insufficient_permission_is_rejected() {
+ let state = TestState::with_bot_permission(EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ });
+ let result = extract::<EditAccessLevel>(
+ bot_request(VALID_BOT_TOKEN, BotScope::Team, chat(false)),
+ &state,
+ )
+ .await;
+
+ assert!(matches!(result, Err(ExtractorError::Unauthorized)));
+ assert_eq!(state.entity_access.bot_calls().len(), 1);
assert!(state.entity_access.calls().is_empty());
}
+#[tokio::test]
+async fn acting_owner_bot_still_uses_scoped_policy() {
+ let state = TestState::with_bot_permission(EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ });
+ let extracted = extract::<EditAccessLevel>(
+ bot_request(
+ VALID_BOT_TOKEN,
+ BotScope::User,
+ chat_owned_by(BOT_ACTING_USER_ID, false),
+ ),
+ &state,
+ )
+ .await
+ .expect("acting owner should receive the permission returned by scoped policy");
+
+ assert!(matches!(
+ extracted.entity_access_receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner
+ }
+ ));
+ assert_eq!(state.entity_access.bot_calls().len(), 1);
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn deleted_chat_requires_owner_permission_from_bot_policy() {
+ let owner_state = TestState::with_bot_permission(EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ });
+ extract::<ViewAccessLevel>(
+ bot_request(VALID_BOT_TOKEN, BotScope::Team, chat(true)),
+ &owner_state,
+ )
+ .await
+ .expect("bot with owner permission should access a deleted chat");
+ assert_eq!(owner_state.entity_access.bot_calls().len(), 1);
+
+ let non_owner_state = TestState::with_bot_permission(EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ });
+ let result = extract::<ViewAccessLevel>(
+ bot_request(VALID_BOT_TOKEN, BotScope::Team, chat(true)),
+ &non_owner_state,
+ )
+ .await;
+
+ assert!(matches!(
+ result,
+ Err(ExtractorError::UnauthorizedWithMessage(
+ "only owner can access deleted resource"
+ ))
+ ));
+ assert_eq!(non_owner_state.entity_access.bot_calls().len(), 1);
+}
+
#[tokio::test]
async fn expired_token_preserves_exact_unauthorized_json() {
let state = TestState::new(Some(AccessLevel::Owner));
diff --git a/crates/entity_access/src/inbound/axum_extractors/document.rs b/crates/entity_access/src/inbound/axum_extractors/document.rs
index d1fcb1ddc7..231f5fc075 100644
--- a/crates/entity_access/src/inbound/axum_extractors/document.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/document.rs
@@ -12,11 +12,11 @@ use axum::{
http::request::Parts,
};
use macro_authorization::{
- MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOrInternalService, UserOrInternalServiceAuthorization,
+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor,
};
-use super::{ExtractorError, RequiredPermission};
+use super::{ExtractorError, RequiredPermission, bot::generate_bot_entity_access_receipt};
use crate::domain::{
models::{
AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -57,26 +57,55 @@ where
let service = <Arc<Svc>>::from_ref(state);
let authorization =
- OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ OptionalMacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(
parts, state,
)
.await
.map_err(ExtractorError::from)?;
+
+ let document_context: Extension<DocumentBasic> = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?;
+
+ if let Some(MacroAuthorization::Bot(authentication)) = &authorization.authorization {
+ let entity_access_receipt = generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ authentication,
+ &document_context.document_id,
+ EntityType::Document,
+ )
+ .await?;
+
+ if document_context.deleted_at.is_some()
+ && !matches!(
+ entity_access_receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner
+ }
+ )
+ {
+ return Err(ExtractorError::UnauthorizedWithMessage(
+ "only owner can access deleted resource",
+ ));
+ }
+
+ return Ok(Self {
+ entity_access_receipt,
+ _marker: PhantomData,
+ });
+ }
+
let is_internal_access = authorization
.authorization
.as_ref()
- .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ .is_some_and(MacroAuthorization::is_internal);
let macro_user_id = authorization
.authorization
.as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .and_then(MacroAuthorization::acting_user)
.map(|user| user.macro_user_id.clone());
- let document_context: Extension<DocumentBasic> = parts
- .extract()
- .await
- .map_err(|_| ExtractorError::Internal)?;
-
if macro_user_id.is_none() && is_internal_access {
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
diff --git a/crates/entity_access/src/inbound/axum_extractors/document/test.rs b/crates/entity_access/src/inbound/axum_extractors/document/test.rs
index 0052bbabbb..74185b9905 100644
--- a/crates/entity_access/src/inbound/axum_extractors/document/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/document/test.rs
@@ -1,6 +1,17 @@
-use crate::domain::models::TeamRole;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
+use super::*;
+use crate::{
+ domain::models::{
+ BotAccessScope, BotReceiptScope, EditAccessLevel, EntityAccessAuth, ViewAccessLevel,
+ },
+ inbound::axum_extractors::test_support::{
+ BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID, BotAccessCall,
+ FakeEntityAccessService, MALFORMED_SYSTEM_BOT_TOKEN, VALID_BOT_TOKEN,
+ malformed_system_bot_authentication, user_scoped_bot_authentication,
+ valid_bot_authentication,
+ },
+};
use axum::{
body::{Body, to_bytes},
extract::{FromRef, FromRequestParts},
@@ -16,23 +27,10 @@ use macro_authorization::{
use macro_authorization::{
LEGACY_DSS_INTERNAL_API_KEY_HEADER, LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER,
};
-use macro_user_id::{
- lowercased::Lowercase,
- user_id::{MacroUserId, MacroUserIdStr},
-};
+use macro_user_id::user_id::MacroUserIdStr;
use model::document::DocumentBasic;
use model_user::UserContext;
use rootcause::Report;
-use uuid::Uuid;
-
-use super::*;
-use crate::{
- domain::models::{
- AccessError, BotId, CallChannelInfo, EditAccessLevel, EntityAccessAuth, UserTeamInfo,
- ViewAccessLevel,
- },
- inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
-};
const DOCUMENT_ID: &str = "document-1";
const OWNER_ID: &str = "macro|[email protected]";
@@ -41,137 +39,7 @@ const STANDARD_ACT_AS_ID: &str = "macro|[email protected]";
const LEGACY_ACT_AS_ID: &str = "macro|[email protected]";
const DEFAULT_INTERNAL_ID: &str = "macro|[email protected]";
const INTERNAL_KEY: &str = "valid-internal-key";
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-struct AccessCall {
- user_id: Option<String>,
- entity_id: String,
- entity_type: EntityType,
-}
-
-#[derive(Clone, Debug)]
-struct FakeEntityAccessService {
- access_level: Option<AccessLevel>,
- calls: Arc<Mutex<Vec<AccessCall>>>,
-}
-
-impl FakeEntityAccessService {
- fn new(access_level: Option<AccessLevel>) -> Self {
- Self {
- access_level,
- calls: Arc::new(Mutex::new(Vec::new())),
- }
- }
-
- fn calls(&self) -> Vec<AccessCall> {
- self.calls.lock().expect("calls lock poisoned").clone()
- }
-}
-
-impl EntityAccessService for FakeEntityAccessService {
- async fn generate_entity_access_receipt<T: RequiredPermission>(
- &self,
- _user_id: &MacroUserId<Lowercase<'_>>,
- _user_org_id: Option<i64>,
- _entity_id: &str,
- _entity_type: EntityType,
- ) -> Result<EntityAccessReceipt<T>, AccessError> {
- panic!("unexpected generate_entity_access_receipt call")
- }
-
- async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
- &self,
- _bot_id: BotId,
- _entity_id: &str,
- _entity_type: EntityType,
- ) -> Result<EntityAccessReceipt<T>, AccessError> {
- panic!("unexpected generate_bot_entity_access_receipt call")
- }
-
- async fn get_access_level(
- &self,
- user_id: Option<&MacroUserId<Lowercase<'_>>>,
- entity_id: &str,
- entity_type: EntityType,
- ) -> Result<Option<AccessLevel>, AccessError> {
- self.calls
- .lock()
- .expect("calls lock poisoned")
- .push(AccessCall {
- user_id: user_id.map(|id| id.as_ref().to_string()),
- entity_id: entity_id.to_string(),
- entity_type,
- });
- Ok(self.access_level)
- }
-
- async fn check_access(
- &self,
- _user_id: Option<&MacroUserId<Lowercase<'_>>>,
- _entity_id: &str,
- _entity_type: EntityType,
- _required_level: AccessLevel,
- ) -> Result<AccessLevel, AccessError> {
- panic!("unexpected check_access call")
- }
-
- async fn check_public_access(
- &self,
- _entity_id: &str,
- _entity_type: EntityType,
- _required_level: AccessLevel,
- ) -> Result<AccessLevel, AccessError> {
- panic!("unexpected check_public_access call")
- }
-
- async fn get_entity_permission(
- &self,
- _user_id: Option<&MacroUserId<Lowercase<'_>>>,
- _entity_id: &str,
- _entity_type: EntityType,
- _user_org_id: Option<i64>,
- ) -> Result<EntityPermission, AccessError> {
- panic!("unexpected get_entity_permission call")
- }
-
- async fn get_crm_entity_permission_with_team(
- &self,
- _user_id: Option<&MacroUserId<Lowercase<'_>>>,
- _entity_id: &str,
- _entity_type: EntityType,
- ) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {
- panic!("unexpected get_crm_entity_permission_with_team call")
- }
-
- async fn get_users_by_entity(
- &self,
- _entity_id: &str,
- _entity_type: EntityType,
- ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
- panic!("unexpected get_users_by_entity call")
- }
-
- async fn get_call_channel(
- &self,
- _call_id: &Uuid,
- ) -> Result<Option<CallChannelInfo>, AccessError> {
- panic!("unexpected get_call_channel call")
- }
-
- async fn get_call_channel_by_channel_id(
- &self,
- _channel_id: &Uuid,
- ) -> Result<Option<CallChannelInfo>, AccessError> {
- panic!("unexpected get_call_channel_by_channel_id call")
- }
-
- async fn get_user_team(
- &self,
- _user_id: &MacroUserId<Lowercase<'_>>,
- ) -> Result<Option<UserTeamInfo>, AccessError> {
- panic!("unexpected get_user_team call")
- }
-}
+const OWNER_ACTING_BOT_TOKEN: &str = "owner-acting-bot-token";
#[derive(Clone, Debug, Default)]
struct FakeAuthorizationService {
@@ -202,11 +70,12 @@ impl MacroAuthorizationService for FakeAuthorizationService {
bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
- if token != VALID_BOT_TOKEN {
- return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ match token {
+ VALID_BOT_TOKEN => Ok(valid_bot_authentication(bot_scope)),
+ MALFORMED_SYSTEM_BOT_TOKEN => Ok(malformed_system_bot_authentication(bot_scope)),
+ OWNER_ACTING_BOT_TOKEN => Ok(owner_scoped_bot_authentication()),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
}
-
- Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -238,9 +107,23 @@ impl TestState {
fn with_authorization(
access_level: Option<AccessLevel>,
authorization: FakeAuthorizationService,
+ ) -> Self {
+ Self::with_service_and_authorization(
+ FakeEntityAccessService::new(access_level),
+ authorization,
+ )
+ }
+
+ fn with_service(entity_access: FakeEntityAccessService) -> Self {
+ Self::with_service_and_authorization(entity_access, FakeAuthorizationService::default())
+ }
+
+ fn with_service_and_authorization(
+ entity_access: FakeEntityAccessService,
+ authorization: FakeAuthorizationService,
) -> Self {
Self {
- entity_access: Arc::new(FakeEntityAccessService::new(access_level)),
+ entity_access: Arc::new(entity_access),
authorization: MacroAuthorizationState::new(Arc::new(authorization)),
}
}
@@ -267,6 +150,18 @@ fn user_context(user_id: &str) -> UserContext {
}
}
+fn owner_scoped_bot_authentication() -> BotAuthentication {
+ let mut authentication = user_scoped_bot_authentication();
+ let acting_user = authentication
+ .acting_user
+ .as_mut()
+ .expect("user-scoped bot should have an acting user");
+ acting_user.macro_user_id =
+ MacroUserIdStr::parse_from_str(OWNER_ID).expect("owner id should be valid");
+ acting_user.user_context = user_context(OWNER_ID);
+ authentication
+}
+
fn document(deleted: bool) -> DocumentBasic {
let mut document = DocumentBasic {
document_id: DOCUMENT_ID.to_string(),
@@ -304,6 +199,22 @@ fn request(token: Option<&str>, document: DocumentBasic) -> Request<Body> {
request
}
+fn bot_request(bot_scope: BotScope, token: &str, document: DocumentBasic) -> Request<Body> {
+ let mut request = request(None, document);
+ request.headers_mut().insert(
+ BOT_TOKEN_HEADER,
+ token.parse().expect("bot token should be valid"),
+ );
+ request.headers_mut().insert(
+ BOT_SCOPE_HEADER,
+ bot_scope
+ .as_str()
+ .parse()
+ .expect("bot scope should be valid"),
+ );
+ request
+}
+
fn internal_request(
key_header: &'static str,
user_header: Option<&'static str>,
@@ -504,33 +415,199 @@ async fn invalid_internal_credentials_are_rejected_without_acl_lookup() {
}
#[tokio::test]
-async fn bot_credentials_are_forbidden_without_acl_lookup() {
- let state = TestState::new(Some(AccessLevel::Owner));
- let mut request = request(None, document(false));
- request.headers_mut().insert(
- BOT_TOKEN_HEADER,
- VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
+async fn user_scoped_bot_uses_acting_user_scope() {
+ let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ },
+ ));
+
+ let extracted = extract::<ViewAccessLevel>(
+ bot_request(BotScope::User, VALID_BOT_TOKEN, document(false)),
+ &state,
+ )
+ .await
+ .expect("user-scoped bot should use its delegated access");
+
+ assert_eq!(
+ extracted
+ .entity_access_receipt
+ .get_authenticated_bot()
+ .expect("receipt should authenticate a bot")
+ .bot_id(),
+ BOT_ID
);
- request.headers_mut().insert(
- BOT_SCOPE_HEADER,
- BotScope::User
- .as_str()
- .parse()
- .expect("bot scope should be valid"),
+ assert_eq!(
+ extracted
+ .entity_access_receipt
+ .get_authenticated_bot_auth()
+ .expect("receipt should retain bot scope")
+ .scope(),
+ &BotReceiptScope::User {
+ acting_user: MacroUserIdStr::parse_from_str(BOT_ACTING_USER_ID)
+ .expect("acting user id should be valid"),
+ }
);
- let error = extract::<ViewAccessLevel>(request, &state)
- .await
- .expect_err("bot credentials should be forbidden");
- let response = error.into_response();
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::User {
+ user_id: MacroUserIdStr::parse_from_str(BOT_ACTING_USER_ID)
+ .expect("acting user id should be valid"),
+ user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
+ },
+ entity_id: DOCUMENT_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+ assert!(state.entity_access.calls().is_empty());
+}
- assert_eq!(response.status(), StatusCode::FORBIDDEN);
- let body = to_bytes(response.into_body(), usize::MAX)
- .await
- .expect("response body should be readable");
- assert_eq!(body.as_ref(), br#"{"message":"forbidden"}"#);
+#[tokio::test]
+async fn team_scoped_bot_uses_owning_team_scope() {
+ let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ },
+ ));
+
+ let extracted = extract::<EditAccessLevel>(
+ bot_request(BotScope::Team, VALID_BOT_TOKEN, document(false)),
+ &state,
+ )
+ .await
+ .expect("team-scoped bot should use its team access");
+
+ assert_eq!(
+ extracted
+ .entity_access_receipt
+ .get_authenticated_bot_auth()
+ .expect("receipt should retain bot scope")
+ .scope(),
+ &BotReceiptScope::Team {
+ team_id: BOT_TEAM_ID,
+ }
+ );
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: DOCUMENT_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn user_scoped_bot_without_acting_user_is_rejected_before_acl_lookup() {
+ let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ ));
+
+ let error = extract::<ViewAccessLevel>(
+ bot_request(BotScope::User, MALFORMED_SYSTEM_BOT_TOKEN, document(false)),
+ &state,
+ )
+ .await
+ .expect_err("user scope should require an acting user");
+
+ assert!(matches!(
+ error,
+ ExtractorError::UnauthorizedWithMessage("bot user scope requires an acting user")
+ ));
+ assert!(state.entity_access.bot_calls().is_empty());
assert!(state.entity_access.calls().is_empty());
}
+#[tokio::test]
+async fn bot_receipt_must_satisfy_the_required_access_level() {
+ let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ },
+ ));
+
+ let result = extract::<EditAccessLevel>(
+ bot_request(BotScope::Team, VALID_BOT_TOKEN, document(false)),
+ &state,
+ )
+ .await;
+
+ assert!(matches!(result, Err(ExtractorError::Unauthorized)));
+ assert_eq!(state.entity_access.bot_calls().len(), 1);
+}
+
+#[tokio::test]
+async fn bot_acting_as_document_owner_still_uses_scoped_service() {
+ let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ ));
+
+ let extracted = extract::<EditAccessLevel>(
+ bot_request(BotScope::User, OWNER_ACTING_BOT_TOKEN, document(false)),
+ &state,
+ )
+ .await
+ .expect("the scoped service should delegate owner access");
+
+ assert!(matches!(
+ extracted.entity_access_receipt.auth(),
+ EntityAccessAuth::Bot(_)
+ ));
+ assert_eq!(state.entity_access.bot_calls().len(), 1);
+ assert!(state.entity_access.calls().is_empty());
+ assert_eq!(
+ state.entity_access.bot_calls()[0].scope,
+ BotAccessScope::User {
+ user_id: MacroUserIdStr::parse_from_str(OWNER_ID).expect("owner id should be valid"),
+ user_org_id: None,
+ }
+ );
+}
+
+#[tokio::test]
+async fn deleted_document_requires_owner_permission_from_scoped_service() {
+ let owner_state = TestState::with_service(
+ FakeEntityAccessService::new(None).with_bot_permission(EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ }),
+ );
+ extract::<EditAccessLevel>(
+ bot_request(BotScope::Team, VALID_BOT_TOKEN, document(true)),
+ &owner_state,
+ )
+ .await
+ .expect("owner permission should allow deleted document access");
+ assert_eq!(owner_state.entity_access.bot_calls().len(), 1);
+
+ let edit_state = TestState::with_service(
+ FakeEntityAccessService::new(None).with_bot_permission(EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ }),
+ );
+ let result = extract::<ViewAccessLevel>(
+ bot_request(BotScope::Team, VALID_BOT_TOKEN, document(true)),
+ &edit_state,
+ )
+ .await;
+
+ assert!(matches!(
+ result,
+ Err(ExtractorError::UnauthorizedWithMessage(
+ "only owner can access deleted resource"
+ ))
+ ));
+ assert_eq!(edit_state.entity_access.bot_calls().len(), 1);
+}
+
#[tokio::test]
async fn expired_token_preserves_exact_unauthorized_json() {
let state = TestState::new(Some(AccessLevel::Owner));
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_body.rs b/crates/entity_access/src/inbound/axum_extractors/entity_body.rs
index 9d83e2396b..c701726737 100644
--- a/crates/entity_access/src/inbound/axum_extractors/entity_body.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_body.rs
@@ -10,12 +10,12 @@ use axum::{
extract::{FromRef, FromRequest, Request},
};
use macro_authorization::{
- MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOrInternalService, UserOrInternalServiceAuthorization,
+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor,
};
use serde::{Deserialize, de::DeserializeOwned};
-use super::{ExtractorError, RequiredPermission};
+use super::{ExtractorError, RequiredPermission, bot::generate_bot_entity_access_receipt};
use crate::domain::{
models::{Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType},
ports::EntityAccessService,
@@ -28,7 +28,7 @@ struct EntityBodyFields {
entity_id: String,
}
-/// Validates that an authenticated user has access to an entity identified in the request body.
+/// Validates that an authenticated principal has access to an entity identified in the request body.
///
/// Type parameter `T` specifies the required access level, `Svc` is the entity access service,
/// `V` is the typed request body, and `Auth` is the authorization service. This extractor consumes
@@ -49,7 +49,7 @@ where
Svc: EntityAccessService,
MacroAuthorizationState<Auth>: FromRef<S>,
Auth: MacroAuthorizationService,
- V: DeserializeOwned,
+ V: DeserializeOwned + Send,
S: Send + Sync + 'static,
{
type Rejection = ExtractorError;
@@ -57,19 +57,18 @@ where
#[tracing::instrument(err, skip(req, state))]
async fn from_request(mut req: Request, state: &S) -> Result<Self, Self::Rejection> {
let authorization = req
- .extract_parts_with_state::<
- OptionalMacroAuthorizationExtractor<Auth, UserOrInternalService>,
- _,
- >(state)
+ .extract_parts_with_state::<OptionalMacroAuthorizationExtractor<Auth, AnyPrincipal>, _>(
+ state,
+ )
.await
- .map_err(ExtractorError::from)?;
- let user = authorization
+ .map_err(ExtractorError::from)?
.authorization
- .as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
- .map(|user| user.macro_user_id.clone())
.ok_or(ExtractorError::Unauthorized)?;
+ if matches!(authorization, MacroAuthorization::Internal(None)) {
+ return Err(ExtractorError::Unauthorized);
+ }
+
let Json(json): Json<serde_json::Value> = req
.extract()
.await
@@ -81,6 +80,31 @@ where
.map_err(|_| ExtractorError::BadRequest("Invalid entity body"))?;
let service = Arc::<Svc>::from_ref(state);
+ if let MacroAuthorization::Bot(authentication) = &authorization {
+ let inner = deserialize_body(json)?;
+ let entity_access_receipt = generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ authentication,
+ &entity_id,
+ entity_type,
+ )
+ .await?;
+
+ return Ok(Self {
+ entity_access_receipt,
+ inner,
+ _marker: PhantomData,
+ });
+ }
+
+ let user = match authorization {
+ MacroAuthorization::User(user) | MacroAuthorization::Internal(Some(user)) => {
+ user.macro_user_id
+ }
+ MacroAuthorization::Bot(_) | MacroAuthorization::Internal(None) => {
+ unreachable!("bot and identity-less internal access returned above")
+ }
+ };
let access_level = service
.get_access_level(Some(&user), &entity_id, entity_type)
.await
@@ -101,9 +125,12 @@ where
entity_permission,
_marker: PhantomData,
},
- inner: serde_json::from_value(json)
- .map_err(|_| ExtractorError::BadRequest("Invalid request body"))?,
+ inner: deserialize_body(json)?,
_marker: PhantomData,
})
}
}
+
+fn deserialize_body<V: DeserializeOwned>(json: serde_json::Value) -> Result<V, ExtractorError> {
+ serde_json::from_value(json).map_err(|_| ExtractorError::BadRequest("Invalid request body"))
+}
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs b/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs
index 4ae7fe45d6..74af44ba20 100644
--- a/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs
@@ -5,17 +5,21 @@ use axum::{
routing::post,
};
use macro_authorization::{
- BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotScope, INTERNAL_API_KEY_HEADER,
+ INTERNAL_MACRO_USER_ID_HEADER,
};
use serde::Deserialize;
use tower::ServiceExt;
use super::*;
use crate::{
- domain::models::{AccessLevel, EditAccessLevel, EntityAccessAuth, EntityType, ViewAccessLevel},
+ domain::models::{
+ AccessLevel, BotAccessScope, EditAccessLevel, EntityAccessAuth, EntityType, ViewAccessLevel,
+ },
inbound::axum_extractors::test_support::{
- AccessCall, FakeAuthorizationService, FakeEntityAccessService, INTERNAL_KEY, TestState,
- USER_ID, VALID_BOT_TOKEN,
+ AccessCall, BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID,
+ BotAccessCall, FakeAuthorizationService, FakeEntityAccessService, INTERNAL_KEY,
+ MALFORMED_SYSTEM_BOT_TOKEN, TestState, USER_ID, VALID_BOT_TOKEN,
},
};
@@ -174,21 +178,95 @@ async fn identity_less_internal_access_is_rejected_before_body_and_acl_lookup()
}
#[tokio::test]
-async fn bot_access_is_forbidden_before_body_and_acl_lookup() {
- let state = TestState::new(Some(AccessLevel::Owner));
+async fn user_scoped_bot_access_uses_the_acting_users_scope_and_preserves_the_typed_body() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
+ .body(body("document", ENTITY_ID))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ response_body(response).await,
+ "bot:document:entity-1:document:entity-1:7"
+ );
+ let calls = state.entity_access.bot_calls();
+ assert_eq!(calls.len(), 1);
+ let call = &calls[0];
+ assert_eq!(call.bot_id, BOT_ID);
+ assert_eq!(call.entity_id, ENTITY_ID);
+ assert_eq!(call.entity_type, EntityType::Document);
+ match &call.scope {
+ BotAccessScope::User {
+ user_id,
+ user_org_id,
+ } => {
+ assert_eq!(user_id.as_ref(), BOT_ACTING_USER_ID);
+ assert_eq!(
+ *user_org_id,
+ Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID))
+ );
+ }
+ BotAccessScope::Team { .. } => panic!("expected user scope"),
+ }
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn team_scoped_bot_access_uses_the_owning_team_scope() {
+ let state = TestState::new(Some(AccessLevel::View));
let response = router(state.clone())
.oneshot(
request("/view")
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
- .header(BOT_SCOPE_HEADER, "user")
+ .header(BOT_SCOPE_HEADER, BotScope::Team.as_str())
+ .body(body("document", ENTITY_ID))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn user_scoped_bot_without_an_acting_user_is_rejected() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(BOT_TOKEN_HEADER, MALFORMED_SYSTEM_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.body(body("document", ENTITY_ID))
.unwrap(),
)
.await
.unwrap();
- assert_eq!(response.status(), StatusCode::FORBIDDEN);
- assert_eq!(response_body(response).await, r#"{"message":"forbidden"}"#);
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"bot user scope requires an acting user"}"#
+ );
+ assert!(state.entity_access.bot_calls().is_empty());
assert!(state.entity_access.calls().is_empty());
}
@@ -226,6 +304,25 @@ async fn view_access_does_not_satisfy_edit_access() {
assert_eq!(state.entity_access.calls().len(), 1);
}
+#[tokio::test]
+async fn bot_permission_must_satisfy_the_required_access_level() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = router(state.clone())
+ .oneshot(
+ request("/edit")
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::Team.as_str())
+ .body(body("document", ENTITY_ID))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(state.entity_access.bot_calls().len(), 1);
+ assert!(state.entity_access.calls().is_empty());
+}
+
#[tokio::test]
async fn missing_and_malformed_json_are_rejected_before_acl_lookup() {
let state = TestState::new(Some(AccessLevel::View));
@@ -272,12 +369,13 @@ async fn missing_entity_fields_are_rejected_before_acl_lookup() {
}
#[tokio::test]
-async fn unknown_entity_types_are_rejected_before_acl_lookup() {
+async fn unsupported_entity_types_are_rejected_before_acl_lookup() {
let state = TestState::new(Some(AccessLevel::View));
let response = router(state.clone())
.oneshot(
request("/view")
- .header(header::AUTHORIZATION, "Bearer valid")
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::Team.as_str())
.body(body("thread", ENTITY_ID))
.unwrap(),
)
@@ -285,11 +383,12 @@ async fn unknown_entity_types_are_rejected_before_acl_lookup() {
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert!(state.entity_access.bot_calls().is_empty());
assert!(state.entity_access.calls().is_empty());
}
#[tokio::test]
-async fn typed_body_failure_is_rejected_after_acl_lookup() {
+async fn typed_body_failure_is_rejected_after_user_acl_lookup() {
let state = TestState::new(Some(AccessLevel::View));
let response = router(state.clone())
.oneshot(
@@ -314,6 +413,27 @@ async fn typed_body_failure_is_rejected_after_acl_lookup() {
);
}
+#[tokio::test]
+async fn bot_typed_body_failure_is_rejected_before_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = router(state.clone())
+ .oneshot(
+ request("/view")
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::Team.as_str())
+ .body(Body::from(
+ r#"{"entityType":"document","entityId":"entity-1","position":"first"}"#,
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert!(state.entity_access.bot_calls().is_empty());
+ assert!(state.entity_access.calls().is_empty());
+}
+
#[tokio::test]
async fn channels_and_static_files_keep_get_access_level_semantics() {
let state = TestState::new(Some(AccessLevel::View));
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs b/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs
index 61fd70f614..028d219975 100644
--- a/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs
@@ -11,15 +11,15 @@ use axum::{
http::request::Parts,
};
use macro_authorization::{
- MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOrInternalService, UserOrInternalServiceAuthorization,
+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor,
};
-use super::ExtractorError;
+use super::{ExtractorError, bot::generate_bot_entity_access_receipt};
use crate::domain::{
models::{
- AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
- ViewAccessLevel,
+ AccessLevel, AnyEntityPermission, Entity, EntityAccessAuth, EntityAccessReceipt,
+ EntityPermission, EntityType,
},
ports::EntityAccessService,
};
@@ -38,7 +38,7 @@ struct EntityPermissionParams {
#[derive(Debug)]
pub struct EntityPermissionExtractor<Svc, Auth> {
/// The entity access receipt
- pub entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
+ pub entity_access_receipt: EntityAccessReceipt<AnyEntityPermission>,
_marker: PhantomData<(Svc, Auth)>,
}
@@ -57,21 +57,11 @@ where
let service = <Arc<Svc>>::from_ref(state);
let authorization =
- OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ OptionalMacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(
parts, state,
)
.await
.map_err(ExtractorError::from)?;
- let is_internal_access = authorization
- .authorization
- .as_ref()
- .is_some_and(UserOrInternalServiceAuthorization::is_internal);
- let (macro_user_id, user_context) = authorization
- .authorization
- .as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
- .map(|user| (Some(user.macro_user_id.clone()), user.user_context.clone()))
- .unwrap_or_default();
let Path(EntityPermissionParams {
entity_type,
@@ -82,6 +72,32 @@ where
let parsed_type = parse_entity_type(&entity_type)?;
+ if let Some(MacroAuthorization::Bot(authentication)) = authorization.authorization.as_ref()
+ {
+ let entity_access_receipt = generate_bot_entity_access_receipt::<AnyEntityPermission>(
+ service.as_ref(),
+ authentication,
+ &entity_id,
+ parsed_type,
+ )
+ .await?;
+
+ return Ok(Self {
+ entity_access_receipt,
+ _marker: PhantomData,
+ });
+ }
+
+ let (is_internal_access, acting_user) = match authorization.authorization.as_ref() {
+ Some(MacroAuthorization::User(user)) => (false, Some(user)),
+ Some(MacroAuthorization::Internal(user)) => (true, user.as_ref()),
+ Some(MacroAuthorization::Bot(_)) => unreachable!("bot authorization returned above"),
+ None => (false, None),
+ };
+ let (macro_user_id, user_context) = acting_user
+ .map(|user| (Some(user.macro_user_id.clone()), user.user_context.clone()))
+ .unwrap_or_default();
+
if is_internal_access && macro_user_id.is_none() {
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs b/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs
index 690d4a5008..cc58ba8ada 100644
--- a/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs
@@ -1,4 +1,3 @@
-use crate::domain::models::TeamRole;
use std::sync::{Arc, Mutex};
use axum::{
@@ -28,12 +27,17 @@ use super::EntityPermissionExtractor;
use crate::{
domain::{
models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, EntityAccessAuth,
- EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission, UserTeamInfo,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, Entity,
+ EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType, ParticipantRole,
+ RequiredPermission, TeamRole, UserTeamInfo,
},
ports::EntityAccessService,
},
- inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
+ inbound::axum_extractors::test_support::{
+ BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID,
+ MALFORMED_SYSTEM_BOT_TOKEN, VALID_BOT_TOKEN, malformed_system_bot_authentication,
+ valid_bot_authentication,
+ },
};
const USER_ID: &str = "macro|[email protected]";
@@ -54,14 +58,28 @@ enum EntityAccessCall {
entity_type: EntityType,
required_level: AccessLevel,
},
+ GenerateBotReceipt {
+ bot_id: BotId,
+ scope: BotAccessScope,
+ entity_id: String,
+ entity_type: EntityType,
+ },
}
#[derive(Clone, Default)]
struct FakeEntityAccessService {
+ bot_permission: Option<EntityPermission>,
calls: Arc<Mutex<Vec<EntityAccessCall>>>,
}
impl FakeEntityAccessService {
+ fn with_bot_permission(permission: EntityPermission) -> Self {
+ Self {
+ bot_permission: Some(permission),
+ calls: Arc::default(),
+ }
+ }
+
fn calls(&self) -> Vec<EntityAccessCall> {
self.calls.lock().expect("calls lock poisoned").clone()
}
@@ -80,11 +98,30 @@ impl EntityAccessService for FakeEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
- _bot_id: BotId,
- _entity_id: &str,
- _entity_type: EntityType,
+ bot_id: BotId,
+ scope: BotAccessScope,
+ entity_id: &str,
+ entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
- panic!("unexpected generate_bot_entity_access_receipt call")
+ self.calls.lock().expect("calls lock poisoned").push(
+ EntityAccessCall::GenerateBotReceipt {
+ bot_id,
+ scope: scope.clone(),
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ );
+
+ let permission = self.bot_permission.ok_or(AccessError::Unauthorized)?;
+ EntityAccessReceipt::try_new_bot(
+ bot_id.into_storage_id(),
+ (&scope).into(),
+ Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ permission,
+ )
}
async fn get_access_level(
@@ -231,11 +268,11 @@ impl MacroAuthorizationService for FakeAuthorizationService {
.expect("calls lock poisoned")
.push(AuthorizationCall::Bot(token.to_string()));
- if token != VALID_BOT_TOKEN {
- return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ match token {
+ VALID_BOT_TOKEN => Ok(valid_bot_authentication(bot_scope)),
+ MALFORMED_SYSTEM_BOT_TOKEN => Ok(malformed_system_bot_authentication(bot_scope)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
}
-
- Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -295,7 +332,7 @@ async fn handler(
let receipt = extractor.entity_access_receipt;
let auth = match receipt.auth {
EntityAccessAuth::Authenticated(user_id) => json!({ "authenticated": user_id.to_string() }),
- EntityAccessAuth::Bot(bot_id) => json!({ "bot": bot_id.to_string() }),
+ EntityAccessAuth::Bot(bot_auth) => json!({ "bot": bot_auth }),
EntityAccessAuth::Unauthenticated => json!("unauthenticated"),
EntityAccessAuth::Internal => json!("internal"),
};
@@ -309,7 +346,18 @@ async fn handler(
}
fn test_router() -> (Router, FakeEntityAccessService, FakeAuthorizationService) {
- let entity_access = FakeEntityAccessService::default();
+ test_router_with_service(FakeEntityAccessService::default())
+}
+
+fn bot_test_router(
+ permission: EntityPermission,
+) -> (Router, FakeEntityAccessService, FakeAuthorizationService) {
+ test_router_with_service(FakeEntityAccessService::with_bot_permission(permission))
+}
+
+fn test_router_with_service(
+ entity_access: FakeEntityAccessService,
+) -> (Router, FakeEntityAccessService, FakeAuthorizationService) {
let authorization = FakeAuthorizationService::default();
let state = TestState {
entity_access: Arc::new(entity_access.clone()),
@@ -431,8 +479,10 @@ async fn invalid_and_expired_tokens_preserve_authorization_rejections() {
}
#[tokio::test]
-async fn bot_credentials_are_forbidden_without_permission_lookup() {
- let (router, entity_access, authorization) = test_router();
+async fn user_scoped_bot_uses_acting_user_organization_context() {
+ let (router, entity_access, authorization) = bot_test_router(EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ });
let request = empty_body(
request(&format!("/entity/document/{ENTITY_ID}"))
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
@@ -441,15 +491,171 @@ async fn bot_credentials_are_forbidden_without_permission_lookup() {
let (status, body) = send(&router, request).await;
- assert_eq!(status, StatusCode::FORBIDDEN);
- assert_eq!(body, json!({ "message": "forbidden" }));
- assert!(entity_access.calls().is_empty());
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(
+ body["auth"],
+ json!({
+ "bot": {
+ "bot_id": BOT_ID.into_storage_id().to_string(),
+ "scope": "user",
+ "acting_user": BOT_ACTING_USER_ID,
+ }
+ })
+ );
+ assert_eq!(body["permission"]["access_level"], "edit");
+ assert_eq!(
+ entity_access.calls(),
+ [EntityAccessCall::GenerateBotReceipt {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::User {
+ user_id: MacroUserIdStr::try_from(BOT_ACTING_USER_ID.to_string()).unwrap(),
+ user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
+ },
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
assert_eq!(
authorization.calls(),
[AuthorizationCall::Bot(VALID_BOT_TOKEN.to_string())]
);
}
+#[tokio::test]
+async fn user_scoped_bot_without_acting_user_is_unauthorized() {
+ let (router, entity_access, authorization) = test_router();
+ let request = empty_body(
+ request(&format!("/entity/document/{ENTITY_ID}"))
+ .header(BOT_TOKEN_HEADER, MALFORMED_SYSTEM_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str()),
+ );
+
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ body,
+ json!({ "message": "bot user scope requires an acting user" })
+ );
+ assert!(entity_access.calls().is_empty());
+ assert_eq!(
+ authorization.calls(),
+ [AuthorizationCall::Bot(
+ MALFORMED_SYSTEM_BOT_TOKEN.to_string()
+ )]
+ );
+}
+
+#[tokio::test]
+async fn team_scoped_bot_supports_channel_permissions() {
+ for (permission, expected_permission) in [
+ (
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ },
+ json!({ "type": "channel_role", "role": "member" }),
+ ),
+ (
+ EntityPermission::ChannelViewOnly,
+ json!({ "type": "channel_view_only" }),
+ ),
+ ] {
+ let (router, entity_access, _authorization) = bot_test_router(permission);
+ let request = empty_body(
+ request(&format!("/entity/channel/{ENTITY_ID}"))
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::Team.as_str()),
+ );
+
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["permission"], expected_permission);
+ assert_eq!(
+ entity_access.calls(),
+ [EntityAccessCall::GenerateBotReceipt {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Channel,
+ }]
+ );
+ }
+}
+
+#[tokio::test]
+async fn team_scoped_bot_receives_team_role_receipt() {
+ let (router, entity_access, _authorization) = bot_test_router(EntityPermission::TeamRole {
+ role: TeamRole::Member,
+ });
+ let team_id = BOT_TEAM_ID.to_string();
+ let request = empty_body(
+ request(&format!("/entity/team/{team_id}"))
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::Team.as_str()),
+ );
+
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(
+ body["auth"],
+ json!({
+ "bot": {
+ "bot_id": BOT_ID.into_storage_id().to_string(),
+ "scope": "team",
+ "team_id": BOT_TEAM_ID,
+ }
+ })
+ );
+ assert_eq!(
+ body["permission"],
+ json!({ "type": "team_role", "role": "member" })
+ );
+ assert_eq!(
+ entity_access.calls(),
+ [EntityAccessCall::GenerateBotReceipt {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: team_id,
+ entity_type: EntityType::Team,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn bot_with_insufficient_access_is_unauthorized() {
+ let (router, entity_access, _authorization) = test_router();
+ let request = empty_body(
+ request(&format!("/entity/document/{ENTITY_ID}"))
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::Team.as_str()),
+ );
+
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ body,
+ json!({ "message": "User does not have access to the requested resource" })
+ );
+ assert_eq!(
+ entity_access.calls(),
+ [EntityAccessCall::GenerateBotReceipt {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+}
+
#[tokio::test]
async fn internal_request_with_acting_user_looks_up_the_users_permission() {
let (router, entity_access, authorization) = test_router();
diff --git a/crates/entity_access/src/inbound/axum_extractors/foreign_entity.rs b/crates/entity_access/src/inbound/axum_extractors/foreign_entity.rs
index 53be6d4ec3..89619e2263 100644
--- a/crates/entity_access/src/inbound/axum_extractors/foreign_entity.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/foreign_entity.rs
@@ -13,12 +13,12 @@ use axum::{
http::request::Parts,
};
use macro_authorization::{
- MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOrInternalService, UserOrInternalServiceAuthorization,
+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor,
};
use uuid::Uuid;
-use super::{ExtractorError, RequiredPermission};
+use super::{ExtractorError, RequiredPermission, bot::generate_bot_entity_access_receipt};
use crate::domain::{
models::{
AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -63,19 +63,35 @@ where
let foreign_entity_id = extract_foreign_entity_id(&path_params)?.to_string();
let authorization =
- OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ OptionalMacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(
parts, state,
)
.await
.map_err(ExtractorError::from)?;
+
+ if let Some(MacroAuthorization::Bot(authentication)) = &authorization.authorization {
+ let entity_access_receipt = generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ authentication,
+ &foreign_entity_id,
+ EntityType::ForeignEntity,
+ )
+ .await?;
+
+ return Ok(Self {
+ entity_access_receipt,
+ _marker: PhantomData,
+ });
+ }
+
let is_internal_access = authorization
.authorization
.as_ref()
- .is_some_and(UserOrInternalServiceAuthorization::is_internal);
+ .is_some_and(MacroAuthorization::is_internal);
let macro_user_id = authorization
.authorization
.as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
+ .and_then(MacroAuthorization::acting_user)
.map(|user| user.macro_user_id.clone());
if macro_user_id.is_none() && is_internal_access {
diff --git a/crates/entity_access/src/inbound/axum_extractors/foreign_entity/test.rs b/crates/entity_access/src/inbound/axum_extractors/foreign_entity/test.rs
index e682258d7b..24a810bdf9 100644
--- a/crates/entity_access/src/inbound/axum_extractors/foreign_entity/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/foreign_entity/test.rs
@@ -4,50 +4,254 @@ use axum::{
http::{Request, StatusCode},
routing::get,
};
-use macro_authorization::{BOT_SCOPE_HEADER, BOT_TOKEN_HEADER};
+use macro_authorization::{BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotScope, INTERNAL_API_KEY_HEADER};
+use macro_user_id::user_id::MacroUserIdStr;
use tower::ServiceExt;
use super::*;
use crate::{
- domain::models::{AccessLevel, ViewAccessLevel},
+ domain::models::{
+ AccessLevel, BotAccessScope, CommentAccessLevel, EntityAccessAuth, ViewAccessLevel,
+ },
inbound::axum_extractors::test_support::{
- FakeAuthorizationService, FakeEntityAccessService, TestState, VALID_BOT_TOKEN,
+ BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID, BotAccessCall,
+ FakeAuthorizationService, FakeEntityAccessService, INTERNAL_KEY,
+ MALFORMED_SYSTEM_BOT_TOKEN, TestState, VALID_BOT_TOKEN,
},
};
-const FOREIGN_ENTITY_ID: &str = "550e8400-e29b-41d4-a716-446655440000";
+const USER_SCOPE_FOREIGN_ENTITY_ID: &str = "550e8400-e29b-41d4-a716-446655440000";
+const TEAM_PAIR_FOREIGN_ENTITY_ID: &str = "550e8400-e29b-41d4-a716-446655440001";
+const BOT_PRINCIPAL_FOREIGN_ENTITY_ID: &str = "550e8400-e29b-41d4-a716-446655440002";
+const UNRELATED_FOREIGN_ENTITY_ID: &str = "550e8400-e29b-41d4-a716-446655440003";
type ViewExtractor = ForeignEntityAccessLevelExtractor<
ViewAccessLevel,
FakeEntityAccessService,
FakeAuthorizationService,
>;
+type CommentExtractor = ForeignEntityAccessLevelExtractor<
+ CommentAccessLevel,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+>;
-async fn handler(_access: ViewExtractor) -> StatusCode {
+async fn view_handler(access: ViewExtractor) -> &'static str {
+ match access.entity_access_receipt.auth() {
+ EntityAccessAuth::Bot(_) => "bot",
+ EntityAccessAuth::Internal => "internal",
+ EntityAccessAuth::Authenticated(_) => "user",
+ EntityAccessAuth::Unauthenticated => "anonymous",
+ }
+}
+
+async fn comment_handler(_access: CommentExtractor) -> StatusCode {
StatusCode::OK
}
-#[tokio::test]
-async fn bot_credentials_are_forbidden_without_permission_lookup() {
- let state = TestState::new(Some(AccessLevel::Owner));
- let router = Router::new()
- .route("/foreign/{foreign_entity_id}", get(handler))
- .with_state(state.clone());
- let request = Request::get(format!("/foreign/{FOREIGN_ENTITY_ID}"))
- .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
- .header(BOT_SCOPE_HEADER, "user")
+fn router(state: TestState) -> Router {
+ Router::new()
+ .route("/foreign/{foreign_entity_id}", get(view_handler))
+ .route("/foreign-comment/{id}", get(comment_handler))
+ .with_state(state)
+}
+
+fn bot_request(path: &str, scope: BotScope, token: &str) -> Request<Body> {
+ Request::get(path)
+ .header(BOT_TOKEN_HEADER, token)
+ .header(BOT_SCOPE_HEADER, scope.as_str())
.body(Body::empty())
- .expect("request should be valid");
+ .expect("bot request should be valid")
+}
+async fn send(router: Router, request: Request<Body>) -> (StatusCode, String) {
let response = router
.oneshot(request)
.await
.expect("request should complete");
-
- assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ let status = response.status();
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("response body should be readable");
- assert_eq!(body.as_ref(), br#"{"message":"forbidden"}"#);
+
+ (
+ status,
+ String::from_utf8(body.to_vec()).expect("response body should be UTF-8"),
+ )
+}
+
+#[tokio::test]
+async fn user_scoped_bot_uses_acting_user_scope_and_retains_bot_auth() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let request = bot_request(
+ &format!("/foreign/{USER_SCOPE_FOREIGN_ENTITY_ID}"),
+ BotScope::User,
+ VALID_BOT_TOKEN,
+ );
+
+ let (status, body) = send(router(state.clone()), request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body, "bot");
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::User {
+ user_id: MacroUserIdStr::parse_from_str(BOT_ACTING_USER_ID)
+ .expect("acting user ID should be valid"),
+ user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
+ },
+ entity_id: USER_SCOPE_FOREIGN_ENTITY_ID.to_string(),
+ entity_type: EntityType::ForeignEntity,
+ }]
+ );
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn team_scoped_bot_accepts_team_pair_access() {
+ assert_team_scoped_access(TEAM_PAIR_FOREIGN_ENTITY_ID).await;
+}
+
+#[tokio::test]
+async fn team_scoped_bot_accepts_direct_bot_principal_access() {
+ assert_team_scoped_access(BOT_PRINCIPAL_FOREIGN_ENTITY_ID).await;
+}
+
+async fn assert_team_scoped_access(foreign_entity_id: &str) {
+ let state = TestState::new(Some(AccessLevel::View));
+ let request = bot_request(
+ &format!("/foreign/{foreign_entity_id}"),
+ BotScope::Team,
+ VALID_BOT_TOKEN,
+ );
+
+ let (status, body) = send(router(state.clone()), request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body, "bot");
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: foreign_entity_id.to_string(),
+ entity_type: EntityType::ForeignEntity,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn team_scoped_bot_propagates_unrelated_source_denial() {
+ let state = TestState::new(None);
+ let request = bot_request(
+ &format!("/foreign/{UNRELATED_FOREIGN_ENTITY_ID}"),
+ BotScope::Team,
+ VALID_BOT_TOKEN,
+ );
+
+ let (status, _body) = send(router(state.clone()), request).await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: UNRELATED_FOREIGN_ENTITY_ID.to_string(),
+ entity_type: EntityType::ForeignEntity,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn user_scoped_bot_without_acting_user_is_unauthorized() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let request = bot_request(
+ &format!("/foreign/{USER_SCOPE_FOREIGN_ENTITY_ID}"),
+ BotScope::User,
+ MALFORMED_SYSTEM_BOT_TOKEN,
+ );
+
+ let (status, body) = send(router(state.clone()), request).await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ body,
+ r#"{"message":"bot user scope requires an acting user"}"#
+ );
+ assert!(state.entity_access.bot_calls().is_empty());
+}
+
+#[tokio::test]
+async fn malformed_foreign_entity_id_is_rejected_before_access_lookup() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let request = bot_request("/foreign/not-a-uuid", BotScope::Team, VALID_BOT_TOKEN);
+
+ let (status, body) = send(router(state.clone()), request).await;
+
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert_eq!(
+ body,
+ r#"{"message":"Bad request: invalid foreign entity ID format"}"#
+ );
+ assert!(state.entity_access.bot_calls().is_empty());
+}
+
+#[tokio::test]
+async fn foreign_entity_access_satisfies_only_view_level_requirements() {
+ let view_state = TestState::new(Some(AccessLevel::View));
+ let view_request = bot_request(
+ &format!("/foreign/{TEAM_PAIR_FOREIGN_ENTITY_ID}"),
+ BotScope::Team,
+ VALID_BOT_TOKEN,
+ );
+ let (view_status, _) = send(router(view_state), view_request).await;
+ assert_eq!(view_status, StatusCode::OK);
+
+ let comment_state = TestState::new(Some(AccessLevel::View));
+ let comment_request = bot_request(
+ &format!("/foreign-comment/{TEAM_PAIR_FOREIGN_ENTITY_ID}"),
+ BotScope::Team,
+ VALID_BOT_TOKEN,
+ );
+ let (comment_status, _) = send(router(comment_state.clone()), comment_request).await;
+
+ assert_eq!(comment_status, StatusCode::UNAUTHORIZED);
+ assert_eq!(comment_state.entity_access.bot_calls().len(), 1);
+}
+
+#[tokio::test]
+async fn anonymous_requests_are_rejected_without_access_lookup() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let request = Request::get(format!("/foreign/{USER_SCOPE_FOREIGN_ENTITY_ID}"))
+ .body(Body::empty())
+ .expect("anonymous request should be valid");
+
+ let (status, _) = send(router(state.clone()), request).await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert!(state.entity_access.calls().is_empty());
+ assert!(state.entity_access.bot_calls().is_empty());
+}
+
+#[tokio::test]
+async fn identity_less_internal_request_receives_view_without_access_lookup() {
+ let state = TestState::new(None);
+ let request = Request::get(format!("/foreign/{USER_SCOPE_FOREIGN_ENTITY_ID}"))
+ .header(INTERNAL_API_KEY_HEADER, INTERNAL_KEY)
+ .body(Body::empty())
+ .expect("internal request should be valid");
+
+ let (status, body) = send(router(state.clone()), request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body, "internal");
assert!(state.entity_access.calls().is_empty());
+ assert!(state.entity_access.bot_calls().is_empty());
}
diff --git a/crates/entity_access/src/inbound/axum_extractors/history.rs b/crates/entity_access/src/inbound/axum_extractors/history.rs
index 78c4324fcf..effa445ee4 100644
--- a/crates/entity_access/src/inbound/axum_extractors/history.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/history.rs
@@ -11,11 +11,11 @@ use axum::{
http::request::Parts,
};
use macro_authorization::{
- MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOrInternalService, UserOrInternalServiceAuthorization,
+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor,
};
-use super::{ExtractorError, RequiredPermission};
+use super::{ExtractorError, RequiredPermission, bot::generate_bot_entity_access_receipt};
use crate::domain::{
models::{
AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -59,31 +59,47 @@ where
let service = <Arc<Svc>>::from_ref(state);
let authorization =
- OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ OptionalMacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(
parts, state,
)
.await
.map_err(ExtractorError::from)?;
- let is_internal_access = authorization
- .authorization
- .as_ref()
- .is_some_and(UserOrInternalServiceAuthorization::is_internal);
- let macro_user_id = authorization
- .authorization
- .as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
- .map(|user| user.macro_user_id.clone());
let Path(HistoryParams { item_id, item_type }) =
<Path<HistoryParams>>::from_request_parts(parts, state)
.await
.map_err(|_| ExtractorError::BadRequest("Missing item_id or item_type in path"))?;
- // Parse the item_type string into EntityType
let entity_type: EntityType = item_type
.parse()
.map_err(|_| ExtractorError::BadRequest("Invalid item_type"))?;
+ if let Some(MacroAuthorization::Bot(authentication)) = authorization.authorization.as_ref()
+ {
+ let entity_access_receipt = generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ authentication,
+ &item_id,
+ entity_type,
+ )
+ .await?;
+
+ return Ok(Self {
+ entity_access_receipt,
+ _marker: PhantomData,
+ });
+ }
+
+ let is_internal_access = authorization
+ .authorization
+ .as_ref()
+ .is_some_and(MacroAuthorization::is_internal);
+ let macro_user_id = authorization
+ .authorization
+ .as_ref()
+ .and_then(MacroAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone());
+
if macro_user_id.is_none() && is_internal_access {
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
diff --git a/crates/entity_access/src/inbound/axum_extractors/history/test.rs b/crates/entity_access/src/inbound/axum_extractors/history/test.rs
index 94afd9569c..d4dd7cbe4a 100644
--- a/crates/entity_access/src/inbound/axum_extractors/history/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/history/test.rs
@@ -5,16 +5,21 @@ use axum::{
routing::post,
};
use macro_authorization::{
- BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotScope, INTERNAL_API_KEY_HEADER,
+ INTERNAL_MACRO_USER_ID_HEADER,
};
+use macro_user_id::user_id::MacroUserIdStr;
use tower::ServiceExt;
use super::*;
use crate::{
- domain::models::{AccessLevel, EntityAccessAuth, EntityType, ViewAccessLevel},
+ domain::models::{
+ AccessLevel, BotAccessScope, EditAccessLevel, EntityAccessAuth, EntityType, ViewAccessLevel,
+ },
inbound::axum_extractors::test_support::{
- AccessCall, FakeAuthorizationService, FakeEntityAccessService, INTERNAL_KEY, TestState,
- USER_ID, VALID_BOT_TOKEN,
+ AccessCall, BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID,
+ BotAccessCall, FakeAuthorizationService, FakeEntityAccessService, INTERNAL_KEY,
+ MALFORMED_SYSTEM_BOT_TOKEN, TestState, USER_ID, VALID_BOT_TOKEN,
},
};
@@ -22,9 +27,19 @@ const ITEM_ID: &str = "document-1";
type ViewExtractor =
HistoryAccessExtractor<ViewAccessLevel, FakeEntityAccessService, FakeAuthorizationService>;
+type EditExtractor =
+ HistoryAccessExtractor<EditAccessLevel, FakeEntityAccessService, FakeAuthorizationService>;
+
+async fn view_handler(access: ViewExtractor) -> &'static str {
+ receipt_auth_name(access.entity_access_receipt.auth())
+}
-async fn handler(access: ViewExtractor) -> &'static str {
- match access.entity_access_receipt.auth() {
+async fn edit_handler(access: EditExtractor) -> &'static str {
+ receipt_auth_name(access.entity_access_receipt.auth())
+}
+
+fn receipt_auth_name(auth: &EntityAccessAuth) -> &'static str {
+ match auth {
EntityAccessAuth::Authenticated(_) => "authenticated",
EntityAccessAuth::Unauthenticated => "unauthenticated",
EntityAccessAuth::Internal => "internal",
@@ -32,14 +47,32 @@ async fn handler(access: ViewExtractor) -> &'static str {
}
}
-fn router(state: TestState) -> Router {
+fn view_router(state: TestState) -> Router {
Router::new()
- .route("/history/{item_type}/{item_id}", post(handler))
+ .route("/history/{item_type}/{item_id}", post(view_handler))
+ .with_state(state)
+}
+
+fn edit_router(state: TestState) -> Router {
+ Router::new()
+ .route("/history/{item_type}/{item_id}", post(edit_handler))
.with_state(state)
}
fn request() -> axum::http::request::Builder {
- Request::post(format!("/history/document/{ITEM_ID}"))
+ request_for("document")
+}
+
+fn request_for(item_type: &str) -> axum::http::request::Builder {
+ Request::post(format!("/history/{item_type}/{ITEM_ID}"))
+}
+
+fn bot_request(item_type: &str, scope: BotScope, token: &str) -> Request<Body> {
+ request_for(item_type)
+ .header(BOT_TOKEN_HEADER, token)
+ .header(BOT_SCOPE_HEADER, scope.as_str())
+ .body(Body::empty())
+ .expect("bot request should be valid")
}
async fn response_body(response: axum::response::Response) -> String {
@@ -52,7 +85,7 @@ async fn response_body(response: axum::response::Response) -> String {
#[tokio::test]
async fn anonymous_history_access_uses_public_acl() {
let state = TestState::new(Some(AccessLevel::View));
- let response = router(state.clone())
+ let response = view_router(state.clone())
.oneshot(request().body(Body::empty()).unwrap())
.await
.unwrap();
@@ -67,12 +100,13 @@ async fn anonymous_history_access_uses_public_acl() {
entity_type: EntityType::Document,
}]
);
+ assert!(state.entity_access.bot_calls().is_empty());
}
#[tokio::test]
async fn identity_less_internal_history_access_receives_owner_without_acl_lookup() {
let state = TestState::new(None);
- let response = router(state.clone())
+ let response = view_router(state.clone())
.oneshot(
request()
.header(INTERNAL_API_KEY_HEADER, INTERNAL_KEY)
@@ -85,12 +119,13 @@ async fn identity_less_internal_history_access_receives_owner_without_acl_lookup
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response_body(response).await, "internal");
assert!(state.entity_access.calls().is_empty());
+ assert!(state.entity_access.bot_calls().is_empty());
}
#[tokio::test]
async fn internal_history_act_as_identity_uses_acl() {
let state = TestState::new(Some(AccessLevel::View));
- let response = router(state.clone())
+ let response = view_router(state.clone())
.oneshot(
request()
.header(INTERNAL_API_KEY_HEADER, INTERNAL_KEY)
@@ -107,31 +142,145 @@ async fn internal_history_act_as_identity_uses_acl() {
state.entity_access.calls()[0].user_id.as_deref(),
Some(USER_ID)
);
+ assert!(state.entity_access.bot_calls().is_empty());
}
#[tokio::test]
-async fn bot_history_access_is_forbidden_before_acl_lookup() {
- let state = TestState::new(Some(AccessLevel::Owner));
- let response = router(state.clone())
- .oneshot(
- request()
- .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
- .header(BOT_SCOPE_HEADER, "user")
- .body(Body::empty())
- .unwrap(),
- )
+async fn user_scoped_bot_uses_the_acting_user_scope() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = view_router(state.clone())
+ .oneshot(bot_request("document", BotScope::User, VALID_BOT_TOKEN))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "bot");
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::User {
+ user_id: MacroUserIdStr::parse_from_str(BOT_ACTING_USER_ID)
+ .expect("acting user ID should be valid"),
+ user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
+ },
+ entity_id: ITEM_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn team_scoped_bot_uses_the_owning_team_scope() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = view_router(state.clone())
+ .oneshot(bot_request("document", BotScope::Team, VALID_BOT_TOKEN))
.await
.unwrap();
- assert_eq!(response.status(), StatusCode::FORBIDDEN);
- assert_eq!(response_body(response).await, r#"{"message":"forbidden"}"#);
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "bot");
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: ITEM_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn user_scoped_bot_without_an_acting_user_is_rejected() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = view_router(state.clone())
+ .oneshot(bot_request(
+ "document",
+ BotScope::User,
+ MALFORMED_SYSTEM_BOT_TOKEN,
+ ))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"bot user scope requires an acting user"}"#
+ );
+ assert!(state.entity_access.bot_calls().is_empty());
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn malformed_item_type_is_rejected_before_bot_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = view_router(state.clone())
+ .oneshot(bot_request(
+ "not-an-entity-type",
+ BotScope::Team,
+ VALID_BOT_TOKEN,
+ ))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"Bad request: Invalid item_type"}"#
+ );
+ assert!(state.entity_access.bot_calls().is_empty());
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn unsupported_bot_entity_type_preserves_the_service_rejection() {
+ let state = TestState::new(None);
+ let response = view_router(state.clone())
+ .oneshot(bot_request("user", BotScope::Team, VALID_BOT_TOKEN))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"Bad request: Unsupported bot entity type"}"#
+ );
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: ITEM_ID.to_string(),
+ entity_type: EntityType::User,
+ }]
+ );
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn bot_with_insufficient_permission_is_rejected() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = edit_router(state.clone())
+ .oneshot(bot_request("document", BotScope::Team, VALID_BOT_TOKEN))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(state.entity_access.bot_calls().len(), 1);
assert!(state.entity_access.calls().is_empty());
}
#[tokio::test]
async fn expired_history_credentials_preserve_authorization_rejection() {
let state = TestState::new(Some(AccessLevel::Owner));
- let response = router(state.clone())
+ let response = view_router(state.clone())
.oneshot(
request()
.header(header::AUTHORIZATION, "Bearer expired")
@@ -147,4 +296,5 @@ async fn expired_history_credentials_preserve_authorization_rejection() {
r#"{"message":"jwt expired"}"#
);
assert!(state.entity_access.calls().is_empty());
+ assert!(state.entity_access.bot_calls().is_empty());
}
diff --git a/crates/entity_access/src/inbound/axum_extractors/mod.rs b/crates/entity_access/src/inbound/axum_extractors/mod.rs
index 9b45427719..cb9ac5d919 100644
--- a/crates/entity_access/src/inbound/axum_extractors/mod.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/mod.rs
@@ -8,6 +8,7 @@ mod test;
#[cfg(test)]
mod test_support;
+mod bot;
mod call;
mod channel;
mod chat;
diff --git a/crates/entity_access/src/inbound/axum_extractors/pin.rs b/crates/entity_access/src/inbound/axum_extractors/pin.rs
index b44181782e..0faf29d5d5 100644
--- a/crates/entity_access/src/inbound/axum_extractors/pin.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/pin.rs
@@ -12,11 +12,11 @@ use axum::{
extract::{FromRef, FromRequest, Path, Request},
};
use macro_authorization::{
- MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOrInternalService, UserOrInternalServiceAuthorization,
+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor,
};
-use super::{ExtractorError, RequiredPermission};
+use super::{ExtractorError, RequiredPermission, bot::generate_bot_entity_access_receipt};
use crate::domain::{
models::{Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType},
ports::EntityAccessService,
@@ -68,18 +68,20 @@ where
let service = <Arc<Svc>>::from_ref(state);
let authorization = req
- .extract_parts_with_state::<
- OptionalMacroAuthorizationExtractor<Auth, UserOrInternalService>,
- _,
- >(state)
+ .extract_parts_with_state::<OptionalMacroAuthorizationExtractor<Auth, AnyPrincipal>, _>(
+ state,
+ )
.await
- .map_err(ExtractorError::from)?;
- let macro_user_id = authorization
+ .map_err(ExtractorError::from)?
.authorization
- .as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
- .map(|user| user.macro_user_id.clone())
.ok_or(ExtractorError::Unauthorized)?;
+ let macro_user_id = match &authorization {
+ MacroAuthorization::User(user) | MacroAuthorization::Internal(Some(user)) => {
+ Some(user.macro_user_id.clone())
+ }
+ MacroAuthorization::Bot(_) => None,
+ MacroAuthorization::Internal(None) => return Err(ExtractorError::Unauthorized),
+ };
let Path(PinParams { pinned_item_id }) = req
.extract_parts_with_state(state)
@@ -101,30 +103,43 @@ where
.parse()
.map_err(|_| ExtractorError::BadRequest("Invalid pin_type"))?;
- let access_level = match service
- .get_access_level(Some(&macro_user_id), &pinned_item_id, entity_type)
- .await
- .map_err(ExtractorError::from)?
- {
- Some(access_level) => access_level,
- None => return Err(ExtractorError::Unauthorized),
- };
-
- let permission = EntityPermission::AccessLevel { access_level };
- if !permission.satisfies::<T>() {
- return Err(ExtractorError::Unauthorized);
+ let entity_access_receipt = match authorization {
+ MacroAuthorization::Bot(authentication) => {
+ generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ &authentication,
+ &pinned_item_id,
+ entity_type,
+ )
+ .await?
+ }
+ MacroAuthorization::User(_) | MacroAuthorization::Internal(Some(_)) => {
+ let macro_user_id = macro_user_id.ok_or(ExtractorError::Unauthorized)?;
+ let access_level = service
+ .get_access_level(Some(&macro_user_id), &pinned_item_id, entity_type)
+ .await
+ .map_err(ExtractorError::from)?
+ .ok_or(ExtractorError::Unauthorized)?;
+ let permission = EntityPermission::AccessLevel { access_level };
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
+ }
+
+ EntityAccessReceipt {
+ entity: Entity {
+ entity_id: pinned_item_id,
+ entity_type,
+ },
+ auth: EntityAccessAuth::Authenticated(macro_user_id),
+ entity_permission: permission,
+ _marker: PhantomData,
+ }
+ }
+ MacroAuthorization::Internal(None) => return Err(ExtractorError::Unauthorized),
};
Ok(Self {
- entity_access_receipt: EntityAccessReceipt {
- entity: Entity {
- entity_id: pinned_item_id,
- entity_type,
- },
- auth: EntityAccessAuth::Authenticated(macro_user_id),
- entity_permission: permission,
- _marker: PhantomData,
- },
+ entity_access_receipt,
inner: serde_json::from_value(json_clone)
.map_err(|_| ExtractorError::BadRequest("Invalid request body"))?,
pin_type: JsonBodyWithPinType { pin_type },
diff --git a/crates/entity_access/src/inbound/axum_extractors/pin/test.rs b/crates/entity_access/src/inbound/axum_extractors/pin/test.rs
index 9beadcb00d..99c1b55b61 100644
--- a/crates/entity_access/src/inbound/axum_extractors/pin/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/pin/test.rs
@@ -7,15 +7,19 @@ use axum::{
use macro_authorization::{
BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
};
+use macro_user_id::user_id::MacroUserIdStr;
use serde::Deserialize;
use tower::ServiceExt;
use super::*;
use crate::{
- domain::models::{AccessLevel, EntityAccessAuth, EntityType, ViewAccessLevel},
+ domain::models::{
+ AccessLevel, BotAccessScope, EditAccessLevel, EntityAccessAuth, EntityType, ViewAccessLevel,
+ },
inbound::axum_extractors::test_support::{
- AccessCall, FakeAuthorizationService, FakeEntityAccessService, INTERNAL_KEY, TestState,
- USER_ID, VALID_BOT_TOKEN,
+ AccessCall, BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID,
+ BotAccessCall, FakeAuthorizationService, FakeEntityAccessService, INTERNAL_KEY,
+ MALFORMED_SYSTEM_BOT_TOKEN, TestState, USER_ID, VALID_BOT_TOKEN,
},
};
@@ -34,6 +38,12 @@ type ViewExtractor = PinAccessLevelExtractor<
PinBody,
FakeAuthorizationService,
>;
+type EditExtractor = PinAccessLevelExtractor<
+ EditAccessLevel,
+ FakeEntityAccessService,
+ PinBody,
+ FakeAuthorizationService,
+>;
async fn handler(access: ViewExtractor) -> String {
let auth = match access.entity_access_receipt.auth() {
@@ -60,7 +70,11 @@ fn request() -> axum::http::request::Builder {
}
fn body() -> Body {
- Body::from(r#"{"pinType":"document","pinIndex":7}"#)
+ body_with_pin_type("document")
+}
+
+fn body_with_pin_type(pin_type: &str) -> Body {
+ Body::from(format!(r#"{{"pinType":"{pin_type}","pinIndex":7}}"#))
}
async fn response_body(response: axum::response::Response) -> String {
@@ -153,12 +167,74 @@ async fn internal_pin_act_as_identity_uses_acl() {
}
#[tokio::test]
-async fn bot_pin_access_is_forbidden_before_acl_lookup() {
- let state = TestState::new(Some(AccessLevel::Owner));
+async fn user_scoped_bot_uses_scoped_access_and_preserves_the_typed_body() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = router(state.clone())
+ .oneshot(
+ request()
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, "user")
+ .body(body())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "bot:document:document:7");
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::User {
+ user_id: MacroUserIdStr::parse_from_str(BOT_ACTING_USER_ID)
+ .expect("bot acting user id should be valid"),
+ user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
+ },
+ entity_id: ITEM_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn team_scoped_bot_uses_scoped_access() {
+ let state = TestState::new(Some(AccessLevel::View));
let response = router(state.clone())
.oneshot(
request()
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, "team")
+ .body(body())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "bot:document:document:7");
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: ITEM_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn user_scoped_bot_without_an_acting_user_is_rejected() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let response = router(state.clone())
+ .oneshot(
+ request()
+ .header(BOT_TOKEN_HEADER, MALFORMED_SYSTEM_BOT_TOKEN)
.header(BOT_SCOPE_HEADER, "user")
.body(body())
.unwrap(),
@@ -166,8 +242,108 @@ async fn bot_pin_access_is_forbidden_before_acl_lookup() {
.await
.unwrap();
- assert_eq!(response.status(), StatusCode::FORBIDDEN);
- assert_eq!(response_body(response).await, r#"{"message":"forbidden"}"#);
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"bot user scope requires an acting user"}"#
+ );
+ assert!(state.entity_access.bot_calls().is_empty());
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn bot_with_insufficient_access_is_rejected() {
+ async fn edit_handler(_access: EditExtractor) {}
+
+ let state = TestState::new(Some(AccessLevel::View));
+ let router = Router::new()
+ .route("/pins/{pinned_item_id}", post(edit_handler))
+ .with_state(state.clone());
+ let response = router
+ .oneshot(
+ request()
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, "team")
+ .body(body())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(state.entity_access.bot_calls().len(), 1);
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn malformed_or_missing_pin_type_is_rejected_before_bot_acl_lookup() {
+ for body in [
+ Body::from(r#"{"pinIndex":7}"#),
+ Body::from(r#"{"pinType":7,"pinIndex":7}"#),
+ ] {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let response = router(state.clone())
+ .oneshot(
+ request()
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, "team")
+ .body(body)
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"Bad request: body is missing pinType"}"#
+ );
+ assert!(state.entity_access.bot_calls().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn unknown_pin_type_is_rejected_before_bot_acl_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let response = router(state.clone())
+ .oneshot(
+ request()
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, "team")
+ .body(body_with_pin_type("unsupported"))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"Bad request: Invalid pin_type"}"#
+ );
+ assert!(state.entity_access.bot_calls().is_empty());
+}
+
+#[tokio::test]
+async fn unsupported_bot_entity_type_preserves_the_service_rejection() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let response = router(state.clone())
+ .oneshot(
+ request()
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, "team")
+ .body(body_with_pin_type("user"))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"Bad request: Unsupported bot entity type"}"#
+ );
+ assert_eq!(state.entity_access.bot_calls().len(), 1);
assert!(state.entity_access.calls().is_empty());
}
diff --git a/crates/entity_access/src/inbound/axum_extractors/project.rs b/crates/entity_access/src/inbound/axum_extractors/project.rs
index 4e5bfdcae5..ba8af05203 100644
--- a/crates/entity_access/src/inbound/axum_extractors/project.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/project.rs
@@ -12,13 +12,13 @@ use axum::{
http::request::Parts,
};
use macro_authorization::{
- MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOrInternalService, UserOrInternalServiceAuthorization,
+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor,
};
use macro_user_id::user_id::MacroUserIdStr;
use serde::de::DeserializeOwned;
-use super::{ExtractorError, RequiredPermission};
+use super::{ExtractorError, RequiredPermission, bot::generate_bot_entity_access_receipt};
use crate::domain::{
models::{
AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -59,100 +59,97 @@ where
let service = <Arc<Svc>>::from_ref(state);
let authorization =
- OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ OptionalMacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(
parts, state,
)
.await
.map_err(ExtractorError::from)?;
- let is_internal_access = authorization
- .authorization
- .as_ref()
- .is_some_and(UserOrInternalServiceAuthorization::is_internal);
- let macro_user_id = authorization
- .authorization
- .as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
- .map(|user| user.macro_user_id.clone());
let project_context: Extension<BasicProject> = parts
.extract()
.await
.map_err(|_| ExtractorError::Internal)?;
- if macro_user_id.is_none() && is_internal_access {
+ if matches!(
+ authorization.authorization.as_ref(),
+ Some(MacroAuthorization::Internal(None))
+ ) {
return Ok(Self {
- entity_access_receipt: EntityAccessReceipt {
- entity: Entity {
- entity_id: project_context.id.clone(),
- entity_type: EntityType::Project,
- },
- auth: EntityAccessAuth::Internal,
- entity_permission: EntityPermission::AccessLevel {
+ entity_access_receipt: project_access_receipt(
+ &project_context.id,
+ EntityAccessAuth::Internal,
+ EntityPermission::AccessLevel {
access_level: AccessLevel::Owner,
},
- _marker: PhantomData,
- },
+ ),
_marker: PhantomData,
});
}
- // Check ownership only if authenticated
+ let macro_user_id = match authorization.authorization.as_ref() {
+ Some(MacroAuthorization::User(user))
+ | Some(MacroAuthorization::Internal(Some(user))) => Some(user.macro_user_id.clone()),
+ Some(MacroAuthorization::Bot(_)) | Some(MacroAuthorization::Internal(None)) | None => {
+ None
+ }
+ };
+
if let Some(ref user_id) = macro_user_id
&& project_context.user_id == *user_id
{
return Ok(Self {
- entity_access_receipt: EntityAccessReceipt {
- entity: Entity {
- entity_id: project_context.id.clone(),
- entity_type: EntityType::Project,
- },
- auth: EntityAccessAuth::Authenticated(user_id.clone()),
- entity_permission: EntityPermission::AccessLevel {
+ entity_access_receipt: project_access_receipt(
+ &project_context.id,
+ EntityAccessAuth::Authenticated(user_id.clone()),
+ EntityPermission::AccessLevel {
access_level: AccessLevel::Owner,
},
- _marker: PhantomData,
- },
+ ),
+ _marker: PhantomData,
+ });
+ }
+
+ if let Some(MacroAuthorization::Bot(bot)) = authorization.authorization.as_ref() {
+ let entity_access_receipt = generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ bot,
+ &project_context.id,
+ EntityType::Project,
+ )
+ .await?;
+
+ if project_context.deleted_at.is_some()
+ && !matches!(
+ entity_access_receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner
+ }
+ )
+ {
+ return Err(ExtractorError::UnauthorizedWithMessage(
+ "only owner can access deleted resource",
+ ));
+ }
+
+ return Ok(Self {
+ entity_access_receipt,
_marker: PhantomData,
});
}
- // Deleted items are only accessible by owner
+ // Deleted items are only accessible by owner.
if project_context.deleted_at.is_some() {
return Err(ExtractorError::UnauthorizedWithMessage(
"only owner can access deleted resource",
));
}
- let access_level = match service
- .get_access_level(
- macro_user_id.as_deref(),
- &project_context.id,
- EntityType::Project,
- )
- .await
- .map_err(ExtractorError::from)?
- {
- Some(access_level) => access_level,
- None => return Err(ExtractorError::Unauthorized),
- };
-
- let permission = EntityPermission::AccessLevel { access_level };
- if !permission.satisfies::<T>() {
- return Err(ExtractorError::Unauthorized);
- };
+ let entity_access_receipt =
+ get_project_access_receipt(service.as_ref(), macro_user_id, &project_context.id)
+ .await?;
Ok(Self {
- entity_access_receipt: EntityAccessReceipt {
- entity: Entity {
- entity_id: project_context.id.clone(),
- entity_type: EntityType::Project,
- },
- auth: macro_user_id
- .map(EntityAccessAuth::Authenticated)
- .unwrap_or(EntityAccessAuth::Unauthenticated),
- entity_permission: permission,
- _marker: PhantomData,
- },
+ entity_access_receipt,
_marker: PhantomData,
})
}
@@ -208,8 +205,8 @@ impl ProjectOrParentId {
///
/// Downstream consumers also use the body (which is an antipattern) so we need
/// to keep the value around. Identity is resolved through
-/// [`OptionalMacroAuthorizationExtractor`], which natively supports internal
-/// authorization. Type parameter `T` specifies the required project access
+/// [`OptionalMacroAuthorizationExtractor`], which natively supports all
+/// principals. Type parameter `T` specifies the required project access
/// level, `V` is the request body, `Svc` is the entity access service, and
/// `Auth` is the authorization service.
#[derive(Debug)]
@@ -276,22 +273,12 @@ where
async fn from_request(mut req: Request, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let authorization: OptionalMacroAuthorizationExtractor<Auth, UserOrInternalService> = req
+ let authorization: OptionalMacroAuthorizationExtractor<Auth, AnyPrincipal> = req
.extract_parts_with_state(state)
.await
.map_err(ExtractorError::from)?;
- let is_internal_access = authorization
- .authorization
- .as_ref()
- .is_some_and(UserOrInternalServiceAuthorization::is_internal);
- let macro_user_id = authorization
- .authorization
- .as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
- .map(|user| user.macro_user_id.clone());
- let has_internal_owner_access = macro_user_id.is_none() && is_internal_access;
-
- extract_project_body_access(req, service, macro_user_id, has_internal_owner_access)
+
+ extract_project_body_access(req, service, authorization.authorization)
.await
.map(Self::from_outcome)
}
@@ -311,8 +298,7 @@ enum ProjectBodyAccessOutcome<T: RequiredPermission, V> {
async fn extract_project_body_access<T, V, Svc>(
req: Request,
service: Arc<Svc>,
- macro_user_id: Option<MacroUserIdStr<'static>>,
- has_internal_owner_access: bool,
+ authorization: Option<MacroAuthorization>,
) -> Result<ProjectBodyAccessOutcome<T, V>, ExtractorError>
where
T: RequiredPermission,
@@ -338,29 +324,28 @@ where
});
}
- let entity_access_receipt = if has_internal_owner_access {
- project_access_receipt(
+ let entity_access_receipt = match authorization {
+ Some(MacroAuthorization::Internal(None)) => project_access_receipt(
project.id(),
EntityAccessAuth::Internal,
EntityPermission::AccessLevel {
access_level: AccessLevel::Owner,
},
- )
- } else {
- let access_level = service
- .get_access_level(macro_user_id.as_deref(), project.id(), EntityType::Project)
- .await
- .map_err(ExtractorError::from)?
- .ok_or(ExtractorError::Unauthorized)?;
- let permission = EntityPermission::AccessLevel { access_level };
- if !permission.satisfies::<T>() {
- return Err(ExtractorError::Unauthorized);
+ ),
+ Some(MacroAuthorization::Bot(bot)) => {
+ generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ &bot,
+ project.id(),
+ EntityType::Project,
+ )
+ .await?
}
- let auth = macro_user_id
- .map(EntityAccessAuth::Authenticated)
- .unwrap_or(EntityAccessAuth::Unauthenticated);
-
- project_access_receipt(project.id(), auth, permission)
+ Some(MacroAuthorization::User(user)) | Some(MacroAuthorization::Internal(Some(user))) => {
+ get_project_access_receipt(service.as_ref(), Some(user.macro_user_id), project.id())
+ .await?
+ }
+ None => get_project_access_receipt(service.as_ref(), None, project.id()).await?,
};
Ok(ProjectBodyAccessOutcome::FoundProject {
@@ -370,6 +355,27 @@ where
})
}
+async fn get_project_access_receipt<T: RequiredPermission>(
+ service: &impl EntityAccessService,
+ macro_user_id: Option<MacroUserIdStr<'static>>,
+ project_id: &str,
+) -> Result<EntityAccessReceipt<T>, ExtractorError> {
+ let access_level = service
+ .get_access_level(macro_user_id.as_deref(), project_id, EntityType::Project)
+ .await
+ .map_err(ExtractorError::from)?
+ .ok_or(ExtractorError::Unauthorized)?;
+ let permission = EntityPermission::AccessLevel { access_level };
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
+ }
+ let auth = macro_user_id
+ .map(EntityAccessAuth::Authenticated)
+ .unwrap_or(EntityAccessAuth::Unauthenticated);
+
+ Ok(project_access_receipt(project_id, auth, permission))
+}
+
fn deserialize_body<V: DeserializeOwned>(json: serde_json::Value) -> Result<V, ExtractorError> {
serde_json::from_value(json).map_err(|_| ExtractorError::BadRequest("Invalid request body"))
}
diff --git a/crates/entity_access/src/inbound/axum_extractors/project/test.rs b/crates/entity_access/src/inbound/axum_extractors/project/test.rs
index 243b8f8b69..6b4f305a12 100644
--- a/crates/entity_access/src/inbound/axum_extractors/project/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/project/test.rs
@@ -20,10 +20,14 @@ use uuid::Uuid;
use super::*;
use crate::{
domain::models::{
- AccessError, BotId, CallChannelInfo, EditAccessLevel, EntityAccessAuth, UserTeamInfo,
- ViewAccessLevel,
+ AccessError, BotAccessScope, BotId, CallChannelInfo, EditAccessLevel, EntityAccessAuth,
+ UserTeamInfo, ViewAccessLevel,
+ },
+ inbound::axum_extractors::test_support::{
+ BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID, BotAccessCall,
+ MALFORMED_SYSTEM_BOT_TOKEN, VALID_BOT_TOKEN, malformed_system_bot_authentication,
+ valid_bot_authentication,
},
- inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
};
const PROJECT_ID: &str = "project-1";
@@ -52,20 +56,32 @@ struct AccessCall {
#[derive(Clone, Debug)]
struct FakeEntityAccessService {
access_level: Option<AccessLevel>,
+ bot_permission: Option<EntityPermission>,
calls: Arc<Mutex<Vec<AccessCall>>>,
+ bot_calls: Arc<Mutex<Vec<BotAccessCall>>>,
}
impl FakeEntityAccessService {
fn new(access_level: Option<AccessLevel>) -> Self {
Self {
access_level,
+ bot_permission: access_level
+ .map(|access_level| EntityPermission::AccessLevel { access_level }),
calls: Arc::new(Mutex::new(Vec::new())),
+ bot_calls: Arc::new(Mutex::new(Vec::new())),
}
}
fn calls(&self) -> Vec<AccessCall> {
self.calls.lock().expect("calls lock poisoned").clone()
}
+
+ fn bot_calls(&self) -> Vec<BotAccessCall> {
+ self.bot_calls
+ .lock()
+ .expect("bot calls lock poisoned")
+ .clone()
+ }
}
impl EntityAccessService for FakeEntityAccessService {
@@ -81,11 +97,31 @@ impl EntityAccessService for FakeEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
- _bot_id: BotId,
- _entity_id: &str,
- _entity_type: EntityType,
+ bot_id: BotId,
+ scope: BotAccessScope,
+ entity_id: &str,
+ entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
- panic!("unexpected generate_bot_entity_access_receipt call")
+ self.bot_calls
+ .lock()
+ .expect("bot calls lock poisoned")
+ .push(BotAccessCall {
+ bot_id,
+ scope: scope.clone(),
+ entity_id: entity_id.to_string(),
+ entity_type,
+ });
+
+ let permission = self.bot_permission.ok_or(AccessError::Unauthorized)?;
+ EntityAccessReceipt::try_new_bot(
+ bot_id.into_storage_id(),
+ (&scope).into(),
+ Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ permission,
+ )
}
async fn get_access_level(
@@ -193,11 +229,11 @@ impl MacroAuthorizationService for FakeAuthorizationService {
bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
- if token != VALID_BOT_TOKEN {
- return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ match token {
+ VALID_BOT_TOKEN => Ok(valid_bot_authentication(bot_scope)),
+ MALFORMED_SYSTEM_BOT_TOKEN => Ok(malformed_system_bot_authentication(bot_scope)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
}
-
- Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -277,11 +313,11 @@ fn bearer_request(body: &str, token: &str) -> Request<Body> {
.expect("request should be valid")
}
-fn bot_request(body: &str) -> Request<Body> {
+fn bot_request(body: &str, scope: BotScope, token: &str) -> Request<Body> {
Request::post("/")
.header(header::CONTENT_TYPE, "application/json")
- .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
- .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
+ .header(BOT_TOKEN_HEADER, token)
+ .header(BOT_SCOPE_HEADER, scope.as_str())
.body(Body::from(body.to_string()))
.expect("request should be valid")
}
@@ -300,9 +336,13 @@ fn internal_request(body: &str, user_id: Option<&str>) -> Request<Body> {
}
fn project(deleted: bool) -> BasicProject {
+ project_owned_by(deleted, OWNER_ID)
+}
+
+fn project_owned_by(deleted: bool, owner_id: &'static str) -> BasicProject {
BasicProject {
id: PROJECT_ID.to_string(),
- user_id: MacroUserIdStr::parse_from_str(OWNER_ID).expect("owner id should be valid"),
+ user_id: MacroUserIdStr::parse_from_str(owner_id).expect("owner id should be valid"),
parent_id: None,
name: "Test project".to_string(),
deleted_at: deleted.then(|| {
@@ -327,6 +367,12 @@ fn project_request(token: Option<&str>, project: BasicProject) -> Request<Body>
request
}
+fn bot_project_request(scope: BotScope, token: &str, project: BasicProject) -> Request<Body> {
+ let mut request = bot_request("", scope, token);
+ request.extensions_mut().insert(project);
+ request
+}
+
fn internal_project_request(user_id: Option<&str>, project: BasicProject) -> Request<Body> {
let mut request = internal_request("", user_id);
request.extensions_mut().insert(project);
@@ -379,33 +425,138 @@ async fn authenticated_project_owner_bypasses_access_lookup() {
}
#[tokio::test]
-async fn bot_project_access_is_forbidden_before_acl_lookup() {
+async fn user_scoped_bot_project_owner_delegates_to_the_service() {
let state = TestState::new(Some(AccessLevel::Owner));
- let mut request = project_request(None, project(false));
- request.headers_mut().insert(
- BOT_TOKEN_HEADER,
- VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
+ let extracted = extract_project_access::<EditAccessLevel>(
+ bot_project_request(
+ BotScope::User,
+ VALID_BOT_TOKEN,
+ project_owned_by(false, BOT_ACTING_USER_ID),
+ ),
+ &state,
+ )
+ .await
+ .expect("the scoped service should delegate owner access");
+
+ assert_eq!(
+ extracted
+ .entity_access_receipt
+ .get_authenticated_bot()
+ .expect("receipt should authenticate the bot")
+ .bot_id(),
+ BOT_ID
);
- request.headers_mut().insert(
- BOT_SCOPE_HEADER,
- BotScope::User
- .as_str()
- .parse()
- .expect("bot scope should be valid"),
+ assert!(matches!(
+ extracted.entity_access_receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner
+ }
+ ));
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::User {
+ user_id: MacroUserIdStr::parse_from_str(BOT_ACTING_USER_ID)
+ .expect("bot acting user id should be valid"),
+ user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
+ },
+ entity_id: PROJECT_ID.to_string(),
+ entity_type: EntityType::Project,
+ }]
);
- let error = extract_project_access::<ViewAccessLevel>(request, &state)
- .await
- .expect_err("bot credentials should be forbidden");
- let response = error.into_response();
-
- assert_eq!(response.status(), StatusCode::FORBIDDEN);
- let body = to_bytes(response.into_body(), usize::MAX)
- .await
- .expect("response body should be readable");
- assert_eq!(body.as_ref(), br#"{"message":"forbidden"}"#);
assert!(state.entity_access.calls().is_empty());
}
+#[tokio::test]
+async fn team_scoped_bot_project_access_uses_the_scoped_service() {
+ let state = TestState::new(Some(AccessLevel::Edit));
+ let extracted = extract_project_access::<EditAccessLevel>(
+ bot_project_request(BotScope::Team, VALID_BOT_TOKEN, project(false)),
+ &state,
+ )
+ .await
+ .expect("team-scoped project access should be allowed");
+
+ assert!(matches!(
+ extracted.entity_access_receipt.auth(),
+ EntityAccessAuth::Bot(_)
+ ));
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: PROJECT_ID.to_string(),
+ entity_type: EntityType::Project,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn user_scoped_bot_without_acting_user_is_rejected() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let result = extract_project_access::<ViewAccessLevel>(
+ bot_project_request(BotScope::User, MALFORMED_SYSTEM_BOT_TOKEN, project(false)),
+ &state,
+ )
+ .await;
+
+ assert!(matches!(
+ result,
+ Err(ExtractorError::UnauthorizedWithMessage(
+ "bot user scope requires an acting user"
+ ))
+ ));
+ assert!(state.entity_access.bot_calls().is_empty());
+}
+
+#[tokio::test]
+async fn bot_project_access_below_the_required_level_is_rejected() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let result = extract_project_access::<EditAccessLevel>(
+ bot_project_request(BotScope::Team, VALID_BOT_TOKEN, project(false)),
+ &state,
+ )
+ .await;
+
+ assert!(matches!(result, Err(ExtractorError::Unauthorized)));
+ assert_eq!(state.entity_access.bot_calls().len(), 1);
+}
+
+#[tokio::test]
+async fn deleted_project_requires_owner_permission_from_the_bot_service() {
+ let owner_state = TestState::new(Some(AccessLevel::Owner));
+ let extracted = extract_project_access::<ViewAccessLevel>(
+ bot_project_request(BotScope::Team, VALID_BOT_TOKEN, project(true)),
+ &owner_state,
+ )
+ .await
+ .expect("a bot receipt with owner permission should access a deleted project");
+ assert!(matches!(
+ extracted.entity_access_receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner
+ }
+ ));
+
+ let view_state = TestState::new(Some(AccessLevel::View));
+ let result = extract_project_access::<ViewAccessLevel>(
+ bot_project_request(BotScope::Team, VALID_BOT_TOKEN, project(true)),
+ &view_state,
+ )
+ .await;
+ assert!(matches!(
+ result,
+ Err(ExtractorError::UnauthorizedWithMessage(
+ "only owner can access deleted resource"
+ ))
+ ));
+ assert_eq!(view_state.entity_access.bot_calls().len(), 1);
+}
+
#[tokio::test]
async fn deleted_project_rejects_non_owner_before_access_lookup() {
let state = TestState::new(Some(AccessLevel::Owner));
@@ -511,24 +662,127 @@ async fn direct_project_id_with_sufficient_access_returns_receipt_and_body() {
}
#[tokio::test]
-async fn bot_project_body_access_is_forbidden_before_acl_lookup() {
+async fn user_scoped_bot_project_body_access_preserves_the_typed_body() {
let state = TestState::new(Some(AccessLevel::Owner));
- let error = EditExtractor::from_request(
- bot_request(r#"{"name":"document","projectId":"project-1"}"#),
+ let result = EditExtractor::from_request(
+ bot_request(
+ r#"{"name":"document","projectId":"project-1"}"#,
+ BotScope::User,
+ VALID_BOT_TOKEN,
+ ),
&state,
)
.await
- .expect_err("bot credentials should be forbidden");
- let response = error.into_response();
+ .expect("the user-scoped bot should receive delegated owner access");
- assert_eq!(response.status(), StatusCode::FORBIDDEN);
- let body = to_bytes(response.into_body(), usize::MAX)
- .await
- .expect("response body should be readable");
- assert_eq!(body.as_ref(), br#"{"message":"forbidden"}"#);
+ let ProjectBodyAccessLevelExtractorV2::FoundProject {
+ entity_access_receipt,
+ body,
+ ..
+ } = result
+ else {
+ panic!("project should be found")
+ };
+
+ assert_eq!(body.name, "document");
+ assert_eq!(body.project_id.as_deref(), Some(PROJECT_ID));
+ assert!(matches!(
+ entity_access_receipt.auth(),
+ EntityAccessAuth::Bot(_)
+ ));
+ assert!(matches!(
+ entity_access_receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner
+ }
+ ));
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::User {
+ user_id: MacroUserIdStr::parse_from_str(BOT_ACTING_USER_ID)
+ .expect("bot acting user id should be valid"),
+ user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
+ },
+ entity_id: PROJECT_ID.to_string(),
+ entity_type: EntityType::Project,
+ }]
+ );
assert!(state.entity_access.calls().is_empty());
}
+#[tokio::test]
+async fn team_scoped_bot_project_body_access_uses_the_scoped_service() {
+ let state = TestState::new(Some(AccessLevel::Edit));
+ let result = EditExtractor::from_request(
+ bot_request(
+ r#"{"name":"document","projectParentId":"parent-project"}"#,
+ BotScope::Team,
+ VALID_BOT_TOKEN,
+ ),
+ &state,
+ )
+ .await
+ .expect("team-scoped bot access should be allowed");
+
+ let ProjectBodyAccessLevelExtractorV2::FoundProject { project, body, .. } = result else {
+ panic!("parent project should be found")
+ };
+ assert_eq!(project.id(), "parent-project");
+ assert_eq!(body.project_parent_id.as_deref(), Some("parent-project"));
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: "parent-project".to_string(),
+ entity_type: EntityType::Project,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn user_scoped_bot_project_body_without_acting_user_is_rejected() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let result = EditExtractor::from_request(
+ bot_request(
+ r#"{"name":"document","projectId":"project-1"}"#,
+ BotScope::User,
+ MALFORMED_SYSTEM_BOT_TOKEN,
+ ),
+ &state,
+ )
+ .await;
+
+ assert!(matches!(
+ result,
+ Err(ExtractorError::UnauthorizedWithMessage(
+ "bot user scope requires an acting user"
+ ))
+ ));
+ assert!(state.entity_access.bot_calls().is_empty());
+}
+
+#[tokio::test]
+async fn bot_project_body_access_below_the_required_level_is_rejected() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let result = EditExtractor::from_request(
+ bot_request(
+ r#"{"name":"document","projectId":"project-1"}"#,
+ BotScope::Team,
+ VALID_BOT_TOKEN,
+ ),
+ &state,
+ )
+ .await;
+
+ assert!(matches!(result, Err(ExtractorError::Unauthorized)));
+ assert_eq!(state.entity_access.bot_calls().len(), 1);
+}
+
#[tokio::test]
async fn parent_project_id_is_used_for_access_lookup() {
let state = TestState::new(Some(AccessLevel::Owner));
@@ -629,6 +883,37 @@ async fn malformed_json_and_invalid_body_are_distinguished() {
));
}
+#[tokio::test]
+async fn bot_project_body_parse_failures_are_preserved() {
+ let malformed_state = TestState::new(Some(AccessLevel::Edit));
+ let malformed_json = EditExtractor::from_request(
+ bot_request("{", BotScope::Team, VALID_BOT_TOKEN),
+ &malformed_state,
+ )
+ .await;
+ assert!(matches!(
+ malformed_json,
+ Err(ExtractorError::BadRequest("Invalid JSON body"))
+ ));
+ assert!(malformed_state.entity_access.bot_calls().is_empty());
+
+ let invalid_body_state = TestState::new(Some(AccessLevel::Edit));
+ let invalid_body = EditExtractor::from_request(
+ bot_request(
+ r#"{"name":42,"projectId":"project-1"}"#,
+ BotScope::Team,
+ VALID_BOT_TOKEN,
+ ),
+ &invalid_body_state,
+ )
+ .await;
+ assert!(matches!(
+ invalid_body,
+ Err(ExtractorError::BadRequest("Invalid request body"))
+ ));
+ assert_eq!(invalid_body_state.entity_access.bot_calls().len(), 1);
+}
+
#[tokio::test]
async fn anonymous_access_uses_public_project_access() {
let state = TestState::new(Some(AccessLevel::View));
diff --git a/crates/entity_access/src/inbound/axum_extractors/team.rs b/crates/entity_access/src/inbound/axum_extractors/team.rs
index 6043726b57..df30fe642b 100644
--- a/crates/entity_access/src/inbound/axum_extractors/team.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/team.rs
@@ -1,8 +1,8 @@
//! Team access extractor.
//!
//! Unlike the other access extractors, this one does not take a team id from
-//! the path — it resolves whichever team the authenticated user belongs to
-//! and reports the role they hold.
+//! the path. It resolves the team represented by the authenticated principal
+//! and reports the role granted under that principal's access scope.
#[cfg(test)]
mod test;
@@ -16,13 +16,17 @@ use axum::{
http::request::Parts,
};
-use super::{ExtractorError, RequiredPermission};
+use super::{ExtractorError, RequiredPermission, bot::map_bot_access_scope};
use crate::domain::{
- models::{Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType},
+ models::{
+ AccessError, BotAccessScope, Entity, EntityAccessAuth, EntityAccessReceipt,
+ EntityPermission, EntityType,
+ },
ports::EntityAccessService,
};
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
+ AnyPrincipal, BotAuthentication, MacroAuthorization, MacroAuthorizationExtractor,
+ MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::user_id::MacroUserIdStr;
@@ -51,7 +55,7 @@ impl<T: RequiredPermission> TeamAccessOutcome<T> {
}
}
-async fn team_access_outcome<T, Svc>(
+async fn user_team_access_outcome<T, Svc>(
service: &Svc,
macro_user_id: MacroUserIdStr<'static>,
) -> Result<TeamAccessOutcome<T>, ExtractorError>
@@ -85,7 +89,66 @@ where
}))
}
-/// Authorizes a user and resolves their optional team membership.
+async fn bot_team_access_outcome<T, Svc>(
+ service: &Svc,
+ authentication: &BotAuthentication,
+) -> Result<TeamAccessOutcome<T>, ExtractorError>
+where
+ T: RequiredPermission,
+ Svc: EntityAccessService,
+{
+ let scope = map_bot_access_scope(authentication)?;
+ let team_id = match &scope {
+ BotAccessScope::User { user_id, .. } => {
+ let Some(team_info) = service
+ .get_user_team(user_id)
+ .await
+ .map_err(ExtractorError::from)?
+ else {
+ return Ok(TeamAccessOutcome::NotInTeam);
+ };
+ team_info.team_id
+ }
+ BotAccessScope::Team { team_id } => *team_id,
+ };
+
+ match service
+ .generate_bot_entity_access_receipt::<T>(
+ authentication.bot_id,
+ scope,
+ &team_id.to_string(),
+ EntityType::Team,
+ )
+ .await
+ {
+ Ok(receipt) => Ok(TeamAccessOutcome::Qualifying(receipt)),
+ Err(AccessError::Unauthorized) => Ok(TeamAccessOutcome::InsufficientRole),
+ Err(error) => Err(ExtractorError::from(error)),
+ }
+}
+
+async fn principal_team_access_outcome<T, Svc>(
+ service: &Svc,
+ authorization: MacroAuthorization,
+) -> Result<TeamAccessOutcome<T>, ExtractorError>
+where
+ T: RequiredPermission,
+ Svc: EntityAccessService,
+{
+ match authorization {
+ MacroAuthorization::User(user) | MacroAuthorization::Internal(Some(user)) => {
+ user_team_access_outcome::<T, Svc>(service, user.macro_user_id).await
+ }
+ MacroAuthorization::Bot(authentication) => {
+ bot_team_access_outcome::<T, Svc>(service, &authentication).await
+ }
+ MacroAuthorization::Internal(None) => {
+ Err(ExtractorError::UnauthorizedWithMessage("unauthorized"))
+ }
+ }
+}
+
+/// Authorizes a principal and resolves its optional team access.
///
/// The extractor uses the required [`MacroAuthorizationExtractor`], so missing,
/// invalid, and identity-less internal credentials are rejected. A qualifying
@@ -93,7 +156,7 @@ where
/// `None`.
#[derive(Debug)]
pub struct OptionalMacroUserTeamExtractorV2<T: RequiredPermission, Svc, Auth> {
- /// The entity access receipt, if the authorized user has a qualifying team membership.
+ /// The entity access receipt, if the principal has qualifying team access.
pub entity_access_receipt: Option<EntityAccessReceipt<T>>,
_marker: PhantomData<(T, Svc, Auth)>,
}
@@ -124,15 +187,13 @@ where
#[tracing::instrument(err, skip(state, parts))]
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let authorization: MacroAuthorizationExtractor<Auth, UserOrInternal> = parts
+ let authorization: MacroAuthorizationExtractor<Auth, AnyPrincipal> = parts
.extract_with_state(state)
.await
.map_err(ExtractorError::from)?;
- let outcome = team_access_outcome::<T, Svc>(
- service.as_ref(),
- authorization.authorization.user.macro_user_id,
- )
- .await?;
+ let outcome =
+ principal_team_access_outcome::<T, Svc>(service.as_ref(), authorization.authorization)
+ .await?;
Ok(Self {
entity_access_receipt: outcome.into_optional_receipt(),
@@ -141,15 +202,15 @@ where
}
}
-/// Authorizes a user and resolves their required team membership.
+/// Authorizes a principal and resolves its required team access.
///
/// The extractor uses [`MacroAuthorizationExtractor`] to authenticate the request.
-/// It returns an [`EntityAccessReceipt`] when the user belongs to a team and their
-/// role satisfies `T`. A user without a team receives `"not in a team"`; a user
-/// whose role does not satisfy `T` receives `"you do not have a high enough role"`.
+/// It returns an [`EntityAccessReceipt`] when the principal has team access whose
+/// role satisfies `T`. A user without a team receives `"not in a team"`; a role
+/// that does not satisfy `T` receives `"you do not have a high enough role"`.
#[derive(Debug)]
pub struct MacroUserTeamExtractorV2<T: RequiredPermission, Svc, Auth> {
- /// The entity access receipt for the authorized team member.
+ /// The entity access receipt for the authorized principal.
pub entity_access_receipt: EntityAccessReceipt<T>,
_marker: PhantomData<(T, Svc, Auth)>,
}
@@ -168,16 +229,14 @@ where
#[tracing::instrument(err, skip(state, parts))]
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let authorization: MacroAuthorizationExtractor<Auth, UserOrInternal> = parts
+ let authorization: MacroAuthorizationExtractor<Auth, AnyPrincipal> = parts
.extract_with_state(state)
.await
.map_err(ExtractorError::from)?;
- let entity_access_receipt = team_access_outcome::<T, Svc>(
- service.as_ref(),
- authorization.authorization.user.macro_user_id,
- )
- .await?
- .into_required_receipt()?;
+ let entity_access_receipt =
+ principal_team_access_outcome::<T, Svc>(service.as_ref(), authorization.authorization)
+ .await?
+ .into_required_receipt()?;
Ok(Self {
entity_access_receipt,
diff --git a/crates/entity_access/src/inbound/axum_extractors/team/test.rs b/crates/entity_access/src/inbound/axum_extractors/team/test.rs
index fe28b327c2..46ed836b31 100644
--- a/crates/entity_access/src/inbound/axum_extractors/team/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/team/test.rs
@@ -27,10 +27,15 @@ use uuid::Uuid;
use super::*;
use crate::{
domain::models::{
- AccessError, AccessLevel, AdminTeamRole, BotId, CallChannelInfo, EntityAccessAuth,
- EntityPermission, TeamRole, UserTeamInfo,
+ AccessError, AccessLevel, AdminTeamRole, BotAccessScope, BotId, BotReceiptScope,
+ CallChannelInfo, EntityAccessAuth, EntityPermission, MemberTeamRole, OwnerTeamRole,
+ TeamRole, UserTeamInfo,
+ },
+ inbound::axum_extractors::test_support::{
+ BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID, BotAccessCall,
+ MALFORMED_SYSTEM_BOT_TOKEN, VALID_BOT_TOKEN, malformed_system_bot_authentication,
+ valid_bot_authentication,
},
- inbound::axum_extractors::test_support::{VALID_BOT_TOKEN, valid_bot_authentication},
};
const USER_ID: &str = "macro|[email protected]";
@@ -44,13 +49,23 @@ type V2Extractor = OptionalMacroUserTeamExtractorV2<
FakeEntityAccessService,
FakeAuthorizationService,
>;
+type OptionalMemberV2Extractor = OptionalMacroUserTeamExtractorV2<
+ MemberTeamRole,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+>;
type RequiredV2Extractor =
MacroUserTeamExtractorV2<AdminTeamRole, FakeEntityAccessService, FakeAuthorizationService>;
+type RequiredMemberV2Extractor =
+ MacroUserTeamExtractorV2<MemberTeamRole, FakeEntityAccessService, FakeAuthorizationService>;
+type RequiredOwnerV2Extractor =
+ MacroUserTeamExtractorV2<OwnerTeamRole, FakeEntityAccessService, FakeAuthorizationService>;
#[derive(Clone, Debug, Default)]
struct FakeEntityAccessService {
memberships: Arc<HashMap<String, UserTeamInfo>>,
membership_lookups: Arc<Mutex<Vec<String>>>,
+ bot_calls: Arc<Mutex<Vec<BotAccessCall>>>,
}
impl FakeEntityAccessService {
@@ -71,6 +86,13 @@ impl FakeEntityAccessService {
.expect("membership lookups lock poisoned")
.clone()
}
+
+ fn bot_calls(&self) -> Vec<BotAccessCall> {
+ self.bot_calls
+ .lock()
+ .expect("bot calls lock poisoned")
+ .clone()
+ }
}
impl EntityAccessService for FakeEntityAccessService {
@@ -86,11 +108,43 @@ impl EntityAccessService for FakeEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
- _bot_id: BotId,
- _entity_id: &str,
- _entity_type: EntityType,
+ bot_id: BotId,
+ scope: BotAccessScope,
+ entity_id: &str,
+ entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
- panic!("unexpected generate_bot_entity_access_receipt call")
+ self.bot_calls
+ .lock()
+ .expect("bot calls lock poisoned")
+ .push(BotAccessCall {
+ bot_id,
+ scope: scope.clone(),
+ entity_id: entity_id.to_string(),
+ entity_type,
+ });
+
+ let requested_team_id = Uuid::parse_str(entity_id)
+ .map_err(|_| AccessError::BadRequest("Invalid team ID format"))?;
+ let role = match &scope {
+ BotAccessScope::User { user_id, .. } => self
+ .memberships
+ .get(user_id.as_ref())
+ .filter(|team| team.team_id == requested_team_id)
+ .map(|team| team.role)
+ .ok_or(AccessError::Unauthorized)?,
+ BotAccessScope::Team { team_id } if *team_id == requested_team_id => TeamRole::Member,
+ BotAccessScope::Team { .. } => return Err(AccessError::Unauthorized),
+ };
+
+ EntityAccessReceipt::try_new_bot(
+ bot_id.into_storage_id(),
+ (&scope).into(),
+ Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ EntityPermission::TeamRole { role },
+ )
}
async fn get_access_level(
@@ -202,11 +256,11 @@ impl MacroAuthorizationService for FakeAuthorizationService {
bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
- if token != VALID_BOT_TOKEN {
- return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ match token {
+ VALID_BOT_TOKEN => Ok(valid_bot_authentication(bot_scope)),
+ MALFORMED_SYSTEM_BOT_TOKEN => Ok(malformed_system_bot_authentication(bot_scope)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
}
-
- Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -272,6 +326,14 @@ fn bearer_request(token: &str) -> Request<Body> {
.expect("request should be valid")
}
+fn bot_request(token: &str, scope: BotScope) -> Request<Body> {
+ Request::builder()
+ .header(BOT_TOKEN_HEADER, token)
+ .header(BOT_SCOPE_HEADER, scope.as_str())
+ .body(Body::empty())
+ .expect("request should be valid")
+}
+
async fn extract_v2(
request: Request<Body>,
state: &TestState,
@@ -280,6 +342,14 @@ async fn extract_v2(
V2Extractor::from_request_parts(&mut parts, state).await
}
+async fn extract_optional_member_v2(
+ request: Request<Body>,
+ state: &TestState,
+) -> Result<OptionalMemberV2Extractor, ExtractorError> {
+ let (mut parts, _) = request.into_parts();
+ OptionalMemberV2Extractor::from_request_parts(&mut parts, state).await
+}
+
async fn extract_required_v2(
request: Request<Body>,
state: &TestState,
@@ -288,6 +358,22 @@ async fn extract_required_v2(
RequiredV2Extractor::from_request_parts(&mut parts, state).await
}
+async fn extract_required_member_v2(
+ request: Request<Body>,
+ state: &TestState,
+) -> Result<RequiredMemberV2Extractor, ExtractorError> {
+ let (mut parts, _) = request.into_parts();
+ RequiredMemberV2Extractor::from_request_parts(&mut parts, state).await
+}
+
+async fn extract_required_owner_v2(
+ request: Request<Body>,
+ state: &TestState,
+) -> Result<RequiredOwnerV2Extractor, ExtractorError> {
+ let (mut parts, _) = request.into_parts();
+ RequiredOwnerV2Extractor::from_request_parts(&mut parts, state).await
+}
+
async fn response_parts(response: Response) -> (StatusCode, String) {
let status = response.status();
let body = to_bytes(response.into_body(), usize::MAX)
@@ -297,7 +383,11 @@ async fn response_parts(response: Response) -> (StatusCode, String) {
(status, body)
}
-fn assert_receipt(receipt: &EntityAccessReceipt<AdminTeamRole>, user_id: &str, role: TeamRole) {
+fn assert_receipt<T: RequiredPermission>(
+ receipt: &EntityAccessReceipt<T>,
+ user_id: &str,
+ role: TeamRole,
+) {
assert_eq!(receipt.entity().entity_id, TEAM_ID.to_string());
assert_eq!(receipt.entity().entity_type, EntityType::Team);
assert!(matches!(
@@ -310,6 +400,25 @@ fn assert_receipt(receipt: &EntityAccessReceipt<AdminTeamRole>, user_id: &str, r
));
}
+fn assert_bot_receipt<T: RequiredPermission>(
+ receipt: &EntityAccessReceipt<T>,
+ team_id: Uuid,
+ role: TeamRole,
+ scope: BotReceiptScope,
+) {
+ assert_eq!(receipt.entity().entity_id, team_id.to_string());
+ assert_eq!(receipt.entity().entity_type, EntityType::Team);
+ assert_eq!(receipt.get_authenticated_bot().unwrap().bot_id(), BOT_ID);
+ assert_eq!(
+ receipt.get_authenticated_bot_auth().unwrap().scope(),
+ &scope
+ );
+ assert!(matches!(
+ receipt.entity_permission(),
+ EntityPermission::TeamRole { role: actual_role } if *actual_role == role
+ ));
+}
+
#[tokio::test]
async fn required_v2_accepts_bearer_credentials_for_a_qualifying_member() {
let state = state(
@@ -380,46 +489,200 @@ async fn required_v2_rejects_expired_credentials() {
}
#[tokio::test]
-async fn team_extractors_forbid_bots_without_membership_lookup() {
- let optional_state = state(
+async fn team_scoped_bot_gets_member_receipts_from_both_extractors() {
+ let state = state(
FakeEntityAccessService::default(),
FakeAuthorizationService::default(),
);
- let optional_error = extract_v2(
- Request::builder()
- .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
- .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
- .body(Body::empty())
- .expect("request should be valid"),
- &optional_state,
+
+ let optional = extract_optional_member_v2(bot_request(VALID_BOT_TOKEN, BotScope::Team), &state)
+ .await
+ .expect("team-scoped bot should be authorized");
+ let optional_receipt = optional
+ .entity_access_receipt
+ .expect("Member should satisfy optional team access");
+ assert_bot_receipt(
+ &optional_receipt,
+ BOT_TEAM_ID,
+ TeamRole::Member,
+ BotReceiptScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ );
+
+ let required = extract_required_member_v2(bot_request(VALID_BOT_TOKEN, BotScope::Team), &state)
+ .await
+ .expect("team-scoped bot should satisfy required Member access");
+ assert_bot_receipt(
+ &required.entity_access_receipt,
+ BOT_TEAM_ID,
+ TeamRole::Member,
+ BotReceiptScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ );
+
+ assert!(state.entity_access.membership_lookups().is_empty());
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [
+ BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: BOT_TEAM_ID.to_string(),
+ entity_type: EntityType::Team,
+ },
+ BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: BOT_TEAM_ID.to_string(),
+ entity_type: EntityType::Team,
+ },
+ ]
+ );
+}
+
+#[tokio::test]
+async fn team_scoped_bot_cannot_satisfy_admin_or_owner_requirements() {
+ let state = state(
+ FakeEntityAccessService::default(),
+ FakeAuthorizationService::default(),
+ );
+
+ let optional = extract_v2(bot_request(VALID_BOT_TOKEN, BotScope::Team), &state)
+ .await
+ .expect("insufficient optional team access should still extract");
+ assert!(optional.entity_access_receipt.is_none());
+
+ let admin_error = extract_required_v2(bot_request(VALID_BOT_TOKEN, BotScope::Team), &state)
+ .await
+ .expect_err("team-scoped bot should not receive Admin access");
+ assert!(matches!(
+ admin_error,
+ ExtractorError::UnauthorizedWithMessage("you do not have a high enough role")
+ ));
+
+ let owner_error =
+ extract_required_owner_v2(bot_request(VALID_BOT_TOKEN, BotScope::Team), &state)
+ .await
+ .expect_err("team-scoped bot should not receive Owner access");
+ assert!(matches!(
+ owner_error,
+ ExtractorError::UnauthorizedWithMessage("you do not have a high enough role")
+ ));
+}
+
+#[tokio::test]
+async fn user_scoped_bot_uses_acting_users_team_and_actual_admin_role() {
+ let state = state(
+ FakeEntityAccessService::default().with_membership(BOT_ACTING_USER_ID, TeamRole::Admin),
+ FakeAuthorizationService::default(),
+ );
+
+ let extracted = extract_required_v2(bot_request(VALID_BOT_TOKEN, BotScope::User), &state)
+ .await
+ .expect("acting admin should satisfy required Admin access");
+
+ assert_bot_receipt(
+ &extracted.entity_access_receipt,
+ TEAM_ID,
+ TeamRole::Admin,
+ BotReceiptScope::User {
+ acting_user: MacroUserIdStr::try_from(BOT_ACTING_USER_ID.to_string())
+ .expect("valid acting user id"),
+ },
+ );
+ assert_eq!(
+ state.entity_access.membership_lookups(),
+ [BOT_ACTING_USER_ID.to_string()]
+ );
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::User {
+ user_id: MacroUserIdStr::try_from(BOT_ACTING_USER_ID.to_string())
+ .expect("valid acting user id"),
+ user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
+ },
+ entity_id: TEAM_ID.to_string(),
+ entity_type: EntityType::Team,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn user_scoped_bot_without_acting_user_is_unauthorized() {
+ let state = state(
+ FakeEntityAccessService::default(),
+ FakeAuthorizationService::default(),
+ );
+
+ let error = extract_required_v2(
+ bot_request(MALFORMED_SYSTEM_BOT_TOKEN, BotScope::User),
+ &state,
)
.await
- .expect_err("bot credentials should be forbidden");
- let (status, body) = response_parts(optional_error.into_response()).await;
+ .expect_err("user scope without an acting user should fail");
- assert_eq!(status, StatusCode::FORBIDDEN);
- assert_eq!(body, r#"{"message":"forbidden"}"#);
- assert!(optional_state.entity_access.membership_lookups().is_empty());
+ assert!(matches!(
+ error,
+ ExtractorError::UnauthorizedWithMessage("bot user scope requires an acting user")
+ ));
+ assert!(state.entity_access.membership_lookups().is_empty());
+ assert!(state.entity_access.bot_calls().is_empty());
+}
- let required_state = state(
+#[tokio::test]
+async fn user_scoped_bot_without_team_membership_has_no_team_access() {
+ let state = state(
FakeEntityAccessService::default(),
FakeAuthorizationService::default(),
);
- let required_error = extract_required_v2(
- Request::builder()
- .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
- .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
- .body(Body::empty())
- .expect("request should be valid"),
- &required_state,
+
+ let optional = extract_v2(bot_request(VALID_BOT_TOKEN, BotScope::User), &state)
+ .await
+ .expect("missing optional team access should still extract");
+ assert!(optional.entity_access_receipt.is_none());
+
+ let error = extract_required_v2(bot_request(VALID_BOT_TOKEN, BotScope::User), &state)
+ .await
+ .expect_err("acting user without a team should fail required extraction");
+ assert!(matches!(
+ error,
+ ExtractorError::UnauthorizedWithMessage("not in a team")
+ ));
+ assert_eq!(
+ state.entity_access.membership_lookups(),
+ [
+ BOT_ACTING_USER_ID.to_string(),
+ BOT_ACTING_USER_ID.to_string(),
+ ]
+ );
+ assert!(state.entity_access.bot_calls().is_empty());
+}
+
+#[tokio::test]
+async fn team_scoped_bot_without_team_id_is_unauthorized() {
+ let state = state(
+ FakeEntityAccessService::default(),
+ FakeAuthorizationService::default(),
+ );
+
+ let error = extract_required_member_v2(
+ bot_request(MALFORMED_SYSTEM_BOT_TOKEN, BotScope::Team),
+ &state,
)
.await
- .expect_err("bot credentials should be forbidden");
- let (status, body) = response_parts(required_error.into_response()).await;
+ .expect_err("team scope without an owning team should fail");
- assert_eq!(status, StatusCode::FORBIDDEN);
- assert_eq!(body, r#"{"message":"forbidden"}"#);
- assert!(required_state.entity_access.membership_lookups().is_empty());
+ assert!(matches!(error, ExtractorError::Unauthorized));
+ assert!(state.entity_access.membership_lookups().is_empty());
+ assert!(state.entity_access.bot_calls().is_empty());
}
#[tokio::test]
diff --git a/crates/entity_access/src/inbound/axum_extractors/test_support.rs b/crates/entity_access/src/inbound/axum_extractors/test_support.rs
index 2738919e63..f77f2b8307 100644
--- a/crates/entity_access/src/inbound/axum_extractors/test_support.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/test_support.rs
@@ -1,10 +1,10 @@
-use crate::domain::models::TeamRole;
use std::sync::{Arc, Mutex};
use axum::extract::FromRef;
use macro_authorization::{
BotActingUserClaims, BotAuthentication, BotScope, InternalIdentityClaims,
MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+ MacroUserAuthentication,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -17,15 +17,20 @@ use uuid::Uuid;
use super::RequiredPermission;
use crate::domain::{
models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, EntityAccessReceipt, EntityPermission,
- EntityType, UserTeamInfo,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, Entity,
+ EntityAccessReceipt, EntityPermission, EntityType, TeamRole, UserTeamInfo,
},
ports::EntityAccessService,
};
pub(super) const INTERNAL_KEY: &str = "valid-internal-key";
pub(super) const USER_ID: &str = "macro|[email protected]";
+pub(super) const BOT_ACTING_USER_ID: &str = "macro|[email protected]";
+pub(super) const BOT_ACTING_USER_ORGANIZATION_ID: i32 = 42;
+pub(super) const BOT_ID: BotId = BotId::new_from_uuid(Uuid::from_u128(1));
+pub(super) const BOT_TEAM_ID: Uuid = Uuid::from_u128(3);
pub(super) const VALID_BOT_TOKEN: &str = "valid-bot-token";
+pub(super) const MALFORMED_SYSTEM_BOT_TOKEN: &str = "malformed-system-bot-token";
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct AccessCall {
@@ -34,23 +39,48 @@ pub(super) struct AccessCall {
pub(super) entity_type: EntityType,
}
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub(super) struct BotAccessCall {
+ pub(super) bot_id: BotId,
+ pub(super) scope: BotAccessScope,
+ pub(super) entity_id: String,
+ pub(super) entity_type: EntityType,
+}
+
#[derive(Clone, Debug)]
pub(super) struct FakeEntityAccessService {
access_level: Option<AccessLevel>,
+ bot_permission: Option<EntityPermission>,
calls: Arc<Mutex<Vec<AccessCall>>>,
+ bot_calls: Arc<Mutex<Vec<BotAccessCall>>>,
}
impl FakeEntityAccessService {
pub(super) fn new(access_level: Option<AccessLevel>) -> Self {
Self {
access_level,
+ bot_permission: access_level
+ .map(|access_level| EntityPermission::AccessLevel { access_level }),
calls: Arc::new(Mutex::new(Vec::new())),
+ bot_calls: Arc::new(Mutex::new(Vec::new())),
}
}
+ pub(super) fn with_bot_permission(mut self, permission: EntityPermission) -> Self {
+ self.bot_permission = Some(permission);
+ self
+ }
+
pub(super) fn calls(&self) -> Vec<AccessCall> {
self.calls.lock().expect("calls lock poisoned").clone()
}
+
+ pub(super) fn bot_calls(&self) -> Vec<BotAccessCall> {
+ self.bot_calls
+ .lock()
+ .expect("bot calls lock poisoned")
+ .clone()
+ }
}
impl EntityAccessService for FakeEntityAccessService {
@@ -66,11 +96,38 @@ impl EntityAccessService for FakeEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
- _bot_id: BotId,
- _entity_id: &str,
- _entity_type: EntityType,
+ bot_id: BotId,
+ scope: BotAccessScope,
+ entity_id: &str,
+ entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
- panic!("unexpected generate_bot_entity_access_receipt call")
+ self.bot_calls
+ .lock()
+ .expect("bot calls lock poisoned")
+ .push(BotAccessCall {
+ bot_id,
+ scope: scope.clone(),
+ entity_id: entity_id.to_string(),
+ entity_type,
+ });
+
+ if matches!(
+ entity_type,
+ EntityType::User | EntityType::ChannelMessage | EntityType::StaticFile
+ ) {
+ return Err(AccessError::BadRequest("Unsupported bot entity type"));
+ }
+
+ let permission = self.bot_permission.ok_or(AccessError::Unauthorized)?;
+ EntityAccessReceipt::try_new_bot(
+ bot_id.into_storage_id(),
+ (&scope).into(),
+ Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ permission,
+ )
}
async fn get_access_level(
@@ -177,11 +234,11 @@ impl MacroAuthorizationService for FakeAuthorizationService {
bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
- if token != VALID_BOT_TOKEN {
- return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ match token {
+ VALID_BOT_TOKEN => Ok(valid_bot_authentication(bot_scope)),
+ MALFORMED_SYSTEM_BOT_TOKEN => Ok(malformed_system_bot_authentication(bot_scope)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
}
-
- Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -198,20 +255,58 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
pub(super) fn valid_bot_authentication(bot_scope: BotScope) -> BotAuthentication {
+ match bot_scope {
+ BotScope::User => user_scoped_bot_authentication(),
+ BotScope::Team => team_scoped_bot_authentication(),
+ }
+}
+
+pub(super) fn user_scoped_bot_authentication() -> BotAuthentication {
BotAuthentication {
- bot_id: BotId::new_from_uuid(Uuid::from_u128(1)),
+ bot_id: BOT_ID,
+ token_id: Uuid::from_u128(2),
+ bot_scope: BotScope::User,
+ team_id: None,
+ acting_user: Some(MacroUserAuthentication {
+ macro_user_id: MacroUserIdStr::try_from(BOT_ACTING_USER_ID.to_string())
+ .expect("valid bot acting user id"),
+ user_context: user_context_with_organization(
+ BOT_ACTING_USER_ID,
+ Some(BOT_ACTING_USER_ORGANIZATION_ID),
+ ),
+ }),
+ }
+}
+
+pub(super) fn team_scoped_bot_authentication() -> BotAuthentication {
+ BotAuthentication {
+ bot_id: BOT_ID,
+ token_id: Uuid::from_u128(2),
+ bot_scope: BotScope::Team,
+ team_id: Some(BOT_TEAM_ID),
+ acting_user: None,
+ }
+}
+
+pub(super) fn malformed_system_bot_authentication(bot_scope: BotScope) -> BotAuthentication {
+ BotAuthentication {
+ bot_id: BOT_ID,
token_id: Uuid::from_u128(2),
bot_scope,
- team_id: (bot_scope == BotScope::Team).then_some(Uuid::from_u128(3)),
+ team_id: None,
acting_user: None,
}
}
fn user_context(user_id: &str) -> UserContext {
+ user_context_with_organization(user_id, None)
+}
+
+fn user_context_with_organization(user_id: &str, organization_id: Option<i32>) -> UserContext {
UserContext {
user_id: user_id.to_string(),
fusion_user_id: "fusion-user-id".to_string(),
- organization_id: None,
+ organization_id,
permissions: None,
}
}
diff --git a/crates/entity_access/src/inbound/axum_extractors/thread.rs b/crates/entity_access/src/inbound/axum_extractors/thread.rs
index 8832a6c947..41c967f9fd 100644
--- a/crates/entity_access/src/inbound/axum_extractors/thread.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/thread.rs
@@ -13,11 +13,11 @@ use axum::{
http::request::Parts,
};
use macro_authorization::{
- MacroAuthorizationService, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOrInternalService, UserOrInternalServiceAuthorization,
+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor,
};
-use super::{ExtractorError, RequiredPermission};
+use super::{ExtractorError, RequiredPermission, bot::generate_bot_entity_access_receipt};
use crate::domain::{
models::{
AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
@@ -54,20 +54,12 @@ where
let service = <Arc<Svc>>::from_ref(state);
let authorization =
- OptionalMacroAuthorizationExtractor::<Auth, UserOrInternalService>::from_request_parts(
+ OptionalMacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(
parts, state,
)
.await
- .map_err(ExtractorError::from)?;
- let is_internal_access = authorization
- .authorization
- .as_ref()
- .is_some_and(UserOrInternalServiceAuthorization::is_internal);
- let macro_user_id = authorization
- .authorization
- .as_ref()
- .and_then(UserOrInternalServiceAuthorization::acting_user)
- .map(|user| user.macro_user_id.clone());
+ .map_err(ExtractorError::from)?
+ .authorization;
let Path(path_params): Path<HashMap<String, String>> = parts
.extract()
@@ -81,6 +73,29 @@ where
))?
.clone();
+ if let Some(MacroAuthorization::Bot(authentication)) = authorization.as_ref() {
+ let entity_access_receipt = generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ authentication,
+ &thread_id,
+ EntityType::EmailThread,
+ )
+ .await?;
+
+ return Ok(Self {
+ entity_access_receipt,
+ _marker: PhantomData,
+ });
+ }
+
+ let is_internal_access = authorization
+ .as_ref()
+ .is_some_and(MacroAuthorization::is_internal);
+ let macro_user_id = authorization
+ .as_ref()
+ .and_then(MacroAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone());
+
if macro_user_id.is_none() && is_internal_access {
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
diff --git a/crates/entity_access/src/inbound/axum_extractors/thread/test.rs b/crates/entity_access/src/inbound/axum_extractors/thread/test.rs
index 23a71b6306..514d9cd585 100644
--- a/crates/entity_access/src/inbound/axum_extractors/thread/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/thread/test.rs
@@ -12,16 +12,20 @@ use macro_authorization::{
INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
+use macro_user_id::user_id::MacroUserIdStr;
use model_user::UserContext;
use rootcause::Report;
use tower::ServiceExt;
use super::*;
use crate::{
- domain::models::{EditAccessLevel, EntityAccessAuth, ViewAccessLevel},
+ domain::models::{
+ BotAccessScope, EditAccessLevel, EntityAccessAuth, EntityPermission, ViewAccessLevel,
+ },
inbound::axum_extractors::test_support::{
- AccessCall, FakeEntityAccessService, INTERNAL_KEY, USER_ID, VALID_BOT_TOKEN,
- valid_bot_authentication,
+ AccessCall, BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID,
+ BotAccessCall, FakeEntityAccessService, INTERNAL_KEY, MALFORMED_SYSTEM_BOT_TOKEN, USER_ID,
+ VALID_BOT_TOKEN, malformed_system_bot_authentication, valid_bot_authentication,
},
};
@@ -62,11 +66,11 @@ impl MacroAuthorizationService for FakeAuthorizationService {
bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
- if token != VALID_BOT_TOKEN {
- return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ match token {
+ VALID_BOT_TOKEN => Ok(valid_bot_authentication(bot_scope)),
+ MALFORMED_SYSTEM_BOT_TOKEN => Ok(malformed_system_bot_authentication(bot_scope)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
}
-
- Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -108,9 +112,23 @@ impl TestState {
fn with_authorization(
access_level: Option<AccessLevel>,
authorization: FakeAuthorizationService,
+ ) -> Self {
+ Self::with_service_and_authorization(
+ FakeEntityAccessService::new(access_level),
+ authorization,
+ )
+ }
+
+ fn with_service(entity_access: FakeEntityAccessService) -> Self {
+ Self::with_service_and_authorization(entity_access, FakeAuthorizationService::default())
+ }
+
+ fn with_service_and_authorization(
+ entity_access: FakeEntityAccessService,
+ authorization: FakeAuthorizationService,
) -> Self {
Self {
- entity_access: Arc::new(FakeEntityAccessService::new(access_level)),
+ entity_access: Arc::new(entity_access),
authorization: MacroAuthorizationState::new(Arc::new(authorization)),
}
}
@@ -310,12 +328,88 @@ async fn default_internal_user_uses_the_users_acl() {
}
#[tokio::test]
-async fn bot_thread_access_is_forbidden_before_acl_lookup() {
- let state = TestState::new(Some(AccessLevel::Owner));
+async fn user_scoped_bot_delegates_acting_user_access_to_the_scoped_service() {
+ let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ ));
+ let response = edit_router(state.clone())
+ .oneshot(
+ request()
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "bot");
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::User {
+ user_id: MacroUserIdStr::try_from(BOT_ACTING_USER_ID.to_string())
+ .expect("acting user id should be valid"),
+ user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
+ },
+ entity_id: THREAD_ID.to_string(),
+ entity_type: EntityType::EmailThread,
+ }]
+ );
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn team_scoped_bot_receives_only_its_scoped_repository_access() {
+ let state = TestState::with_service(
+ FakeEntityAccessService::new(Some(AccessLevel::Owner)).with_bot_permission(
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ },
+ ),
+ );
let response = view_router(state.clone())
.oneshot(
request()
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::Team.as_str())
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "bot");
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: THREAD_ID.to_string(),
+ entity_type: EntityType::EmailThread,
+ }]
+ );
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn user_scoped_bot_without_an_acting_user_is_rejected() {
+ let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ ));
+ let response = view_router(state.clone())
+ .oneshot(
+ request()
+ .header(BOT_TOKEN_HEADER, MALFORMED_SYSTEM_BOT_TOKEN)
.header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.body(Body::empty())
.unwrap(),
@@ -323,8 +417,35 @@ async fn bot_thread_access_is_forbidden_before_acl_lookup() {
.await
.unwrap();
- assert_eq!(response.status(), StatusCode::FORBIDDEN);
- assert_eq!(response_body(response).await, r#"{"message":"forbidden"}"#);
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"bot user scope requires an acting user"}"#
+ );
+ assert!(state.entity_access.bot_calls().is_empty());
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn bot_with_insufficient_permission_is_rejected() {
+ let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ },
+ ));
+ let response = edit_router(state.clone())
+ .oneshot(
+ request()
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::Team.as_str())
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(state.entity_access.bot_calls().len(), 1);
assert!(state.entity_access.calls().is_empty());
}
diff --git a/crates/entity_access/src/outbound.rs b/crates/entity_access/src/outbound.rs
index d1138bb246..9ce3e900a8 100644
--- a/crates/entity_access/src/outbound.rs
+++ b/crates/entity_access/src/outbound.rs
@@ -4,4 +4,6 @@
mod pg_access_repo;
-pub use pg_access_repo::{PgAccessRepository, SourceIds, get_bot_source_ids, get_user_source_ids};
+pub use pg_access_repo::{
+ PgAccessRepository, SourceIds, get_team_scope_source_ids, get_user_source_ids,
+};
diff --git a/crates/entity_access/src/outbound/pg_access_repo/mod.rs b/crates/entity_access/src/outbound/pg_access_repo/mod.rs
index 566365b050..844bd59263 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/mod.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/mod.rs
@@ -2,7 +2,7 @@
mod queries;
-pub use queries::{SourceIds, get_bot_source_ids, get_user_source_ids};
+pub use queries::{SourceIds, get_team_scope_source_ids, get_user_source_ids};
#[cfg(test)]
mod test;
@@ -48,6 +48,16 @@ fn foreign_entity_source_pairs(
(source_ids, source_auth_entities)
}
+fn team_foreign_entity_source_pairs(
+ team_id: Uuid,
+ bot_principal: &str,
+) -> (Vec<String>, Vec<String>) {
+ (
+ vec![team_id.to_string(), bot_principal.to_string()],
+ vec!["team".to_string(), "user".to_string()],
+ )
+}
+
impl AccessRepository for PgAccessRepository {
#[tracing::instrument(err, skip(self))]
async fn get_document_access(
@@ -149,9 +159,10 @@ impl AccessRepository for PgAccessRepository {
}
#[tracing::instrument(err, skip(self))]
- async fn get_bot_entity_access(
+ async fn get_team_entity_access(
&self,
bot_id: BotId,
+ team_id: Uuid,
entity_id: &str,
entity_type: EntityType,
) -> Result<Option<AccessLevel>, AccessError> {
@@ -159,7 +170,7 @@ impl AccessRepository for PgAccessRepository {
.parse::<Uuid>()
.map_err(|_| AccessError::BadRequest("Invalid entity ID format"))?;
let bot_principal = bot_id.into_storage_id();
- let source_ids = queries::get_bot_source_ids(&self.pool, &bot_principal)
+ let source_ids = queries::get_team_scope_source_ids(&self.pool, &bot_principal, &team_id)
.await
.map_err(|_| AccessError::Internal)?;
@@ -196,7 +207,7 @@ impl AccessRepository for PgAccessRepository {
| EntityType::CrmCompany
| EntityType::CrmContact => {
return Err(AccessError::BadRequest(
- "Unsupported entity type for bot access",
+ "Unsupported entity type for team item access",
));
}
};
@@ -205,16 +216,87 @@ impl AccessRepository for PgAccessRepository {
}
#[tracing::instrument(err, skip(self))]
- async fn get_bot_channel_role(
+ async fn get_team_channel_role(
&self,
channel_id: &Uuid,
+ team_id: Uuid,
bot_id: BotId,
) -> Result<ChannelRoleResult, AccessError> {
let bot_principal = bot_id.into_storage_id();
- Ok(
- queries::channel_role::get_bot_channel_role(&self.pool, channel_id, &bot_principal)
- .await?,
+ Ok(queries::channel_role::get_team_channel_role(
+ &self.pool,
+ channel_id,
+ &team_id,
+ &bot_principal,
+ )
+ .await?)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn has_team_foreign_entity_access(
+ &self,
+ foreign_entity_id: &str,
+ team_id: Uuid,
+ bot_id: BotId,
+ ) -> Result<bool, AccessError> {
+ let foreign_entity_uuid = foreign_entity_id
+ .parse::<Uuid>()
+ .map_err(|_| AccessError::BadRequest("Invalid foreign entity ID format"))?;
+ let bot_principal = bot_id.into_storage_id();
+ let scope_sources =
+ queries::get_team_scope_source_ids(&self.pool, &bot_principal, &team_id)
+ .await
+ .map_err(|_| AccessError::Internal)?;
+
+ if !scope_sources.0.contains(&team_id.to_string())
+ || !scope_sources.0.contains(&bot_principal.to_string())
+ {
+ return Ok(false);
+ }
+
+ let (source_ids, source_auth_entities) =
+ team_foreign_entity_source_pairs(team_id, bot_principal.as_ref());
+ Ok(queries::foreign_entity_access::has_foreign_entity_access(
+ &self.pool,
+ &foreign_entity_uuid,
+ &source_ids,
+ &source_auth_entities,
+ )
+ .await?)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_team_crm_company_access(
+ &self,
+ company_id: &str,
+ team_id: Uuid,
+ ) -> Result<Option<CrmEntityAccess>, AccessError> {
+ let company_uuid = company_id
+ .parse::<Uuid>()
+ .map_err(|_| AccessError::BadRequest("Invalid CRM company ID format"))?;
+ Ok(queries::crm_company_access::get_team_crm_company_access(
+ &self.pool,
+ &company_uuid,
+ &team_id,
)
+ .await?)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_team_crm_contact_access(
+ &self,
+ contact_id: &str,
+ team_id: Uuid,
+ ) -> Result<Option<CrmEntityAccess>, AccessError> {
+ let contact_uuid = contact_id
+ .parse::<Uuid>()
+ .map_err(|_| AccessError::BadRequest("Invalid CRM contact ID format"))?;
+ Ok(queries::crm_contact_access::get_team_crm_contact_access(
+ &self.pool,
+ &contact_uuid,
+ &team_id,
+ )
+ .await?)
}
#[tracing::instrument(err, skip(self))]
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
index f00e6af5ae..fb974627e3 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
@@ -16,6 +16,12 @@ struct ChannelRoleRow {
is_team_member: bool,
}
+/// Row returned from the team-scoped channel role query.
+struct TeamChannelRoleRow {
+ role: Option<String>,
+ is_matching_team_channel: bool,
+}
+
/// Parse a participant role string from the database.
fn parse_role(s: &str) -> ParticipantRole {
match s {
@@ -108,34 +114,43 @@ pub async fn get_channel_role(
Ok(ChannelRoleResult::NoAccess)
}
-/// Get a bot's explicit role in a channel.
+/// Get a bot's channel role while operating in its owning team's scope.
///
-/// Unlike [`get_channel_role`], public and organization channels do not grant a
-/// default role. The bot must exist, not be soft-deleted, and have an active
-/// participant row.
+/// An active participant row grants its stored role in any channel. Without an
+/// active participant row, only a team channel owned by the supplied team
+/// grants view-only access. The bot must be active and owned by that team.
#[tracing::instrument(err, skip(pool))]
-pub async fn get_bot_channel_role(
+pub async fn get_team_channel_role(
pool: &PgPool,
channel_id: &Uuid,
+ team_id: &Uuid,
bot_principal: &BotIdStr<'_>,
) -> Result<ChannelRoleResult, sqlx::Error> {
- let row = sqlx::query!(
+ let row = sqlx::query_as!(
+ TeamChannelRoleRow,
r#"
- SELECT cp.role::text as "role?"
+ SELECT
+ cp.role::text AS "role?",
+ (
+ b.id IS NOT NULL
+ AND c.channel_type = 'team'
+ AND c.team_id = $3
+ ) AS "is_matching_team_channel!"
FROM comms_channels c
+ LEFT JOIN bots b
+ ON b.id = $4
+ AND b.team_id = $3
+ AND b.deleted_at IS NULL
LEFT JOIN comms_channel_participants cp
- ON cp.channel_id = c.id
- AND cp.user_id = $2
- AND cp.left_at IS NULL
- AND EXISTS (
- SELECT 1
- FROM bots b
- WHERE b.id = $3 AND b.deleted_at IS NULL
- )
+ ON cp.channel_id = c.id
+ AND cp.user_id = $2
+ AND cp.left_at IS NULL
+ AND b.id IS NOT NULL
WHERE c.id = $1
"#,
channel_id,
bot_principal.as_ref(),
+ team_id,
bot_principal.as_uuid(),
)
.fetch_optional(pool)
@@ -145,8 +160,13 @@ pub async fn get_bot_channel_role(
return Ok(ChannelRoleResult::NotFound);
};
- Ok(match row.role.as_deref() {
- Some(role) => ChannelRoleResult::Role(parse_role(role)),
- None => ChannelRoleResult::NoAccess,
- })
+ if let Some(role) = row.role.as_deref() {
+ return Ok(ChannelRoleResult::Role(parse_role(role)));
+ }
+
+ if row.is_matching_team_channel {
+ return Ok(ChannelRoleResult::ViewOnly);
+ }
+
+ Ok(ChannelRoleResult::NoAccess)
}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role/test.rs
index 96e7ce90b3..2f52aacce6 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role/test.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role/test.rs
@@ -4,6 +4,7 @@ use macro_db_migrator::MACRO_DB_MIGRATIONS;
use sqlx::PgPool;
const TEAM_ALPHA: Uuid = Uuid::from_u128(0x000000000000000000000000000ea001);
+const TEAM_BETA: Uuid = Uuid::from_u128(0x000000000000000000000000000ea002);
async fn insert_channel(
pool: &PgPool,
@@ -58,27 +59,15 @@ async fn insert_user_participant(
Ok(())
}
-async fn insert_public_channel(pool: &PgPool, channel_id: Uuid) {
+async fn insert_team_bot(pool: &PgPool, bot_principal: &BotIdStr<'_>, team_id: Uuid) {
sqlx::query!(
r#"
- INSERT INTO comms_channels (id, name, channel_type, owner_id)
- VALUES ($1, 'Bot Channel', 'public', 'owner')
- "#,
- channel_id,
- )
- .execute(pool)
- .await
- .unwrap();
-}
-
-async fn insert_bot(pool: &PgPool, bot_principal: &BotIdStr<'_>) {
- sqlx::query!(
- r#"
- INSERT INTO bots (id, kind, name, handle)
- VALUES ($1, 'system', 'Test Bot', $2)
+ INSERT INTO bots (id, kind, team_id, name, handle)
+ VALUES ($1, 'owned', $2, 'Team Bot', $3)
"#,
bot_principal.as_uuid(),
- format!("test-bot-{}", bot_principal.as_uuid()),
+ team_id,
+ format!("team-bot-{}", bot_principal.as_uuid()),
)
.execute(pool)
.await
@@ -196,59 +185,112 @@ async fn non_team_channels_do_not_grant_team_members_view_only(pool: PgPool) ->
Ok(())
}
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn bot_channel_role_active_participant_receives_stored_role(
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_channel_role_explicit_participation_wins_in_any_channel(
pool: PgPool,
) -> anyhow::Result<()> {
let channel_id = Uuid::new_v4();
let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();
- insert_public_channel(&pool, channel_id).await;
- insert_bot(&pool, &principal).await;
+ insert_channel(&pool, channel_id, "private", None).await?;
+ insert_team_bot(&pool, &principal, TEAM_ALPHA).await;
insert_bot_participant(&pool, channel_id, &principal, false).await;
- let role = get_bot_channel_role(&pool, &channel_id, &principal).await?;
+ let role = get_team_channel_role(&pool, &channel_id, &TEAM_ALPHA, &principal).await?;
assert_eq!(role, ChannelRoleResult::Role(ParticipantRole::Admin));
Ok(())
}
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn bot_channel_role_public_channel_non_participant_has_no_access(
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_channel_role_matching_team_channel_is_view_only(pool: PgPool) -> anyhow::Result<()> {
+ let channel_id = Uuid::new_v4();
+ let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();
+ insert_channel(&pool, channel_id, "team", Some(TEAM_ALPHA)).await?;
+ insert_team_bot(&pool, &principal, TEAM_ALPHA).await;
+
+ let role = get_team_channel_role(&pool, &channel_id, &TEAM_ALPHA, &principal).await?;
+
+ assert_eq!(role, ChannelRoleResult::ViewOnly);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_channel_role_other_team_channel_has_no_implicit_access(
pool: PgPool,
) -> anyhow::Result<()> {
let channel_id = Uuid::new_v4();
let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();
- insert_public_channel(&pool, channel_id).await;
- insert_bot(&pool, &principal).await;
+ insert_channel(&pool, channel_id, "team", Some(TEAM_BETA)).await?;
+ insert_team_bot(&pool, &principal, TEAM_ALPHA).await;
- let role = get_bot_channel_role(&pool, &channel_id, &principal).await?;
+ let role = get_team_channel_role(&pool, &channel_id, &TEAM_ALPHA, &principal).await?;
assert_eq!(role, ChannelRoleResult::NoAccess);
Ok(())
}
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn bot_channel_role_departed_participant_has_no_access(pool: PgPool) -> anyhow::Result<()> {
- let channel_id = Uuid::new_v4();
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_channel_role_non_team_channels_have_no_implicit_access(
+ pool: PgPool,
+) -> anyhow::Result<()> {
let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();
- insert_public_channel(&pool, channel_id).await;
- insert_bot(&pool, &principal).await;
- insert_bot_participant(&pool, channel_id, &principal, true).await;
+ insert_team_bot(&pool, &principal, TEAM_ALPHA).await;
- let role = get_bot_channel_role(&pool, &channel_id, &principal).await?;
+ for channel_type in ["public", "private", "direct_message"] {
+ let channel_id = Uuid::new_v4();
+ insert_channel(&pool, channel_id, channel_type, None).await?;
- assert_eq!(role, ChannelRoleResult::NoAccess);
+ let role = get_team_channel_role(&pool, &channel_id, &TEAM_ALPHA, &principal).await?;
+
+ assert_eq!(
+ role,
+ ChannelRoleResult::NoAccess,
+ "{channel_type} channels must not grant implicit access"
+ );
+ }
Ok(())
}
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn bot_channel_role_soft_deleted_participant_has_no_access(
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_channel_role_departed_participation_does_not_grant_a_role(
pool: PgPool,
) -> anyhow::Result<()> {
let channel_id = Uuid::new_v4();
let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();
- insert_public_channel(&pool, channel_id).await;
- insert_bot(&pool, &principal).await;
+ insert_channel(&pool, channel_id, "team", Some(TEAM_ALPHA)).await?;
+ insert_team_bot(&pool, &principal, TEAM_ALPHA).await;
+ insert_bot_participant(&pool, channel_id, &principal, true).await;
+
+ let role = get_team_channel_role(&pool, &channel_id, &TEAM_ALPHA, &principal).await?;
+
+ assert_eq!(role, ChannelRoleResult::ViewOnly);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_channel_role_soft_deleted_bot_has_no_access(pool: PgPool) -> anyhow::Result<()> {
+ let channel_id = Uuid::new_v4();
+ let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();
+ insert_channel(&pool, channel_id, "team", Some(TEAM_ALPHA)).await?;
+ insert_team_bot(&pool, &principal, TEAM_ALPHA).await;
insert_bot_participant(&pool, channel_id, &principal, false).await;
sqlx::query!(
"UPDATE bots SET deleted_at = now() WHERE id = $1",
@@ -257,19 +299,37 @@ async fn bot_channel_role_soft_deleted_participant_has_no_access(
.execute(&pool)
.await?;
- let role = get_bot_channel_role(&pool, &channel_id, &principal).await?;
+ let role = get_team_channel_role(&pool, &channel_id, &TEAM_ALPHA, &principal).await?;
assert_eq!(role, ChannelRoleResult::NoAccess);
Ok(())
}
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn bot_channel_role_unknown_channel_is_not_found(pool: PgPool) -> anyhow::Result<()> {
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_channel_role_mismatched_bot_team_has_no_access(pool: PgPool) -> anyhow::Result<()> {
let channel_id = Uuid::new_v4();
let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();
- insert_bot(&pool, &principal).await;
+ insert_channel(&pool, channel_id, "team", Some(TEAM_BETA)).await?;
+ insert_team_bot(&pool, &principal, TEAM_ALPHA).await;
+
+ let role = get_team_channel_role(&pool, &channel_id, &TEAM_BETA, &principal).await?;
+
+ assert_eq!(role, ChannelRoleResult::NoAccess);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_channel_role_unknown_channel_is_not_found(pool: PgPool) -> anyhow::Result<()> {
+ let principal = BotId::new_from_uuid(Uuid::new_v4()).into_storage_id();
+ insert_team_bot(&pool, &principal, TEAM_ALPHA).await;
- let role = get_bot_channel_role(&pool, &channel_id, &principal).await?;
+ let role = get_team_channel_role(&pool, &Uuid::new_v4(), &TEAM_ALPHA, &principal).await?;
assert_eq!(role, ChannelRoleResult::NotFound);
Ok(())
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/crm_company_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/crm_company_access.rs
index e273963b9b..624ec45ca3 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/crm_company_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/crm_company_access.rs
@@ -1,5 +1,8 @@
//! Query for CRM company access level.
+#[cfg(test)]
+mod test;
+
use crate::domain::models::{AccessLevel, CrmEntityAccess, TeamRole};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use sqlx::PgPool;
@@ -47,6 +50,32 @@ pub async fn get_crm_company_access(
}))
}
+/// Resolve team-scoped access to a visible CRM company owned by the team.
+#[tracing::instrument(err, skip(pool))]
+pub async fn get_team_crm_company_access(
+ pool: &PgPool,
+ company_id: &Uuid,
+ team_id: &Uuid,
+) -> Result<Option<CrmEntityAccess>, sqlx::Error> {
+ sqlx::query_as!(
+ CrmEntityAccess,
+ r#"
+ SELECT
+ 'view'::"AccessLevel" AS "access_level!: AccessLevel",
+ team_id AS "team_id!",
+ 'member'::team_role AS "team_role!: TeamRole"
+ FROM crm_companies
+ WHERE id = $1
+ AND team_id = $2
+ AND hidden = false
+ "#,
+ company_id,
+ team_id,
+ )
+ .fetch_optional(pool)
+ .await
+}
+
/// Map a team role + hidden flag to an [`AccessLevel`].
///
/// Every team role can edit visible CRM rows (members included, so they can
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/crm_company_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/crm_company_access/test.rs
new file mode 100644
index 0000000000..b40a9e27bc
--- /dev/null
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/crm_company_access/test.rs
@@ -0,0 +1,81 @@
+use super::*;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+
+const TEAM_ALPHA: Uuid = Uuid::from_u128(0x000000000000000000000000000ea001);
+const TEAM_BETA: Uuid = Uuid::from_u128(0x000000000000000000000000000ea002);
+
+async fn insert_company(
+ pool: &PgPool,
+ company_id: Uuid,
+ team_id: Uuid,
+ hidden: bool,
+) -> anyhow::Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO crm_companies (
+ id,
+ team_id,
+ hidden,
+ first_interaction,
+ last_interaction
+ )
+ VALUES ($1, $2, $3, now(), now())
+ "#,
+ company_id,
+ team_id,
+ hidden,
+ )
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_crm_company_access_returns_view_member_facts(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = Uuid::new_v4();
+ insert_company(&pool, company_id, TEAM_ALPHA, false).await?;
+
+ let access = get_team_crm_company_access(&pool, &company_id, &TEAM_ALPHA).await?;
+
+ assert_eq!(
+ access,
+ Some(CrmEntityAccess {
+ access_level: AccessLevel::View,
+ team_id: TEAM_ALPHA,
+ team_role: TeamRole::Member,
+ })
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_crm_company_access_denies_hidden_company(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = Uuid::new_v4();
+ insert_company(&pool, company_id, TEAM_ALPHA, true).await?;
+
+ let access = get_team_crm_company_access(&pool, &company_id, &TEAM_ALPHA).await?;
+
+ assert_eq!(access, None);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_crm_company_access_denies_other_team(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = Uuid::new_v4();
+ insert_company(&pool, company_id, TEAM_ALPHA, false).await?;
+
+ let access = get_team_crm_company_access(&pool, &company_id, &TEAM_BETA).await?;
+
+ assert_eq!(access, None);
+ Ok(())
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/crm_contact_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/crm_contact_access.rs
index f18cce5d70..66eed95100 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/crm_contact_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/crm_contact_access.rs
@@ -1,6 +1,9 @@
//! Query for CRM contact access level.
-use crate::domain::models::{CrmEntityAccess, TeamRole};
+#[cfg(test)]
+mod test;
+
+use crate::domain::models::{AccessLevel, CrmEntityAccess, TeamRole};
use crate::outbound::pg_access_repo::queries::crm_company_access::team_role_to_access_level;
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use sqlx::PgPool;
@@ -49,3 +52,34 @@ pub async fn get_crm_contact_access(
})
}))
}
+
+/// Resolve team-scoped access to a visible CRM contact owned by the team.
+///
+/// A hidden contact or hidden parent company is not visible in team scope.
+#[tracing::instrument(err, skip(pool))]
+pub async fn get_team_crm_contact_access(
+ pool: &PgPool,
+ contact_id: &Uuid,
+ team_id: &Uuid,
+) -> Result<Option<CrmEntityAccess>, sqlx::Error> {
+ sqlx::query_as!(
+ CrmEntityAccess,
+ r#"
+ SELECT
+ 'view'::"AccessLevel" AS "access_level!: AccessLevel",
+ c.team_id AS "team_id!",
+ 'member'::team_role AS "team_role!: TeamRole"
+ FROM crm_contacts ct
+ JOIN crm_companies c
+ ON c.id = ct.company_id
+ WHERE ct.id = $1
+ AND c.team_id = $2
+ AND ct.hidden = false
+ AND c.hidden = false
+ "#,
+ contact_id,
+ team_id,
+ )
+ .fetch_optional(pool)
+ .await
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/crm_contact_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/crm_contact_access/test.rs
new file mode 100644
index 0000000000..3662ffecba
--- /dev/null
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/crm_contact_access/test.rs
@@ -0,0 +1,131 @@
+use super::*;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+
+const TEAM_ALPHA: Uuid = Uuid::from_u128(0x000000000000000000000000000ea001);
+const TEAM_BETA: Uuid = Uuid::from_u128(0x000000000000000000000000000ea002);
+
+async fn insert_company(
+ pool: &PgPool,
+ company_id: Uuid,
+ team_id: Uuid,
+ hidden: bool,
+) -> anyhow::Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO crm_companies (
+ id,
+ team_id,
+ hidden,
+ first_interaction,
+ last_interaction
+ )
+ VALUES ($1, $2, $3, now(), now())
+ "#,
+ company_id,
+ team_id,
+ hidden,
+ )
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+async fn insert_contact(
+ pool: &PgPool,
+ contact_id: Uuid,
+ company_id: Uuid,
+ hidden: bool,
+) -> anyhow::Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO crm_contacts (
+ id,
+ company_id,
+ email,
+ hidden,
+ first_interaction,
+ last_interaction
+ )
+ VALUES ($1, $2, $3, $4, now(), now())
+ "#,
+ contact_id,
+ company_id,
+ format!("contact-{contact_id}@example.com"),
+ hidden,
+ )
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_crm_contact_access_returns_view_member_facts(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = Uuid::new_v4();
+ let contact_id = Uuid::new_v4();
+ insert_company(&pool, company_id, TEAM_ALPHA, false).await?;
+ insert_contact(&pool, contact_id, company_id, false).await?;
+
+ let access = get_team_crm_contact_access(&pool, &contact_id, &TEAM_ALPHA).await?;
+
+ assert_eq!(
+ access,
+ Some(CrmEntityAccess {
+ access_level: AccessLevel::View,
+ team_id: TEAM_ALPHA,
+ team_role: TeamRole::Member,
+ })
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_crm_contact_access_denies_hidden_contact(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = Uuid::new_v4();
+ let contact_id = Uuid::new_v4();
+ insert_company(&pool, company_id, TEAM_ALPHA, false).await?;
+ insert_contact(&pool, contact_id, company_id, true).await?;
+
+ let access = get_team_crm_contact_access(&pool, &contact_id, &TEAM_ALPHA).await?;
+
+ assert_eq!(access, None);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_crm_contact_access_denies_hidden_parent_company(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = Uuid::new_v4();
+ let contact_id = Uuid::new_v4();
+ insert_company(&pool, company_id, TEAM_ALPHA, true).await?;
+ insert_contact(&pool, contact_id, company_id, false).await?;
+
+ let access = get_team_crm_contact_access(&pool, &contact_id, &TEAM_ALPHA).await?;
+
+ assert_eq!(access, None);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../../fixtures", scripts("user_team"))
+)]
+async fn team_crm_contact_access_denies_other_team(pool: PgPool) -> anyhow::Result<()> {
+ let company_id = Uuid::new_v4();
+ let contact_id = Uuid::new_v4();
+ insert_company(&pool, company_id, TEAM_ALPHA, false).await?;
+ insert_contact(&pool, contact_id, company_id, false).await?;
+
+ let access = get_team_crm_contact_access(&pool, &contact_id, &TEAM_BETA).await?;
+
+ assert_eq!(access, None);
+ Ok(())
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/mod.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/mod.rs
index 0fdb7878dc..b1fbffb4be 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/mod.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/mod.rs
@@ -77,7 +77,7 @@ pub async fn get_user_source_ids(
}
}
-/// Grabs a bot's active channel, owning team, and principal source ids.
+/// Grabs the source ids available to a bot operating in its owning team's scope.
#[tracing::instrument(skip(pool), err)]
#[cfg_attr(
not(test),
@@ -85,39 +85,49 @@ pub async fn get_user_source_ids(
time = 30,
result = true,
key = "String",
- convert = r#"{bot_id.to_string()}"#,
+ convert = r#"{format!("{}:{}", bot_id, team_id)}"#,
)
)]
-pub async fn get_bot_source_ids(
+pub async fn get_team_scope_source_ids(
pool: &Pool<Postgres>,
bot_id: &BotIdStr<'_>,
+ team_id: &uuid::Uuid,
) -> anyhow::Result<SourceIds> {
let source_ids = sqlx::query_scalar!(
r#"
WITH active_bot AS (
- SELECT team_id
+ SELECT id
FROM bots
- WHERE id = $2 AND deleted_at IS NULL
+ WHERE id = $2
+ AND team_id = $3
+ AND deleted_at IS NULL
)
- SELECT cp.channel_id::text
+ SELECT $1::text AS "source_id!"
FROM active_bot
- JOIN comms_channel_participants cp
- ON cp.user_id = $1 AND cp.left_at IS NULL
- UNION ALL
- SELECT team_id::text
+ UNION
+ SELECT $3::text
FROM active_bot
- WHERE team_id IS NOT NULL
- UNION ALL
- SELECT $1
+ UNION
+ SELECT c.id::text
FROM active_bot
+ JOIN comms_channels c
+ ON c.channel_type = 'team'
+ AND c.team_id = $3
+ UNION
+ SELECT cp.channel_id::text
+ FROM active_bot
+ JOIN comms_channel_participants cp
+ ON cp.user_id = $1
+ AND cp.left_at IS NULL
"#,
bot_id.as_ref(),
bot_id.as_uuid(),
+ team_id,
)
.fetch_all(pool)
.await?;
- Ok(SourceIds(source_ids.into_iter().flatten().collect()))
+ Ok(SourceIds(source_ids))
}
/// Grabs all user IDs with access to an entity via the entity_access table.
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/test.rs
index 561557786e..694bc018e5 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/test.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/test.rs
@@ -82,6 +82,21 @@ async fn insert_channel(pool: &PgPool, channel_id: Uuid) {
.unwrap();
}
+async fn insert_team_channel(pool: &PgPool, channel_id: Uuid, team_id: Uuid) {
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channels (id, name, channel_type, owner_id, team_id)
+ VALUES ($1, 'Bot Team Channel', 'team', $2, $3)
+ "#,
+ channel_id,
+ BOT_OWNER,
+ team_id,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
async fn insert_bot_participant(pool: &PgPool, channel_id: Uuid, bot_id: BotId, departed: bool) {
let principal = bot_id.into_storage_id();
sqlx::query!(
@@ -136,56 +151,86 @@ async fn insert_thread(pool: &PgPool, owner_macro_id: &str, email: &str) -> (Uui
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn bot_source_ids_team_scoped_bot_includes_channels_team_and_principal(
+async fn team_scope_source_ids_include_only_owning_team_and_active_bot_sources(
pool: PgPool,
) -> anyhow::Result<()> {
let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let bot_principal = bot_id.into_storage_id();
let team_id = Uuid::new_v4();
- let first_channel_id = Uuid::new_v4();
- let second_channel_id = Uuid::new_v4();
+ let other_team_id = Uuid::new_v4();
+ let team_channel_id = Uuid::new_v4();
+ let other_team_channel_id = Uuid::new_v4();
+ let private_channel_id = Uuid::new_v4();
+ let departed_channel_id = Uuid::new_v4();
+
insert_team(&pool, team_id).await;
+ let other_owner_id = format!("macro|{other_team_id}@corp.test");
+ let other_owner_email = format!("{other_team_id}@corp.test");
+ insert_user(&pool, &other_owner_id, &other_owner_email).await;
+ sqlx::query!(
+ "INSERT INTO team (id, name, owner_id) VALUES ($1, 'Other Bot Team', $2)",
+ other_team_id,
+ other_owner_id,
+ )
+ .execute(&pool)
+ .await?;
insert_owned_bot(&pool, bot_id, None, Some(team_id)).await;
- insert_channel(&pool, first_channel_id).await;
- insert_channel(&pool, second_channel_id).await;
- insert_bot_participant(&pool, first_channel_id, bot_id, false).await;
- insert_bot_participant(&pool, second_channel_id, bot_id, false).await;
-
- let source_ids = source_id_set(get_bot_source_ids(&pool, &bot_principal).await?);
+ insert_team_channel(&pool, team_channel_id, team_id).await;
+ insert_team_channel(&pool, other_team_channel_id, other_team_id).await;
+ insert_channel(&pool, private_channel_id).await;
+ insert_channel(&pool, departed_channel_id).await;
+ insert_bot_participant(&pool, team_channel_id, bot_id, false).await;
+ insert_bot_participant(&pool, private_channel_id, bot_id, false).await;
+ insert_bot_participant(&pool, departed_channel_id, bot_id, true).await;
+
+ let source_ids = get_team_scope_source_ids(&pool, &bot_principal, &team_id).await?;
+ let source_count = source_ids.0.len();
+ let actual = source_id_set(source_ids);
let expected = HashSet::from([
- first_channel_id.to_string(),
- second_channel_id.to_string(),
team_id.to_string(),
+ team_channel_id.to_string(),
+ private_channel_id.to_string(),
bot_principal.to_string(),
]);
- assert_eq!(source_ids, expected);
+ assert_eq!(actual, expected);
+ assert_eq!(
+ source_count,
+ actual.len(),
+ "source ids must be deduplicated"
+ );
+ assert!(!actual.contains(&other_team_channel_id.to_string()));
+ assert!(!actual.contains(&departed_channel_id.to_string()));
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn bot_source_ids_user_scoped_bot_does_not_inherit_owner(pool: PgPool) -> anyhow::Result<()> {
+async fn team_scope_source_ids_reject_mismatched_team(pool: PgPool) -> anyhow::Result<()> {
let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let bot_principal = bot_id.into_storage_id();
- insert_owned_bot(&pool, bot_id, Some(BOT_OWNER), None).await;
+ let owning_team_id = Uuid::new_v4();
+ let supplied_team_id = Uuid::new_v4();
- let source_ids = source_id_set(get_bot_source_ids(&pool, &bot_principal).await?);
+ insert_team(&pool, owning_team_id).await;
+ insert_owned_bot(&pool, bot_id, None, Some(owning_team_id)).await;
- assert_eq!(source_ids, HashSet::from([bot_principal.to_string()]));
- assert!(!source_ids.contains(BOT_OWNER));
+ let source_ids = get_team_scope_source_ids(&pool, &bot_principal, &supplied_team_id).await?;
+
+ assert!(source_ids.0.is_empty());
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn bot_source_ids_soft_deleted_bot_has_no_sources(pool: PgPool) -> anyhow::Result<()> {
+async fn team_scope_source_ids_reject_soft_deleted_bot(pool: PgPool) -> anyhow::Result<()> {
let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let bot_principal = bot_id.into_storage_id();
let team_id = Uuid::new_v4();
- let channel_id = Uuid::new_v4();
+ let team_channel_id = Uuid::new_v4();
+
insert_team(&pool, team_id).await;
insert_owned_bot(&pool, bot_id, None, Some(team_id)).await;
- insert_channel(&pool, channel_id).await;
- insert_bot_participant(&pool, channel_id, bot_id, false).await;
+ insert_team_channel(&pool, team_channel_id, team_id).await;
+ insert_bot_participant(&pool, team_channel_id, bot_id, false).await;
sqlx::query!(
"UPDATE bots SET deleted_at = now() WHERE id = $1",
bot_id.as_uuid(),
@@ -193,25 +238,9 @@ async fn bot_source_ids_soft_deleted_bot_has_no_sources(pool: PgPool) -> anyhow:
.execute(&pool)
.await?;
- let source_ids = source_id_set(get_bot_source_ids(&pool, &bot_principal).await?);
-
- assert!(source_ids.is_empty());
- Ok(())
-}
-
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn bot_source_ids_excludes_departed_channels(pool: PgPool) -> anyhow::Result<()> {
- let bot_id = BotId::new_from_uuid(Uuid::new_v4());
- let bot_principal = bot_id.into_storage_id();
- let channel_id = Uuid::new_v4();
- insert_owned_bot(&pool, bot_id, Some(BOT_OWNER), None).await;
- insert_channel(&pool, channel_id).await;
- insert_bot_participant(&pool, channel_id, bot_id, true).await;
-
- let source_ids = source_id_set(get_bot_source_ids(&pool, &bot_principal).await?);
+ let source_ids = get_team_scope_source_ids(&pool, &bot_principal, &team_id).await?;
- assert_eq!(source_ids, HashSet::from([bot_principal.to_string()]));
- assert!(!source_ids.contains(&channel_id.to_string()));
+ assert!(source_ids.0.is_empty());
Ok(())
}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/test.rs b/crates/entity_access/src/outbound/pg_access_repo/test.rs
index adcbc4c343..9acd9be741 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/test.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/test.rs
@@ -528,15 +528,17 @@ async fn insert_pg_bot_channel(
pool: &PgPool,
channel_id: Uuid,
channel_type: &str,
+ team_id: Option<Uuid>,
) -> anyhow::Result<()> {
sqlx::query!(
r#"
- INSERT INTO comms_channels (id, name, channel_type, owner_id)
- VALUES ($1, 'PG Bot Channel', $2::text::comms_channel_type, $3)
+ INSERT INTO comms_channels (id, name, channel_type, owner_id, team_id)
+ VALUES ($1, 'PG Bot Channel', $2::text::comms_channel_type, $3, $4)
"#,
channel_id,
channel_type,
PG_BOT_OWNER,
+ team_id,
)
.execute(pool)
.await?;
@@ -601,73 +603,126 @@ async fn insert_pg_bot_entity_access(
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn pg_bot_document_grant_through_active_channel(pool: PgPool) -> anyhow::Result<()> {
+async fn team_item_access_includes_team_channels_and_bot_grants(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::new_v4();
let bot_id = BotId::new_from_uuid(Uuid::new_v4());
- let channel_id = Uuid::new_v4();
- let document_id = Uuid::new_v4();
- insert_pg_bot(&pool, bot_id, Some(PG_BOT_OWNER), None).await?;
- insert_pg_bot_channel(&pool, channel_id, "private").await?;
- insert_pg_bot_participant(&pool, channel_id, bot_id, "member").await?;
- insert_pg_bot_entity_access(
- &pool,
- document_id,
- "document",
- &channel_id.to_string(),
- "channel",
- AccessLevel::Edit,
- )
- .await?;
+ let bot_principal = bot_id.into_storage_id();
+ let private_channel_id = Uuid::new_v4();
+ let team_channel_id = Uuid::new_v4();
+ insert_pg_bot_team(&pool, team_id).await?;
+ insert_pg_bot(&pool, bot_id, None, Some(team_id)).await?;
+ insert_pg_bot_channel(&pool, private_channel_id, "private", None).await?;
+ insert_pg_bot_channel(&pool, team_channel_id, "team", Some(team_id)).await?;
+ insert_pg_bot_participant(&pool, private_channel_id, bot_id, "member").await?;
+
+ let grants = [
+ (team_id.to_string(), "team", AccessLevel::View),
+ (team_channel_id.to_string(), "channel", AccessLevel::Comment),
+ (private_channel_id.to_string(), "channel", AccessLevel::Edit),
+ (bot_principal.to_string(), "user", AccessLevel::Owner),
+ ];
+ let repo = PgAccessRepository::new(pool);
- let access = PgAccessRepository::new(pool)
- .get_bot_entity_access(bot_id, &document_id.to_string(), EntityType::Document)
+ for (source_id, source_type, expected) in grants {
+ let document_id = Uuid::new_v4();
+ insert_pg_bot_entity_access(
+ &repo.pool,
+ document_id,
+ "document",
+ &source_id,
+ source_type,
+ expected,
+ )
.await?;
- assert_eq!(access, Some(AccessLevel::Edit));
+ let access = repo
+ .get_team_entity_access(
+ bot_id,
+ team_id,
+ &document_id.to_string(),
+ EntityType::Document,
+ )
+ .await?;
+ assert_eq!(access, Some(expected), "source {source_id}");
+ }
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn pg_bot_team_grant_is_available_only_to_team_scoped_bot(
- pool: PgPool,
-) -> anyhow::Result<()> {
+async fn team_item_access_preserves_public_grants(pool: PgPool) -> anyhow::Result<()> {
let team_id = Uuid::new_v4();
- let team_bot_id = BotId::new_from_uuid(Uuid::new_v4());
- let user_bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let document_id = Uuid::new_v4();
+ let permission_id = Uuid::new_v4().to_string();
insert_pg_bot_team(&pool, team_id).await?;
- insert_pg_bot(&pool, team_bot_id, None, Some(team_id)).await?;
- insert_pg_bot(&pool, user_bot_id, Some(PG_BOT_OWNER), None).await?;
- insert_pg_bot_entity_access(
- &pool,
- document_id,
- "document",
- &team_id.to_string(),
- "team",
- AccessLevel::Comment,
+ insert_pg_bot(&pool, bot_id, None, Some(team_id)).await?;
+ sqlx::query!(
+ r#"INSERT INTO "Document" (id, name, owner) VALUES ($1, 'Public Document', $2)"#,
+ document_id.to_string(),
+ PG_BOT_OWNER,
)
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO "SharePermission" (id, "isPublic", "publicAccessLevel")
+ VALUES ($1, true, 'comment')
+ "#,
+ permission_id.as_str(),
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO "DocumentPermission" ("documentId", "sharePermissionId")
+ VALUES ($1, $2)
+ "#,
+ document_id.to_string(),
+ permission_id.as_str(),
+ )
+ .execute(&pool)
.await?;
- let repo = PgAccessRepository::new(pool);
- let team_access = repo
- .get_bot_entity_access(team_bot_id, &document_id.to_string(), EntityType::Document)
- .await?;
- let user_access = repo
- .get_bot_entity_access(user_bot_id, &document_id.to_string(), EntityType::Document)
+ let access = PgAccessRepository::new(pool)
+ .get_team_entity_access(
+ bot_id,
+ team_id,
+ &document_id.to_string(),
+ EntityType::Document,
+ )
.await?;
- assert_eq!(team_access, Some(AccessLevel::Comment));
- assert_eq!(user_access, None);
+ assert_eq!(access, Some(AccessLevel::Comment));
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn pg_bot_ungranted_document_returns_none(pool: PgPool) -> anyhow::Result<()> {
+async fn team_item_access_rejects_another_team(pool: PgPool) -> anyhow::Result<()> {
+ let owning_team_id = Uuid::new_v4();
+ let other_team_id = Uuid::new_v4();
let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let document_id = Uuid::new_v4();
- insert_pg_bot(&pool, bot_id, Some(PG_BOT_OWNER), None).await?;
+ insert_pg_bot_team(&pool, owning_team_id).await?;
+ insert_pg_bot(&pool, bot_id, None, Some(owning_team_id)).await?;
+ insert_pg_bot_entity_access(
+ &pool,
+ document_id,
+ "document",
+ &owning_team_id.to_string(),
+ "team",
+ AccessLevel::Owner,
+ )
+ .await?;
let access = PgAccessRepository::new(pool)
- .get_bot_entity_access(bot_id, &document_id.to_string(), EntityType::Document)
+ .get_team_entity_access(
+ bot_id,
+ other_team_id,
+ &document_id.to_string(),
+ EntityType::Document,
+ )
.await?;
assert_eq!(access, None);
@@ -675,25 +730,13 @@ async fn pg_bot_ungranted_document_returns_none(pool: PgPool) -> anyhow::Result<
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn pg_bot_email_thread_receives_view_from_containing_project(
- pool: PgPool,
-) -> anyhow::Result<()> {
+async fn team_thread_access_does_not_inherit_inbox_ownership(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::new_v4();
let bot_id = BotId::new_from_uuid(Uuid::new_v4());
- let channel_id = Uuid::new_v4();
- let project_id = Uuid::new_v4();
let link_id = Uuid::new_v4();
let thread_id = Uuid::new_v4();
- insert_pg_bot_user(&pool).await?;
- insert_pg_bot(&pool, bot_id, Some(PG_BOT_OWNER), None).await?;
- insert_pg_bot_channel(&pool, channel_id, "private").await?;
- insert_pg_bot_participant(&pool, channel_id, bot_id, "member").await?;
- sqlx::query!(
- r#"INSERT INTO "Project" (id, name, "userId") VALUES ($1, 'PG Bot Project', $2)"#,
- project_id.to_string(),
- PG_BOT_OWNER,
- )
- .execute(&pool)
- .await?;
+ insert_pg_bot_team(&pool, team_id).await?;
+ insert_pg_bot(&pool, bot_id, None, Some(team_id)).await?;
sqlx::query!(
r#"
INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)
@@ -705,83 +748,181 @@ async fn pg_bot_email_thread_receives_view_from_containing_project(
.execute(&pool)
.await?;
sqlx::query!(
- "INSERT INTO email_threads (id, link_id, project_id) VALUES ($1, $2, $3)",
+ "INSERT INTO email_threads (id, link_id) VALUES ($1, $2)",
thread_id,
link_id,
- project_id.to_string(),
)
.execute(&pool)
.await?;
- insert_pg_bot_entity_access(
- &pool,
- project_id,
- "project",
- &channel_id.to_string(),
- "channel",
- AccessLevel::Owner,
- )
- .await?;
let access = PgAccessRepository::new(pool)
- .get_bot_entity_access(bot_id, &thread_id.to_string(), EntityType::EmailThread)
+ .get_team_entity_access(
+ bot_id,
+ team_id,
+ &thread_id.to_string(),
+ EntityType::EmailThread,
+ )
.await?;
- assert_eq!(access, Some(AccessLevel::View));
+ assert_eq!(access, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_channel_role_uses_scoped_channel_rules(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::new_v4();
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let team_channel_id = Uuid::new_v4();
+ let public_channel_id = Uuid::new_v4();
+ insert_pg_bot_team(&pool, team_id).await?;
+ insert_pg_bot(&pool, bot_id, None, Some(team_id)).await?;
+ insert_pg_bot_channel(&pool, team_channel_id, "team", Some(team_id)).await?;
+ insert_pg_bot_channel(&pool, public_channel_id, "public", None).await?;
+ let repo = PgAccessRepository::new(pool);
+
+ assert_eq!(
+ repo.get_team_channel_role(&team_channel_id, team_id, bot_id)
+ .await?,
+ ChannelRoleResult::ViewOnly,
+ );
+ assert_eq!(
+ repo.get_team_channel_role(&public_channel_id, team_id, bot_id)
+ .await?,
+ ChannelRoleResult::NoAccess,
+ );
+
+ insert_pg_bot_participant(&repo.pool, public_channel_id, bot_id, "admin").await?;
+ assert_eq!(
+ repo.get_team_channel_role(&public_channel_id, team_id, bot_id)
+ .await?,
+ ChannelRoleResult::Role(ParticipantRole::Admin),
+ );
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn pg_bot_channel_role_requires_explicit_canonical_participation(
+async fn team_foreign_entity_access_uses_only_team_and_bot_pairs(
pool: PgPool,
) -> anyhow::Result<()> {
- let participating_bot_id = BotId::new_from_uuid(Uuid::new_v4());
- let other_bot_id = BotId::new_from_uuid(Uuid::new_v4());
- let channel_id = Uuid::new_v4();
- insert_pg_bot(&pool, participating_bot_id, Some(PG_BOT_OWNER), None).await?;
- insert_pg_bot(&pool, other_bot_id, Some(PG_BOT_OWNER), None).await?;
- insert_pg_bot_channel(&pool, channel_id, "public").await?;
- insert_pg_bot_participant(&pool, channel_id, participating_bot_id, "admin").await?;
+ let team_id = Uuid::new_v4();
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let bot_principal = bot_id.into_storage_id();
+ insert_pg_bot_team(&pool, team_id).await?;
+ insert_pg_bot(&pool, bot_id, None, Some(team_id)).await?;
let repo = PgAccessRepository::new(pool);
- let participating_role = repo
- .get_bot_channel_role(&channel_id, participating_bot_id)
- .await?;
- let non_participating_role = repo.get_bot_channel_role(&channel_id, other_bot_id).await?;
+ let team_entity_id = Uuid::new_v4();
+ insert_foreign_entity(&repo.pool, team_entity_id, &team_id.to_string(), "team").await?;
+ let bot_entity_id = Uuid::new_v4();
+ insert_foreign_entity(&repo.pool, bot_entity_id, bot_principal.as_ref(), "user").await?;
+ let wrong_namespace_id = Uuid::new_v4();
+ insert_foreign_entity(
+ &repo.pool,
+ wrong_namespace_id,
+ bot_principal.as_ref(),
+ "team",
+ )
+ .await?;
+
+ for entity_id in [team_entity_id, bot_entity_id] {
+ assert!(
+ repo.has_team_foreign_entity_access(&entity_id.to_string(), team_id, bot_id)
+ .await?
+ );
+ }
+ assert!(
+ !repo
+ .has_team_foreign_entity_access(&wrong_namespace_id.to_string(), team_id, bot_id)
+ .await?
+ );
+ assert!(
+ !repo
+ .has_team_foreign_entity_access(&team_entity_id.to_string(), Uuid::new_v4(), bot_id,)
+ .await?
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_crm_access_is_view_only_for_visible_owned_rows(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::new_v4();
+ insert_pg_bot_team(&pool, team_id).await?;
+ let visible_company = insert_crm_company(&pool, &team_id.to_string(), false).await?;
+ let hidden_company = insert_crm_company(&pool, &team_id.to_string(), true).await?;
+ let visible_contact = insert_crm_contact(&pool, visible_company, false).await?;
+ let hidden_contact = insert_crm_contact(&pool, visible_company, true).await?;
+ let repo = PgAccessRepository::new(pool);
+ let expected = CrmEntityAccess {
+ access_level: AccessLevel::View,
+ team_id,
+ team_role: TeamRole::Member,
+ };
assert_eq!(
- participating_role,
- ChannelRoleResult::Role(ParticipantRole::Admin)
+ repo.get_team_crm_company_access(&visible_company.to_string(), team_id)
+ .await?,
+ Some(expected),
+ );
+ assert_eq!(
+ repo.get_team_crm_company_access(&hidden_company.to_string(), team_id)
+ .await?,
+ None,
+ );
+ assert_eq!(
+ repo.get_team_crm_contact_access(&visible_contact.to_string(), team_id)
+ .await?,
+ Some(expected),
+ );
+ assert_eq!(
+ repo.get_team_crm_contact_access(&hidden_contact.to_string(), team_id)
+ .await?,
+ None,
);
- assert_eq!(non_participating_role, ChannelRoleResult::NoAccess);
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn pg_bot_entity_access_rejects_malformed_uuid(pool: PgPool) -> anyhow::Result<()> {
+async fn team_scoped_repository_methods_reject_malformed_ids(pool: PgPool) -> anyhow::Result<()> {
+ let repo = PgAccessRepository::new(pool);
let bot_id = BotId::new_from_uuid(Uuid::new_v4());
- let error = PgAccessRepository::new(pool)
- .get_bot_entity_access(bot_id, "not-a-uuid", EntityType::Document)
- .await
- .expect_err("malformed entity ID should be rejected");
+ let team_id = Uuid::new_v4();
assert!(matches!(
- error,
- AccessError::BadRequest("Invalid entity ID format")
+ repo.get_team_entity_access(bot_id, team_id, "bad", EntityType::Document)
+ .await,
+ Err(AccessError::BadRequest("Invalid entity ID format"))
+ ));
+ assert!(matches!(
+ repo.has_team_foreign_entity_access("bad", team_id, bot_id)
+ .await,
+ Err(AccessError::BadRequest("Invalid foreign entity ID format"))
+ ));
+ assert!(matches!(
+ repo.get_team_crm_company_access("bad", team_id).await,
+ Err(AccessError::BadRequest("Invalid CRM company ID format"))
+ ));
+ assert!(matches!(
+ repo.get_team_crm_contact_access("bad", team_id).await,
+ Err(AccessError::BadRequest("Invalid CRM contact ID format"))
));
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn pg_bot_entity_access_rejects_unsupported_entity_type(pool: PgPool) -> anyhow::Result<()> {
- let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+async fn team_item_access_rejects_unsupported_entity_type(pool: PgPool) -> anyhow::Result<()> {
let error = PgAccessRepository::new(pool)
- .get_bot_entity_access(bot_id, &Uuid::new_v4().to_string(), EntityType::CrmCompany)
+ .get_team_entity_access(
+ BotId::new_from_uuid(Uuid::new_v4()),
+ Uuid::new_v4(),
+ &Uuid::new_v4().to_string(),
+ EntityType::CrmCompany,
+ )
.await
- .expect_err("unsupported bot entity type should be rejected");
+ .expect_err("unsupported team item type should be rejected");
assert!(matches!(
error,
- AccessError::BadRequest("Unsupported entity type for bot access")
+ AccessError::BadRequest("Unsupported entity type for team item access")
));
Ok(())
}
diff --git a/crates/foreign_entity/src/inbound/axum_router/tests.rs b/crates/foreign_entity/src/inbound/axum_router/tests.rs
index 0185a5a1b2..06d83b875b 100644
--- a/crates/foreign_entity/src/inbound/axum_router/tests.rs
+++ b/crates/foreign_entity/src/inbound/axum_router/tests.rs
@@ -10,8 +10,8 @@ use axum::{
use chrono::{DateTime, Utc};
use entity_access::domain::{
models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, EntityAccessReceipt, EntityPermission,
- EntityType, RequiredPermission, UserTeamInfo, ViewAccessLevel,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityAccessReceipt,
+ EntityPermission, EntityType, RequiredPermission, UserTeamInfo, ViewAccessLevel,
},
ports::EntityAccessService,
};
@@ -160,6 +160,7 @@ impl EntityAccessService for NoopEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
diff --git a/crates/graphql_email/src/loaders/test.rs b/crates/graphql_email/src/loaders/test.rs
index 0525687a9d..8680ee32d5 100644
--- a/crates/graphql_email/src/loaders/test.rs
+++ b/crates/graphql_email/src/loaders/test.rs
@@ -7,8 +7,8 @@ use std::sync::{
use email::domain::models::EmailErr;
use entity_access::domain::{
models::{
- AccessLevel, BotId, CallChannelInfo, EntityAccessReceipt, EntityPermission, EntityType,
- RequiredPermission, UserTeamInfo, ViewAccessLevel,
+ AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityAccessReceipt, EntityPermission,
+ EntityType, RequiredPermission, UserTeamInfo, ViewAccessLevel,
},
ports::EntityAccessService,
};
@@ -63,6 +63,7 @@ impl EntityAccessService for TestAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
diff --git a/crates/integration_tests/local_e2e/README.md b/crates/integration_tests/local_e2e/README.md
index 25f1308c4b..d5f793fd9a 100644
--- a/crates/integration_tests/local_e2e/README.md
+++ b/crates/integration_tests/local_e2e/README.md
@@ -11,3 +11,26 @@ services. The command starts an isolated named stack through the xtask local
orchestrator, seeds it, and supplies its generated env and proxy URLs to
`local_e2e_test_support`. The fixtures are the same files used by `seed_cli`
and Playwright.
+
+## Scoped bot entity access
+
+`bot_entity_access` connects directly to MacroDB to create an isolated
+team-owned bot, token, channels, and document grants, then exercises DSS's
+`/entity/{entity_type}/{entity_id}/permissions` endpoint under team and user
+scope. It uses random UUIDs and removes its rows after verification.
+
+Compile the test without requiring the local stack:
+
+```bash
+nix develop --command cargo test -p local_e2e_integration_tests --test bot_entity_access --no-run
+```
+
+To run it against an already-running local stack:
+
+```bash
+nix develop --command cargo test -p local_e2e_integration_tests --test bot_entity_access -- --ignored --nocapture
+```
+
+The test reads `LOCAL_E2E_DATABASE_URL` and
+`LOCAL_E2E_DOCUMENT_STORAGE_URL`, falling back to the standard local MacroDB
+and DSS addresses.
diff --git a/crates/integration_tests/local_e2e/tests/bot_entity_access.rs b/crates/integration_tests/local_e2e/tests/bot_entity_access.rs
new file mode 100644
index 0000000000..73cfbe561e
--- /dev/null
+++ b/crates/integration_tests/local_e2e/tests/bot_entity_access.rs
@@ -0,0 +1,469 @@
+use anyhow::{Context, ensure};
+use local_e2e_test_support::{LocalE2eConfig, LocalE2eServices};
+use reqwest::{Client, StatusCode};
+use serde_json::{Value, json};
+use sqlx::{PgPool, postgres::PgPoolOptions};
+use uuid::Uuid;
+
+const DEFAULT_LOCAL_DATABASE_URL: &str = "postgres://user:password@localhost:5432/macrodb";
+const BOT_TOKEN_HEADER: &str = "x-macro-bot-token";
+const BOT_SCOPE_HEADER: &str = "x-macro-bot-scope";
+const BOT_FOR_MACRO_USER_ID_HEADER: &str = "x-macro-bot-for-macro-user-id";
+const BOT_FOR_FUSIONAUTH_USER_ID_HEADER: &str = "x-macro-bot-for-fusionauth-user-id";
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-rust` plus document_storage_service"]
+async fn scoped_bot_resolves_document_access_through_dss() -> anyhow::Result<()> {
+ let config = LocalE2eConfig::load()?;
+ let services = LocalE2eServices::from_config(&config)?;
+ let pool = connect_db(&config).await?;
+ let fixture = ScopedBotFixture::seed(pool, services).await?;
+
+ let verification_result = verify_scoped_access(&fixture).await;
+ let cleanup_result = fixture.cleanup().await;
+
+ combine_verification_and_cleanup(verification_result, cleanup_result)
+}
+
+struct ScopedBotFixture {
+ pool: PgPool,
+ services: LocalE2eServices,
+ http: Client,
+ macro_user_uuid: Uuid,
+ acting_user_id: String,
+ fusion_user_id: String,
+ team_id: Uuid,
+ bot_id: Uuid,
+ bot_token: String,
+ bot_private_channel_id: Uuid,
+ user_private_channel_id: Uuid,
+ public_channel_id: Uuid,
+ team_document_id: Uuid,
+ bot_channel_document_id: Uuid,
+ user_channel_document_id: Uuid,
+}
+
+impl ScopedBotFixture {
+ #[allow(
+ clippy::disallowed_methods,
+ reason = "local E2E fixture SQL is validated against the runtime stack"
+ )]
+ async fn seed(pool: PgPool, services: LocalE2eServices) -> anyhow::Result<Self> {
+ let macro_user_uuid = Uuid::new_v4();
+ let fusion_user_id = Uuid::new_v4().to_string();
+ let email = format!("bot-entity-access-{macro_user_uuid}@macro.local");
+ let acting_user_id = format!("macro|{email}");
+ let team_id = Uuid::new_v4();
+ let bot_id = Uuid::new_v4();
+ let bot_token_id = Uuid::new_v4();
+ let bot_token = format!("mbot_local_e2e_{}", Uuid::new_v4().simple());
+ let bot_private_channel_id = Uuid::new_v4();
+ let user_private_channel_id = Uuid::new_v4();
+ let public_channel_id = Uuid::new_v4();
+ let team_document_id = Uuid::new_v4();
+ let bot_channel_document_id = Uuid::new_v4();
+ let user_channel_document_id = Uuid::new_v4();
+ let mut transaction = pool
+ .begin()
+ .await
+ .context("failed to begin scoped bot fixture transaction")?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO macro_user (id, username, email, stripe_customer_id)
+ VALUES ($1, $2, $3, $4)
+ "#,
+ )
+ .bind(macro_user_uuid)
+ .bind(&email)
+ .bind(&email)
+ .bind(format!("local_e2e_{macro_user_uuid}"))
+ .execute(&mut *transaction)
+ .await
+ .context("failed to insert scoped bot acting macro user")?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO "User" (id, email, macro_user_id)
+ VALUES ($1, $2, $3)
+ "#,
+ )
+ .bind(&fusion_user_id)
+ .bind(&email)
+ .bind(macro_user_uuid)
+ .execute(&mut *transaction)
+ .await
+ .context("failed to insert scoped bot acting user")?;
+
+ sqlx::query("INSERT INTO team (id, name, owner_id) VALUES ($1, $2, $3)")
+ .bind(team_id)
+ .bind(format!("Scoped bot E2E {team_id}"))
+ .bind(&fusion_user_id)
+ .execute(&mut *transaction)
+ .await
+ .context("failed to insert scoped bot team")?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO team_user (user_id, team_id, team_role)
+ VALUES ($1, $2, 'owner'::team_role)
+ "#,
+ )
+ .bind(&fusion_user_id)
+ .bind(team_id)
+ .execute(&mut *transaction)
+ .await
+ .context("failed to add acting user to scoped bot team")?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO bots (id, kind, team_id, name, handle, created_by)
+ VALUES ($1, 'owned', $2, $3, $4, $5)
+ "#,
+ )
+ .bind(bot_id)
+ .bind(team_id)
+ .bind(format!("Scoped bot E2E {bot_id}"))
+ .bind(format!("scoped-bot-{bot_id}"))
+ .bind(&acting_user_id)
+ .execute(&mut *transaction)
+ .await
+ .context("failed to insert scoped bot")?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO bot_tokens (id, bot_id, token, label)
+ VALUES ($1, $2, $3, 'local E2E scoped access')
+ "#,
+ )
+ .bind(bot_token_id)
+ .bind(bot_id)
+ .bind(&bot_token)
+ .execute(&mut *transaction)
+ .await
+ .context("failed to insert scoped bot token")?;
+
+ for (channel_id, channel_name, channel_type) in [
+ (
+ bot_private_channel_id,
+ "Scoped bot private channel",
+ "private",
+ ),
+ (
+ user_private_channel_id,
+ "Scoped acting-user private channel",
+ "private",
+ ),
+ (public_channel_id, "Scoped bot public channel", "public"),
+ ] {
+ sqlx::query(
+ r#"
+ INSERT INTO comms_channels (id, name, channel_type, owner_id)
+ VALUES ($1, $2, $3::comms_channel_type, $4)
+ "#,
+ )
+ .bind(channel_id)
+ .bind(format!("{channel_name} {channel_id}"))
+ .bind(channel_type)
+ .bind(&acting_user_id)
+ .execute(&mut *transaction)
+ .await
+ .with_context(|| format!("failed to insert {channel_type} channel {channel_id}"))?;
+ }
+
+ sqlx::query(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, role, user_id)
+ VALUES ($1, 'member'::comms_participant_role, $2)
+ "#,
+ )
+ .bind(bot_private_channel_id)
+ .bind(format!("bot|{bot_id}"))
+ .execute(&mut *transaction)
+ .await
+ .context("failed to add bot to private channel")?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, role, user_id)
+ VALUES ($1, 'member'::comms_participant_role, $2)
+ "#,
+ )
+ .bind(user_private_channel_id)
+ .bind(&acting_user_id)
+ .execute(&mut *transaction)
+ .await
+ .context("failed to add acting user to private channel")?;
+
+ let grants = [
+ (team_document_id, team_id.to_string(), "team"),
+ (
+ bot_channel_document_id,
+ bot_private_channel_id.to_string(),
+ "channel",
+ ),
+ (
+ user_channel_document_id,
+ user_private_channel_id.to_string(),
+ "channel",
+ ),
+ ];
+ for (document_id, source_id, source_type) in grants {
+ sqlx::query(
+ r#"
+ INSERT INTO entity_access (
+ entity_id,
+ entity_type,
+ source_id,
+ source_type,
+ access_level
+ )
+ VALUES (
+ $1,
+ 'document',
+ $2,
+ $3::entity_access_source_type,
+ 'view'::"AccessLevel"
+ )
+ "#,
+ )
+ .bind(document_id)
+ .bind(source_id)
+ .bind(source_type)
+ .execute(&mut *transaction)
+ .await
+ .with_context(|| format!("failed to grant access to document {document_id}"))?;
+ }
+
+ transaction
+ .commit()
+ .await
+ .context("failed to commit scoped bot fixture")?;
+
+ Ok(Self {
+ pool,
+ services,
+ http: Client::new(),
+ macro_user_uuid,
+ acting_user_id,
+ fusion_user_id,
+ team_id,
+ bot_id,
+ bot_token,
+ bot_private_channel_id,
+ user_private_channel_id,
+ public_channel_id,
+ team_document_id,
+ bot_channel_document_id,
+ user_channel_document_id,
+ })
+ }
+
+ async fn permission(
+ &self,
+ entity_type: &str,
+ entity_id: Uuid,
+ scope: &str,
+ include_acting_user: bool,
+ ) -> anyhow::Result<PermissionResponse> {
+ let url = format!(
+ "{}/entity/{entity_type}/{entity_id}/permissions",
+ self.services.document_storage_url()
+ );
+ let mut request = self
+ .http
+ .get(&url)
+ .header(BOT_TOKEN_HEADER, &self.bot_token)
+ .header(BOT_SCOPE_HEADER, scope);
+ if include_acting_user {
+ request = request
+ .header(BOT_FOR_MACRO_USER_ID_HEADER, &self.acting_user_id)
+ .header(BOT_FOR_FUSIONAUTH_USER_ID_HEADER, &self.fusion_user_id);
+ }
+
+ let response = request
+ .send()
+ .await
+ .with_context(|| format!("failed to request entity permission from {url}"))?;
+ let status = response.status();
+ let body_text = response
+ .text()
+ .await
+ .with_context(|| format!("failed to read entity permission response from {url}"))?;
+ let body = serde_json::from_str(&body_text).with_context(|| {
+ format!("failed to decode entity permission response from {url}: {body_text}")
+ })?;
+
+ Ok(PermissionResponse { status, body })
+ }
+
+ #[allow(
+ clippy::disallowed_methods,
+ reason = "local E2E cleanup SQL is validated against the runtime stack"
+ )]
+ async fn cleanup(&self) -> anyhow::Result<()> {
+ let document_ids = [
+ self.team_document_id,
+ self.bot_channel_document_id,
+ self.user_channel_document_id,
+ ];
+ let channel_ids = [
+ self.bot_private_channel_id,
+ self.user_private_channel_id,
+ self.public_channel_id,
+ ];
+ let mut transaction = self
+ .pool
+ .begin()
+ .await
+ .context("failed to begin scoped bot cleanup transaction")?;
+
+ sqlx::query("DELETE FROM entity_access WHERE entity_id = ANY($1)")
+ .bind(&document_ids[..])
+ .execute(&mut *transaction)
+ .await
+ .context("failed to delete scoped bot entity access")?;
+ sqlx::query("DELETE FROM comms_channels WHERE id = ANY($1)")
+ .bind(&channel_ids[..])
+ .execute(&mut *transaction)
+ .await
+ .context("failed to delete scoped bot channels")?;
+ sqlx::query("DELETE FROM bots WHERE id = $1")
+ .bind(self.bot_id)
+ .execute(&mut *transaction)
+ .await
+ .context("failed to delete scoped bot")?;
+ sqlx::query("DELETE FROM team WHERE id = $1")
+ .bind(self.team_id)
+ .execute(&mut *transaction)
+ .await
+ .context("failed to delete scoped bot team")?;
+ sqlx::query("DELETE FROM \"User\" WHERE id = $1")
+ .bind(&self.fusion_user_id)
+ .execute(&mut *transaction)
+ .await
+ .context("failed to delete scoped bot acting user")?;
+ sqlx::query("DELETE FROM macro_user WHERE id = $1")
+ .bind(self.macro_user_uuid)
+ .execute(&mut *transaction)
+ .await
+ .context("failed to delete scoped bot acting macro user")?;
+
+ transaction
+ .commit()
+ .await
+ .context("failed to commit scoped bot cleanup")
+ }
+}
+
+struct PermissionResponse {
+ status: StatusCode,
+ body: Value,
+}
+
+async fn verify_scoped_access(fixture: &ScopedBotFixture) -> anyhow::Result<()> {
+ assert_access(
+ fixture
+ .permission("document", fixture.team_document_id, "team", false)
+ .await?,
+ "team-shared document under team scope",
+ )?;
+ assert_access(
+ fixture
+ .permission("document", fixture.bot_channel_document_id, "team", false)
+ .await?,
+ "bot private-channel document under team scope",
+ )?;
+ assert_no_access(
+ fixture
+ .permission("document", fixture.user_channel_document_id, "team", false)
+ .await?,
+ "acting-user private-channel document under team scope",
+ )?;
+ assert_access(
+ fixture
+ .permission("document", fixture.user_channel_document_id, "user", true)
+ .await?,
+ "acting-user private-channel document under user scope",
+ )?;
+ assert_user_scope_requires_acting_user(
+ fixture
+ .permission("document", fixture.user_channel_document_id, "user", false)
+ .await?,
+ )?;
+ assert_no_access(
+ fixture
+ .permission("channel", fixture.public_channel_id, "team", false)
+ .await?,
+ "public channel under team scope",
+ )?;
+
+ Ok(())
+}
+
+fn assert_access(response: PermissionResponse, context: &str) -> anyhow::Result<()> {
+ let expected = json!({
+ "status": "access",
+ "permission": {
+ "type": "access_level",
+ "access_level": "view",
+ },
+ });
+ ensure!(
+ response.status == StatusCode::OK && response.body == expected,
+ "expected access for {context}, got {}: {}",
+ response.status,
+ response.body
+ );
+ Ok(())
+}
+
+fn assert_no_access(response: PermissionResponse, context: &str) -> anyhow::Result<()> {
+ ensure!(
+ response.status == StatusCode::OK && response.body == json!({ "status": "no_access" }),
+ "expected no access for {context}, got {}: {}",
+ response.status,
+ response.body
+ );
+ Ok(())
+}
+
+fn assert_user_scope_requires_acting_user(response: PermissionResponse) -> anyhow::Result<()> {
+ ensure!(
+ response.status == StatusCode::UNAUTHORIZED,
+ "expected user scope without acting-user headers to return 401, got {}: {}",
+ response.status,
+ response.body
+ );
+ ensure!(
+ response.body == json!({ "message": "bot user scope requires an acting user" }),
+ "unexpected missing acting-user response: {}",
+ response.body
+ );
+ Ok(())
+}
+
+fn combine_verification_and_cleanup(
+ verification_result: anyhow::Result<()>,
+ cleanup_result: anyhow::Result<()>,
+) -> anyhow::Result<()> {
+ match (verification_result, cleanup_result) {
+ (Ok(()), Ok(())) => Ok(()),
+ (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
+ (Err(verification_error), Err(cleanup_error)) => anyhow::bail!(
+ "scoped bot verification failed: {verification_error:#}; cleanup also failed: {cleanup_error:#}"
+ ),
+ }
+}
+
+async fn connect_db(config: &LocalE2eConfig) -> anyhow::Result<PgPool> {
+ let database_url = config
+ .get("LOCAL_E2E_DATABASE_URL")
+ .unwrap_or(DEFAULT_LOCAL_DATABASE_URL)
+ .replace("@postgres:", "@localhost:");
+ PgPoolOptions::new()
+ .max_connections(2)
+ .connect(&database_url)
+ .await
+ .context("failed to connect to MacroDB for scoped bot E2E setup")
+}
diff --git a/crates/macro_authorization/src/domain/bot_authorizer/test.rs b/crates/macro_authorization/src/domain/bot_authorizer/test.rs
index 1dba87f487..4100de2c73 100644
--- a/crates/macro_authorization/src/domain/bot_authorizer/test.rs
+++ b/crates/macro_authorization/src/domain/bot_authorizer/test.rs
@@ -250,6 +250,28 @@ async fn authorizes_current_team_member_and_rejects_non_member() {
}
}
+#[tokio::test]
+async fn rejects_consistent_claims_for_a_user_who_is_not_the_owner() {
+ let non_owner = ResolvedBotActingUser {
+ macro_user_id: MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),
+ fusion_user_id: "fusion-other".to_string(),
+ organization_id: Some(ORGANIZATION_ID),
+ };
+ let claims = BotActingUserClaims {
+ user_id: Some(non_owner.macro_user_id.as_ref().to_string()),
+ fusion_user_id: Some(non_owner.fusion_user_id.clone()),
+ organization_id: non_owner.organization_id,
+ };
+ let mut repo = FakeRepo::owned_by_user();
+ repo.acting_user = Some(non_owner);
+
+ let result = BotAuthorizerService::new(repo)
+ .authorize_bot(RAW_TOKEN, BotScope::User, Some(claims))
+ .await;
+
+ assert_error(result, MacroAuthorizationError::ActingUserNotAuthorized);
+}
+
#[tokio::test]
async fn rejects_system_bot_claims_before_user_lookups() {
let mut repo = FakeRepo::owned_by_user();
diff --git a/crates/projects/src/inbound/axum_router/tests.rs b/crates/projects/src/inbound/axum_router/tests.rs
index 65f3f8de54..6f3232297b 100644
--- a/crates/projects/src/inbound/axum_router/tests.rs
+++ b/crates/projects/src/inbound/axum_router/tests.rs
@@ -11,8 +11,8 @@ use axum::{
};
use entity_access::domain::{
models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, EntityAccessReceipt, EntityPermission,
- EntityType, RequiredPermission, UserTeamInfo,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityAccessReceipt,
+ EntityPermission, EntityType, RequiredPermission, UserTeamInfo,
},
ports::EntityAccessService,
};
@@ -278,6 +278,7 @@ impl EntityAccessService for FakeEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rs
index 20d00ed06b..ca361636e3 100644
--- a/crates/properties/src/domain/test.rs
+++ b/crates/properties/src/domain/test.rs
@@ -11,8 +11,8 @@ use crate::domain::{
use anyhow::anyhow;
use document_sub_type::DocumentSubType;
use entity_access::domain::models::{
- AccessLevel, BotId, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission,
- EntityType as AccessEntityType, ViewAccessLevel,
+ AccessLevel, BotId, BotReceiptScope, Entity, EntityAccessAuth, EntityAccessReceipt,
+ EntityPermission, EntityType as AccessEntityType, ViewAccessLevel,
};
use macro_user_id::user_id::MacroUserIdStr;
use models_properties::{
@@ -68,6 +68,9 @@ fn bot_receipt_has_no_authenticated_user_identity() {
let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"));
let receipt = EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_bot(
bot_id.into_storage_id(),
+ BotReceiptScope::Team {
+ team_id: Uuid::new_v4(),
+ },
"document-1",
entity_access::domain::models::EntityType::Document,
);
@@ -298,6 +301,9 @@ async fn test_link_parent_task_rejects_bot_and_unauthenticated_callers() {
let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"));
let bot_access = EditReceipt::dangerously_assert_bot(
bot_id.into_storage_id(),
+ BotReceiptScope::Team {
+ team_id: Uuid::new_v4(),
+ },
&task_id.to_string(),
AccessEntityType::Document,
);
diff --git a/crates/properties/src/inbound/axum_router/test.rs b/crates/properties/src/inbound/axum_router/test.rs
index 9189e14f4d..26a94fdcd6 100644
--- a/crates/properties/src/inbound/axum_router/test.rs
+++ b/crates/properties/src/inbound/axum_router/test.rs
@@ -9,8 +9,8 @@ use axum::{
};
use entity_access::domain::{
models::{
- AccessError, AccessLevel, BotId, CallChannelInfo, EntityAccessAuth, EntityAccessReceipt,
- EntityPermission, EntityType, RequiredPermission, UserTeamInfo,
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityAccessAuth,
+ EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission, UserTeamInfo,
},
ports::EntityAccessService,
};
@@ -112,6 +112,7 @@ impl EntityAccessService for FakeEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
diff --git a/crates/soup/src/inbound/axum_router/tests.rs b/crates/soup/src/inbound/axum_router/tests.rs
index 8220a19bf7..b5ef44a348 100644
--- a/crates/soup/src/inbound/axum_router/tests.rs
+++ b/crates/soup/src/inbound/axum_router/tests.rs
@@ -7,7 +7,7 @@ use email::domain::{
models::{EmailErr, PreviewView, PreviewViewStandardLabel, UserProvider},
ports::EmailService,
};
-use entity_access::domain::models::{BotId, EntityAccessReceipt, ViewAccessLevel};
+use entity_access::domain::models::{BotAccessScope, BotId, EntityAccessReceipt, ViewAccessLevel};
use http_body_util::BodyExt;
use item_filters::EntityFilters;
use macro_authorization::{
@@ -376,6 +376,7 @@ impl entity_access::domain::ports::EntityAccessService for MockEntityAccess {
>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: entity_access::domain::models::EntityType,
) -> Result<
diff --git a/crates/teams/src/inbound/axum_router/test.rs b/crates/teams/src/inbound/axum_router/test.rs
index cf874e1ce8..b7eda7426b 100644
--- a/crates/teams/src/inbound/axum_router/test.rs
+++ b/crates/teams/src/inbound/axum_router/test.rs
@@ -11,8 +11,9 @@ use axum::{
};
use entity_access::domain::{
models::{
- AccessError, AccessLevel, AdminTeamRole, BotId, CallChannelInfo, EntityAccessReceipt,
- EntityPermission, EntityType, MemberTeamRole, RequiredPermission, TeamRole, UserTeamInfo,
+ AccessError, AccessLevel, AdminTeamRole, BotAccessScope, BotId, CallChannelInfo,
+ EntityAccessReceipt, EntityPermission, EntityType, MemberTeamRole, RequiredPermission,
+ TeamRole, UserTeamInfo,
},
ports::EntityAccessService,
};
@@ -431,6 +432,7 @@ impl EntityAccessService for FakeEntityAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rs
index 8b0c81e9f4..00180cd17b 100644
--- a/crates/webhook/src/domain/ingestion/test.rs
+++ b/crates/webhook/src/domain/ingestion/test.rs
@@ -25,8 +25,8 @@ use documents::domain::events::{
DocumentUpdatedMetadata,
};
use entity_access::domain::models::{
- AccessLevel, BotId, CallChannelInfo, EntityAccessReceipt, EntityPermission, RequiredPermission,
- TeamRole, UserTeamInfo,
+ AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityAccessReceipt, EntityPermission,
+ RequiredPermission, TeamRole, UserTeamInfo,
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use serde_json::Value;
@@ -95,6 +95,7 @@ impl EntityAccessService for MockAccessService {
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
&self,
_bot_id: BotId,
+ _scope: BotAccessScope,
_entity_id: &str,
_entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {