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.

fix(bot): team bot require team admin (#5126)

Will Hutchinsonb81eeeee6b55
diff --git a/.sqlx/query-2962547036135d2bc0b1c7c325d15964e1ec8cec583d3fe8a94dfd81c66cefca.json b/.sqlx/query-2962547036135d2bc0b1c7c325d15964e1ec8cec583d3fe8a94dfd81c66cefca.json
new file mode 100644
index 0000000000..5c28ee0295
--- /dev/null
+++ b/.sqlx/query-2962547036135d2bc0b1c7c325d15964e1ec8cec583d3fe8a94dfd81c66cefca.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM team_user\n WHERE user_id = $1\n AND team_id = $2\n AND team_role IN ('admin'::team_role, 'owner'::team_role)\n ) AS \"can_administer!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "can_administer!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "2962547036135d2bc0b1c7c325d15964e1ec8cec583d3fe8a94dfd81c66cefca"
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequest.ts
index 832ffec88f..1376ae490c 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequest.ts
@@ -22,7 +22,7 @@ export interface CreateChannelScopedBotRequest {
handle: string;
/** Display name. */
name: string;
- /** Team owner. Omit for a user-owned bot. */
+ /** Team owner. The caller must be a team administrator or owner. Omit for a user-owned bot. */
team_id?: CreateChannelScopedBotRequestTeamId;
/** Optional token expiration timestamp. */
token_expires_at?: CreateChannelScopedBotRequestTokenExpiresAt;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTeamId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTeamId.ts
index b77598e408..9986687b7d 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTeamId.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestTeamId.ts
@@ -6,6 +6,6 @@
*/
/**
- * Team owner. Omit for a user-owned bot.
+ * Team owner. The caller must be a team administrator or owner. Omit for a user-owned bot.
*/
export type CreateChannelScopedBotRequestTeamId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index ad810a900e..3561c1ee10 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -1981,7 +1981,9 @@ export const createChannelScopedBotBody = zod
team_id: zod
.uuid()
.nullish()
- .describe('Team owner. Omit for a user-owned bot.'),
+ .describe(
+ 'Team owner. The caller must be a team administrator or owner. Omit for a user-owned bot.'
+ ),
token_expires_at: zod.iso
.datetime({})
.nullish()
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 92d7ee7521..ee95e0d1c5 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -12662,7 +12662,7 @@
"team_id": {
"type": ["string", "null"],
"format": "uuid",
- "description": "Team owner. Omit for a user-owned bot."
+ "description": "Team owner. The caller must be a team administrator or owner. Omit for a user-owned bot."
},
"token_expires_at": {
"type": ["string", "null"],
diff --git a/crates/bots/src/domain/models.rs b/crates/bots/src/domain/models.rs
index a075fb8745..ea5d090967 100644
--- a/crates/bots/src/domain/models.rs
+++ b/crates/bots/src/domain/models.rs
@@ -184,7 +184,7 @@ pub struct BotTokenCandidate {
#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct CreateBotRequest {
- /// Team owner. Omit for a user-owned bot.
+ /// Team owner. The caller must be a team administrator or owner. Omit for a user-owned bot.
pub team_id: Option<Uuid>,
/// Display name.
pub name: String,
@@ -232,7 +232,7 @@ pub struct AddChannelBotRequest {
#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct CreateChannelScopedBotRequest {
- /// Team owner. Omit for a user-owned bot.
+ /// Team owner. The caller must be a team administrator or owner. Omit for a user-owned bot.
pub team_id: Option<Uuid>,
/// Display name.
pub name: String,
diff --git a/crates/bots/src/domain/ports.rs b/crates/bots/src/domain/ports.rs
index 8935b9b6ab..dced2f2644 100644
--- a/crates/bots/src/domain/ports.rs
+++ b/crates/bots/src/domain/ports.rs
@@ -56,6 +56,13 @@ pub trait BotRepo: Clone + Send + Sync + 'static {
bot_id: BotId,
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+ /// Check whether a user is an administrator or owner of a team.
+ fn user_can_administer_team(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ team_id: Uuid,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
/// Patch an active bot.
fn patch_bot(
&self,
@@ -133,14 +140,14 @@ pub trait BotRepo: Clone + Send + Sync + 'static {
/// Bot service.
pub trait BotService: Clone + Send + Sync + 'static {
- /// Create a bot owned by the caller or one of their teams.
+ /// Create a bot owned by the caller or a team they administer.
fn create_bot(
&self,
caller: MacroUserIdStr<'static>,
req: CreateBotRequest,
) -> impl Future<Output = Result<Bot, BotError>> + Send;
- /// Create a bot owned by the caller and scoped to a channel.
+ /// Create a bot owned by the caller or a team they administer and scoped to a channel.
fn create_channel_scoped_bot(
&self,
caller: MacroUserIdStr<'static>,
diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rs
index 678066dd75..459d3862c9 100644
--- a/crates/bots/src/domain/service.rs
+++ b/crates/bots/src/domain/service.rs
@@ -76,7 +76,7 @@ where
if let Some(team_id) = team_id {
if !self
.repo
- .user_has_team(caller.clone(), team_id)
+ .user_can_administer_team(caller.clone(), team_id)
.await
.map_err(|err| BotError::Repo(err.into()))?
{
diff --git a/crates/bots/src/outbound/pg_bots_repo.rs b/crates/bots/src/outbound/pg_bots_repo.rs
index 4f6bc36d40..925d798c72 100644
--- a/crates/bots/src/outbound/pg_bots_repo.rs
+++ b/crates/bots/src/outbound/pg_bots_repo.rs
@@ -444,6 +444,30 @@ impl BotRepo for PgBotsRepo {
Ok(is_active)
}
+ async fn user_can_administer_team(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ team_id: Uuid,
+ ) -> Result<bool, Self::Err> {
+ let can_administer = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM team_user
+ WHERE user_id = $1
+ AND team_id = $2
+ AND team_role IN ('admin'::team_role, 'owner'::team_role)
+ ) AS "can_administer!"
+ "#,
+ caller.as_ref(),
+ team_id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to check team administration permission")?;
+ Ok(can_administer)
+ }
+
async fn patch_bot(
&self,
bot_id: BotId,
diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rs
index fa924e94d8..f9f016ad7a 100644
--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs
+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs
@@ -16,6 +16,8 @@ use std::sync::{Arc, Mutex};
const USER_OWNER: &str = "macro|[email protected]";
const USER_OTHER: &str = "macro|[email protected]";
const TEAM_MEMBER: &str = "macro|[email protected]";
+const TEAM_ADMIN: &str = "macro|[email protected]";
+const TEAM_OWNER: &str = "macro|[email protected]";
const TEAM_OTHER: &str = "macro|[email protected]";
fn user_id(value: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(value.to_string()).expect("valid macro user id")
@@ -173,30 +175,36 @@ async fn insert_user(pool: &PgPool, user_id: &str) -> anyhow::Result<()> {
Ok(())
}
-async fn insert_team_member(pool: &PgPool, team_id: Uuid, member_id: &str) -> anyhow::Result<()> {
- insert_user(pool, member_id).await?;
- sqlx::query(
+async fn insert_team_user(
+ pool: &PgPool,
+ team_id: Uuid,
+ user_id: &str,
+ role: &str,
+) -> anyhow::Result<()> {
+ insert_user(pool, user_id).await?;
+ sqlx::query!(
r#"
INSERT INTO team (id, name, owner_id)
VALUES ($1, $2, $3)
ON CONFLICT (id) DO NOTHING
"#,
+ team_id,
+ "Platform",
+ user_id,
)
- .bind(team_id)
- .bind("Platform")
- .bind(member_id)
.execute(pool)
.await?;
- sqlx::query(
+ sqlx::query!(
r#"
INSERT INTO team_user (user_id, team_id, team_role)
- VALUES ($1, $2, 'member'::team_role)
+ VALUES ($1, $2, $3::text::team_role)
ON CONFLICT (user_id, team_id) DO NOTHING
"#,
+ user_id,
+ team_id,
+ role,
)
- .bind(member_id)
- .bind(team_id)
.execute(pool)
.await?;
@@ -324,27 +332,63 @@ async fn create_user_owned_bot_records_user_owner(pool: PgPool) -> anyhow::Resul
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn create_team_owned_bot_requires_team_membership(pool: PgPool) -> anyhow::Result<()> {
+async fn create_team_owned_bot_requires_team_admin_or_owner(pool: PgPool) -> anyhow::Result<()> {
let service = service(&pool);
let team_id = Uuid::new_v4();
- insert_team_member(&pool, team_id, TEAM_MEMBER).await?;
+ insert_team_user(&pool, team_id, TEAM_OWNER, "owner").await?;
+ insert_team_user(&pool, team_id, TEAM_ADMIN, "admin").await?;
+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;
- let mut req = create_req("team-datadog");
- req.team_id = Some(team_id);
+ for (creator, handle) in [(TEAM_OWNER, "team-owner"), (TEAM_ADMIN, "team-admin")] {
+ let mut req = create_req(handle);
+ req.team_id = Some(team_id);
- let bot = service
- .create_bot(user_id(TEAM_MEMBER), req.clone())
- .await?;
+ let bot = service.create_bot(user_id(creator), req).await?;
+ assert_eq!(bot.owner, Some(BotOwner::Team { team_id }));
+ }
- assert_eq!(bot.owner, Some(BotOwner::Team { team_id }));
+ let mut req = create_req("team-member");
+ req.team_id = Some(team_id);
+ let err = service
+ .create_bot(user_id(TEAM_MEMBER), req.clone())
+ .await
+ .expect_err("ordinary team member must not create a team-owned bot");
+ assert!(matches!(err, BotError::Unauthorized));
let err = service
.create_bot(user_id(TEAM_OTHER), req)
.await
- .expect_err("non-team member must not create team-owned bot");
+ .expect_err("non-team member must not create a team-owned bot");
+ assert!(matches!(err, BotError::Unauthorized));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_team_owned_channel_scoped_bot_requires_team_admin(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let service = service(&pool);
+ let team_id = Uuid::new_v4();
+ let channel_id = Uuid::new_v4();
+ insert_team_user(&pool, team_id, TEAM_ADMIN, "admin").await?;
+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;
+ insert_channel(&pool, channel_id).await?;
+
+ let mut req = create_channel_scoped_req("team-scoped-channel");
+ req.team_id = Some(team_id);
+
+ let err = service
+ .create_channel_scoped_bot(user_id(TEAM_MEMBER), channel_id, req.clone())
+ .await
+ .expect_err("ordinary team member must not create a team-owned channel-scoped bot");
assert!(matches!(err, BotError::Unauthorized));
+ let created = service
+ .create_channel_scoped_bot(user_id(TEAM_ADMIN), channel_id, req)
+ .await?;
+ assert_eq!(created.bot.owner, Some(BotOwner::Team { team_id }));
+
Ok(())
}
@@ -706,11 +750,11 @@ async fn lifecycle_creation_publishes_exact_sanitized_events(pool: PgPool) -> an
.await?;
let team_id = Uuid::new_v4();
- insert_team_member(&pool, team_id, TEAM_MEMBER).await?;
+ insert_team_user(&pool, team_id, TEAM_ADMIN, "admin").await?;
let mut team_request = create_req("event-team");
team_request.team_id = Some(team_id);
let team_bot = service
- .create_bot(user_id(TEAM_MEMBER), team_request)
+ .create_bot(user_id(TEAM_ADMIN), team_request)
.await?;
let channel_id = Uuid::new_v4();
@@ -754,7 +798,7 @@ async fn lifecycle_creation_publishes_exact_sanitized_events(pool: PgPool) -> an
"handle": team_bot.handle,
"description": team_bot.description,
"avatar_url": team_bot.avatar_url,
- "created_by_user_id": TEAM_MEMBER,
+ "created_by_user_id": TEAM_ADMIN,
"channel_id": null,
"created_at": team_bot.created_at,
}),
@@ -788,13 +832,13 @@ async fn patch_and_delete_publish_requested_fields_and_team_owner(
pool: PgPool,
) -> anyhow::Result<()> {
let team_id = Uuid::new_v4();
- insert_team_member(&pool, team_id, TEAM_MEMBER).await?;
+ insert_team_user(&pool, team_id, TEAM_ADMIN, "admin").await?;
let broker = RecordingEventBroker::default();
let service = recording_service(&pool, broker.clone());
let mut create_request = create_req("event-mutations");
create_request.team_id = Some(team_id);
let bot = service
- .create_bot(user_id(TEAM_MEMBER), create_request)
+ .create_bot(user_id(TEAM_ADMIN), create_request)
.await?;
broker.clear();
@@ -805,7 +849,7 @@ async fn patch_and_delete_publish_requested_fields_and_team_owner(
avatar_url: None,
};
let patched = service
- .patch_bot(user_id(TEAM_MEMBER), bot.id, patch_request)
+ .patch_bot(user_id(TEAM_ADMIN), bot.id, patch_request)
.await?;
let events = broker.events();
@@ -817,7 +861,7 @@ async fn patch_and_delete_publish_requested_fields_and_team_owner(
json!({
"bot_id": bot.id,
"owner": { "type": "team", "team_id": team_id },
- "actor_user_id": TEAM_MEMBER,
+ "actor_user_id": TEAM_ADMIN,
"name": "Renamed alerts",
"handle": null,
"description": "Replacement description",
@@ -828,7 +872,7 @@ async fn patch_and_delete_publish_requested_fields_and_team_owner(
assert_no_token_material(&events[0].payload, None);
broker.clear();
- service.delete_bot(user_id(TEAM_MEMBER), bot.id).await?;
+ service.delete_bot(user_id(TEAM_ADMIN), bot.id).await?;
let events = broker.events();
assert_eq!(events.len(), 1);
assert_event(
@@ -838,7 +882,7 @@ async fn patch_and_delete_publish_requested_fields_and_team_owner(
json!({
"bot_id": bot.id,
"owner": { "type": "team", "team_id": team_id },
- "actor_user_id": TEAM_MEMBER,
+ "actor_user_id": TEAM_ADMIN,
}),
);
assert_no_token_material(&events[0].payload, None);