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(auth-service): Change stripe tier endpoint (#2655)

Evan Hutnikc8daa6845c6e
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 5243d716ad..617acdde47 100644
--- a/js/app/packages/service-clients/service-auth/generated/client.ts
+++ b/js/app/packages/service-clients/service-auth/generated/client.ts
@@ -29,6 +29,7 @@ import type {
PasswordlessCallbackParams,
PasswordlessRequest,
PasswordRequest,
+ PatchSubscriptionTierRequest,
PatchTeamRequest,
PatchTeamUserTierRequest,
PatchUserGroupRequest,
@@ -3450,22 +3451,22 @@ export type createCheckoutSessionResponse200 = {
};
export type createCheckoutSessionResponse400 = {
- data: string;
+ data: ErrorResponse;
status: 400;
};
export type createCheckoutSessionResponse404 = {
- data: string;
+ data: ErrorResponse;
status: 404;
};
export type createCheckoutSessionResponse409 = {
- data: string;
+ data: ErrorResponse;
status: 409;
};
export type createCheckoutSessionResponse500 = {
- data: string;
+ data: ErrorResponse;
status: 500;
};
@@ -3522,12 +3523,12 @@ export type createPortalSessionResponse200 = {
};
export type createPortalSessionResponse400 = {
- data: string;
+ data: ErrorResponse;
status: 400;
};
export type createPortalSessionResponse500 = {
- data: string;
+ data: ErrorResponse;
status: 500;
};
@@ -3573,6 +3574,84 @@ export const createPortalSession = async (
} as createPortalSessionResponse;
};
+/**
+ * @summary Updates the user's subscription tier, swapping both their RBAC role and Stripe subscription line item.
+ */
+export type patchSubscriptionTierResponse200 = {
+ data: void;
+ status: 200;
+};
+
+export type patchSubscriptionTierResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type patchSubscriptionTierResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
+export type patchSubscriptionTierResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type patchSubscriptionTierResponse409 = {
+ data: ErrorResponse;
+ status: 409;
+};
+
+export type patchSubscriptionTierResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type patchSubscriptionTierResponseSuccess =
+ patchSubscriptionTierResponse200 & {
+ headers: Headers;
+ };
+export type patchSubscriptionTierResponseError = (
+ | patchSubscriptionTierResponse400
+ | patchSubscriptionTierResponse403
+ | patchSubscriptionTierResponse404
+ | patchSubscriptionTierResponse409
+ | patchSubscriptionTierResponse500
+) & {
+ headers: Headers;
+};
+
+export type patchSubscriptionTierResponse =
+ | patchSubscriptionTierResponseSuccess
+ | patchSubscriptionTierResponseError;
+
+export const getPatchSubscriptionTierUrl = () => {
+ return `/user/stripe/subscription`;
+};
+
+export const patchSubscriptionTier = async (
+ patchSubscriptionTierRequest: PatchSubscriptionTierRequest,
+ options?: RequestInit
+): Promise<patchSubscriptionTierResponse> => {
+ const res = await fetch(getPatchSubscriptionTierUrl(), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchSubscriptionTierRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: patchSubscriptionTierResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as patchSubscriptionTierResponse;
+};
+
/**
* @summary Updates the user's tutorialComplete flag.
*/
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
index 6f5983f157..ba79e2b2c7 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
@@ -39,6 +39,7 @@ export * from './passwordlessCallbackParams';
export * from './passwordlessRequest';
export * from './passwordlessRequestReferralCode';
export * from './passwordRequest';
+export * from './patchSubscriptionTierRequest';
export * from './patchTeamRequest';
export * from './patchTeamRequestName';
export * from './patchTeamUserTierRequest';
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/patchSubscriptionTierRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchSubscriptionTierRequest.ts
new file mode 100644
index 0000000000..c14bcf3763
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/patchSubscriptionTierRequest.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { StripeProductTier } from './stripeProductTier';
+
+/**
+ * Request body for changing the user's subscription tier
+ */
+export interface PatchSubscriptionTierRequest {
+ /** The new tier to move the user to */
+ newTier: StripeProductTier;
+}
diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.json
index 05cc575dda..07ddef1efb 100644
--- a/js/app/packages/service-clients/service-auth/openapi.json
+++ b/js/app/packages/service-clients/service-auth/openapi.json
@@ -2953,9 +2953,9 @@
"400": {
"description": "",
"content": {
- "text/plain": {
+ "application/json": {
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -2963,9 +2963,9 @@
"404": {
"description": "",
"content": {
- "text/plain": {
+ "application/json": {
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -2973,9 +2973,9 @@
"409": {
"description": "",
"content": {
- "text/plain": {
+ "application/json": {
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -2983,9 +2983,9 @@
"500": {
"description": "",
"content": {
- "text/plain": {
+ "application/json": {
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -3022,9 +3022,9 @@
"400": {
"description": "",
"content": {
- "text/plain": {
+ "application/json": {
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -3032,9 +3032,81 @@
"500": {
"description": "",
"content": {
- "text/plain": {
+ "application/json": {
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/user/stripe/subscription": {
+ "patch": {
+ "tags": ["user::stripe"],
+ "summary": "Updates the user's subscription tier, swapping both their RBAC role and Stripe subscription line item.",
+ "operationId": "patch_subscription_tier",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PatchSubscriptionTierRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": ""
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -3447,6 +3519,17 @@
}
}
},
+ "PatchSubscriptionTierRequest": {
+ "type": "object",
+ "description": "Request body for changing the user's subscription tier",
+ "required": ["newTier"],
+ "properties": {
+ "newTier": {
+ "$ref": "#/components/schemas/StripeProductTier",
+ "description": "The new tier to move the user to"
+ }
+ }
+ },
"PatchTeamRequest": {
"type": "object",
"description": "Request to update a team",
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index bb73580cf8..0dda191fa5 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -653,6 +653,7 @@ dependencies = [
"sha1",
"sqlx",
"sqs_client",
+ "strum",
"teams",
"thiserror 2.0.17",
"time",
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index 58ee8286d3..71bad8dad3 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -111,6 +111,7 @@ sqs_client = { path = "../sqs_client", default-features = false, features = [
"search",
"email",
] }
+strum = { workspace = true }
teams = { path = "../teams" }
thiserror = { workspace = true }
time = { workspace = true }
diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rs
index b53d1b7a8a..e8645417cd 100644
--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs
+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs
@@ -27,8 +27,8 @@ use crate::api::user::patch_user_onboarding::PatchUserOnboardingRequest;
use crate::api::user::post_get_names::PostGetNamesRequestBody;
use crate::api::user::post_get_names_with_email::GetNamesWithEmailRequestBody;
use crate::api::user::stripe::{
- CreateCheckoutSessionRequest, CreatePortalSessionRequest, StripeProductTier,
- StripeSessionResponse,
+ CreateCheckoutSessionRequest, CreatePortalSessionRequest, PatchSubscriptionTierRequest,
+ StripeProductTier, StripeSessionResponse,
};
use crate::api::{
email, health, jwt, link, login, logout, merge, mobile_welcome_email, oauth, oauth2,
@@ -100,6 +100,7 @@ use model::user::{
user::patch_tutorial::handler,
user::stripe::create_checkout_session,
user::stripe::create_portal_session,
+ user::stripe::patch_subscription_tier,
/// /session
session::session_login::handler,
@@ -172,6 +173,7 @@ use model::user::{
StripeProductTier,
CreateCheckoutSessionRequest,
CreatePortalSessionRequest,
+ PatchSubscriptionTierRequest,
StripeSessionResponse,
// User onboarding
diff --git a/rust/cloud-storage/authentication_service/src/api/user/mod.rs b/rust/cloud-storage/authentication_service/src/api/user/mod.rs
index 0c359411ea..b3f737bb12 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/mod.rs
@@ -59,6 +59,10 @@ fn router_with_auth(state: ApiContext, jwt_args: JwtValidationArgs) -> Router<Ap
)
.route("/stripe/checkout", post(stripe::create_checkout_session))
.route("/stripe/portal", post(stripe::create_portal_session))
+ .route(
+ "/stripe/subscription",
+ patch(stripe::patch_subscription_tier),
+ )
.route(
"/legacy_user_permissions",
get(get_legacy_user_permissions::handler),
diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rs
similarity index 57%
rename from rust/cloud-storage/authentication_service/src/api/user/stripe.rs
rename to rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rs
index 5578635252..03515ce965 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/stripe.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rs
@@ -1,63 +1,12 @@
-use axum::{
- Extension, Json,
- extract::State,
- http::StatusCode,
- response::{IntoResponse, Response},
-};
-use serde::{Deserialize, Serialize};
-use stripe::{ParseIdError, StripeError};
-use thiserror::Error;
+use axum::{Extension, Json, extract::State};
+use serde::Deserialize;
use utoipa::ToSchema;
+use super::{StripeOperationError, StripeProductTier, StripeSessionResponse};
use crate::api::context::ApiContext;
+use model::response::ErrorResponse;
use model::user::UserContext;
-// Shared error type for Stripe operations
-#[derive(Debug, Error)]
-pub enum StripeOperationError {
- #[error("Failed to parse user id")]
- ParseId(#[from] macro_user_id::error::ParseErr),
- #[error("Internal server error")]
- DbErr(#[from] sqlx::Error),
- #[error("User does not have a stripe id")]
- MissingStripeId,
- #[error("Invalid stripe id")]
- StripeIdParse(#[from] ParseIdError),
- #[error("Internal stripe error")]
- StripeErr(#[from] StripeError),
- #[error("Invalid promo code")]
- PromoCodeNotFound,
- #[error("Internal server error")]
- UnexpectedStripeResponse,
- #[error("User already has an active subscription")]
- AlreadySubscribed,
-}
-
-impl IntoResponse for StripeOperationError {
- fn into_response(self) -> Response {
- let status = match &self {
- StripeOperationError::ParseId(_) => StatusCode::BAD_REQUEST,
- StripeOperationError::DbErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
- StripeOperationError::MissingStripeId => StatusCode::BAD_REQUEST,
- StripeOperationError::StripeIdParse(_) => StatusCode::BAD_REQUEST,
- StripeOperationError::StripeErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
- StripeOperationError::PromoCodeNotFound => StatusCode::NOT_FOUND,
- StripeOperationError::UnexpectedStripeResponse => StatusCode::INTERNAL_SERVER_ERROR,
- StripeOperationError::AlreadySubscribed => StatusCode::CONFLICT,
- };
- (status, self.to_string()).into_response()
- }
-}
-
-#[derive(Debug, Deserialize, Default, ToSchema)]
-#[serde(rename_all = "lowercase")]
-pub enum StripeProductTier {
- #[default]
- Haiku,
- Sonnet,
- Opus,
-}
-
/// Tracking metadata for conversion attribution
#[derive(Debug, Default, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
@@ -88,22 +37,6 @@ pub struct CreateCheckoutSessionRequest {
pub tier: StripeProductTier,
}
-/// Response containing the Stripe session URL
-#[derive(Debug, Serialize, ToSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct StripeSessionResponse {
- /// The URL to redirect the user to
- pub url: String,
-}
-
-/// Request body for creating a Stripe portal session
-#[derive(Debug, Deserialize, ToSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct CreatePortalSessionRequest {
- /// The URL to redirect to after leaving the portal
- pub return_url: String,
-}
-
/// Creates a Stripe checkout session for the user to subscribe.
#[utoipa::path(
post,
@@ -112,10 +45,10 @@ pub struct CreatePortalSessionRequest {
request_body = CreateCheckoutSessionRequest,
responses(
(status = 200, body = StripeSessionResponse),
- (status = 400, body = String),
- (status = 404, body = String),
- (status = 409, body = String),
- (status = 500, body = String),
+ (status = 400, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 409, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
)
)]
#[tracing::instrument(skip(ctx, user_context), err, fields(user_id = %user_context.user_id))]
@@ -230,52 +163,9 @@ pub async fn create_checkout_session(
.url
.ok_or(StripeOperationError::UnexpectedStripeResponse)?;
- let url = url::Url::parse(&url).map_err(|_| StripeOperationError::UnexpectedStripeResponse)?;
-
- Ok(Json(StripeSessionResponse {
- url: url.to_string(),
- }))
-}
-
-/// Creates a Stripe billing portal session.
-#[utoipa::path(
- post,
- path = "/user/stripe/portal",
- operation_id = "create_portal_session",
- request_body = CreatePortalSessionRequest,
- responses(
- (status = 200, body = StripeSessionResponse),
- (status = 400, body = String),
- (status = 500, body = String),
- )
-)]
-#[tracing::instrument(skip(ctx, user_context), err, fields(user_id = %user_context.user_id))]
-pub async fn create_portal_session(
- State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
- Json(req): Json<CreatePortalSessionRequest>,
-) -> Result<Json<StripeSessionResponse>, StripeOperationError> {
- let user_id =
- macro_user_id::user_id::MacroUserId::parse_from_str(&user_context.user_id)?.lowercase();
-
- // Get the stripe customer ID from the database
- let stripe_customer_id =
- macro_db_client::user::get::get_stripe_customer_id_by_user_id(&ctx.db, &user_id)
- .await?
- .ok_or(StripeOperationError::MissingStripeId)?;
-
- let customer_id: stripe::CustomerId = stripe_customer_id.parse()?;
-
- // Create the billing portal session
- let mut params = stripe::CreateBillingPortalSession::new(customer_id);
- params.return_url = Some(req.return_url.as_str());
-
- let session = stripe::BillingPortalSession::create(&ctx.stripe_client, params).await?;
-
- let url = url::Url::parse(&session.url)
- .map_err(|_| StripeOperationError::UnexpectedStripeResponse)?;
+ // Validate but return the exact URL Stripe gave us — session URLs are signed/opaque
+ // and `Url::parse(...).to_string()` can normalize in ways that break the signature.
+ url::Url::parse(&url).map_err(|_| StripeOperationError::UnexpectedStripeResponse)?;
- Ok(Json(StripeSessionResponse {
- url: url.to_string(),
- }))
+ Ok(Json(StripeSessionResponse { url }))
}
diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/create_portal_session.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_portal_session.rs
new file mode 100644
index 0000000000..cc90f2b902
--- /dev/null
+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_portal_session.rs
@@ -0,0 +1,58 @@
+use axum::{Extension, Json, extract::State};
+use serde::Deserialize;
+use utoipa::ToSchema;
+
+use super::{StripeOperationError, StripeSessionResponse};
+use crate::api::context::ApiContext;
+use model::response::ErrorResponse;
+use model::user::UserContext;
+
+/// Request body for creating a Stripe portal session
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreatePortalSessionRequest {
+ /// The URL to redirect to after leaving the portal
+ pub return_url: String,
+}
+
+/// Creates a Stripe billing portal session.
+#[utoipa::path(
+ post,
+ path = "/user/stripe/portal",
+ operation_id = "create_portal_session",
+ request_body = CreatePortalSessionRequest,
+ responses(
+ (status = 200, body = StripeSessionResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx, user_context), err, fields(user_id = %user_context.user_id))]
+pub async fn create_portal_session(
+ State(ctx): State<ApiContext>,
+ user_context: Extension<UserContext>,
+ Json(req): Json<CreatePortalSessionRequest>,
+) -> Result<Json<StripeSessionResponse>, StripeOperationError> {
+ let user_id =
+ macro_user_id::user_id::MacroUserId::parse_from_str(&user_context.user_id)?.lowercase();
+
+ // Get the stripe customer ID from the database
+ let stripe_customer_id =
+ macro_db_client::user::get::get_stripe_customer_id_by_user_id(&ctx.db, &user_id)
+ .await?
+ .ok_or(StripeOperationError::MissingStripeId)?;
+
+ let customer_id: stripe::CustomerId = stripe_customer_id.parse()?;
+
+ // Create the billing portal session
+ let mut params = stripe::CreateBillingPortalSession::new(customer_id);
+ params.return_url = Some(req.return_url.as_str());
+
+ let session = stripe::BillingPortalSession::create(&ctx.stripe_client, params).await?;
+
+ // Validate but return the exact URL Stripe gave us — session URLs are signed/opaque
+ // and `Url::parse(...).to_string()` can normalize in ways that break the signature.
+ url::Url::parse(&session.url).map_err(|_| StripeOperationError::UnexpectedStripeResponse)?;
+
+ Ok(Json(StripeSessionResponse { url: session.url }))
+}
diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/mod.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/mod.rs
new file mode 100644
index 0000000000..6e03a54d76
--- /dev/null
+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/mod.rs
@@ -0,0 +1,9 @@
+mod create_checkout_session;
+mod create_portal_session;
+mod patch_subscription_tier;
+mod shared;
+
+pub use create_checkout_session::*;
+pub use create_portal_session::*;
+pub use patch_subscription_tier::*;
+pub use shared::{StripeOperationError, StripeProductTier, StripeSessionResponse};
diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/patch_subscription_tier.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/patch_subscription_tier.rs
new file mode 100644
index 0000000000..333d790431
--- /dev/null
+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/patch_subscription_tier.rs
@@ -0,0 +1,332 @@
+use std::collections::HashSet;
+
+use axum::{Extension, Json, extract::State};
+use macro_user_id::user_id::MacroUserIdStr;
+use roles_and_permissions::domain::{
+ model::{RoleId, UserRolesAndPermissionsError},
+ port::UserRolesAndPermissionsService,
+};
+use serde::Deserialize;
+use strum::IntoEnumIterator;
+use teams::domain::team_repo::TeamService;
+use utoipa::ToSchema;
+
+use super::{StripeOperationError, StripeProductTier};
+use crate::api::context::ApiContext;
+use crate::config::StripePriceIds;
+use model::response::ErrorResponse;
+use model::user::UserContext;
+
+/// Request body for changing the user's subscription tier
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct PatchSubscriptionTierRequest {
+ /// The new tier to move the user to
+ pub new_tier: StripeProductTier,
+}
+
+/// Updates the user's subscription tier, swapping both their RBAC role and Stripe subscription line item.
+#[utoipa::path(
+ patch,
+ path = "/user/stripe/subscription",
+ operation_id = "patch_subscription_tier",
+ request_body = PatchSubscriptionTierRequest,
+ responses(
+ (status = 200),
+ (status = 400, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 409, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx, user_context), err, fields(user_id = %user_context.user_id))]
+pub async fn patch_subscription_tier(
+ State(ctx): State<ApiContext>,
+ user_context: Extension<UserContext>,
+ Json(req): Json<PatchSubscriptionTierRequest>,
+) -> Result<(), StripeOperationError> {
+ let user_id = MacroUserIdStr::parse_from_str(&user_context.user_id)?;
+
+ // Team members can't manage their own tier — the team owner's tier change flow
+ // (`PATCH /team/{id}/tier`) owns billing for the whole team. Checked before taking the
+ // lock so we don't pin a connection for a user who can't use this endpoint anyway.
+ if !ctx.teams_service.get_user_teams(&user_id).await?.is_empty() {
+ return Err(StripeOperationError::UserInTeam);
+ }
+
+ // Serialize concurrent subscription mutations for this user (double-clicks, racing tabs,
+ // user + webhook). Lock is released when `txn` is committed or dropped at end of handler.
+ let mut txn = ctx.db.begin().await?;
+ if !macro_db_client::advisory_lock::try_acquire_user_subscription_xact_lock(&mut txn, &user_id)
+ .await?
+ {
+ return Err(StripeOperationError::SubscriptionUpdateInProgress);
+ }
+
+ let new_tier = req.new_tier;
+ let new_price_id = price_id_for_tier(&ctx.stripe_price_ids, new_tier);
+
+ let user_roles = ctx
+ .user_roles_and_permissions_service
+ .get_user_roles(&user_id)
+ .await?;
+
+ let old_tier = find_current_sub_tier(&user_roles)?;
+
+ if old_tier == new_tier {
+ return Err(StripeOperationError::TierUnchanged);
+ }
+
+ let old_price_id = price_id_for_tier(&ctx.stripe_price_ids, old_tier);
+ let old_role = tier_to_sub_role(old_tier);
+ let new_role = tier_to_sub_role(new_tier);
+
+ let stripe_customer_id =
+ macro_db_client::user::get::get_stripe_customer_id_by_user_id(&ctx.db, &user_id)
+ .await?
+ .ok_or(StripeOperationError::MissingStripeId)?;
+ let customer_id: stripe::CustomerId = stripe_customer_id.parse()?;
+
+ let subscription = fetch_active_subscription(&ctx.stripe_client, customer_id).await?;
+ let old_item_id = find_subscription_item_id(&subscription, old_price_id)?;
+
+ let roles_service = ctx.user_roles_and_permissions_service.as_ref();
+ swap_user_role(roles_service, &user_id, &old_role, &new_role).await?;
+
+ // Stripe idempotency: guarantees a retried call (e.g. our 200 got lost in flight) won't
+ // double-apply the tier swap. Key is stable per logical operation; Stripe's own 24h TTL
+ // handles the "after some window, treat as new operation" case. Uses an explicit stable
+ // string for the tier (rather than `Debug`) so that renaming an enum variant doesn't
+ // rotate every in-flight key and break dedup.
+ let idempotency_key = format!(
+ "patch_subscription_tier:{user_id}:{}:{}:{}",
+ tier_key_str(old_tier),
+ tier_key_str(new_tier),
+ subscription.id,
+ );
+ let idempotent_client = ctx
+ .stripe_client
+ .as_ref()
+ .clone()
+ .with_strategy(stripe::RequestStrategy::Idempotent(idempotency_key.clone()));
+
+ if let Err(stripe_err) = swap_subscription_item(
+ &idempotent_client,
+ &subscription.id,
+ &old_item_id,
+ new_price_id,
+ )
+ .await
+ {
+ // Include subscription id, prices, and idempotency key so on-call can reconcile:
+ // if Stripe actually applied the change server-side but returned a network error,
+ // we just rolled back RBAC and left it desynced. The idempotency key + subscription
+ // id uniquely identify the operation for manual inspection.
+ match rollback_role_swap(roles_service, &user_id, &old_role, &new_role).await {
+ Ok(()) => tracing::error!(
+ error = ?stripe_err,
+ subscription_id = %subscription.id,
+ old_price_id = old_price_id,
+ new_price_id = new_price_id,
+ idempotency_key = %idempotency_key,
+ "stripe subscription update failed, role swap rolled back",
+ ),
+ Err(rollback_err) => tracing::error!(
+ error = ?stripe_err,
+ rollback_error = ?rollback_err,
+ subscription_id = %subscription.id,
+ old_price_id = old_price_id,
+ new_price_id = new_price_id,
+ idempotency_key = %idempotency_key,
+ old_role = ?old_role,
+ new_role = ?new_role,
+ "stripe subscription update failed AND rollback failed — user state inconsistent",
+ ),
+ }
+ return Err(stripe_err.into());
+ }
+
+ txn.commit().await?;
+ Ok(())
+}
+
+/// Maps a subscription tier to the RBAC role a user holds while subscribed at that tier.
+fn tier_to_sub_role(tier: StripeProductTier) -> RoleId {
+ match tier {
+ StripeProductTier::Haiku => RoleId::SubHaiku,
+ StripeProductTier::Sonnet => RoleId::SubSonnet,
+ StripeProductTier::Opus => RoleId::SubOpus,
+ }
+}
+
+/// Stable string form of a tier for use in externally-visible keys (idempotency keys, etc.).
+/// Must remain stable even if enum variants are renamed — otherwise in-flight idempotency
+/// keys would rotate and dedup would break.
+fn tier_key_str(tier: StripeProductTier) -> &'static str {
+ match tier {
+ StripeProductTier::Haiku => "haiku",
+ StripeProductTier::Sonnet => "sonnet",
+ StripeProductTier::Opus => "opus",
+ }
+}
+
+/// Returns the Stripe price ID configured for the given tier.
+fn price_id_for_tier(price_ids: &StripePriceIds, tier: StripeProductTier) -> &str {
+ match tier {
+ StripeProductTier::Haiku => price_ids.stripe_price_id_haiku.as_ref(),
+ StripeProductTier::Sonnet => price_ids.stripe_price_id_sonnet.as_ref(),
+ StripeProductTier::Opus => price_ids.stripe_price_id_opus.as_ref(),
+ }
+}
+
+/// Identifies the user's current subscription tier by scanning their RBAC role set.
+/// Refuses to guess if the user somehow holds more than one Sub\* role — a drifted state that
+/// would otherwise let us pick arbitrarily and silently leave the other role behind.
+#[tracing::instrument(skip(roles), err)]
+fn find_current_sub_tier(
+ roles: &HashSet<RoleId>,
+) -> Result<StripeProductTier, StripeOperationError> {
+ let matches: Vec<StripeProductTier> = StripeProductTier::iter()
+ .filter(|tier| roles.contains(&tier_to_sub_role(*tier)))
+ .collect();
+
+ match matches.as_slice() {
+ [] => Err(StripeOperationError::NoSubscriptionRole),
+ [tier] => Ok(*tier),
+ tiers => {
+ tracing::error!(
+ tiers = ?tiers,
+ "user holds multiple Sub* roles — refusing to change tier",
+ );
+ Err(StripeOperationError::InconsistentSubscriptionRoles)
+ }
+ }
+}
+
+/// Fetches the customer's single active Stripe subscription. Solo users are expected to have
+/// exactly one; this endpoint is blocked for team members earlier in the handler, so a customer
+/// with zero active subs here is genuinely "nothing to patch" and surfaces as 404.
+#[tracing::instrument(skip(stripe_client), err, fields(customer_id = %customer_id))]
+async fn fetch_active_subscription(
+ stripe_client: &stripe::Client,
+ customer_id: stripe::CustomerId,
+) -> Result<stripe::Subscription, StripeOperationError> {
+ let mut list_params = stripe::ListSubscriptions::new();
+ list_params.customer = Some(customer_id);
+ list_params.status = Some(stripe::SubscriptionStatusFilter::Active);
+ list_params.limit = Some(1);
+
+ stripe::Subscription::list(stripe_client, &list_params)
+ .await?
+ .data
+ .into_iter()
+ .next()
+ .ok_or(StripeOperationError::NoActiveSubscription)
+}
+
+/// Finds the subscription line item whose price matches `price_id` and returns its id.
+/// Returning `UnexpectedStripeResponse` here would indicate Stripe is in a state we don't model
+/// (e.g. the user's role points at a tier their subscription no longer contains).
+fn find_subscription_item_id(
+ subscription: &stripe::Subscription,
+ price_id: &str,
+) -> Result<String, StripeOperationError> {
+ subscription
+ .items
+ .data
+ .iter()
+ .find(|item| {
+ item.price
+ .as_ref()
+ .map(|p| p.id.as_str() == price_id)
+ .unwrap_or(false)
+ })
+ .map(|item| item.id.to_string())
+ .ok_or(StripeOperationError::UnexpectedStripeResponse)
+}
+
+/// Swaps a user's subscription tier role: upserts `new_role`, then removes `old_role`.
+///
+/// Ordering matters: upsert-then-remove means a partial failure leaves the user with *both*
+/// roles (transient multi-role state, caught by `find_current_sub_tier` on the next request),
+/// whereas remove-then-upsert could leave them with *zero* Sub roles and locked out of their
+/// plan.
+#[tracing::instrument(skip(service), err, fields(user_id = %user_id, old_role = ?old_role, new_role = ?new_role))]
+async fn swap_user_role<S: UserRolesAndPermissionsService>(
+ service: &S,
+ user_id: &MacroUserIdStr<'_>,
+ old_role: &RoleId,
+ new_role: &RoleId,
+) -> Result<(), UserRolesAndPermissionsError> {
+ service
+ .dangerous_upsert_roles_for_user(user_id, one_role(new_role))
+ .await?;
+
+ service
+ .dangerous_remove_roles_from_user(user_id, &one_role(old_role))
+ .await?;
+
+ Ok(())
+}
+
+/// Wraps a single role in a `NonEmpty` slice. Infallible: the slice always has length 1.
+fn one_role(role: &RoleId) -> non_empty::NonEmpty<&[RoleId]> {
+ non_empty::NonEmpty::new(std::slice::from_ref(role))
+ .expect("slice::from_ref always yields a non-empty slice")
+}
+
+/// Swaps the subscription's line item from `old_item_id` to a new item at `new_price_id`.
+///
+/// Uses delete-old + add-new (quantity 1) in a single `Subscription::update` call rather than
+/// mutating the existing item's price, matching the pattern used by the teams tier-swap code
+/// path. `AlwaysInvoice` proration bills the pro-rated difference immediately so the customer
+/// isn't charged the full new rate on their next cycle.
+#[tracing::instrument(
+ skip(stripe_client),
+ err,
+ fields(subscription_id = %subscription_id, old_item_id = old_item_id, new_price_id = new_price_id),
+)]
+async fn swap_subscription_item(
+ stripe_client: &stripe::Client,
+ subscription_id: &stripe::SubscriptionId,
+ old_item_id: &str,
+ new_price_id: &str,
+) -> Result<(), stripe::StripeError> {
+ let update_params = stripe::UpdateSubscription {
+ items: Some(vec![
+ stripe::UpdateSubscriptionItems {
+ id: Some(old_item_id.to_string()),
+ deleted: Some(true),
+ ..Default::default()
+ },
+ stripe::UpdateSubscriptionItems {
+ price: Some(new_price_id.to_string()),
+ quantity: Some(1),
+ ..Default::default()
+ },
+ ]),
+ proration_behavior: Some(
+ stripe::generated::billing::subscription::SubscriptionProrationBehavior::AlwaysInvoice,
+ ),
+ ..Default::default()
+ };
+
+ stripe::Subscription::update(stripe_client, subscription_id, update_params).await?;
+ Ok(())
+}
+
+/// Reverts the role swap after a failed Stripe update.
+///
+/// On failure the caller is responsible for logging — combining the rollback error with the
+/// originating Stripe error in a single structured log line gives alerting a complete picture
+/// of the inconsistent state.
+#[tracing::instrument(skip(service), err, fields(user_id = %user_id, old_role = ?old_role, new_role = ?new_role))]
+async fn rollback_role_swap<S: UserRolesAndPermissionsService>(
+ service: &S,
+ user_id: &MacroUserIdStr<'_>,
+ old_role: &RoleId,
+ new_role: &RoleId,
+) -> Result<(), UserRolesAndPermissionsError> {
+ swap_user_role(service, user_id, new_role, old_role).await
+}
diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/shared.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/shared.rs
new file mode 100644
index 0000000000..6078d8288f
--- /dev/null
+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/shared.rs
@@ -0,0 +1,100 @@
+use axum::{
+ Json,
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use model::response::ErrorResponse;
+use roles_and_permissions::domain::model::UserRolesAndPermissionsError;
+use serde::{Deserialize, Serialize};
+use stripe::{ParseIdError, StripeError};
+use thiserror::Error;
+use utoipa::ToSchema;
+
+/// Shared error type for Stripe operations
+#[derive(Debug, Error)]
+pub enum StripeOperationError {
+ #[error("Failed to parse user id")]
+ ParseId(#[from] macro_user_id::error::ParseErr),
+ #[error("Internal server error")]
+ DbErr(#[from] sqlx::Error),
+ #[error("User does not have a stripe id")]
+ MissingStripeId,
+ #[error("Invalid stripe id")]
+ StripeIdParse(#[from] ParseIdError),
+ #[error("Internal stripe error")]
+ StripeErr(#[from] StripeError),
+ #[error("Invalid promo code")]
+ PromoCodeNotFound,
+ #[error("Internal server error")]
+ UnexpectedStripeResponse,
+ #[error("User already has an active subscription")]
+ AlreadySubscribed,
+ #[error("User does not have an active subscription")]
+ NoActiveSubscription,
+ #[error("User does not have a subscription tier role")]
+ NoSubscriptionRole,
+ #[error("User has multiple subscription tier roles")]
+ InconsistentSubscriptionRoles,
+ #[error("Another subscription update is already in progress for this user")]
+ SubscriptionUpdateInProgress,
+ #[error("User is a member of a team; tier is managed by the team owner")]
+ UserInTeam,
+ #[error("Teams service error")]
+ TeamsErr(#[from] teams::domain::model::TeamError),
+ #[error("Subscription is already on the requested tier")]
+ TierUnchanged,
+ #[error("Roles and permissions error")]
+ RolesErr(#[from] UserRolesAndPermissionsError),
+}
+
+impl IntoResponse for StripeOperationError {
+ fn into_response(self) -> Response {
+ let status = match &self {
+ // ParseId and StripeIdParse come from trusted server-side sources (JWT-populated
+ // user id, DB-stored Stripe customer id) — a parse failure is a server/auth
+ // misconfiguration, not bad client input. Map to 500 so metrics don't blame callers.
+ StripeOperationError::ParseId(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ StripeOperationError::DbErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ StripeOperationError::MissingStripeId => StatusCode::BAD_REQUEST,
+ StripeOperationError::StripeIdParse(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ StripeOperationError::StripeErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ StripeOperationError::PromoCodeNotFound => StatusCode::NOT_FOUND,
+ StripeOperationError::UnexpectedStripeResponse => StatusCode::INTERNAL_SERVER_ERROR,
+ StripeOperationError::AlreadySubscribed => StatusCode::CONFLICT,
+ StripeOperationError::NoActiveSubscription => StatusCode::NOT_FOUND,
+ StripeOperationError::NoSubscriptionRole => StatusCode::NOT_FOUND,
+ StripeOperationError::InconsistentSubscriptionRoles => {
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ StripeOperationError::SubscriptionUpdateInProgress => StatusCode::CONFLICT,
+ StripeOperationError::UserInTeam => StatusCode::FORBIDDEN,
+ StripeOperationError::TeamsErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ StripeOperationError::TierUnchanged => StatusCode::BAD_REQUEST,
+ StripeOperationError::RolesErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+ (
+ status,
+ Json(ErrorResponse {
+ message: self.to_string().into(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default, ToSchema, strum::EnumIter)]
+#[serde(rename_all = "lowercase")]
+pub enum StripeProductTier {
+ #[default]
+ Haiku,
+ Sonnet,
+ Opus,
+}
+
+/// Response containing the Stripe session URL
+#[derive(Debug, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct StripeSessionResponse {
+ /// The URL to redirect the user to
+ pub url: String,
+}
diff --git a/rust/cloud-storage/macro_db_client/src/advisory_lock/mod.rs b/rust/cloud-storage/macro_db_client/src/advisory_lock/mod.rs
index 038719bace..34fd7a0558 100644
--- a/rust/cloud-storage/macro_db_client/src/advisory_lock/mod.rs
+++ b/rust/cloud-storage/macro_db_client/src/advisory_lock/mod.rs
@@ -9,18 +9,22 @@ use sqlx::{Postgres, Transaction};
#[cfg(test)]
mod test;
-/// Namespace constant for refresh token locks to avoid collisions with other advisory locks
-const REFRESH_TOKEN_LOCK_NAMESPACE: i64 = 1_000_000_000;
+// Namespaces occupy the high bits so per-namespace key ranges are disjoint from each other
+// (and the user-id hash occupies the low 31 bits). With the previous additive scheme
+// (namespaces 1e9 / 2e9 + 31-bit hash) the ranges overlapped by ~1.15B keys, which could
+// cause a refresh-token lock for user A to spuriously block a subscription lock for user B.
+/// Namespace constant for refresh token locks
+const REFRESH_TOKEN_LOCK_NAMESPACE: i64 = 1 << 32;
+/// Namespace constant for subscription-mutation locks
+const SUBSCRIPTION_LOCK_NAMESPACE: i64 = 2 << 32;
-/// Computes an advisory lock key from a user ID string.
-/// Combines a namespace constant with a hash of the user ID.
-fn compute_lock_key<'a>(user_id: &MacroUserId<Lowercase<'a>>) -> i64 {
+/// Computes an advisory lock key from a namespace and user ID. The namespace occupies
+/// the high bits and the user-id hash occupies the low 31 bits so namespaces are disjoint.
+fn compute_lock_key(namespace: i64, user_id: &MacroUserId<Lowercase<'_>>) -> i64 {
let mut hasher = DefaultHasher::new();
user_id.as_ref().hash(&mut hasher);
let hash = hasher.finish();
- // Use the lower 32 bits of the hash combined with the namespace
- // to create a unique lock key
- REFRESH_TOKEN_LOCK_NAMESPACE + (hash as i64 & 0x7FFFFFFF)
+ namespace | (hash as i64 & 0x7FFFFFFF)
}
/// Attempts to acquire a transaction-level advisory lock for the given user ID.
@@ -28,12 +32,37 @@ fn compute_lock_key<'a>(user_id: &MacroUserId<Lowercase<'a>>) -> i64 {
///
/// The lock is automatically released when the transaction commits or rolls back.
/// This is the preferred method over session-level locks as it prevents lock leaks.
-#[tracing::instrument(skip(transaction))]
-pub async fn try_acquire_user_refresh_xact_lock<'a>(
+#[tracing::instrument(skip(transaction), err)]
+pub async fn try_acquire_user_refresh_xact_lock(
transaction: &mut Transaction<'_, Postgres>,
- user_id: &MacroUserId<Lowercase<'a>>,
+ user_id: &MacroUserId<Lowercase<'_>>,
) -> anyhow::Result<bool> {
- let lock_key = compute_lock_key(user_id);
+ let lock_key = compute_lock_key(REFRESH_TOKEN_LOCK_NAMESPACE, user_id);
+
+ let result = sqlx::query_scalar!(
+ r#"
+ SELECT pg_try_advisory_xact_lock($1)
+ "#,
+ lock_key
+ )
+ .fetch_one(transaction.as_mut())
+ .await?;
+
+ Ok(result.unwrap_or(false))
+}
+
+/// Attempts to acquire a transaction-level advisory lock guarding subscription mutations
+/// for the given user. Returns `true` if the lock was acquired, `false` if another
+/// transaction already holds it.
+///
+/// Callers should hold the enclosing transaction open for the full duration of the critical
+/// section; the lock is released on commit or rollback.
+#[tracing::instrument(skip(transaction), err)]
+pub async fn try_acquire_user_subscription_xact_lock(
+ transaction: &mut Transaction<'_, Postgres>,
+ user_id: &MacroUserId<Lowercase<'_>>,
+) -> Result<bool, sqlx::Error> {
+ let lock_key = compute_lock_key(SUBSCRIPTION_LOCK_NAMESPACE, user_id);
let result = sqlx::query_scalar!(
r#"