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(email-service): Block users (#1114)

Evan Hutnik75a6a604d492
diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.ts
index 9e7b4f4bd4..35870b0130 100644
--- a/js/app/packages/service-clients/service-email/generated/client.ts
+++ b/js/app/packages/service-clients/service-email/generated/client.ts
@@ -11,6 +11,8 @@ import type {
AddForwardedAttachmentResponse,
ApiPaginatedThreadCursor,
ArchiveThreadRequest,
+ BlockSenderRequest,
+ BlockSenderResponse,
CancelBackfillParams,
CreateDraftRequest,
CreateDraftResponse,
@@ -28,6 +30,7 @@ import type {
GetThreadParams,
GetThreadResponse,
InitResponse,
+ ListBlockedResponse,
ListContactsResponse,
ListLabelsResponse,
ListLinksParams,
@@ -434,6 +437,197 @@ export const listContacts = async (
} as listContactsResponse;
};
+/**
+ * @summary Block a sender by creating a Gmail filter that sends their emails to trash.
+ */
+export type blockSenderResponse201 = {
+ data: BlockSenderResponse;
+ status: 201;
+};
+
+export type blockSenderResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type blockSenderResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type blockSenderResponse409 = {
+ data: ErrorResponse;
+ status: 409;
+};
+
+export type blockSenderResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type blockSenderResponseSuccess = blockSenderResponse201 & {
+ headers: Headers;
+};
+export type blockSenderResponseError = (
+ | blockSenderResponse400
+ | blockSenderResponse401
+ | blockSenderResponse409
+ | blockSenderResponse500
+) & {
+ headers: Headers;
+};
+
+export type blockSenderResponse =
+ | blockSenderResponseSuccess
+ | blockSenderResponseError;
+
+export const getBlockSenderUrl = () => {
+ return `/email/contacts/block`;
+};
+
+export const blockSender = async (
+ blockSenderRequest: BlockSenderRequest,
+ options?: RequestInit
+): Promise<blockSenderResponse> => {
+ const res = await fetch(getBlockSenderUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(blockSenderRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: blockSenderResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as blockSenderResponse;
+};
+
+/**
+ * @summary Unblock a sender by removing their block filter from Gmail.
+ */
+export type unblockSenderResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type unblockSenderResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type unblockSenderResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type unblockSenderResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type unblockSenderResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type unblockSenderResponseSuccess = unblockSenderResponse204 & {
+ headers: Headers;
+};
+export type unblockSenderResponseError = (
+ | unblockSenderResponse400
+ | unblockSenderResponse401
+ | unblockSenderResponse404
+ | unblockSenderResponse500
+) & {
+ headers: Headers;
+};
+
+export type unblockSenderResponse =
+ | unblockSenderResponseSuccess
+ | unblockSenderResponseError;
+
+export const getUnblockSenderUrl = (emailAddress: string) => {
+ return `/email/contacts/block/${emailAddress}`;
+};
+
+export const unblockSender = async (
+ emailAddress: string,
+ options?: RequestInit
+): Promise<unblockSenderResponse> => {
+ const res = await fetch(getUnblockSenderUrl(emailAddress), {
+ ...options,
+ method: 'DELETE',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: unblockSenderResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as unblockSenderResponse;
+};
+
+/**
+ * @summary List all blocked senders for the authenticated user.
+ */
+export type listBlockedSendersResponse200 = {
+ data: ListBlockedResponse;
+ status: 200;
+};
+
+export type listBlockedSendersResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type listBlockedSendersResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type listBlockedSendersResponseSuccess =
+ listBlockedSendersResponse200 & {
+ headers: Headers;
+ };
+export type listBlockedSendersResponseError = (
+ | listBlockedSendersResponse401
+ | listBlockedSendersResponse500
+) & {
+ headers: Headers;
+};
+
+export type listBlockedSendersResponse =
+ | listBlockedSendersResponseSuccess
+ | listBlockedSendersResponseError;
+
+export const getListBlockedSendersUrl = () => {
+ return `/email/contacts/blocked`;
+};
+
+export const listBlockedSenders = async (
+ options?: RequestInit
+): Promise<listBlockedSendersResponse> => {
+ const res = await fetch(getListBlockedSendersUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: listBlockedSendersResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as listBlockedSendersResponse;
+};
+
/**
* @summary Create a draft.
*/
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/blockSenderRequest.ts b/js/app/packages/service-clients/service-email/generated/schemas/blockSenderRequest.ts
new file mode 100644
index 0000000000..186e17d0e3
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/blockSenderRequest.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Request to block a sender.
+ */
+export interface BlockSenderRequest {
+ /** The email address of the sender to block. */
+ email_address: string;
+}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/blockSenderResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/blockSenderResponse.ts
new file mode 100644
index 0000000000..d14ee57970
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/blockSenderResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response after blocking a sender.
+ */
+export interface BlockSenderResponse {
+ /** The ID of the filter created in Gmail. */
+ filter_id: string;
+}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
index f443fd3539..81e5df8009 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
@@ -135,6 +135,8 @@ export * from './backfillJob';
export * from './backfillJobLinkId';
export * from './backfillJobStatus';
export * from './backfillJobThreadsRequestedLimit';
+export * from './blockSenderRequest';
+export * from './blockSenderResponse';
export * from './cancelBackfillParams';
export * from './contact';
export * from './contactEmailAddress';
@@ -180,6 +182,7 @@ export * from './labelType';
export * from './labelTypeProperty';
export * from './link';
export * from './linkSignature';
+export * from './listBlockedResponse';
export * from './listContactsResponse';
export * from './listContactsResponseContacts';
export * from './listLabelsResponse';
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/listBlockedResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/listBlockedResponse.ts
new file mode 100644
index 0000000000..79a36cf27e
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/listBlockedResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response containing list of blocked email addresses.
+ */
+export interface ListBlockedResponse {
+ /** List of email addresses that are currently blocked. */
+ blocked_emails: string[];
+}
diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.json
index b12b7e613e..e712b71392 100644
--- a/js/app/packages/service-clients/service-email/openapi.json
+++ b/js/app/packages/service-clients/service-email/openapi.json
@@ -370,6 +370,177 @@
}
}
},
+ "/email/contacts/block": {
+ "post": {
+ "tags": ["Contacts"],
+ "summary": "Block a sender by creating a Gmail filter that sends their emails to trash.",
+ "operationId": "block_sender",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BlockSenderRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BlockSenderResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "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"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/email/contacts/block/{email_address}": {
+ "delete": {
+ "tags": ["Contacts"],
+ "summary": "Unblock a sender by removing their block filter from Gmail.",
+ "operationId": "unblock_sender",
+ "parameters": [
+ {
+ "name": "email_address",
+ "in": "path",
+ "description": "The email address of the sender to unblock.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/email/contacts/blocked": {
+ "get": {
+ "tags": ["Contacts"],
+ "summary": "List all blocked senders for the authenticated user.",
+ "operationId": "list_blocked_senders",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListBlockedResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/email/drafts": {
"post": {
"tags": ["Drafts"],
@@ -3234,6 +3405,28 @@
"type": "string",
"enum": ["Init", "InProgress", "Complete", "Cancelled", "Failed"]
},
+ "BlockSenderRequest": {
+ "type": "object",
+ "description": "Request to block a sender.",
+ "required": ["email_address"],
+ "properties": {
+ "email_address": {
+ "type": "string",
+ "description": "The email address of the sender to block."
+ }
+ }
+ },
+ "BlockSenderResponse": {
+ "type": "object",
+ "description": "Response after blocking a sender.",
+ "required": ["filter_id"],
+ "properties": {
+ "filter_id": {
+ "type": "string",
+ "description": "The ID of the filter created in Gmail."
+ }
+ }
+ },
"CancelBackfillParams": {
"type": "object",
"required": ["job_id"],
@@ -3608,6 +3801,20 @@
}
}
},
+ "ListBlockedResponse": {
+ "type": "object",
+ "description": "Response containing list of blocked email addresses.",
+ "required": ["blocked_emails"],
+ "properties": {
+ "blocked_emails": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "List of email addresses that are currently blocked."
+ }
+ }
+ },
"ListContactsResponse": {
"type": "object",
"required": ["contacts"],
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 69fd0bcff0..cfd017b34a 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -99,7 +99,7 @@ macro_env = { path = "../macro_env" }
mailparse = "0.16.1"
macro_env_var = { path = "../macro_env_var" }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
- "auth",
+ "auth", "cloud_storage"
] }
last_online_tracker = { path = "../last_online_tracker" }
notification = { path = "../notification" }
diff --git a/rust/cloud-storage/email_service/src/api/email/contacts/block_sender.rs b/rust/cloud-storage/email_service/src/api/email/contacts/block_sender.rs
new file mode 100644
index 0000000000..a1dd283a6f
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/api/email/contacts/block_sender.rs
@@ -0,0 +1,131 @@
+use crate::api::context::ApiContext;
+use axum::extract::State;
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::{Extension, Json};
+use gmail_client::{Filter, GmailError};
+use model::response::ErrorResponse;
+use strum_macros::AsRefStr;
+use thiserror::Error;
+use utoipa::ToSchema;
+
+#[derive(Debug, Error, AsRefStr)]
+pub enum BlockSenderError {
+ #[error("Validation error: {0}")]
+ Validation(String),
+
+ #[error("Sender is already blocked")]
+ AlreadyBlocked,
+
+ #[error("Gmail API error: {0}")]
+ GmailError(String),
+
+ #[error("Internal error")]
+ InternalError(#[from] anyhow::Error),
+}
+
+impl IntoResponse for BlockSenderError {
+ fn into_response(self) -> Response {
+ let status_code = match &self {
+ BlockSenderError::Validation(_) => StatusCode::BAD_REQUEST,
+ BlockSenderError::AlreadyBlocked => StatusCode::CONFLICT,
+ BlockSenderError::GmailError(_) | BlockSenderError::InternalError(_) => {
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ };
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: self.to_string().as_str(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+impl From<GmailError> for BlockSenderError {
+ fn from(e: GmailError) -> Self {
+ match e {
+ GmailError::Conflict(_) => BlockSenderError::AlreadyBlocked,
+ _ => BlockSenderError::GmailError(e.to_string()),
+ }
+ }
+}
+
+/// Request to block a sender.
+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct BlockSenderRequest {
+ /// The email address of the sender to block.
+ pub email_address: String,
+}
+
+/// Response after blocking a sender.
+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct BlockSenderResponse {
+ /// The ID of the filter created in Gmail.
+ pub filter_id: String,
+}
+
+/// Block a sender by creating a Gmail filter that sends their emails to trash.
+#[utoipa::path(
+ post,
+ tag = "Contacts",
+ path = "/email/contacts/block",
+ operation_id = "block_sender",
+ request_body = BlockSenderRequest,
+ responses(
+ (status = 201, body = BlockSenderResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 409, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx, gmail_token), err)]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ gmail_token: Extension<String>,
+ Json(req): Json<BlockSenderRequest>,
+) -> Result<(StatusCode, Json<BlockSenderResponse>), BlockSenderError> {
+ validate_email(&req.email_address)?;
+
+ // Check if sender is already blocked
+ let existing_filter = ctx
+ .gmail_client
+ .find_block_filter_for_sender(&gmail_token, &req.email_address)
+ .await?;
+
+ if existing_filter.is_some() {
+ return Err(BlockSenderError::AlreadyBlocked);
+ }
+
+ // Create the block filter
+ let filter: Filter = ctx
+ .gmail_client
+ .block_sender(&gmail_token, &req.email_address)
+ .await?;
+
+ let filter_id = filter.id.unwrap_or_default();
+
+ Ok((StatusCode::CREATED, Json(BlockSenderResponse { filter_id })))
+}
+
+fn validate_email(email: &str) -> Result<(), BlockSenderError> {
+ if email.trim().is_empty() {
+ return Err(BlockSenderError::Validation(
+ "Email address cannot be empty".to_string(),
+ ));
+ }
+ if !email.contains('@') {
+ return Err(BlockSenderError::Validation(
+ "Invalid email address format".to_string(),
+ ));
+ }
+ if email.len() > 254 {
+ return Err(BlockSenderError::Validation(
+ "Email address is too long".to_string(),
+ ));
+ }
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/src/api/email/contacts/list_blocked.rs b/rust/cloud-storage/email_service/src/api/email/contacts/list_blocked.rs
new file mode 100644
index 0000000000..18208d3d4a
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/api/email/contacts/list_blocked.rs
@@ -0,0 +1,72 @@
+use crate::api::context::ApiContext;
+use axum::extract::State;
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::{Extension, Json};
+use gmail_client::GmailError;
+use model::response::ErrorResponse;
+use strum_macros::AsRefStr;
+use thiserror::Error;
+use utoipa::ToSchema;
+
+#[derive(Debug, Error, AsRefStr)]
+pub enum ListBlockedError {
+ #[error("Gmail API error: {0}")]
+ GmailError(String),
+
+ #[error("Internal error")]
+ InternalError(#[from] anyhow::Error),
+}
+
+impl IntoResponse for ListBlockedError {
+ fn into_response(self) -> Response {
+ let status_code = match &self {
+ ListBlockedError::GmailError(_) | ListBlockedError::InternalError(_) => {
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ };
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: self.to_string().as_str(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+impl From<GmailError> for ListBlockedError {
+ fn from(e: GmailError) -> Self {
+ ListBlockedError::GmailError(e.to_string())
+ }
+}
+
+/// Response containing list of blocked email addresses.
+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct ListBlockedResponse {
+ /// List of email addresses that are currently blocked.
+ pub blocked_emails: Vec<String>,
+}
+
+/// List all blocked senders for the authenticated user.
+#[utoipa::path(
+ get,
+ tag = "Contacts",
+ path = "/email/contacts/blocked",
+ operation_id = "list_blocked_senders",
+ responses(
+ (status = 200, body = ListBlockedResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx, gmail_token), err)]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ gmail_token: Extension<String>,
+) -> Result<Json<ListBlockedResponse>, ListBlockedError> {
+ let blocked_emails = ctx.gmail_client.list_blocked_senders(&gmail_token).await?;
+
+ Ok(Json(ListBlockedResponse { blocked_emails }))
+}
diff --git a/rust/cloud-storage/email_service/src/api/email/contacts/mod.rs b/rust/cloud-storage/email_service/src/api/email/contacts/mod.rs
index cfbbb8243b..95f09c558e 100644
--- a/rust/cloud-storage/email_service/src/api/email/contacts/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/contacts/mod.rs
@@ -1,9 +1,41 @@
use crate::api::ApiContext;
use axum::Router;
-use axum::routing::get;
+use axum::routing::{delete, get, post};
+use tower::ServiceBuilder;
+pub(crate) mod block_sender;
pub(crate) mod list;
+pub(crate) mod list_blocked;
+pub(crate) mod unblock_sender;
-pub fn router() -> Router<ApiContext> {
- Router::new().route("/", get(list::list_contacts_handler))
+pub fn router(state: ApiContext) -> Router<ApiContext> {
+ Router::new()
+ .route("/", get(list::list_contacts_handler))
+ .route(
+ "/block",
+ post(block_sender::handler).layer(ServiceBuilder::new().layer(
+ axum::middleware::from_fn_with_state(
+ state.clone(),
+ crate::api::middleware::gmail_token::attach_gmail_token,
+ ),
+ )),
+ )
+ .route(
+ "/block/{email_address}",
+ delete(unblock_sender::handler).layer(ServiceBuilder::new().layer(
+ axum::middleware::from_fn_with_state(
+ state.clone(),
+ crate::api::middleware::gmail_token::attach_gmail_token,
+ ),
+ )),
+ )
+ .route(
+ "/blocked",
+ get(list_blocked::handler).layer(ServiceBuilder::new().layer(
+ axum::middleware::from_fn_with_state(
+ state,
+ crate::api::middleware::gmail_token::attach_gmail_token,
+ ),
+ )),
+ )
}
diff --git a/rust/cloud-storage/email_service/src/api/email/contacts/unblock_sender.rs b/rust/cloud-storage/email_service/src/api/email/contacts/unblock_sender.rs
new file mode 100644
index 0000000000..eb6c6a8dcd
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/api/email/contacts/unblock_sender.rs
@@ -0,0 +1,125 @@
+use crate::api::context::ApiContext;
+use axum::extract::{Path, State};
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::{Extension, Json};
+use gmail_client::GmailError;
+use model::response::ErrorResponse;
+use strum_macros::AsRefStr;
+use thiserror::Error;
+use utoipa::IntoParams;
+
+#[derive(Debug, Error, AsRefStr)]
+pub enum UnblockSenderError {
+ #[error("Validation error: {0}")]
+ Validation(String),
+
+ #[error("Sender is not blocked")]
+ NotBlocked,
+
+ #[error("Gmail API error: {0}")]
+ GmailError(String),
+
+ #[error("Internal error")]
+ InternalError(#[from] anyhow::Error),
+}
+
+impl IntoResponse for UnblockSenderError {
+ fn into_response(self) -> Response {
+ let status_code = match &self {
+ UnblockSenderError::Validation(_) => StatusCode::BAD_REQUEST,
+ UnblockSenderError::NotBlocked => StatusCode::NOT_FOUND,
+ UnblockSenderError::GmailError(_) | UnblockSenderError::InternalError(_) => {
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ };
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: self.to_string().as_str(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+impl From<GmailError> for UnblockSenderError {
+ fn from(e: GmailError) -> Self {
+ match e {
+ GmailError::NotFound(_) => UnblockSenderError::NotBlocked,
+ _ => UnblockSenderError::GmailError(e.to_string()),
+ }
+ }
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, IntoParams)]
+pub struct PathParams {
+ /// The email address of the sender to unblock.
+ pub email_address: String,
+}
+
+/// Unblock a sender by removing their block filter from Gmail.
+#[utoipa::path(
+ delete,
+ tag = "Contacts",
+ path = "/email/contacts/block/{email_address}",
+ operation_id = "unblock_sender",
+ params(PathParams),
+ responses(
+ (status = 204),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx, gmail_token), err)]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ gmail_token: Extension<String>,
+ Path(PathParams { email_address }): Path<PathParams>,
+) -> Result<impl IntoResponse, UnblockSenderError> {
+ validate_email(&email_address)?;
+
+ // Check if sender is currently blocked
+ let existing_filter = ctx
+ .gmail_client
+ .find_block_filter_for_sender(&gmail_token, &email_address)
+ .await?;
+
+ if existing_filter.is_none() {
+ return Err(UnblockSenderError::NotBlocked);
+ }
+
+ // Unblock the sender
+ let was_unblocked = ctx
+ .gmail_client
+ .unblock_sender(&gmail_token, &email_address)
+ .await?;
+
+ if !was_unblocked {
+ return Err(UnblockSenderError::NotBlocked);
+ }
+
+ Ok(StatusCode::NO_CONTENT)
+}
+
+fn validate_email(email: &str) -> Result<(), UnblockSenderError> {
+ if email.trim().is_empty() {
+ return Err(UnblockSenderError::Validation(
+ "Email address cannot be empty".to_string(),
+ ));
+ }
+ if !email.contains('@') {
+ return Err(UnblockSenderError::Validation(
+ "Invalid email address format".to_string(),
+ ));
+ }
+ if email.len() > 254 {
+ return Err(UnblockSenderError::Validation(
+ "Email address is too long".to_string(),
+ ));
+ }
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/src/api/email/mod.rs b/rust/cloud-storage/email_service/src/api/email/mod.rs
index ff9ec93a42..8920eb725f 100644
--- a/rust/cloud-storage/email_service/src/api/email/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/mod.rs
@@ -23,7 +23,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
.nest("/drafts", drafts::router(state.clone()))
.nest("/messages", messages::router(state.clone()))
.nest("/links", links::router())
- .nest("/contacts", contacts::router())
+ .nest("/contacts", contacts::router(state.clone()))
.nest("/backfill", backfill::router(state.clone()))
.nest("/settings", settings::router(state.clone()))
.nest("/sync", sync::router(state.clone()))
diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rs
index d693ae6161..a5dc0ba6ea 100644
--- a/rust/cloud-storage/email_service/src/api/swagger.rs
+++ b/rust/cloud-storage/email_service/src/api/swagger.rs
@@ -2,7 +2,9 @@ use crate::api::email::attachments::get::GetAttachmentResponse;
use crate::api::email::attachments::get_document_id::GetAttachmentDocumentIDResponse;
use crate::api::email::backfill::cancel::CancelBackfillParams;
use crate::api::email::backfill::get::{GetActiveBackfillJobResponse, GetBackfillJobResponse};
+use crate::api::email::contacts::block_sender::{BlockSenderRequest, BlockSenderResponse};
use crate::api::email::contacts::list::ListContactsResponse;
+use crate::api::email::contacts::list_blocked::ListBlockedResponse;
use crate::api::email::drafts::add_attachment::{
AddDraftAttachmentRequest, AddDraftAttachmentResponse,
};
@@ -75,6 +77,9 @@ use utoipa::OpenApi;
email::labels::delete::handler,
inbound::list_labels_handler,
email::contacts::list::list_contacts_handler,
+ email::contacts::block_sender::handler,
+ email::contacts::unblock_sender::handler,
+ email::contacts::list_blocked::handler,
email::sync::disable::disable_handler,
email::settings::patch::patch_settings_handler,
),
@@ -131,6 +136,9 @@ use utoipa::OpenApi;
// Contact types
ListContactsResponse,
ContactInfoWithInteraction,
+ BlockSenderRequest,
+ BlockSenderResponse,
+ ListBlockedResponse,
// Sort/filter types
ApiSortMethod,
// Legacy service types (keeping for backward compatibility)
diff --git a/rust/cloud-storage/gmail_client/src/filters.rs b/rust/cloud-storage/gmail_client/src/filters.rs
new file mode 100644
index 0000000000..ca5e24c393
--- /dev/null
+++ b/rust/cloud-storage/gmail_client/src/filters.rs
@@ -0,0 +1,241 @@
+use crate::GmailClient;
+use models_email::gmail::error::GmailError;
+use models_email::gmail::filters::{Filter, FilterAction, FilterCriteria, ListFiltersResponse};
+
+/// Creates a filter to block a user by sending their emails to TRASH.
+/// This replicates the "Block Sender" functionality in the Superhuman UI.
+#[tracing::instrument(skip(client, access_token), err)]
+pub(crate) async fn block_sender(
+ client: &GmailClient,
+ access_token: &str,
+ email_to_block: &str,
+) -> Result<Filter, GmailError> {
+ let filter = Filter {
+ id: None,
+ criteria: FilterCriteria {
+ from: Some(email_to_block.to_string()),
+ to: None,
+ subject: None,
+ query: None,
+ negated_query: None,
+ has_attachment: None,
+ exclude_chats: None,
+ },
+
+ action: FilterAction {
+ add_label_ids: Some(vec!["TRASH".to_string()]),
+ remove_label_ids: None,
+ forward: None,
+ },
+ };
+
+ create_filter(client, access_token, filter).await
+}
+
+/// Creates a new Gmail filter.
+#[tracing::instrument(skip(client, access_token), err)]
+pub(crate) async fn create_filter(
+ client: &GmailClient,
+ access_token: &str,
+ filter: Filter,
+) -> Result<Filter, GmailError> {
+ let url = format!("{}/users/me/settings/filters", client.base_url);
+
+ let http_client = client.inner.clone();
+
+ let response = http_client
+ .post(&url)
+ .bearer_auth(access_token)
+ .json(&filter)
+ .send()
+ .await
+ .map_err(|e| GmailError::HttpRequest(e.to_string()))?;
+
+ let response = response.error_for_status().map_err(|e| match e.status() {
+ Some(status) if status.as_u16() == 401 => GmailError::Unauthorized,
+ Some(status) if status.as_u16() == 429 => GmailError::RateLimitExceeded,
+ Some(status) if status.as_u16() == 409 => {
+ GmailError::Conflict("Filter already exists".to_string())
+ }
+ _ => GmailError::ApiError(e.to_string()),
+ })?;
+
+ let created_filter = response
+ .json::<Filter>()
+ .await
+ .map_err(|e| GmailError::BodyReadError(e.to_string()))?;
+
+ Ok(created_filter)
+}
+
+/// Lists all filters for the user.
+#[tracing::instrument(skip(client, access_token), err)]
+pub(crate) async fn list_filters(
+ client: &GmailClient,
+ access_token: &str,
+) -> Result<Vec<Filter>, GmailError> {
+ let url = format!("{}/users/me/settings/filters", client.base_url);
+
+ let http_client = client.inner.clone();
+
+ let response = http_client
+ .get(&url)
+ .bearer_auth(access_token)
+ .send()
+ .await
+ .map_err(|e| GmailError::HttpRequest(e.to_string()))?;
+
+ let response = response.error_for_status().map_err(|e| match e.status() {
+ Some(status) if status.as_u16() == 401 => GmailError::Unauthorized,
+ Some(status) if status.as_u16() == 429 => GmailError::RateLimitExceeded,
+ _ => GmailError::ApiError(e.to_string()),
+ })?;
+
+ let filters_response = response
+ .json::<ListFiltersResponse>()
+ .await
+ .map_err(|e| GmailError::BodyReadError(e.to_string()))?;
+
+ Ok(filters_response.filter)
+}
+
+/// Gets a specific filter by ID.
+#[tracing::instrument(skip(client, access_token), err)]
+pub(crate) async fn get_filter(
+ client: &GmailClient,
+ access_token: &str,
+ filter_id: &str,
+) -> Result<Filter, GmailError> {
+ let url = format!(
+ "{}/users/me/settings/filters/{}",
+ client.base_url, filter_id
+ );
+
+ let http_client = client.inner.clone();
+
+ let response = http_client
+ .get(&url)
+ .bearer_auth(access_token)
+ .send()
+ .await
+ .map_err(|e| GmailError::HttpRequest(e.to_string()))?;
+
+ let response = response.error_for_status().map_err(|e| match e.status() {
+ Some(status) if status.as_u16() == 401 => GmailError::Unauthorized,
+ Some(status) if status.as_u16() == 429 => GmailError::RateLimitExceeded,
+ Some(status) if status.as_u16() == 404 => {
+ GmailError::NotFound(format!("Filter {} not found", filter_id))
+ }
+ _ => GmailError::ApiError(e.to_string()),
+ })?;
+
+ let filter = response
+ .json::<Filter>()
+ .await
+ .map_err(|e| GmailError::BodyReadError(e.to_string()))?;
+
+ Ok(filter)
+}
+
+/// Deletes a filter by ID (can be used to "unblock" a user).
+#[tracing::instrument(skip(client, access_token), err)]
+pub(crate) async fn delete_filter(
+ client: &GmailClient,
+ access_token: &str,
+ filter_id: &str,
+) -> Result<(), GmailError> {
+ let url = format!(
+ "{}/users/me/settings/filters/{}",
+ client.base_url, filter_id
+ );
+
+ let http_client = client.inner.clone();
+
+ let response = http_client
+ .delete(&url)
+ .bearer_auth(access_token)
+ .send()
+ .await
+ .map_err(|e| GmailError::HttpRequest(e.to_string()))?;
+
+ response.error_for_status().map_err(|e| match e.status() {
+ Some(status) if status.as_u16() == 401 => GmailError::Unauthorized,
+ Some(status) if status.as_u16() == 429 => GmailError::RateLimitExceeded,
+ Some(status) if status.as_u16() == 404 => {
+ GmailError::NotFound(format!("Filter {} not found", filter_id))
+ }
+ _ => GmailError::ApiError(e.to_string()),
+ })?;
+
+ Ok(())
+}
+
+/// Finds and returns any existing "block" filters for a specific email address.
+/// This can be used to check if a user is already blocked.
+#[tracing::instrument(skip(client, access_token), err)]
+pub(crate) async fn find_block_filter_for_sender(
+ client: &GmailClient,
+ access_token: &str,
+ email_address: &str,
+) -> Result<Option<Filter>, GmailError> {
+ let filters = list_filters(client, access_token).await?;
+
+ let block_filter = filters.into_iter().find(|f| {
+ if let Some(from) = &f.criteria.from
+ && from.eq_ignore_ascii_case(email_address)
+ {
+ // Check if add_label_ids contains TRASH
+ return f
+ .action
+ .add_label_ids
+ .as_ref()
+ .map(|labels| labels.contains(&"TRASH".to_string()))
+ .unwrap_or(false);
+ }
+ false
+ });
+
+ Ok(block_filter)
+}
+
+/// Unblocks a sender by finding and deleting their block filter.
+/// Returns true if a filter was found and deleted, false if no filter existed.
+#[tracing::instrument(skip(client, access_token), err)]
+pub(crate) async fn unblock_sender(
+ client: &GmailClient,
+ access_token: &str,
+ email_address: &str,
+) -> Result<bool, GmailError> {
+ if let Some(filter) = find_block_filter_for_sender(client, access_token, email_address).await?
+ && let Some(filter_id) = filter.id
+ {
+ delete_filter(client, access_token, &filter_id).await?;
+ return Ok(true);
+ }
+ Ok(false)
+}
+
+/// Lists all blocked senders by finding filters that send emails to TRASH.
+/// Returns a list of email addresses that are currently blocked.
+#[tracing::instrument(skip(client, access_token), err)]
+pub(crate) async fn list_blocked_senders(
+ client: &GmailClient,
+ access_token: &str,
+) -> Result<Vec<String>, GmailError> {
+ let filters = list_filters(client, access_token).await?;
+
+ let blocked_emails = filters
+ .into_iter()
+ .filter(|f| {
+ // Check if add_label_ids contains TRASH
+ f.action
+ .add_label_ids
+ .as_ref()
+ .map(|labels| labels.contains(&"TRASH".to_string()))
+ .unwrap_or(false)
+ })
+ .filter_map(|f| f.criteria.from)
+ .collect();
+
+ Ok(blocked_emails)
+}
diff --git a/rust/cloud-storage/gmail_client/src/lib.rs b/rust/cloud-storage/gmail_client/src/lib.rs
index 14f8156546..7ac15903dc 100644
--- a/rust/cloud-storage/gmail_client/src/lib.rs
+++ b/rust/cloud-storage/gmail_client/src/lib.rs
@@ -1,6 +1,7 @@
pub(crate) mod attachments;
pub(crate) mod auth;
pub(crate) mod contacts;
+pub(crate) mod filters;
pub(crate) mod history;
pub(crate) mod labels;
pub(crate) mod messages;
@@ -23,6 +24,7 @@ use models_email::email::service::message;
use models_email::email::service::thread::ThreadList as ServiceThreadList;
use models_email::gmail::contacts::PersonResource;
pub use models_email::gmail::error::GmailError;
+pub use models_email::gmail::filters::Filter;
use models_email::gmail::inbox_sync::{
GoogleJwtClaims, GooglePublicKeys, JwtVerificationError, KeyMap,
};
@@ -324,4 +326,83 @@ impl GmailClient {
) -> Result<Option<String>, GmailError> {
settings::get_email_signature(self, access_token, email_address).await
}
+
+ /// Blocks a sender by creating a filter that sends their emails to SPAM.
+ /// This replicates the "Block Sender" functionality in the Gmail UI.
+ #[tracing::instrument(skip(self, access_token))]
+ pub async fn block_sender(
+ &self,
+ access_token: &str,
+ email_to_block: &str,
+ ) -> Result<Filter, GmailError> {
+ filters::block_sender(self, access_token, email_to_block).await
+ }
+
+ /// Creates a new Gmail filter.
+ #[tracing::instrument(skip(self, access_token))]
+ pub async fn create_filter(
+ &self,
+ access_token: &str,
+ filter: Filter,
+ ) -> Result<Filter, GmailError> {
+ filters::create_filter(self, access_token, filter).await
+ }
+
+ /// Lists all filters for the user.
+ #[tracing::instrument(skip(self, access_token))]
+ pub async fn list_filters(&self, access_token: &str) -> Result<Vec<Filter>, GmailError> {
+ filters::list_filters(self, access_token).await
+ }
+
+ /// Gets a specific filter by ID.
+ #[tracing::instrument(skip(self, access_token))]
+ pub async fn get_filter(
+ &self,
+ access_token: &str,
+ filter_id: &str,
+ ) -> Result<Filter, GmailError> {
+ filters::get_filter(self, access_token, filter_id).await
+ }
+
+ /// Deletes a filter by ID.
+ #[tracing::instrument(skip(self, access_token))]
+ pub async fn delete_filter(
+ &self,
+ access_token: &str,
+ filter_id: &str,
+ ) -> Result<(), GmailError> {
+ filters::delete_filter(self, access_token, filter_id).await
+ }
+
+ /// Finds and returns any existing "block" filters for a specific email address.
+ /// This can be used to check if a user is already blocked.
+ #[tracing::instrument(skip(self, access_token))]
+ pub async fn find_block_filter_for_sender(
+ &self,
+ access_token: &str,
+ email_address: &str,
+ ) -> Result<Option<Filter>, GmailError> {
+ filters::find_block_filter_for_sender(self, access_token, email_address).await
+ }
+
+ /// Unblocks a sender by finding and deleting their block filter.
+ /// Returns true if a filter was found and deleted, false if no filter existed.
+ #[tracing::instrument(skip(self, access_token))]
+ pub async fn unblock_sender(
+ &self,
+ access_token: &str,
+ email_address: &str,
+ ) -> Result<bool, GmailError> {
+ filters::unblock_sender(self, access_token, email_address).await
+ }
+
+ /// Lists all blocked senders by finding filters that send emails to TRASH.
+ /// Returns a list of email addresses that are currently blocked.
+ #[tracing::instrument(skip(self, access_token))]
+ pub async fn list_blocked_senders(
+ &self,
+ access_token: &str,
+ ) -> Result<Vec<String>, GmailError> {
+ filters::list_blocked_senders(self, access_token).await
+ }
}
diff --git a/rust/cloud-storage/macro_middleware/Cargo.toml b/rust/cloud-storage/macro_middleware/Cargo.toml
index 573e49d1fc..ef89af8a6a 100644
--- a/rust/cloud-storage/macro_middleware/Cargo.toml
+++ b/rust/cloud-storage/macro_middleware/Cargo.toml
@@ -9,6 +9,7 @@ all = ["auth", "cloud_storage", "tracking", "user_permissions"]
auth = ["dep:macro_auth", "dep:url"]
cloud_storage = [
"dep:macro_share_permissions",
+ "dep:macro_user_id",
"dep:model_user",
"dep:permission",
"macro_db_client",
diff --git a/rust/cloud-storage/models_email/src/gmail/filters.rs b/rust/cloud-storage/models_email/src/gmail/filters.rs
new file mode 100644
index 0000000000..f3209bb680
--- /dev/null
+++ b/rust/cloud-storage/models_email/src/gmail/filters.rs
@@ -0,0 +1,51 @@
+use serde::{Deserialize, Serialize};
+
+/// Represents the criteria for a Gmail filter
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FilterCriteria {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub from: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub to: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub subject: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub query: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub negated_query: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub has_attachment: Option<bool>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub exclude_chats: Option<bool>,
+}
+
+/// Represents the action to take when a filter matches
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FilterAction {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub add_label_ids: Option<Vec<String>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub remove_label_ids: Option<Vec<String>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub forward: Option<String>,
+}
+
+/// Represents a Gmail filter
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Filter {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub id: Option<String>,
+ pub criteria: FilterCriteria,
+ pub action: FilterAction,
+}
+
+/// Response from listing filters
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ListFiltersResponse {
+ #[serde(default)]
+ pub filter: Vec<Filter>,
+}
diff --git a/rust/cloud-storage/models_email/src/gmail/mod.rs b/rust/cloud-storage/models_email/src/gmail/mod.rs
index 5f7d375d89..f352e8993f 100644
--- a/rust/cloud-storage/models_email/src/gmail/mod.rs
+++ b/rust/cloud-storage/models_email/src/gmail/mod.rs
@@ -1,5 +1,6 @@
pub mod contacts;
pub mod error;
+pub mod filters;
pub mod history;
pub mod inbox_sync;
pub mod labels;