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(contacts): add client facing endpoint (#2328)

Sean Aye1446624257fe
diff --git a/infra/stacks/contacts-service/Pulumi.dev.yaml b/infra/stacks/contacts-service/Pulumi.dev.yaml
index 9863041d18..93f41cf814 100644
--- a/infra/stacks/contacts-service/Pulumi.dev.yaml
+++ b/infra/stacks/contacts-service/Pulumi.dev.yaml
@@ -5,4 +5,5 @@ config:
contacts-service:fusionauth_issuer: fusionauth-dev.macro.com
contacts-service:jwt_secret_key: fusionauth-jwt-secret-dev
contacts-service:internal_api_key: document-storage-service-auth-key-dev
+ contacts-service:macro_cache_secret_key: macro-cache-dev
contacts-service:macro_db_secret_key: macro-db-dev
diff --git a/infra/stacks/contacts-service/Pulumi.prod.yaml b/infra/stacks/contacts-service/Pulumi.prod.yaml
index 6dd01fe97d..83cb27a4b1 100644
--- a/infra/stacks/contacts-service/Pulumi.prod.yaml
+++ b/infra/stacks/contacts-service/Pulumi.prod.yaml
@@ -5,4 +5,5 @@ config:
contacts-service:fusionauth_issuer: auth.macro.com
contacts-service:jwt_secret_key: fusionauth-jwt-secret-prod
contacts-service:internal_api_key: document-storage-service-auth-key-prod
+ contacts-service:macro_cache_secret_key: macro-cache-prod
contacts-service:macro_db_secret_key: macro-db-prod
diff --git a/infra/stacks/contacts-service/index.ts b/infra/stacks/contacts-service/index.ts
index 74bcccd88c..825c6340c0 100644
--- a/infra/stacks/contacts-service/index.ts
+++ b/infra/stacks/contacts-service/index.ts
@@ -26,6 +26,12 @@ const DATABASE_URL = aws.secretsmanager
})
.apply((secret) => secret.secretString);
+const MACRO_CACHE = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require(`macro_cache_secret_key`),
+ })
+ .apply((secret) => secret.secretString);
+
const JWT_SECRET_KEY = config.require(`jwt_secret_key`);
const jwtSecretKeyArn: pulumi.Output<string> = aws.secretsmanager
.getSecretVersionOutput({ secretId: JWT_SECRET_KEY })
@@ -69,6 +75,10 @@ let containerEnvVars = [
name: 'CONTACTS_QUEUE',
value: pulumi.interpolate`${contactsQueueName}`,
},
+ {
+ name: 'REDIS_URI',
+ value: pulumi.interpolate`redis://${MACRO_CACHE}`,
+ },
{
name: 'JWT_SECRET_KEY',
value: pulumi.interpolate`${JWT_SECRET_KEY}`,
diff --git a/js/app/packages/app/component/app-sidebar/invite-modal.tsx b/js/app/packages/app/component/app-sidebar/invite-modal.tsx
index 96e7577aa9..e5eda7cb59 100644
--- a/js/app/packages/app/component/app-sidebar/invite-modal.tsx
+++ b/js/app/packages/app/component/app-sidebar/invite-modal.tsx
@@ -3,6 +3,8 @@ import { createSignal, Show } from 'solid-js';
import { useReferralCode } from '@core/context/user';
import { getWebOrigin } from '@core/util/webOrigin';
import { authServiceClient } from '@service-auth/client';
+import { contactsClient } from '@service-contacts/client';
+import { isOk } from '@core/util/maybeResult';
import { DialogWrapper } from '@core/component/DialogWrapper';
import { Button } from '@ui/components/Button';
import { toast } from '@core/component/Toast/Toast';
@@ -44,7 +46,10 @@ export const InviteModal = () => {
if (!emails.length) return;
setSending(true);
for (const email of emails) {
- authServiceClient.sendReferralInvite(email);
+ const result = await authServiceClient.sendReferralInvite(email);
+ if (isOk(result)) {
+ contactsClient.addContact(`macro|${email.toLowerCase()}`);
+ }
}
setValue('');
setSending(false);
diff --git a/js/app/packages/app/component/interactive-onboarding/lessons/email-invite.tsx b/js/app/packages/app/component/interactive-onboarding/lessons/email-invite.tsx
index 15089471ef..63867d9989 100644
--- a/js/app/packages/app/component/interactive-onboarding/lessons/email-invite.tsx
+++ b/js/app/packages/app/component/interactive-onboarding/lessons/email-invite.tsx
@@ -4,6 +4,8 @@ import { MockAppChrome } from '../components/MockAppChrome';
import { useReferralCode } from '@core/context/user';
import { getWebOrigin } from '@core/util/webOrigin';
import { authServiceClient } from '@service-auth/client';
+import { contactsClient } from '@service-contacts/client';
+import { isOk } from '@core/util/maybeResult';
function parseEmails(raw: string): string[] {
return raw
@@ -48,7 +50,11 @@ function EmailInviteContent(props: LessonContentProps) {
const emails = parseEmails(value());
if (!emails.length) return;
for (const email of emails) {
- authServiceClient.sendReferralInvite(email);
+ authServiceClient.sendReferralInvite(email).then((result) => {
+ if (isOk(result)) {
+ contactsClient.addContact(`macro|${email.toLowerCase()}`);
+ }
+ });
}
});
diff --git a/js/app/packages/service-clients/service-contacts/client.ts b/js/app/packages/service-clients/service-contacts/client.ts
index bb08215676..fd56cd4c92 100644
--- a/js/app/packages/service-clients/service-contacts/client.ts
+++ b/js/app/packages/service-clients/service-contacts/client.ts
@@ -42,4 +42,11 @@ export const contactsClient = {
(result) => result
);
},
+ async addContact(userId: string) {
+ return contactsFetch(`/contacts`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ user_id: userId }),
+ });
+ },
};
diff --git a/js/app/packages/service-clients/service-contacts/generated/client.ts b/js/app/packages/service-clients/service-contacts/generated/client.ts
index 2a4ac291a7..19fc075237 100644
--- a/js/app/packages/service-clients/service-contacts/generated/client.ts
+++ b/js/app/packages/service-clients/service-contacts/generated/client.ts
@@ -4,7 +4,7 @@
* contacts_service
* OpenAPI spec version: 0.1.0
*/
-import type { GetContactsResponse } from './schemas';
+import type { AddContactRequest, GetContactsResponse } from './schemas';
export type getContactsResponse200 = {
data: GetContactsResponse;
@@ -62,3 +62,57 @@ export const getContacts = async (
headers: res.headers,
} as getContactsResponse;
};
+
+export type addContactResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type addContactResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type addContactResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type addContactResponseSuccess = addContactResponse204 & {
+ headers: Headers;
+};
+export type addContactResponseError = (
+ | addContactResponse401
+ | addContactResponse500
+) & {
+ headers: Headers;
+};
+
+export type addContactResponse =
+ | addContactResponseSuccess
+ | addContactResponseError;
+
+export const getAddContactUrl = () => {
+ return `/contacts`;
+};
+
+export const addContact = async (
+ addContactRequest: AddContactRequest,
+ options?: RequestInit
+): Promise<addContactResponse> => {
+ const res = await fetch(getAddContactUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(addContactRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: addContactResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as addContactResponse;
+};
diff --git a/js/app/packages/service-clients/service-contacts/generated/schemas/addContactRequest.ts b/js/app/packages/service-clients/service-contacts/generated/schemas/addContactRequest.ts
new file mode 100644
index 0000000000..9eef950f69
--- /dev/null
+++ b/js/app/packages/service-clients/service-contacts/generated/schemas/addContactRequest.ts
@@ -0,0 +1,10 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * contacts_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export interface AddContactRequest {
+ user_id: string;
+}
diff --git a/js/app/packages/service-clients/service-contacts/generated/schemas/index.ts b/js/app/packages/service-clients/service-contacts/generated/schemas/index.ts
index 6ca8ee4f8b..31db87d43a 100644
--- a/js/app/packages/service-clients/service-contacts/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-contacts/generated/schemas/index.ts
@@ -5,4 +5,5 @@
* OpenAPI spec version: 0.1.0
*/
+export * from './addContactRequest';
export * from './getContactsResponse';
diff --git a/js/app/packages/service-clients/service-contacts/openapi.json b/js/app/packages/service-clients/service-contacts/openapi.json
index 9e24767f4b..de5529c3c0 100644
--- a/js/app/packages/service-clients/service-contacts/openapi.json
+++ b/js/app/packages/service-clients/service-contacts/openapi.json
@@ -56,11 +56,59 @@
}
}
}
+ },
+ "post": {
+ "tags": ["contacts"],
+ "operationId": "add_contact",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AddContactRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
}
}
},
"components": {
"schemas": {
+ "AddContactRequest": {
+ "type": "object",
+ "required": ["user_id"],
+ "properties": {
+ "user_id": {
+ "type": "string"
+ }
+ }
+ },
"GetContactsResponse": {
"type": "object",
"required": ["contacts"],
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 51bac8b385..5d4626c1f2 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2282,6 +2282,7 @@ dependencies = [
"aws-sdk-secretsmanager",
"aws-sdk-sqs",
"axum",
+ "axum-extra",
"connection_gateway_client",
"contacts_db_client",
"http-body-util",
@@ -2291,7 +2292,12 @@ dependencies = [
"macro_entrypoint",
"macro_env",
"macro_middleware",
+ "macro_user_id",
"model",
+ "model_user",
+ "rate_limit",
+ "redis",
+ "rootcause",
"secretsmanager_client",
"serde",
"serde_json",
diff --git a/rust/cloud-storage/contacts_db_client/src/lib.rs b/rust/cloud-storage/contacts_db_client/src/lib.rs
index f9f525ad9b..0b4e043674 100644
--- a/rust/cloud-storage/contacts_db_client/src/lib.rs
+++ b/rust/cloud-storage/contacts_db_client/src/lib.rs
@@ -1,14 +1,14 @@
use anyhow::Result;
use serde::{Deserialize, Serialize};
-use sqlx::{Pool, Postgres, Transaction};
+use sqlx::{Pool, Postgres};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionRowId {
id: i32,
}
-pub async fn create_connections(
- transaction: &mut Transaction<'_, Postgres>,
+pub async fn create_connections<'a, E: sqlx::Executor<'a, Database = Postgres>>(
+ transaction: E,
connections: Vec<(String, String)>,
) -> Result<(), sqlx::Error> {
let mut query = "INSERT INTO contacts_connections(user1, user2) VALUES ".to_string();
@@ -36,7 +36,7 @@ pub async fn create_connections(
query = query.bind(param);
}
- query.execute(transaction.as_mut()).await?;
+ query.execute(transaction).await?;
Ok(())
}
@@ -95,7 +95,7 @@ mod tests {
//.collect();
let mut transaction = pool.begin().await?;
- create_connections(&mut transaction, connections).await?;
+ create_connections(transaction.as_mut(), connections).await?;
transaction.commit().await?;
let pair = sqlx::query!("SELECT user1, user2 FROM contacts_connections LIMIT 1")
@@ -117,7 +117,7 @@ mod tests {
// Insert in opposite order
let mut transaction = pool.begin().await?;
- create_connections(&mut transaction, connections).await?;
+ create_connections(transaction.as_mut(), connections).await?;
transaction.commit().await?;
let pair = sqlx::query!("SELECT user1, user2 FROM contacts_connections LIMIT 1")
@@ -191,7 +191,7 @@ mod tests {
.collect();
let mut transaction = pool.begin().await?;
- create_connections(&mut transaction, connections).await?;
+ create_connections(transaction.as_mut(), connections).await?;
transaction.commit().await?;
let result = sqlx::query!("SELECT count(*) as count FROM contacts_connections; ")
diff --git a/rust/cloud-storage/contacts_service/Cargo.toml b/rust/cloud-storage/contacts_service/Cargo.toml
index 2ec05f36f5..0a8ecbb1e9 100644
--- a/rust/cloud-storage/contacts_service/Cargo.toml
+++ b/rust/cloud-storage/contacts_service/Cargo.toml
@@ -17,20 +17,25 @@ path = "src/openapi.rs"
anyhow = { workspace = true }
async-trait = { workspace = true }
aws-sdk-secretsmanager = { workspace = true }
-macro_aws_config = { path = "../macro_aws_config" }
aws-sdk-sqs = { workspace = true }
axum = { workspace = true }
+axum-extra = { workspace = true }
connection_gateway_client = { path = "../connection_gateway_client" }
contacts_db_client = { path = "../contacts_db_client" }
http-body-util = { workspace = true }
macro_auth = { path = "../macro_auth" }
+macro_aws_config = { path = "../macro_aws_config" }
macro_cors = { path = "../macro_cors" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
"auth",
] }
+macro_user_id = { path = "../macro_user_id" }
model = { path = "../model" }
+model_user = { path = "../model_user", features = ["axum"] }
+rate_limit = { path = "../rate_limit", features = ["axum"] }
+redis = { workspace = true }
secretsmanager_client = { path = "../secretsmanager_client" }
serde = { workspace = true }
serde_json = { workspace = true }
@@ -47,3 +52,5 @@ mock = []
[dev-dependencies]
macro_auth = { path = "../macro_auth", features = ["testing"] }
+rate_limit = { path = "../rate_limit", features = ["axum", "testing"] }
+rootcause = { workspace = true }
diff --git a/rust/cloud-storage/contacts_service/src/api/context.rs b/rust/cloud-storage/contacts_service/src/api/context.rs
index b41b3f073f..1f9f22e72a 100644
--- a/rust/cloud-storage/contacts_service/src/api/context.rs
+++ b/rust/cloud-storage/contacts_service/src/api/context.rs
@@ -1,40 +1,20 @@
-use crate::{api::ContactsService, config::Config};
+use crate::{api::Service, config::Config};
use axum::extract::FromRef;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
+use rate_limit::{RateLimitServiceImpl, RedisRateLimitAdapter};
use secretsmanager_client::LocalOrRemoteSecret;
use sqlx::PgPool;
use std::sync::Arc;
+pub type RateLimiter = RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>;
+
#[derive(Clone, FromRef)]
pub struct AppState {
pub config: Arc<Config>,
pub db: PgPool,
pub jwt_args: JwtValidationArgs,
pub internal_api_secret: LocalOrRemoteSecret<InternalApiSecretKey>,
- pub contacts_service: Arc<dyn ContactsService>,
-}
-
-impl AppState {
- #[cfg(test)]
- pub fn new_testing() -> Self {
- use sqlx::postgres::PgPoolOptions;
-
- use crate::api::MockService;
-
- let db = PgPoolOptions::new()
- .max_connections(1)
- .connect_lazy("postgres://postgres:password@localhost/test_db")
- .expect("Failed to create mock pool");
-
- AppState {
- config: Arc::new(Config::new_testing()),
- db,
- jwt_args: JwtValidationArgs::new_testing(),
- internal_api_secret: LocalOrRemoteSecret::Local(InternalApiSecretKey::Comptime(
- "testing",
- )),
- contacts_service: Arc::new(MockService),
- }
- }
+ pub contacts_service: Arc<Service>,
+ pub rate_limit_service: RateLimiter,
}
diff --git a/rust/cloud-storage/contacts_service/src/api/mod.rs b/rust/cloud-storage/contacts_service/src/api/mod.rs
index 2d15e45800..9c2412dcc0 100644
--- a/rust/cloud-storage/contacts_service/src/api/mod.rs
+++ b/rust/cloud-storage/contacts_service/src/api/mod.rs
@@ -1,15 +1,19 @@
use crate::api::context::AppState;
use anyhow::Context;
-use async_trait::async_trait;
-use axum::extract::{Json, State};
+use axum::extract::{FromRequestParts, Json, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::routing::get;
-use axum::{Extension, Router};
-use model::user::UserContext;
+use axum::{RequestPartsExt, Router};
+use axum_extra::extract::Cached;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_user::axum_extractor::MacroUserExtractor;
+use rate_limit::inbound::{RateLimitExtractable, rate_limit_middleware};
+use rate_limit::{RateLimitConfig, RateLimitKey, RateLimitService};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use std::sync::Arc;
+use std::time::Duration;
use tracing::instrument;
use utoipa::{OpenApi, ToSchema};
use utoipa_swagger_ui::SwaggerUi;
@@ -43,23 +47,36 @@ pub struct GetContactsResponse {
contacts: Vec<String>,
}
-#[async_trait]
-pub trait ContactsService: Send + Sync + std::fmt::Debug + 'static {
- async fn query_contacts(&self, db: &PgPool, user_id: &str) -> Option<Vec<String>>;
+#[derive(Deserialize, Serialize, Debug, ToSchema)]
+pub struct AddContactRequest {
+ #[schema(value_type = String)]
+ user_id: MacroUserIdStr<'static>,
+}
+
+pub trait ContactsService: Send + Sync + 'static {
+ fn query_contacts(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Option<Vec<String>>> + Send;
+
+ fn add_contact(
+ &self,
+ caller: MacroUserIdStr<'_>,
+ recipient: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<(), anyhow::Error>> + Send;
}
#[cfg(test)]
#[derive(Clone, Debug)]
pub struct MockService;
-#[derive(Clone, Debug, Default)]
-pub struct Service;
+#[derive(Clone, Debug)]
+pub struct Service(pub PgPool);
#[cfg(test)]
-#[async_trait]
impl ContactsService for MockService {
- async fn query_contacts(&self, _db: &PgPool, user_id: &str) -> Option<Vec<String>> {
- if user_id == "a2b9b60f-a7f0-4bee-bcf1-0851eeec1c05" {
+ async fn query_contacts(&self, user_id: MacroUserIdStr<'_>) -> Option<Vec<String>> {
+ if user_id.as_ref() == "macro|[email protected]" {
let contacts = [
"0bcabd1a-1bf5-48d7-b334-5f7e59e8a9ff",
"3a90b186-0288-4819-8e1a-8e10cb685c0c",
@@ -70,7 +87,7 @@ impl ContactsService for MockService {
.collect();
return Some(contacts);
- } else if user_id == "ae2c090c-e478-4454-a001-3df458bf1fe4" {
+ } else if user_id.as_ref() == "macro|[email protected]" {
let contacts = [
"d44caada-98c0-49eb-ab20-6851b824983a",
"5ab8c770-f2cb-4c6c-bc08-ae64569e324c",
@@ -89,14 +106,34 @@ impl ContactsService for MockService {
None
}
+
+ async fn add_contact(
+ &self,
+ _caller: MacroUserIdStr<'_>,
+ _recipient: MacroUserIdStr<'_>,
+ ) -> Result<(), anyhow::Error> {
+ Ok(())
+ }
}
-#[async_trait]
impl ContactsService for Service {
- async fn query_contacts(&self, db: &PgPool, user_id: &str) -> Option<Vec<String>> {
- let contacts = contacts_db_client::get_contacts(db, user_id).await;
+ async fn query_contacts(&self, user_id: MacroUserIdStr<'_>) -> Option<Vec<String>> {
+ let contacts = contacts_db_client::get_contacts(&self.0, user_id.as_ref()).await;
contacts.ok()
}
+
+ async fn add_contact(
+ &self,
+ caller: MacroUserIdStr<'_>,
+ recipient: MacroUserIdStr<'_>,
+ ) -> Result<(), anyhow::Error> {
+ contacts_db_client::create_connections(
+ &self.0,
+ vec![(caller.as_ref().to_string(), recipient.as_ref().to_string())],
+ )
+ .await?;
+ Ok(())
+ }
}
#[utoipa::path(get,
@@ -109,15 +146,12 @@ impl ContactsService for Service {
(status = 404, body=String),
(status = 500, body=String)))
]
-#[instrument(skip(db, user_context), level = "info")]
-pub async fn handler(
- State(db): State<PgPool>,
- State(contacts): State<Arc<dyn ContactsService>>,
- user_context: Extension<UserContext>,
+#[instrument(skip(macro_user_id, contacts), level = "info", fields(user_id = macro_user_id.as_ref()))]
+pub async fn handler<S: ContactsService>(
+ State(contacts): State<Arc<S>>,
+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
) -> impl IntoResponse {
- let user_id = &user_context.user_id.to_lowercase();
- tracing::info!("retrieving contacts for user {}", user_id);
- let contacts = contacts.query_contacts(&db, user_id).await;
+ let contacts = contacts.query_contacts(macro_user_id).await;
if contacts.is_none() {
return (StatusCode::NOT_FOUND, Json(None));
}
@@ -127,53 +161,175 @@ pub async fn handler(
(StatusCode::OK, Json(Some(GetContactsResponse { contacts })))
}
+#[utoipa::path(post,
+ tag = "contacts",
+ operation_id = "add_contact",
+ path = "/contacts",
+ request_body = AddContactRequest,
+ responses(
+ (status = 204),
+ (status = 401, body=String),
+ (status = 500, body=String)))
+]
+#[instrument(skip(service, macro_user_id), err)]
+pub async fn add_contact_handler<S: ContactsService>(
+ State(service): State<Arc<S>>,
+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+ Json(body): Json<AddContactRequest>,
+) -> Result<StatusCode, StatusCode> {
+ service
+ .add_contact(macro_user_id, body.user_id)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "failed to create contact connection");
+ StatusCode::INTERNAL_SERVER_ERROR
+ })?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+/// Rate limit for adding contacts: 50 requests per user per hour.
+pub struct PerUserAddContactRateLimit(MacroUserExtractor);
+
+impl<S> RateLimitExtractable<S> for PerUserAddContactRateLimit
+where
+ S: Send + Sync,
+{
+ fn config() -> RateLimitConfig {
+ RateLimitConfig {
+ max_count: 50,
+ window: Duration::from_mins(60),
+ }
+ }
+
+ fn key(&self) -> RateLimitKey {
+ RateLimitKey::builder(&"per-user-add-contact")
+ .append(&self.0.macro_user_id.as_ref())
+ .finish()
+ }
+}
+
+impl<S> FromRequestParts<S> for PerUserAddContactRateLimit
+where
+ S: Send + Sync,
+{
+ type Rejection = <MacroUserExtractor as FromRequestParts<S>>::Rejection;
+
+ async fn from_request_parts(
+ parts: &mut axum::http::request::Parts,
+ state: &S,
+ ) -> Result<Self, Self::Rejection> {
+ let Cached(user): Cached<MacroUserExtractor> = parts.extract_with_state(state).await?;
+ Ok(Self(user))
+ }
+}
+
fn api_router(app_state: AppState) -> Router {
- contacts_router()
+ contacts_router(app_state.rate_limit_service.clone())
.layer(axum::middleware::from_fn_with_state(
app_state.jwt_args.clone(),
macro_middleware::auth::decode_jwt::handler,
))
- .with_state(app_state)
+ .with_state(app_state.contacts_service)
}
-#[cfg(test)]
-fn test_api_router() -> Router {
- contacts_router().with_state(AppState::new_testing())
-}
+fn contacts_router<R: RateLimitService + Clone, S: ContactsService>(
+ rate_limiter: R,
+) -> Router<Arc<S>> {
+ let post_route = Router::new()
+ .route("/contacts", axum::routing::post(add_contact_handler))
+ .layer(axum::middleware::from_fn_with_state(
+ rate_limiter,
+ rate_limit_middleware::<R, PerUserAddContactRateLimit, R>,
+ ));
-fn contacts_router() -> Router<AppState> {
- Router::new().route("/contacts", get(handler))
+ Router::new()
+ .route("/contacts", get(handler))
+ .merge(post_route)
}
#[cfg(test)]
mod tests {
use super::*;
- use axum::{
- body::Body,
- http::{Request, StatusCode},
- };
+ use axum::{Extension, body::Body, http::Request};
use http_body_util::BodyExt;
+ use model_user::UserContext;
+ use rate_limit::{
+ RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult, RateLimitServiceImpl,
+ domain::models::RateLimitOk,
+ };
+ use rootcause::Report;
use std::collections::HashSet;
use tower::ServiceExt;
- #[tokio::test]
- async fn test_get_contact() {
- let user_id = "a2b9b60f-a7f0-4bee-bcf1-0851eeec1c05";
- let api = test_api_router().layer(Extension(UserContext {
+ #[derive(Clone)]
+ struct MockRateLimitPort {
+ should_exceed: bool,
+ }
+
+ impl rate_limit::RateLimitPort for MockRateLimitPort {
+ async fn check(
+ &self,
+ key: RateLimitKey,
+ config: RateLimitConfig,
+ ) -> Result<RateLimitResult, Report> {
+ if self.should_exceed {
+ Ok(Err(RateLimitExceeded {
+ current_count: config.max_count.saturating_add(1),
+ max_count: config.max_count,
+ retry_after: config.window,
+ }))
+ } else {
+ Ok(Ok(RateLimitOk::new_testing_value(0, key, config)))
+ }
+ }
+
+ async fn decrement(&self, _key: &RateLimitKey) -> Result<(), Report> {
+ Ok(())
+ }
+ }
+
+ fn allowing_rate_limiter() -> RateLimitServiceImpl<MockRateLimitPort> {
+ RateLimitServiceImpl {
+ repo: MockRateLimitPort {
+ should_exceed: false,
+ },
+ }
+ }
+
+ fn exceeding_rate_limiter() -> RateLimitServiceImpl<MockRateLimitPort> {
+ RateLimitServiceImpl {
+ repo: MockRateLimitPort {
+ should_exceed: true,
+ },
+ }
+ }
+
+ fn mock_service() -> Arc<MockService> {
+ Arc::new(MockService)
+ }
+
+ fn test_user_context(user_id: &str) -> UserContext {
+ UserContext {
user_id: user_id.to_string(),
permissions: None,
organization_id: None,
fusion_user_id: "".to_string(),
- }));
+ }
+ }
- let contact_list: HashSet<String> = [
- "0bcabd1a-1bf5-48d7-b334-5f7e59e8a9ff",
- "3a90b186-0288-4819-8e1a-8e10cb685c0c",
- "e3cf7c46-60c9-413a-8f27-57c91c3297cf",
- ]
- .into_iter()
- .map(String::from)
- .collect();
+ fn build_test_router(
+ rate_limiter: RateLimitServiceImpl<MockRateLimitPort>,
+ user_id: &str,
+ ) -> Router {
+ contacts_router(rate_limiter)
+ .with_state(mock_service())
+ .layer(Extension(test_user_context(user_id)))
+ }
+
+ #[tokio::test]
+ async fn test_get_contact() {
+ let user_id = "macro|[email protected]";
+ let api = build_test_router(allowing_rate_limiter(), user_id);
let response = api
.oneshot(
@@ -188,8 +344,16 @@ mod tests {
let body = response.into_body().collect().await.unwrap().to_bytes();
let body: GetContactsResponse = serde_json::from_slice(&body).unwrap();
- assert_eq!(body.contacts.len(), 3, "Not enough contacts");
+ let contact_list: HashSet<String> = [
+ "0bcabd1a-1bf5-48d7-b334-5f7e59e8a9ff",
+ "3a90b186-0288-4819-8e1a-8e10cb685c0c",
+ "e3cf7c46-60c9-413a-8f27-57c91c3297cf",
+ ]
+ .into_iter()
+ .map(String::from)
+ .collect();
+ assert_eq!(body.contacts.len(), 3, "Not enough contacts");
for contact in &body.contacts {
assert!(
contact_list.contains(contact),
@@ -200,14 +364,9 @@ mod tests {
}
#[tokio::test]
- async fn test_get_contact_notfound() {
- let nonexistent_user_id = "d1eff0b9-e1d5-4fb5-a656-1a238323245c";
- let api = test_api_router().layer(Extension(UserContext {
- user_id: nonexistent_user_id.to_string(),
- permissions: None,
- organization_id: None,
- fusion_user_id: "".to_string(),
- }));
+ async fn test_get_contact_not_found() {
+ let user_id = "macro|[email protected]";
+ let api = build_test_router(allowing_rate_limiter(), user_id);
let response = api
.oneshot(
@@ -221,58 +380,62 @@ mod tests {
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
- async fn run_with_id(_pool: PgPool, user_id: &str) -> GetContactsResponse {
- let api = test_api_router().layer(Extension(UserContext {
- user_id: user_id.to_string(),
- permissions: None,
- organization_id: None,
- fusion_user_id: "".to_string(),
- }));
+ #[tokio::test]
+ async fn test_add_contact() {
+ let user_id = "macro|[email protected]";
+ let api = build_test_router(allowing_rate_limiter(), user_id);
let response = api
.oneshot(
Request::builder()
+ .method("POST")
.uri("/contacts")
- .body(Body::empty())
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::json!({"user_id": "macro|[email protected]"}).to_string(),
+ ))
.unwrap(),
)
.await
.unwrap();
- assert_eq!(response.status(), StatusCode::OK);
-
- let body = response.into_body().collect().await.unwrap().to_bytes();
- let body: GetContactsResponse = serde_json::from_slice(&body).unwrap();
- body
+ assert_eq!(response.status(), StatusCode::NO_CONTENT);
}
- // Some integration tests using an actual database query
- #[sqlx::test(fixtures(path = "../fixtures", scripts("user_list")))]
- // Skipped by default because you have to spin up a db,
- // Run with: `cargo test test_get_contacts_with_db -- --ignored`
- #[ignore]
- async fn test_integration_get_contacts_with_db(pool: PgPool) -> sqlx::Result<()> {
- let user_id = "51028bda-67f0-44df-aa21-5853963524f1";
- let body = run_with_id(pool.clone(), user_id).await;
- assert_eq!(body.contacts.len(), 3, "Not enough contacts");
- let expectations: HashSet<String> = [
- "1af59c26-c5b3-480c-9ad1-b87c2a69e72c",
- "80c0effd-1b9d-4eba-ad86-bc52c4a63294",
- "654df835-bb97-48e0-9b5b-0ad71a608dbd",
- ]
- .into_iter()
- .map(String::from)
- .collect();
-
- let reality: HashSet<String> = body.contacts.into_iter().collect();
+ #[tokio::test]
+ async fn test_add_contact_rate_limited() {
+ let user_id = "macro|[email protected]";
+ let api = build_test_router(exceeding_rate_limiter(), user_id);
- assert_eq!(&expectations, &reality);
+ let response = api
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/contacts")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::json!({"user_id": "macro|[email protected]"}).to_string(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
+ }
- // Now try it with a different case
- let user_id = "51028BDA-67F0-44DF-AA21-5853963524F1";
- let body = run_with_id(pool, user_id).await;
- let reality: HashSet<String> = body.contacts.into_iter().collect();
- assert_eq!(&expectations, &reality);
+ #[tokio::test]
+ async fn test_get_not_affected_by_rate_limit() {
+ let user_id = "macro|[email protected]";
+ let api = build_test_router(exceeding_rate_limiter(), user_id);
- Ok(())
+ let response = api
+ .oneshot(
+ Request::builder()
+ .uri("/contacts")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::OK);
}
}
diff --git a/rust/cloud-storage/contacts_service/src/api/swagger.rs b/rust/cloud-storage/contacts_service/src/api/swagger.rs
index 7d637c7ac2..06dd25c9c7 100644
--- a/rust/cloud-storage/contacts_service/src/api/swagger.rs
+++ b/rust/cloud-storage/contacts_service/src/api/swagger.rs
@@ -1,6 +1,6 @@
use utoipa::OpenApi;
-use super::GetContactsResponse;
+use super::{AddContactRequest, GetContactsResponse};
#[derive(OpenApi)]
#[openapi(
@@ -9,10 +9,12 @@ use super::GetContactsResponse;
),
paths(
super::handler,
+ super::add_contact_handler,
),
components(
schemas(
- GetContactsResponse
+ GetContactsResponse,
+ AddContactRequest,
),
),
tags(
diff --git a/rust/cloud-storage/contacts_service/src/config.rs b/rust/cloud-storage/contacts_service/src/config.rs
index 8565b7570c..3dbaf00feb 100644
--- a/rust/cloud-storage/contacts_service/src/config.rs
+++ b/rust/cloud-storage/contacts_service/src/config.rs
@@ -8,6 +8,8 @@ pub struct Config {
pub environment: Environment,
/// The connection URL for the Postgres database this application should use.
pub database_url: String,
+ /// The Redis URI for rate limiting.
+ pub redis_uri: String,
/// SQS URL
pub queue_url: String,
/// The notification queue max messages per poll
@@ -28,6 +30,8 @@ impl Config {
let database_url =
std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let redis_uri = std::env::var("REDIS_URI").context("REDIS_URI must be provided")?;
+
let queue_url =
std::env::var("CONTACTS_QUEUE").context("CONTACTS_QUEUE must be provided")?;
@@ -49,6 +53,7 @@ impl Config {
port,
environment,
database_url,
+ redis_uri,
queue_url,
queue_wait_time_seconds,
queue_max_messages,
@@ -62,6 +67,7 @@ impl Config {
port: 0,
environment: Environment::Local,
database_url: "".to_string(),
+ redis_uri: "".to_string(),
queue_url: "".to_string(),
queue_max_messages: 0,
queue_wait_time_seconds: 0,
diff --git a/rust/cloud-storage/contacts_service/src/main.rs b/rust/cloud-storage/contacts_service/src/main.rs
index 2c2fec8e6a..8ac05d2f6a 100644
--- a/rust/cloud-storage/contacts_service/src/main.rs
+++ b/rust/cloud-storage/contacts_service/src/main.rs
@@ -13,6 +13,7 @@ use contacts_service::queue::MessageQueue;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
+use rate_limit::{RateLimitServiceImpl, RedisRateLimitAdapter};
use secretsmanager_client::SecretManager;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
@@ -84,12 +85,22 @@ async fn main() -> anyhow::Result<()> {
JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)
.await?;
+ let redis_client =
+ redis::Client::open(config.redis_uri.as_str()).context("failed to create redis client")?;
+
+ let rate_limit_service = RateLimitServiceImpl {
+ repo: RedisRateLimitAdapter {
+ redis: redis_client,
+ },
+ };
+
api::setup_and_serve(AppState {
config: Arc::new(config),
- db,
+ db: db.clone(),
jwt_args,
internal_api_secret,
- contacts_service: Arc::new(Service),
+ contacts_service: Arc::new(Service(db)),
+ rate_limit_service,
})
.await?;
Ok(())
diff --git a/rust/cloud-storage/contacts_service/src/queue.rs b/rust/cloud-storage/contacts_service/src/queue.rs
index 84c4abeff3..9440766a90 100644
--- a/rust/cloud-storage/contacts_service/src/queue.rs
+++ b/rust/cloud-storage/contacts_service/src/queue.rs
@@ -85,7 +85,7 @@ async fn connections_message_handler(conmsg: &ConnectionsMessage, queue: &Messag
.into_iter()
.map(|e| (e.a.data.id.to_string(), e.b.data.id.to_string()))
.collect();
- let _ = create_connections(&mut transaction, connection_pairs.clone())
+ let _ = create_connections(transaction.as_mut(), connection_pairs.clone())
.await
.inspect_err(|e| {
tracing::error!("couldn't create connections: {:?}", e);
@@ -103,7 +103,7 @@ async fn add_participants_handler(body: &AddParticipantsMessageBody, queue: &Mes
let db = &queue.db;
let connection_pairs = add_participants(body).await;
let mut transaction = db.begin().await.unwrap();
- let _ = create_connections(&mut transaction, connection_pairs.clone())
+ let _ = create_connections(transaction.as_mut(), connection_pairs.clone())
.await
.inspect_err(|e| {
tracing::error!("couldn't create connections: {:?}", e);
@@ -122,7 +122,7 @@ async fn create_group_handler(body: &CreateGroupMessageBody, queue: &MessageQueu
let db = &queue.db;
let connection_pairs = create_group(body).await;
let mut transaction = db.begin().await.unwrap();
- let _ = create_connections(&mut transaction, connection_pairs.clone())
+ let _ = create_connections(transaction.as_mut(), connection_pairs.clone())
.await
.inspect_err(|e| {
tracing::error!("couldn't create connections: {:?}", e);
@@ -269,15 +269,8 @@ pub async fn add_user_to_group(group: &[String], user: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
- use sqlx::PgPool;
use std::collections::HashSet;
- async fn sqs_dummy() -> SQSWorker {
- let config = macro_aws_config::get_macro_aws_config().await;
- let client = aws_sdk_sqs::Client::new(&config);
- SQSWorker::new(client, "nothing".to_string(), 1, 1)
- }
-
#[test]
fn test_deserialize_connections_message() {
let input_json = include_str!("../tests/fixtures/add_connection.json");
@@ -370,46 +363,6 @@ mod tests {
assert_eq!(body.connections.len(), 0);
}
- #[sqlx::test]
- #[ignore]
- async fn test_connections_message_handler(pool: PgPool) -> sqlx::Result<()> {
- let input_json = include_str!("../tests/fixtures/connections_message.json");
-
- let message: Message = message_from_json(input_json).unwrap();
- let db = pool.clone();
- let sqs = sqs_dummy().await;
- let queue = MessageQueue::new(sqs, db, None);
- match message {
- Message::AddConnection(con) => connections_message_handler(&con, &queue).await,
- _ => panic!("Message not matched properly"),
- };
- let user = "AE2C090C-E478-4454-A001-3DF458BF1FE4";
- let contacts = contacts_db_client::get_contacts(&pool, user).await;
- assert!(contacts.is_ok());
- let contacts = contacts.unwrap();
- dbg!(&contacts);
- assert_eq!(contacts.len(), 7);
-
- let expectations: HashSet<String> = [
- "FF038D36-1AEF-461A-8AA8-34001FA1ABAD",
- "C3F4D826-F8FD-478A-AA66-B5B6BB370CBC",
- "D44CAADA-98C0-49EB-AB20-6851B824983A",
- "5AB8C770-F2CB-4C6C-BC08-AE64569E324C",
- "79A5557B-7827-4E2E-A6AE-F0935CDB762E",
- "C3B1970F-18EE-4DFA-B5FB-E8240E28E51D",
- "9EFFE035-BB12-4FCC-B479-800E1C2551A8",
- ]
- .into_iter()
- .map(String::from)
- .collect();
-
- let reality: HashSet<String> = contacts.into_iter().collect();
-
- assert_eq!(&expectations, &reality);
-
- Ok(())
- }
-
#[tokio::test]
async fn test_add_participants_message_body() {
// The full group: it's assumed the participants are in here already
@@ -434,72 +387,6 @@ mod tests {
assert_eq!(connections.len(), expected_nconnections);
}
- async fn add_participants_handler_tester(
- pool: PgPool,
- body: AddParticipantsMessageBody,
- ) -> sqlx::Result<()> {
- let message: Message = Message::AddParticipants(body);
- let db = pool.clone();
- let sqs = sqs_dummy().await;
- let queue = MessageQueue::new(sqs, db, None);
- match message {
- Message::AddParticipants(body) => add_participants_handler(&body, &queue).await,
- _ => panic!("Message not matched properly"),
- };
-
- let user = "ringo";
- let contacts = contacts_db_client::get_contacts(&pool, user).await;
-
- assert!(contacts.is_ok());
- let contacts = contacts.unwrap();
- dbg!(&contacts);
-
- assert_eq!(contacts.len(), 3);
-
- let expectations: HashSet<String> = ["john", "paul", "george"]
- .into_iter()
- .map(String::from)
- .collect();
-
- let reality: HashSet<String> = contacts.into_iter().collect();
-
- assert_eq!(&expectations, &reality);
-
- Ok(())
- }
-
- #[sqlx::test]
- #[ignore]
- async fn test_integration_add_participants_handler(pool: PgPool) -> sqlx::Result<()> {
- let group = ["paul", "john", "ringo", "george"];
- let participants = ["ringo", "george"];
-
- let body = AddParticipantsMessageBody {
- group: group.into_iter().map(String::from).collect(),
- participants: participants.into_iter().map(String::from).collect(),
- group_id: None,
- };
- add_participants_handler_tester(pool, body).await
- }
-
- // Add participants to the group, but the participants aren't in the group yet
- #[sqlx::test]
- #[ignore]
- async fn test_integration_add_participants_handler_pre_participants(
- pool: PgPool,
- ) -> sqlx::Result<()> {
- let group = ["paul", "john"];
- let participants = ["ringo", "george"];
-
- let body = AddParticipantsMessageBody {
- group: group.into_iter().map(String::from).collect(),
- participants: participants.into_iter().map(String::from).collect(),
- group_id: None,
- };
-
- add_participants_handler_tester(pool, body).await
- }
-
#[tokio::test]
async fn test_create_group_message_body() {
let group = ["paul", "john", "ringo", "george"];
@@ -517,46 +404,6 @@ mod tests {
assert_eq!(connections.len(), expected_nconnections);
}
- #[sqlx::test]
- #[ignore]
- async fn test_integration_create_group_handler(pool: PgPool) -> sqlx::Result<()> {
- let group = ["paul", "john", "ringo", "george"];
-
- let body = CreateGroupMessageBody {
- group: group.into_iter().map(String::from).collect(),
- group_id: None,
- };
-
- let message: Message = Message::CreateGroup(body);
- let db = pool.clone();
- let sqs = sqs_dummy().await;
- let queue = MessageQueue::new(sqs, db, None);
- match message {
- Message::CreateGroup(body) => create_group_handler(&body, &queue).await,
- _ => panic!("Message not matched properly"),
- };
-
- let user = "paul";
- let contacts = contacts_db_client::get_contacts(&pool, user).await;
-
- assert!(contacts.is_ok());
- let contacts = contacts.unwrap();
- dbg!(&contacts);
-
- assert_eq!(contacts.len(), 3);
-
- let expectations: HashSet<String> = ["john", "ringo", "george"]
- .into_iter()
- .map(String::from)
- .collect();
-
- let reality: HashSet<String> = contacts.into_iter().collect();
-
- assert_eq!(&expectations, &reality);
-
- Ok(())
- }
-
#[tokio::test]
async fn test_add_participants_lowercase() {
// full group, including new participants