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.

Seanaye/add/legacy rpc interface (#442)

Sean Ayeb30d99932e29
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index a94e4766a2..2f4f0c776b 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -458,6 +458,23 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+[[package]]
+name = "auth_service_rpc"
+version = "0.1.0"
+dependencies = [
+ "axum",
+ "axum_rpc",
+ "js-sys",
+ "reqwest",
+ "reqwest-middleware",
+ "serde",
+ "serde-wasm-bindgen",
+ "tsify",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+]
+
[[package]]
name = "authentication_service"
version = "0.1.0"
@@ -465,6 +482,7 @@ dependencies = [
"anyhow",
"async-stripe",
"async-stripe-webhook",
+ "auth_service_rpc",
"aws-config",
"aws-sdk-secretsmanager",
"aws-sdk-sesv2",
@@ -476,6 +494,7 @@ dependencies = [
"cookie",
"cool_asserts",
"document_storage_service_client",
+ "doppleganger",
"email_validator",
"futures",
"http-body-util",
@@ -3602,6 +3621,19 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2"
+[[package]]
+name = "gloo-utils"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b5555354113b18c547c1d3a98fbf7fb32a9ff4f6fa112ce823a21641a0ba3aa"
+dependencies = [
+ "js-sys",
+ "serde",
+ "serde_json",
+ "wasm-bindgen",
+ "web-sys",
+]
+
[[package]]
name = "gmail_client"
version = "0.1.0"
@@ -4474,9 +4506,9 @@ dependencies = [
[[package]]
name = "js-sys"
-version = "0.3.77"
+version = "0.3.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f"
+checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8"
dependencies = [
"once_cell",
"wasm-bindgen",
@@ -7642,6 +7674,17 @@ dependencies = [
"serde_derive",
]
+[[package]]
+name = "serde-wasm-bindgen"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b"
+dependencies = [
+ "js-sys",
+ "serde",
+ "wasm-bindgen",
+]
+
[[package]]
name = "serde_core"
version = "1.0.228"
@@ -9035,6 +9078,31 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "tsify"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ec5505497c87f1c050b4392d3f11b49a04537fcb9dc0da57bc0af168a6331f2"
+dependencies = [
+ "gloo-utils",
+ "serde",
+ "serde_json",
+ "tsify-macros",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "tsify-macros"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fc2c44dc9fe4baf55b88e032621b7a11b215a1f0a7de8d0aa04367207d915bc"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "serde_derive_internals",
+ "syn 2.0.98",
+]
+
[[package]]
name = "tungstenite"
version = "0.24.0"
@@ -9471,27 +9539,14 @@ checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"
[[package]]
name = "wasm-bindgen"
-version = "0.2.100"
+version = "0.2.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5"
+checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
-]
-
-[[package]]
-name = "wasm-bindgen-backend"
-version = "0.2.100"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6"
-dependencies = [
- "bumpalo",
- "log",
- "proc-macro2",
- "quote",
- "syn 2.0.98",
"wasm-bindgen-shared",
]
@@ -9509,9 +9564,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
-version = "0.2.100"
+version = "0.2.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407"
+checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -9519,22 +9574,22 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
-version = "0.2.100"
+version = "0.2.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de"
+checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40"
dependencies = [
+ "bumpalo",
"proc-macro2",
"quote",
"syn 2.0.98",
- "wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
-version = "0.2.100"
+version = "0.2.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d"
+checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4"
dependencies = [
"unicode-ident",
]
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index ac714aab77..7d92881d9c 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -30,6 +30,9 @@ async-stripe = { workspace = true, default-features = false, features = [
"runtime-tokio-hyper",
] }
async-stripe-webhook = { version = "1.0.0-alpha.4", default-features = false }
+auth_service_rpc = { path = "../rpc-interface/auth_service", features = [
+ "server",
+] }
aws-config = { workspace = true }
aws-sdk-secretsmanager = { workspace = true }
aws-sdk-sesv2 = { workspace = true }
@@ -40,6 +43,7 @@ chrono = { workspace = true }
comms_service_client = { path = "../comms_service_client" }
cookie = { workspace = true }
document_storage_service_client = { path = "../document_storage_service_client" }
+doppleganger = { workspace = true }
email_validator = { path = "../email_validator" }
futures = { workspace = true }
http-body-util = { workspace = true }
diff --git a/rust/cloud-storage/authentication_service/src/api/user/get_legacy_user_permissions.rs b/rust/cloud-storage/authentication_service/src/api/user/get_legacy_user_permissions.rs
index 92fa1c1b75..a0cbb57066 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/get_legacy_user_permissions.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/get_legacy_user_permissions.rs
@@ -6,6 +6,8 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
+use doppleganger::Doppleganger;
+use macro_middleware::user_permissions::attach_user_permissions::PermissionsExtractor;
use macro_user_id::user_id::MacroUserId;
use roles_and_permissions::domain::model::PermissionId;
@@ -14,7 +16,8 @@ use crate::api::context::ApiContext;
use model::response::ErrorResponse;
use model::user::UserContext;
-#[derive(serde::Serialize, Debug, utoipa::ToSchema)]
+#[derive(serde::Serialize, Debug, utoipa::ToSchema, Doppleganger)]
+#[dg(forward = auth_service_rpc::GetLegacyUserPermissionsResponse)]
#[serde(rename_all = "camelCase")]
pub struct GetLegacyUserPermissionsResponse {
/// The user id
@@ -30,13 +33,20 @@ pub struct GetLegacyUserPermissionsResponse {
/// Whether the user has completed the tutorial
tutorial_complete: bool,
/// The user's group
- group: Option<String>,
+ group: Option<ABGroup>,
/// Whether the user has the chrome extension
has_chrome_ext: bool,
/// Whether the user has trialed through stripe
has_trialed: bool,
}
+#[derive(serde::Serialize, Debug, utoipa::ToSchema, Doppleganger)]
+#[dg(forward = auth_service_rpc::ABGroup)]
+enum ABGroup {
+ A,
+ B,
+}
+
#[derive(thiserror::Error, Debug)]
pub enum GetLegacyUserPermissionsError {
#[error("Internal error")]
@@ -87,23 +97,18 @@ impl IntoResponse for GetLegacyUserPermissionsError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context), err, fields(user_id=%user_context.user_id))]
+#[tracing::instrument(skip(ctx, user_context, permissions), err, fields(user_id=%user_context.user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
-) -> Result<Json<GetLegacyUserPermissionsResponse>, GetLegacyUserPermissionsError> {
+ PermissionsExtractor(permissions): PermissionsExtractor,
+) -> Result<GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsError> {
let user_id = MacroUserId::parse_from_str(&user_context.user_id)
.map_err(|_| GetLegacyUserPermissionsError::InvalidMacroUserId)?
.lowercase();
let email = user_id.email_part().lowercase();
- let permissions: Vec<String> = if let Some(permissions) = user_context.permissions.as_ref() {
- permissions.iter().cloned().collect()
- } else {
- vec![]
- };
-
let legacy_user_info = macro_db_client::user::get::get_legacy_user_info(&ctx.db, &user_id)
.await
.map_err(GetLegacyUserPermissionsError::InternalError)?;
@@ -111,19 +116,13 @@ pub async fn handler(
let license_status = if user_context.organization_id.is_some() {
// organizations default to active license status
"active"
- } else if let Some(permissions) = user_context.permissions.as_ref() {
+ } else if permissions.contains(&PermissionId::ReadProfessionalFeatures.to_string()) {
// If the user has premium permission their license status is active
- if permissions.contains(&PermissionId::ReadProfessionalFeatures.to_string()) {
- "active"
- } else {
- // By default, we can be lazy and just say they are inactive
- // If the requirements change, we will need to update this to actually check the user's
- // stripe subscription if present
- "inactive"
- }
+ "active"
} else {
- // The user is not part of an organization and has no stripe customer id
- // They do not have a license
+ // By default, we can be lazy and just say they are inactive
+ // If the requirements change, we will need to update this to actually check the user's
+ // stripe subscription if present
"inactive"
};
@@ -144,15 +143,19 @@ pub async fn handler(
false
};
- Ok(Json(GetLegacyUserPermissionsResponse {
+ Ok(GetLegacyUserPermissionsResponse {
user_id: user_id.as_ref().to_string(),
email: email.as_ref().to_string(),
- permissions,
+ permissions: permissions.into_iter().collect(),
name: legacy_user_info.name,
license_status: license_status.to_string(),
tutorial_complete: legacy_user_info.tutorial_complete,
- group: legacy_user_info.group,
+ group: match legacy_user_info.group.as_deref() {
+ Some("A" | "a") => Some(ABGroup::A),
+ Some("B" | "b") => Some(ABGroup::B),
+ _ => None,
+ },
has_chrome_ext: legacy_user_info.has_chrome_ext,
has_trialed,
- }))
+ })
}
diff --git a/rust/cloud-storage/authentication_service/src/api/user/get_user_organization.rs b/rust/cloud-storage/authentication_service/src/api/user/get_user_organization.rs
index 1b112ccb2d..d529ffcfd8 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/get_user_organization.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/get_user_organization.rs
@@ -1,16 +1,16 @@
+use crate::api::context::ApiContext;
use axum::{
Extension, Json,
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
};
-
-use crate::api::context::ApiContext;
-
+use doppleganger::Doppleganger;
use model::response::ErrorResponse;
use model::user::UserContext;
-#[derive(Debug, serde::Serialize, utoipa::ToSchema)]
+#[derive(Debug, serde::Serialize, utoipa::ToSchema, Doppleganger)]
+#[dg(forward = auth_service_rpc::UserOrganizationResponse)]
#[serde(rename_all = "camelCase")]
pub struct UserOrganizationResponse {
/// The id of the organization
diff --git a/rust/cloud-storage/authentication_service/src/api/user/legacy_rpc.rs b/rust/cloud-storage/authentication_service/src/api/user/legacy_rpc.rs
new file mode 100644
index 0000000000..5490fe414c
--- /dev/null
+++ b/rust/cloud-storage/authentication_service/src/api/user/legacy_rpc.rs
@@ -0,0 +1,258 @@
+use std::sync::LazyLock;
+
+use auth_service_rpc::{CreatePortalRequest, LegacyApiErr, LegacyApiRpc, StripeUrlResponse};
+use axum::{
+ Extension, Json,
+ extract::{FromRef, State},
+ http::StatusCode,
+ response::IntoResponse,
+};
+use doppleganger::Mirror;
+use macro_env_var::env_var;
+use macro_middleware::user_permissions::attach_user_permissions::PermissionsExtractor;
+use model::user::UserContext;
+use sqlx::PgPool;
+use stripe::{ParseIdError, StripeError};
+use thiserror::Error;
+
+use crate::api::{
+ context::ApiContext,
+ user::{
+ get_legacy_user_permissions::{self, GetLegacyUserPermissionsResponse},
+ get_user_organization,
+ patch_user_group::{self, PatchUserGroupRequest},
+ patch_user_onboarding::{self, PatchUserOnboardingRequest},
+ },
+};
+
+#[derive(Clone)]
+pub(super) struct AuthRpcState(pub(super) ApiContext);
+
+impl FromRef<AuthRpcState> for PgPool {
+ fn from_ref(input: &AuthRpcState) -> Self {
+ input.0.db.clone()
+ }
+}
+
+impl LegacyApiRpc for AuthRpcState {
+ type GetPermsExtractor = (Extension<UserContext>, PermissionsExtractor);
+
+ async fn get_legacy_user_permissions(
+ &self,
+ ctx: Self::GetPermsExtractor,
+ ) -> Result<auth_service_rpc::GetLegacyUserPermissionsResponse, LegacyApiErr> {
+ get_legacy_user_permissions::handler(State(self.0.clone()), ctx.0, ctx.1)
+ .await
+ .map_err(IntoResponse::into_response)
+ .map(GetLegacyUserPermissionsResponse::mirror)
+ }
+
+ type UserExtractor = Extension<UserContext>;
+
+ async fn get_user_organization(
+ &self,
+ ctx: Self::UserExtractor,
+ ) -> Result<Option<auth_service_rpc::UserOrganizationResponse>, LegacyApiErr> {
+ get_user_organization::handler(State(self.0.clone()), ctx)
+ .await
+ .map_err(IntoResponse::into_response)
+ .map(|r| match r {
+ get_user_organization::GetUserOrganizationResponse::NoOrganization => None,
+ get_user_organization::GetUserOrganizationResponse::Organization(
+ user_organization_response,
+ ) => Some(get_user_organization::UserOrganizationResponse::mirror(
+ user_organization_response,
+ )),
+ })
+ }
+
+ async fn patch_user_group(
+ &self,
+ ctx: Self::UserExtractor,
+ req: auth_service_rpc::PatchUserGroupRequest,
+ ) -> Result<(), LegacyApiErr> {
+ patch_user_group::handler(
+ State(self.0.clone()),
+ ctx,
+ Json(PatchUserGroupRequest::mirror(req)),
+ )
+ .await
+ .map_err(IntoResponse::into_response)
+ .map(|_| ())
+ }
+
+ async fn patch_user_onboarding(
+ &self,
+ ctx: Self::UserExtractor,
+ req: auth_service_rpc::PatchUserOnboardingRequest,
+ ) -> Result<(), LegacyApiErr> {
+ patch_user_onboarding::handler(
+ State(self.0.clone()),
+ ctx,
+ Json(PatchUserOnboardingRequest::mirror(req)),
+ )
+ .await
+ .map_err(IntoResponse::into_response)
+ .map(|_| ())
+ }
+
+ async fn create_checkout_session(
+ &self,
+ ctx: Self::UserExtractor,
+ req: auth_service_rpc::CreateCheckoutRequest,
+ ) -> Result<auth_service_rpc::StripeUrlResponse, LegacyApiErr> {
+ inner_create_checkout(&self.0, ctx, req)
+ .await
+ .map_err(IntoResponse::into_response)
+ }
+
+ async fn create_portal_session(
+ &self,
+ ctx: Self::UserExtractor,
+ req: auth_service_rpc::CreatePortalRequest,
+ ) -> Result<auth_service_rpc::StripeUrlResponse, LegacyApiErr> {
+ inner_create_portal(&self.0, ctx, req)
+ .await
+ .map_err(IntoResponse::into_response)
+ }
+}
+
+#[derive(Debug, Error)]
+enum InnerStripeErr {
+ #[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,
+}
+
+impl IntoResponse for InnerStripeErr {
+ fn into_response(self) -> axum::response::Response {
+ let status = match &self {
+ InnerStripeErr::ParseId(_parse_err) => StatusCode::BAD_REQUEST,
+ InnerStripeErr::DbErr(_error) => StatusCode::INTERNAL_SERVER_ERROR,
+ InnerStripeErr::MissingStripeId => StatusCode::BAD_REQUEST,
+ InnerStripeErr::StripeIdParse(_parse_id_error) => StatusCode::BAD_REQUEST,
+ InnerStripeErr::StripeErr(_stripe_error) => StatusCode::INTERNAL_SERVER_ERROR,
+ InnerStripeErr::PromoCodeNotFound => StatusCode::NOT_FOUND,
+ InnerStripeErr::UnExpectedStripeResponse => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+ (status, self.to_string()).into_response()
+ }
+}
+
+env_var!(
+ struct StripePremiumPriceId;
+);
+
+static STRIPE_PRICE_ID: LazyLock<StripePremiumPriceId> = LazyLock::new(|| {
+ match StripePremiumPriceId::new() {
+ Ok(var) => var,
+ // just use this non secret value if the value doesn't exist
+ Err(_) => StripePremiumPriceId::Comptime("price_1PnSgXJaD7zvQeOBfSYgOmZc"),
+ }
+});
+
+async fn inner_create_checkout(
+ state: &ApiContext,
+ ctx: Extension<UserContext>,
+ req: auth_service_rpc::CreateCheckoutRequest,
+) -> Result<auth_service_rpc::StripeUrlResponse, InnerStripeErr> {
+ let user_id = macro_user_id::user_id::MacroUserId::parse_from_str(&ctx.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(&state.db, &user_id)
+ .await?
+ .ok_or_else(|| InnerStripeErr::MissingStripeId)?;
+
+ let customer_id: stripe::CustomerId = stripe_customer_id.parse()?;
+
+ // If a discount code is provided, look up the promotion code ID
+ let promo_code_id = if let Some(ref discount) = req.discount {
+ let mut list_params = stripe::ListPromotionCodes::new();
+ list_params.code = Some(discount);
+ list_params.active = Some(true);
+ list_params.limit = Some(1);
+
+ let promo_codes = stripe::PromotionCode::list(&state.stripe_client, &list_params).await?;
+
+ let promo_code = promo_codes
+ .data
+ .into_iter()
+ .next()
+ .ok_or_else(|| InnerStripeErr::PromoCodeNotFound)?;
+
+ Some(promo_code.id)
+ } else {
+ None
+ };
+
+ // Create the checkout session
+ let params = stripe::CreateCheckoutSession {
+ customer: Some(customer_id),
+ mode: Some(stripe::CheckoutSessionMode::Subscription),
+ success_url: Some(req.success_url.as_str()),
+ cancel_url: Some(req.cancel_url.as_str()),
+ allow_promotion_codes: promo_code_id.is_none().then_some(true),
+ discounts: promo_code_id.map(|id| {
+ vec![stripe::CreateCheckoutSessionDiscounts {
+ promotion_code: Some(id.to_string()),
+ ..Default::default()
+ }]
+ }),
+ // Set up line items
+ line_items: Some(vec![stripe::CreateCheckoutSessionLineItems {
+ price: Some(STRIPE_PRICE_ID.as_ref().to_string()),
+ quantity: Some(1),
+ ..Default::default()
+ }]),
+ ..Default::default()
+ };
+
+ let session = stripe::CheckoutSession::create(&state.stripe_client, params).await?;
+
+ let url = session
+ .url
+ .ok_or_else(|| InnerStripeErr::UnExpectedStripeResponse)?;
+
+ let url = url::Url::parse(&url).map_err(|_| InnerStripeErr::UnExpectedStripeResponse)?;
+
+ Ok(auth_service_rpc::StripeUrlResponse { url })
+}
+
+async fn inner_create_portal(
+ state: &ApiContext,
+ ctx: Extension<UserContext>,
+ req: CreatePortalRequest,
+) -> Result<StripeUrlResponse, InnerStripeErr> {
+ let user_id = macro_user_id::user_id::MacroUserId::parse_from_str(&ctx.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(&state.db, &user_id)
+ .await?
+ .ok_or_else(|| InnerStripeErr::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(&state.stripe_client, params).await?;
+
+ let url =
+ url::Url::parse(&session.url).map_err(|_| InnerStripeErr::UnExpectedStripeResponse)?;
+
+ Ok(auth_service_rpc::StripeUrlResponse { url })
+}
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 2ed5dfa5fe..75f22fadd4 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/mod.rs
@@ -1,3 +1,4 @@
+use auth_service_rpc::LegacyApiRpcRouterBuilder;
use axum::{
Router,
routing::{delete, get, patch, post, put},
@@ -6,7 +7,7 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use tower::ServiceBuilder;
use tower_cookies::CookieManagerLayer;
-use crate::api::ApiContext;
+use crate::api::{ApiContext, user::legacy_rpc::AuthRpcState};
// needs to be public in api crate for swagger
pub(in crate::api) mod create_user;
@@ -17,6 +18,7 @@ pub(in crate::api) mod get_user_info;
pub(in crate::api) mod get_user_link_exists;
pub(in crate::api) mod get_user_organization;
pub(in crate::api) mod get_user_quota;
+pub(in crate::api) mod legacy_rpc;
pub(in crate::api) mod patch_tutorial;
pub(in crate::api) mod patch_user_group;
pub(in crate::api) mod patch_user_onboarding;
@@ -35,25 +37,18 @@ pub fn router(state: ApiContext, jwt_args: JwtValidationArgs) -> Router<ApiConte
}
fn router_with_auth(state: ApiContext, jwt_args: JwtValidationArgs) -> Router<ApiContext> {
+ let rpc_router = LegacyApiRpcRouterBuilder::new(AuthRpcState(state.clone())).build();
+
Router::new()
+ .merge(rpc_router)
.route("/me", get(get_user_info::handler))
.route("/me", delete(delete_user::handler))
- .route(
- "/legacy_user_permissions",
- get(get_legacy_user_permissions::handler).layer(axum::middleware::from_fn_with_state(
- state.clone(),
- macro_middleware::user_permissions::attach_user_permissions::handler,
- )),
- )
.route("/profile_pictures", post(post_profile_pictures::handler))
.route("/profile_picture", put(put_profile_picture::handler))
.route("/name", put(put_name::handler))
.route("/name", get(get_name::handler))
- .route("/organization", get(get_user_organization::handler))
.route("/get_names", post(post_get_names::handler_external))
.route("/link_exists", get(get_user_link_exists::handler))
- .route("/group", patch(patch_user_group::handler))
- .route("/onboarding", patch(patch_user_onboarding::handler))
.route("/tutorial", patch(patch_tutorial::handler))
.route(
"/quota",
diff --git a/rust/cloud-storage/authentication_service/src/api/user/patch_user_group.rs b/rust/cloud-storage/authentication_service/src/api/user/patch_user_group.rs
index 30501f7035..24d4a94639 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/patch_user_group.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/patch_user_group.rs
@@ -4,6 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
+use doppleganger::Doppleganger;
use macro_user_id::user_id::MacroUserId;
use crate::api::context::ApiContext;
@@ -14,7 +15,8 @@ use model::{
};
use utoipa::ToSchema;
-#[derive(Default, Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+#[derive(Default, Debug, serde::Serialize, serde::Deserialize, ToSchema, Doppleganger)]
+#[dg(backward = auth_service_rpc::PatchUserGroupRequest)]
pub struct PatchUserGroupRequest {
/// The group to add the user to
pub group: String,
diff --git a/rust/cloud-storage/authentication_service/src/api/user/patch_user_onboarding.rs b/rust/cloud-storage/authentication_service/src/api/user/patch_user_onboarding.rs
index 4273179fee..cd4d8d41e9 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/patch_user_onboarding.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/patch_user_onboarding.rs
@@ -4,6 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
+use doppleganger::Doppleganger;
use macro_user_id::user_id::MacroUserId;
use crate::api::context::ApiContext;
@@ -14,7 +15,8 @@ use model::{
};
use utoipa::ToSchema;
-#[derive(Default, Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+#[derive(Default, Debug, serde::Serialize, serde::Deserialize, ToSchema, Doppleganger)]
+#[dg(backward = auth_service_rpc::PatchUserOnboardingRequest)]
#[serde(rename_all = "camelCase")]
pub struct PatchUserOnboardingRequest {
/// The first name of the user
diff --git a/rust/cloud-storage/macro_middleware/src/user_permissions/attach_user_permissions.rs b/rust/cloud-storage/macro_middleware/src/user_permissions/attach_user_permissions.rs
index 2a29c92612..cff0cf009c 100644
--- a/rust/cloud-storage/macro_middleware/src/user_permissions/attach_user_permissions.rs
+++ b/rust/cloud-storage/macro_middleware/src/user_permissions/attach_user_permissions.rs
@@ -1,13 +1,52 @@
use crate::error_handler::error_handler;
use axum::{
- Extension,
- extract::{Request, State},
- http::StatusCode,
+ Extension, RequestPartsExt, async_trait,
+ extract::{FromRef, FromRequestParts, Request, State, rejection::ExtensionRejection},
+ http::{StatusCode, request::Parts},
middleware::Next,
- response::Response,
+ response::{IntoResponse, Response},
};
use model::user::UserContext;
use sqlx::PgPool;
+use std::collections::HashSet;
+use thiserror::Error;
+
+#[derive(Debug)]
+pub struct PermissionsExtractor(pub HashSet<String>);
+
+#[derive(Debug, Error)]
+pub enum PermissionErr {
+ #[error("Internal server error")]
+ DbErr(#[from] anyhow::Error),
+ #[error("Internal servier error")]
+ Extension(#[from] ExtensionRejection),
+}
+
+impl IntoResponse for PermissionErr {
+ fn into_response(self) -> Response {
+ (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()).into_response()
+ }
+}
+
+#[async_trait]
+impl<S> FromRequestParts<S> for PermissionsExtractor
+where
+ S: Send + Sync + 'static,
+ PgPool: FromRef<S>,
+{
+ type Rejection = PermissionErr;
+
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let user_ctx: Extension<UserContext> = parts.extract_with_state(state).await?;
+ let db = PgPool::from_ref(state);
+
+ let permissions =
+ macro_db_client::user::get_permissions::get_user_permissions(&db, &user_ctx.user_id)
+ .await?;
+
+ Ok(Self(permissions))
+ }
+}
/// Attaches user permissions to the UserContext
#[tracing::instrument(skip(db, user_context, req, next), fields(user_id=?user_context.user_id))]
diff --git a/rust/cloud-storage/rpc-interface/auth_service/Cargo.toml b/rust/cloud-storage/rpc-interface/auth_service/Cargo.toml
new file mode 100644
index 0000000000..8390305499
--- /dev/null
+++ b/rust/cloud-storage/rpc-interface/auth_service/Cargo.toml
@@ -0,0 +1,34 @@
+[package]
+edition = "2024"
+name = "auth_service_rpc"
+publish = false
+version = "0.1.0"
+
+[lib]
+crate-type = ["cdylib", "rlib"]
+
+[features]
+client = [
+ "dep:reqwest",
+ "dep:reqwest-middleware",
+ "dep:serde-wasm-bindgen",
+ "dep:tsify",
+ "dep:wasm-bindgen",
+ "dep:wasm-bindgen-futures",
+]
+server = ["axum"]
+
+[dependencies]
+axum = { workspace = true, optional = true }
+axum_rpc = { path = "../../rpc/axum_rpc" }
+serde = { workspace = true }
+url = { workspace = true, features = ["serde"] }
+
+# WASM dependencies
+js-sys = { workspace = true }
+reqwest = { workspace = true, optional = true, features = ["json"] }
+reqwest-middleware = { workspace = true, optional = true, features = ["json"] }
+serde-wasm-bindgen = { version = "0.6", optional = true }
+tsify = { version = "0.5", optional = true }
+wasm-bindgen = { version = "0.2", optional = true }
+wasm-bindgen-futures = { version = "0.4", optional = true }
diff --git a/rust/cloud-storage/rpc-interface/auth_service/README.md b/rust/cloud-storage/rpc-interface/auth_service/README.md
new file mode 100644
index 0000000000..d2de54fb6e
--- /dev/null
+++ b/rust/cloud-storage/rpc-interface/auth_service/README.md
@@ -0,0 +1,67 @@
+# auth_service_rpc
+
+RPC interface for the authentication service, supporting both server and client modes.
+
+## Features
+
+- `server`: Enable server-side router generation (Axum)
+- `client`: Enable client-side implementation with WASM support
+
+## Building for WASM (Vite)
+
+To build the WASM module for use with Vite:
+
+```bash
+wasm-pack build --target bundler --features client
+```
+
+This will generate a `pkg/` directory containing the WASM module and JavaScript bindings.
+
+### Development Build
+
+For faster builds during development:
+
+```bash
+wasm-pack build --target bundler --features client --dev
+```
+
+### Using in Vite
+
+In your Vite project, you can import the generated package:
+
+```javascript
+import init, { LegacyGqlRpcClient } from './path/to/pkg/auth_service_rpc.js';
+
+await init();
+
+const client = LegacyGqlRpcClient.construct('https://api.example.com');
+const permissions = await client.get_legacy_user_permissions();
+```
+
+## Usage
+
+### Server
+
+```rust
+use auth_service_rpc::LegacyGqlRpc;
+
+// Implement the trait for your service
+impl LegacyGqlRpc for MyService {
+ // ... implementation
+}
+
+// Build the router
+let router = LegacyGqlRpcRouterBuilder::new(my_service).build();
+```
+
+### Client (Rust)
+
+```rust
+use auth_service_rpc::{LegacyGqlRpc, LegacyGqlRpcClient};
+
+let client = LegacyGqlRpcClient::builder()
+ .build("https://api.example.com".parse().unwrap())
+ .unwrap();
+
+let permissions = client.get_legacy_user_permissions(()).await?;
+```
diff --git a/rust/cloud-storage/rpc-interface/auth_service/justfile b/rust/cloud-storage/rpc-interface/auth_service/justfile
new file mode 100644
index 0000000000..09bd06ab36
--- /dev/null
+++ b/rust/cloud-storage/rpc-interface/auth_service/justfile
@@ -0,0 +1,7 @@
+out_dir := "../../../../js/app/packages/codegen/" + file_name(justfile_directory())
+
+generate:
+ wasm-pack build --target bundler --features client
+ rm -rf {{ out_dir }}
+ mkdir -p ../../../../js/app/packages/codegen
+ mv pkg {{ out_dir }}
diff --git a/rust/cloud-storage/rpc-interface/auth_service/src/lib.rs b/rust/cloud-storage/rpc-interface/auth_service/src/lib.rs
new file mode 100644
index 0000000000..2d6646828d
--- /dev/null
+++ b/rust/cloud-storage/rpc-interface/auth_service/src/lib.rs
@@ -0,0 +1,171 @@
+use axum_rpc::{MaybeSend, MaybeSync, attr_macros};
+use serde::{Deserialize, Serialize};
+use url::Url;
+
+#[derive(Debug, Serialize, Deserialize)]
+#[cfg_attr(
+ feature = "client",
+ derive(tsify::Tsify),
+ tsify(into_wasm_abi, from_wasm_abi)
+)]
+#[serde(rename_all = "camelCase")]
+pub struct GetLegacyUserPermissionsResponse {
+ /// The user id
+ pub user_id: String,
+ /// The permissions the user has
+ pub permissions: Vec<String>,
+ /// The user's email
+ pub email: String,
+ /// The user's name
+ pub name: Option<String>,
+ /// The user's license status
+ pub license_status: String,
+ /// Whether the user has completed the tutorial
+ pub tutorial_complete: bool,
+ /// The user's group
+ pub group: Option<ABGroup>,
+ /// Whether the user has the chrome extension
+ pub has_chrome_ext: bool,
+ /// Whether the user has trialed through stripe
+ pub has_trialed: bool,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[cfg_attr(
+ feature = "client",
+ derive(tsify::Tsify),
+ tsify(into_wasm_abi, from_wasm_abi)
+)]
+pub enum ABGroup {
+ A,
+ B,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[cfg_attr(
+ feature = "client",
+ derive(tsify::Tsify),
+ tsify(into_wasm_abi, from_wasm_abi)
+)]
+#[serde(rename_all = "camelCase")]
+pub struct UserOrganizationResponse {
+ /// The id of the organization
+ pub organization_id: i32,
+ /// The name of the organization
+ pub organization_name: String,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[cfg_attr(
+ feature = "client",
+ derive(tsify::Tsify),
+ tsify(into_wasm_abi, from_wasm_abi)
+)]
+#[serde(rename_all = "camelCase")]
+pub struct PatchUserOnboardingRequest {
+ /// The first name of the user
+ pub first_name: String,
+ /// The last name of the user
+ pub last_name: String,
+ /// The title of the user
+ pub title: String,
+ /// The industry of the user
+ pub industry: String,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[cfg_attr(
+ feature = "client",
+ derive(tsify::Tsify),
+ tsify(into_wasm_abi, from_wasm_abi)
+)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateCheckoutRequest {
+ pub success_url: Url,
+ pub cancel_url: Url,
+ pub discount: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[cfg_attr(
+ feature = "client",
+ derive(tsify::Tsify),
+ tsify(into_wasm_abi, from_wasm_abi)
+)]
+#[serde(rename_all = "camelCase")]
+pub struct CreatePortalRequest {
+ pub return_url: Url,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[cfg_attr(
+ feature = "client",
+ derive(tsify::Tsify),
+ tsify(into_wasm_abi, from_wasm_abi)
+)]
+#[serde(rename_all = "camelCase")]
+pub struct StripeUrlResponse {
+ pub url: Url,
+}
+
+#[cfg(all(feature = "client", not(feature = "server")))]
+pub type LegacyApiErr = axum_rpc::anyhow::Error;
+#[cfg(feature = "server")]
+pub type LegacyApiErr = axum::response::Response;
+
+#[derive(Debug, Serialize, Deserialize)]
+#[cfg_attr(
+ feature = "client",
+ derive(tsify::Tsify),
+ tsify(into_wasm_abi, from_wasm_abi)
+)]
+pub struct PatchUserGroupRequest {
+ /// The group to add the user to
+ pub group: String,
+}
+
+/// this rpc trait replaces the parts we still need to support from the legacy gql service
+#[cfg_attr(
+ all(feature = "client", not(feature = "server")),
+ attr_macros(client(bindgen))
+)]
+#[cfg_attr(feature = "server", attr_macros(router))]
+pub trait LegacyApiRpc: MaybeSend + MaybeSync + 'static {
+ type GetPermsExtractor: 'static;
+
+ fn get_legacy_user_permissions(
+ &self,
+ ctx: Self::GetPermsExtractor,
+ ) -> impl Future<Output = Result<GetLegacyUserPermissionsResponse, LegacyApiErr>> + MaybeSend;
+
+ type UserExtractor: 'static;
+
+ fn get_user_organization(
+ &self,
+ ctx: Self::UserExtractor,
+ ) -> impl Future<Output = Result<Option<UserOrganizationResponse>, LegacyApiErr>> + MaybeSend;
+
+ fn patch_user_group(
+ &self,
+ ctx: Self::UserExtractor,
+ req: PatchUserGroupRequest,
+ ) -> impl Future<Output = Result<(), LegacyApiErr>> + MaybeSend;
+
+ fn patch_user_onboarding(
+ &self,
+ ctx: Self::UserExtractor,
+ req: PatchUserOnboardingRequest,
+ ) -> impl Future<Output = Result<(), LegacyApiErr>> + MaybeSend;
+
+ fn create_checkout_session(
+ &self,
+ ctx: Self::UserExtractor,
+ req: CreateCheckoutRequest,
+ ) -> impl Future<Output = Result<StripeUrlResponse, LegacyApiErr>> + MaybeSend;
+
+ fn create_portal_session(
+ &self,
+ ctx: Self::UserExtractor,
+ req: CreatePortalRequest,
+ ) -> impl Future<Output = Result<StripeUrlResponse, LegacyApiErr>> + MaybeSend;
+}