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(team): create team requires an active stripe subscription (#4045)

Will Hutchinson6d707625a761
diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.ts
index 25c890d5e2..d7f1f6ffa4 100644
--- a/js/app/packages/service-clients/service-auth/generated/client.ts
+++ b/js/app/packages/service-clients/service-auth/generated/client.ts
@@ -2050,6 +2050,11 @@ export type createTeamResponse400 = {
status: 400;
};
+export type createTeamResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
export type createTeamResponse500 = {
data: ErrorResponse;
status: 500;
@@ -2060,6 +2065,7 @@ export type createTeamResponseSuccess = createTeamResponse200 & {
};
export type createTeamResponseError = (
| createTeamResponse400
+ | createTeamResponse403
| createTeamResponse500
) & {
headers: Headers;
diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.json
index 020204047f..5eccaf9145 100644
--- a/js/app/packages/service-clients/service-auth/openapi.json
+++ b/js/app/packages/service-clients/service-auth/openapi.json
@@ -1747,6 +1747,16 @@
}
}
},
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rs
index 2a4d5e4aa5..62ad9f8c8c 100644
--- a/rust/cloud-storage/teams/src/domain/team_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs
@@ -282,6 +282,13 @@ pub trait TeamService: Clone + Send + Sync + 'static {
team_name: &str,
) -> impl Future<Output = Result<Team, CreateTeamError>> + Send;
+ /// Checks whether the user is a premium user, i.e. has an active
+ /// stripe subscription.
+ fn is_user_premium(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<bool, TeamError>> + Send;
+
/// Invites users to a team
/// This will also handle the teams subscription.
/// Returns the team invites created.
diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rs
index 324bbb0878..bdae37eb73 100644
--- a/rust/cloud-storage/teams/src/domain/team_service.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service.rs
@@ -297,6 +297,25 @@ where
Ok(team)
}
+ #[tracing::instrument(skip(self), err)]
+ async fn is_user_premium(&self, user_id: &MacroUserIdStr<'_>) -> Result<bool, TeamError> {
+ let Some(customer_id) = self.team_repository.get_stripe_customer_id(user_id).await? else {
+ return Ok(false);
+ };
+
+ match self
+ .customer_repository
+ .get_subscription_id_for_customer(&customer_id)
+ .await
+ {
+ Ok(_) => Ok(true),
+ Err(CustomerError::NoStripeCustomerId | CustomerError::SubscriptionNotActive) => {
+ Ok(false)
+ }
+ Err(e) => Err(TeamError::StorageLayerError(e.into())),
+ }
+ }
+
#[tracing::instrument(skip(self), err)]
async fn invite_users_to_team(
&self,
diff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rs
index 37c5ba41c9..17a3517ff5 100644
--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs
@@ -446,6 +446,7 @@ struct MockCustomerRepository {
decrement_calls: Arc<Mutex<Vec<(String, u64)>>>,
fail_increment: bool,
fail_decrement: bool,
+ no_active_subscription: bool,
}
impl Default for MockCustomerRepository {
@@ -456,6 +457,7 @@ impl Default for MockCustomerRepository {
decrement_calls: Arc::new(Mutex::new(Vec::new())),
fail_increment: false,
fail_decrement: false,
+ no_active_subscription: false,
}
}
}
@@ -474,8 +476,15 @@ impl CustomerRepository for MockCustomerRepository {
&self,
_: &stripe::CustomerId,
) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send {
+ let no_active_subscription = self.no_active_subscription;
let subscription_id = self.subscription_id.clone();
- async move { Ok(subscription_id) }
+ async move {
+ if no_active_subscription {
+ Err(CustomerError::SubscriptionNotActive)
+ } else {
+ Ok(subscription_id)
+ }
+ }
}
fn increment_seat_count(
@@ -839,6 +848,51 @@ async fn test_create_team_propagates_github_installation_move_failure() {
);
}
+fn build_service_for_premium_check(
+ stripe_customer_id: Option<stripe::CustomerId>,
+ no_active_subscription: bool,
+) -> impl TeamService {
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);
+ team_repo.stripe_customer_id = stripe_customer_id;
+ TeamServiceImpl::new(
+ team_repo,
+ MockCustomerRepository {
+ no_active_subscription,
+ ..Default::default()
+ },
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ )
+}
+
+#[tokio::test]
+async fn test_is_user_premium_with_active_subscription() {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let service = build_service_for_premium_check(Some("cus_test".parse().unwrap()), false);
+
+ assert!(service.is_user_premium(&user_id).await.unwrap());
+}
+
+#[tokio::test]
+async fn test_is_user_premium_without_stripe_customer() {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let service = build_service_for_premium_check(None, false);
+
+ assert!(!service.is_user_premium(&user_id).await.unwrap());
+}
+
+#[tokio::test]
+async fn test_is_user_premium_without_active_subscription() {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let service = build_service_for_premium_check(Some("cus_test".parse().unwrap()), true);
+
+ assert!(!service.is_user_premium(&user_id).await.unwrap());
+}
+
/// When one notification fails, only the successful invite IDs are passed to
/// mark_invites_sent.
#[tokio::test]
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/create_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/create_team.rs
index 7952766183..72093670f7 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/create_team.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/create_team.rs
@@ -1,10 +1,9 @@
use axum::{Json, extract::State};
use entity_access::domain::ports::EntityAccessService;
-use model_user::axum_extractor::MacroUserExtractor;
use crate::domain::{model::Team, team_repo::TeamService};
-use super::TeamRouterState;
+use super::{TeamRouterState, premium_user::PremiumUserExtractor};
/// The request body to create a new team
#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
@@ -21,13 +20,14 @@ pub struct CreateTeamRequest {
responses(
(status = 200, body = Team),
(status = 400, body = model_error_response::ErrorResponse),
+ (status = 403, body = model_error_response::ErrorResponse),
(status = 500, body = model_error_response::ErrorResponse),
),
)]
#[tracing::instrument(skip_all, err)]
pub async fn handler<T: TeamService, Eas: EntityAccessService>(
State(state): State<TeamRouterState<T, Eas>>,
- user: MacroUserExtractor,
+ user: PremiumUserExtractor,
Json(req): Json<CreateTeamRequest>,
) -> Result<Json<Team>, crate::domain::model::CreateTeamError> {
let team = state
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
index f04224447f..ef77a7f709 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
@@ -22,6 +22,8 @@ pub mod join_team;
pub mod patch_team;
/// Enable / disable CRM for a team.
pub mod patch_team_crm_settings;
+/// Extractor ensuring the authenticated user is premium.
+pub mod premium_user;
/// Reject a team invitation.
pub mod reject_invitation;
/// Remove a user from a team.
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/premium_user.rs b/rust/cloud-storage/teams/src/inbound/axum_router/premium_user.rs
new file mode 100644
index 0000000000..298d551299
--- /dev/null
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/premium_user.rs
@@ -0,0 +1,83 @@
+//! Extractor that ensures the authenticated user is a premium user.
+
+use axum::{
+ Json,
+ extract::FromRequestParts,
+ http::{StatusCode, request::Parts},
+ response::{IntoResponse, Response},
+};
+use entity_access::domain::ports::EntityAccessService;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_error_response::ErrorResponse;
+use model_user::axum_extractor::{MacroUserExtractor, UserExtractorErr};
+
+use crate::domain::{model::TeamError, team_repo::TeamService};
+
+use super::TeamRouterState;
+
+/// Extractor that ensures the authenticated user is a premium user
+/// (has an active stripe subscription).
+pub struct PremiumUserExtractor {
+ /// The authenticated premium user's id.
+ pub macro_user_id: MacroUserIdStr<'static>,
+}
+
+/// Rejection returned when the premium user check fails.
+#[derive(Debug, thiserror::Error)]
+pub enum PremiumUserRejection {
+ /// The user could not be extracted from the request.
+ #[error(transparent)]
+ User(#[from] UserExtractorErr),
+ /// The user does not have an active subscription.
+ #[error("active subscription required")]
+ NotPremium,
+ /// The premium check could not be performed.
+ #[error(transparent)]
+ Service(#[from] TeamError),
+}
+
+impl IntoResponse for PremiumUserRejection {
+ fn into_response(self) -> Response {
+ match self {
+ PremiumUserRejection::User(err) => err.into_response(),
+ PremiumUserRejection::NotPremium => (
+ StatusCode::FORBIDDEN,
+ Json(ErrorResponse {
+ message: "active subscription required".into(),
+ }),
+ )
+ .into_response(),
+ PremiumUserRejection::Service(_) => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "internal server error".into(),
+ }),
+ )
+ .into_response(),
+ }
+ }
+}
+
+impl<T, Eas> FromRequestParts<TeamRouterState<T, Eas>> for PremiumUserExtractor
+where
+ T: TeamService,
+ Eas: EntityAccessService,
+{
+ type Rejection = PremiumUserRejection;
+
+ #[tracing::instrument(err, skip(parts, state))]
+ async fn from_request_parts(
+ parts: &mut Parts,
+ state: &TeamRouterState<T, Eas>,
+ ) -> Result<Self, Self::Rejection> {
+ let user = MacroUserExtractor::from_request_parts(parts, state).await?;
+
+ if !state.service.is_user_premium(&user.macro_user_id).await? {
+ return Err(PremiumUserRejection::NotPremium);
+ }
+
+ Ok(Self {
+ macro_user_id: user.macro_user_id,
+ })
+ }
+}