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): provision the first inbox from the Google login callback (#4617)

gbirman485114470a45
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 503a39e812..d33a3c111b 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -957,6 +957,7 @@ dependencies = [
"document_storage_service_client",
"doppleganger",
"doppler-config",
+ "email",
"email_db_client",
"email_validator",
"entity_access",
@@ -4647,6 +4648,7 @@ dependencies = [
"non_empty",
"recursion",
"redis",
+ "reqwest 0.13.4",
"schemars 1.2.1",
"scraper",
"serde",
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index 209ee645ca..3c5c0feefc 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -44,6 +44,7 @@ chrono = { workspace = true }
comms_db_client = { path = "../comms_db_client" }
cookie = { workspace = true }
document_storage_service_client = { path = "../document_storage_service_client" }
+email = { path = "../email", features = ["http_client"] }
doppleganger = { workspace = true }
email_db_client = { path = "../email_db_client" }
email_validator = { path = "../email_validator" }
diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rs
index ab1601a273..ab40ec7cf2 100644
--- a/rust/cloud-storage/authentication_service/src/api/context.rs
+++ b/rust/cloud-storage/authentication_service/src/api/context.rs
@@ -71,6 +71,7 @@ pub(crate) struct ApiContext {
pub stripe_client: Arc<stripe::Client>,
pub document_storage_service_client:
Arc<document_storage_service_client::DocumentStorageServiceClient>,
+ pub email_service_client: Arc<email::outbound::EmailServiceHttpClient>,
pub ses_client: Arc<ses_client::Ses>,
pub notification_ingress_service: Arc<NotificationIngressType>,
pub sqs_client: Arc<sqs_client::SQS>,
diff --git a/rust/cloud-storage/authentication_service/src/api/link/gmail.rs b/rust/cloud-storage/authentication_service/src/api/link/gmail.rs
index 5010e3e9a3..315163816e 100644
--- a/rust/cloud-storage/authentication_service/src/api/link/gmail.rs
+++ b/rust/cloud-storage/authentication_service/src/api/link/gmail.rs
@@ -22,7 +22,7 @@ use crate::api::{
mod test;
const GOOGLE_AUTHORIZATION_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";
-const GMAIL_IDENTITY_PROVIDER_NAME: &str = "google_gmail";
+pub(in crate::api) const GMAIL_IDENTITY_PROVIDER_NAME: &str = "google_gmail";
const GMAIL_SCOPES: &str = "openid profile email https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/contacts.readonly https://www.googleapis.com/auth/contacts.other.readonly https://www.googleapis.com/auth/gmail.settings.basic";
const FREE_INBOX_LIMIT: i64 = 2;
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth2/login.rs b/rust/cloud-storage/authentication_service/src/api/oauth2/login.rs
index d13a709b84..2a606a602d 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth2/login.rs
+++ b/rust/cloud-storage/authentication_service/src/api/oauth2/login.rs
@@ -1,5 +1,6 @@
use crate::api::{
context::ApiContext,
+ link::gmail::GMAIL_IDENTITY_PROVIDER_NAME,
oauth2::{OAuthState, format_redirect_uri},
utils::{
create_access_token_cookie, create_refresh_token_cookie, default_redirect_url,
@@ -10,11 +11,53 @@ use axum::{
Json,
response::{IntoResponse, Redirect, Response},
};
+use email::domain::ports::{FirstInboxProvisionOutcome, FirstInboxProvisioner};
use macro_env::Environment;
use model::response::ErrorResponse;
use reqwest::StatusCode;
use tower_cookies::Cookies;
+/// Provisions the user's primary inbox after a Gmail-scoped login, the moment
+/// the Google grant is minted or refreshed. Fire-and-forget so the login
+/// redirect is never delayed. Init is idempotent and recurs on every login, so
+/// a lost attempt only delays provisioning until the next one.
+fn spawn_first_inbox_provision(ctx: &ApiContext, identity_provider_id: &str, access_token: &str) {
+ let auth_client = ctx.auth_client.clone();
+ let email_service_client = ctx.email_service_client.clone();
+ let identity_provider_id = identity_provider_id.to_string();
+ let access_token = access_token.to_string();
+
+ tokio::spawn(async move {
+ let gmail_idp_id = match auth_client
+ .get_identity_provider_id_by_name(GMAIL_IDENTITY_PROVIDER_NAME)
+ .await
+ {
+ Ok(id) => id,
+ Err(e) => {
+ tracing::warn!(error=?e, "first-inbox provision: unable to resolve gmail idp id");
+ return;
+ }
+ };
+
+ if identity_provider_id != gmail_idp_id {
+ return;
+ }
+
+ match email_service_client
+ .provision_first_inbox(&access_token)
+ .await
+ {
+ Ok(FirstInboxProvisionOutcome::Provisioned) => {
+ tracing::info!("first-inbox provision: inbox initialized on login");
+ }
+ Ok(FirstInboxProvisionOutcome::Skipped) => {}
+ Err(e) => {
+ tracing::warn!(error=?e, "first-inbox provision: init failed");
+ }
+ }
+ });
+}
+
/// Handles logging in through an identity provider
pub(in crate::api::oauth2) async fn handler(
ctx: &ApiContext,
@@ -110,6 +153,8 @@ pub(in crate::api::oauth2) async fn handler(
cookies.add(create_access_token_cookie(&access_token));
cookies.add(create_refresh_token_cookie(&refresh_token));
+ spawn_first_inbox_provision(ctx, &state.identity_provider_id, &access_token);
+
match environment {
Environment::Local => Ok(StatusCode::OK.into_response()), // We don't really care about redirect in local
Environment::Production | Environment::Develop => {
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index b4cd77c737..d4e19b901e 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -22,6 +22,7 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_service_urls::AppServiceUrl;
use macro_service_urls::DocumentStorageServiceUrl;
+use macro_service_urls::EmailServiceUrl;
use native_app_service::{
domain::{models::PlatformData, service::NativeAppServiceImpl},
outbound::DefaultBundleFetcher,
@@ -158,6 +159,10 @@ async fn main() -> anyhow::Result<()> {
);
tracing::trace!("initialized document storage service client");
+ let email_service_client =
+ email::outbound::EmailServiceHttpClient::new(EmailServiceUrl::new()?.to_string());
+ tracing::trace!("initialized email service client");
+
let macro_cache_client =
macro_cache_client::MacroCache::new(config.redis_uri.to_string().as_str());
@@ -327,6 +332,7 @@ async fn main() -> anyhow::Result<()> {
macro_cache_client: Arc::new(macro_cache_client),
stripe_client: Arc::new(stripe_client),
document_storage_service_client: Arc::new(document_storage_service_client),
+ email_service_client: Arc::new(email_service_client),
ses_client: Arc::new(ses_client),
notification_ingress_service,
sqs_client: Arc::new(sqs_client),
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
index 5775ce25ce..d54e5e467a 100644
--- a/rust/cloud-storage/email/Cargo.toml
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -8,6 +8,7 @@ version = "0.1.0"
all = [
"ai_tools",
"gmail_token",
+ "http_client",
"inbound",
"outbound",
"ports",
@@ -34,6 +35,7 @@ axum = [
"models_pagination/axum",
]
gmail_token = ["dep:authentication_service_client", "dep:redis", "ports"]
+http_client = ["dep:reqwest", "ports"]
inbound = ["ports"]
outbound = ["dep:sqlx", "dep:email_db_client", "ports"]
ports = ["crm/ports", "dep:tokio", "frecency/ports"]
@@ -70,6 +72,7 @@ model-error-response = { path = "../model-error-response", optional = true }
model_user = { path = "../model_user", optional = true }
models_pagination = { path = "../models_pagination" }
recursion = { workspace = true }
+reqwest = { workspace = true, optional = true }
schemars = { workspace = true, optional = true, features = ["uuid1"] }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rs
index 956b977025..fc5d2c4e5c 100644
--- a/rust/cloud-storage/email/src/domain/ports.rs
+++ b/rust/cloud-storage/email/src/domain/ports.rs
@@ -531,3 +531,23 @@ impl EmailMessageEnqueuer for NoOpEnqueuer {
Ok(())
}
}
+
+/// Outcome of a first-inbox provisioning attempt.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FirstInboxProvisionOutcome {
+ /// The inbox was provisioned and a backfill was started.
+ Provisioned,
+ /// The service declined the request as a no-op: the inbox is already
+ /// initialized or the user holds no Gmail grant. Expected, not an error.
+ Skipped,
+}
+
+/// Port for provisioning the calling user's primary inbox.
+pub trait FirstInboxProvisioner: Send + Sync + 'static {
+ /// Provisions the caller's primary inbox. Idempotent, so safe to invoke on
+ /// every authentication.
+ fn provision_first_inbox(
+ &self,
+ access_token: &str,
+ ) -> impl Future<Output = anyhow::Result<FirstInboxProvisionOutcome>> + Send;
+}
diff --git a/rust/cloud-storage/email/src/lib.rs b/rust/cloud-storage/email/src/lib.rs
index f76105df0f..0b4b0bc448 100644
--- a/rust/cloud-storage/email/src/lib.rs
+++ b/rust/cloud-storage/email/src/lib.rs
@@ -1,5 +1,5 @@
pub mod domain;
#[cfg(feature = "inbound")]
pub mod inbound;
-#[cfg(feature = "outbound")]
+#[cfg(any(feature = "outbound", feature = "http_client"))]
pub mod outbound;
diff --git a/rust/cloud-storage/email/src/outbound.rs b/rust/cloud-storage/email/src/outbound.rs
index 0edf66c0d3..c52c3db158 100644
--- a/rust/cloud-storage/email/src/outbound.rs
+++ b/rust/cloud-storage/email/src/outbound.rs
@@ -1,8 +1,14 @@
+#[cfg(feature = "outbound")]
mod email_pg_repo;
+#[cfg(feature = "http_client")]
+mod email_service_http;
#[cfg(feature = "gmail_token")]
mod gmail_token_provider;
+#[cfg(feature = "outbound")]
pub use email_pg_repo::EmailPgRepo;
+#[cfg(feature = "http_client")]
+pub use email_service_http::EmailServiceHttpClient;
#[cfg(feature = "gmail_token")]
pub use gmail_token_provider::{
GmailTokenProviderImpl, fetch_gmail_access_token, fetch_gmail_access_token_no_cache,
diff --git a/rust/cloud-storage/email/src/outbound/email_service_http.rs b/rust/cloud-storage/email/src/outbound/email_service_http.rs
new file mode 100644
index 0000000000..32606b57d9
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_service_http.rs
@@ -0,0 +1,65 @@
+use std::time::Duration;
+
+use reqwest::StatusCode;
+
+use crate::domain::ports::{FirstInboxProvisionOutcome, FirstInboxProvisioner};
+
+#[cfg(test)]
+mod test;
+
+const INIT_TIMEOUT: Duration = Duration::from_secs(10);
+
+/// HTTP adapter for the email service's user-facing API, authenticated as the
+/// user via a bearer token. Lets other services drive email flows through the
+/// same routes and authorization the user's own client would use.
+#[derive(Clone, Debug)]
+pub struct EmailServiceHttpClient {
+ url: String,
+ client: reqwest::Client,
+}
+
+impl EmailServiceHttpClient {
+ /// Creates a client rooted at the email service base url.
+ pub fn new(url: String) -> Self {
+ Self {
+ url,
+ client: reqwest::Client::new(),
+ }
+ }
+}
+
+fn classify_init_status(status: StatusCode) -> Option<FirstInboxProvisionOutcome> {
+ if status.is_success() {
+ Some(FirstInboxProvisionOutcome::Provisioned)
+ } else if status == StatusCode::BAD_REQUEST {
+ Some(FirstInboxProvisionOutcome::Skipped)
+ } else {
+ None
+ }
+}
+
+impl FirstInboxProvisioner for EmailServiceHttpClient {
+ /// `POST /email/init`. `Skipped` covers the service's 400 no-op answers
+ /// (inbox already initialized, or no Gmail grant to provision from).
+ async fn provision_first_inbox(
+ &self,
+ access_token: &str,
+ ) -> anyhow::Result<FirstInboxProvisionOutcome> {
+ let res = self
+ .client
+ .post(format!("{}/email/init", self.url))
+ .bearer_auth(access_token)
+ .timeout(INIT_TIMEOUT)
+ .send()
+ .await?;
+
+ let status = res.status();
+ match classify_init_status(status) {
+ Some(outcome) => Ok(outcome),
+ None => {
+ let body = res.text().await.unwrap_or_else(|_| "no body".to_string());
+ anyhow::bail!("HTTP {status}: {body}")
+ }
+ }
+ }
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_service_http/test.rs b/rust/cloud-storage/email/src/outbound/email_service_http/test.rs
new file mode 100644
index 0000000000..ba8b39fc7c
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_service_http/test.rs
@@ -0,0 +1,33 @@
+use super::*;
+
+#[test]
+fn success_statuses_are_provisioned() {
+ assert_eq!(
+ classify_init_status(StatusCode::OK),
+ Some(FirstInboxProvisionOutcome::Provisioned)
+ );
+ assert_eq!(
+ classify_init_status(StatusCode::CREATED),
+ Some(FirstInboxProvisionOutcome::Provisioned)
+ );
+}
+
+#[test]
+fn bad_request_is_skipped() {
+ assert_eq!(
+ classify_init_status(StatusCode::BAD_REQUEST),
+ Some(FirstInboxProvisionOutcome::Skipped)
+ );
+}
+
+#[test]
+fn other_statuses_are_errors() {
+ for status in [
+ StatusCode::UNAUTHORIZED,
+ StatusCode::CONFLICT,
+ StatusCode::TOO_MANY_REQUESTS,
+ StatusCode::INTERNAL_SERVER_ERROR,
+ ] {
+ assert_eq!(classify_init_status(status), None);
+ }
+}