Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(foreign_entity): create router and wire to dss (#3646)
Will Hutchinsona529e00b6998
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/foreignEntity.ts b/js/app/packages/service-clients/service-storage/generated/schemas/foreignEntity.tsnew file mode 100644index 0000000000..53853e6e73--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/foreignEntity.ts@@ -0,0 +1,28 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * A persisted mapping to an entity owned by an external system.+ */+export interface ForeignEntity {+ /** Timestamp when the record was created. */+ createdAt: string;+ /** Identifier assigned by the external system. */+ foreignEntityId: string;+ /** Source system that owns the external identifier. */+ foreignEntitySource: string;+ /** Internal primary key for this foreign entity record. */+ id: string;+ /** Arbitrary metadata stored with the mapping. */+ metadata: unknown;+ /** Internal auth entity namespace this foreign entity is stored for. */+ storedForAuthEntity: string;+ /** Internal entity identifier this foreign entity is stored for. */+ storedForId: string;+ /** Timestamp when the record was last updated. */+ updatedAt: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex 760e27a989..4bdd5a3a6a 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -443,6 +443,7 @@ export * from './fileTypeUpdate';export * from './fileTypeUpdateOneOf';export * from './folderItem';export * from './folderItemFileType';+export * from './foreignEntity';export * from './foreignEntityFilters';export * from './genericErrorResponse';export * from './genericResponse';diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex d82a6c6af7..28512b25b0 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -5191,6 +5191,46 @@ export const getEntityPermissionResponse = zod]).describe('API response envelope for entity permissions.');+/**+ * @summary Get a visible foreign entity by its internal ID.+ */+export const getForeignEntityParams = zod.object({+ id: zod.uuid().describe('Foreign entity ID'),+});++export const getForeignEntityResponse = zod+ .object({+ createdAt: zod.iso+ .datetime({})+ .describe('Timestamp when the record was created.'),+ foreignEntityId: zod+ .string()+ .describe('Identifier assigned by the external system.'),+ foreignEntitySource: zod+ .string()+ .describe('Source system that owns the external identifier.'),+ id: zod+ .uuid()+ .describe('Internal primary key for this foreign entity record.'),+ metadata: zod+ .unknown()+ .describe('Arbitrary metadata stored with the mapping.'),+ storedForAuthEntity: zod+ .string()+ .describe(+ 'Internal auth entity namespace this foreign entity is stored for.'+ ),+ storedForId: zod+ .string()+ .describe(+ 'Internal entity identifier this foreign entity is stored for.'+ ),+ updatedAt: zod.iso+ .datetime({})+ .describe('Timestamp when the record was last updated.'),+ })+ .describe('A persisted mapping to an entity owned by an external system.');+/*** @summary Gets the users history*/diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex b38a9c6ab9..429ca031a5 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -5918,6 +5918,77 @@}}},+ "/foreign_entity/{id}": {+ "get": {+ "tags": ["foreign_entity"],+ "summary": "Get a visible foreign entity by its internal ID.",+ "operationId": "get_foreign_entity",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "Foreign entity ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForeignEntity"+ }+ }+ }+ },+ "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"+ }+ }+ }+ }+ }+ }+ },"/github/install-sync": {"get": {"tags": ["github::inbound::github_sync_router"],@@ -12573,6 +12644,56 @@}}},+ "ForeignEntity": {+ "type": "object",+ "description": "A persisted mapping to an entity owned by an external system.",+ "required": [+ "id",+ "foreignEntityId",+ "foreignEntitySource",+ "metadata",+ "storedForId",+ "storedForAuthEntity",+ "createdAt",+ "updatedAt"+ ],+ "properties": {+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "description": "Timestamp when the record was created."+ },+ "foreignEntityId": {+ "type": "string",+ "description": "Identifier assigned by the external system."+ },+ "foreignEntitySource": {+ "type": "string",+ "description": "Source system that owns the external identifier."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Internal primary key for this foreign entity record."+ },+ "metadata": {+ "description": "Arbitrary metadata stored with the mapping."+ },+ "storedForAuthEntity": {+ "type": "string",+ "description": "Internal auth entity namespace this foreign entity is stored for."+ },+ "storedForId": {+ "type": "string",+ "description": "Internal entity identifier this foreign entity is stored for."+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "description": "Timestamp when the record was last updated."+ }+ }+ },"ForeignEntityFilters": {"type": "object","description": "Filters for foreign entity records.",diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex f0acbda2af..cc74bb3cad 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -4461,18 +4461,25 @@ name = "foreign_entity"version = "0.1.0"dependencies = ["anyhow",+ "axum","chrono",+ "entity_access","filter_ast",+ "http-body-util","item_filters","macro_db_migrator",+ "macro_user_id","macro_uuid",+ "model-error-response","models_pagination","serde","serde_json","sqlx","thiserror 2.0.18","tokio",+ "tower 0.5.3","tracing",+ "utoipa","uuid",]diff --git a/rust/cloud-storage/README.md b/rust/cloud-storage/README.mdindex dfb51bc5fd..b8eb86ba2d 100644--- a/rust/cloud-storage/README.md+++ b/rust/cloud-storage/README.md@@ -74,3 +74,4 @@ shacleantrigger --triggers worker to cleanup unused bom parts--> shacleanworkercache --> shacleanworkershacleanworker --> doc_storage```+diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 10d98dd8fb..4ac1934e54 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -56,7 +56,7 @@ dynamodb_client = { path = "../dynamodb_client" }email = { path = "../email", features = ["outbound", "ports"] }entity_access = { path = "../entity_access", features = ["inbound", "schema"] }entity_access_management = { path = "../entity_access_management" }-foreign_entity = { path = "../foreign_entity" }+foreign_entity = { path = "../foreign_entity", features = ["inbound"] }frecency = { path = "../frecency", features = ["postgres"] }futures = { workspace = true }github = { path = "../github", default-features = false, features = [diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 0dee6c6fed..083e704092 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -50,7 +50,7 @@ use email::{};use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};use foreign_entity::{- domain::service::ForeignEntityServiceImpl,+ domain::service::ForeignEntityServiceImpl, inbound::axum_router::ForeignEntityRouterState,outbound::pg_foreign_entity_repo::PgForeignEntityRepo,};use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};@@ -267,6 +267,10 @@ pub(crate) type DssCallInternalState = InternalCallRouterState<DssCallService>;/// Type alias for the foreign entity service.pub(crate) type ForeignEntityServiceType = ForeignEntityServiceImpl<PgForeignEntityRepo>;+/// Type alias for the foreign entity router state.+pub(crate) type DssForeignEntityState =+ ForeignEntityRouterState<ForeignEntityServiceType, EntityAccessService>;+/// Type alias for the github sync service.pub(crate) type GithubSyncServiceType = GithubSyncServiceImpl<DocumentService,@@ -291,6 +295,7 @@ pub(crate) struct ApiContext {pub dynamodb_client: Arc<DynamodbClient>,pub dynamo_db: aws_sdk_dynamodb::Client,pub soup_router_state: DssSoupState,+ pub foreign_entity_state: DssForeignEntityState,pub sqs_client: Arc<sqs_client::SQS>,pub contacts_ingress: Arc<SqsContactsIngress<SqsContactsQueue>>,pub notification_ingress_service: Arc<NotificationIngressType>,diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rsindex d96017b680..eb58d73502 100644--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs@@ -211,6 +211,12 @@ fn api_router(state: ApiContext) -> Router {"/channels",channels::inbound::axum_router::channels_router(state.channels_state.clone()),)+ .nest(+ "/foreign_entity",+ foreign_entity::inbound::axum_router::foreign_entity_router(+ state.foreign_entity_state.clone(),+ ),+ ).nest("/call",call::inbound::axum_router::call_router(state.call_state.clone()),diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex 5e158214f0..0bca087d46 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -76,6 +76,7 @@ use documents_hex::inbound::axum_router::{edit_document::EditDocumentResponse, get_branch_name::BranchNameResponse,get_short_id::ShortIdResponse,};+use foreign_entity::domain::models::ForeignEntity;use model::document::response::{CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData,DocumentResponseMetadata,@@ -262,6 +263,9 @@ use utoipa::OpenApi;entity::get_entity_permission::handler,+ // foreign_entity+ foreign_entity::inbound::axum_router::get_foreign_entity_handler,+// threadsthreads::edit_thread::edit_thread_handler,@@ -367,6 +371,7 @@ use utoipa::OpenApi;SoupChat,SoupProject,SoupForeignEntity,+ ForeignEntity,SoupApiSort,SoupPage,SoupEnrichedEmailThreadPreview,diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 57de74a723..88450cc1eb 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -60,7 +60,7 @@ use email::{outbound::EmailPgRepo,};use foreign_entity::{- domain::service::ForeignEntityServiceImpl,+ domain::service::ForeignEntityServiceImpl, inbound::axum_router::ForeignEntityRouterState,outbound::pg_foreign_entity_repo::PgForeignEntityRepo,};use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};@@ -406,11 +406,16 @@ async fn main() -> anyhow::Result<()> {sync_app_client_id: config.vars.github_sync_app_client_id.to_string(),},document_service.clone(),- foreign_entity_service,+ foreign_entity_service.clone(),PgGithubSyncRepo::new(db.clone()),GithubSyncClientImpl::default(),);+ let foreign_entity_state = ForeignEntityRouterState::new(+ foreign_entity_service.clone(),+ entity_access_service.clone(),+ );+// Cal.com webhooks → Meta Lead events. Both secrets are loaded here// (rather than on Config) to keep cal/Meta wiring colocated.let cal_webhook_secret = secretsmanager_client@@ -593,6 +598,7 @@ async fn main() -> anyhow::Result<()> {entity_access_service.clone(),),github_sync_service: Arc::new(github_sync_service_impl),+ foreign_entity_state,db: db.clone(),readonly_db: readonly_pool::ReadOnlyPool(readonly_db.clone()),redis_client: Arc::new(Redis::new(redis_client)),diff --git a/rust/cloud-storage/foreign_entity/Cargo.toml b/rust/cloud-storage/foreign_entity/Cargo.tomlindex 26862e0354..55fa24d01a 100644--- a/rust/cloud-storage/foreign_entity/Cargo.toml+++ b/rust/cloud-storage/foreign_entity/Cargo.toml@@ -6,16 +6,26 @@ version = "0.1.0"[features]default = ["outbound", "ports", "service"]+inbound = [+ "dep:axum",+ "dep:model-error-response",+ "dep:utoipa",+ "entity_access/inbound",+ "ports",+]outbound = ["dep:filter_ast", "dep:sqlx", "ports"]-ports = ["dep:item_filters", "dep:models_pagination", "dep:tokio"]+ports = ["dep:entity_access", "dep:item_filters", "dep:models_pagination", "dep:tokio"]service = ["ports"][dependencies]anyhow = { workspace = true }+axum = { workspace = true, optional = true }chrono = { workspace = true }+entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["ports"] }filter_ast = { path = "../filter_ast", optional = true }item_filters = { path = "../item_filters", optional = true }macro_uuid = { path = "../macro_uuid" }+model-error-response = { path = "../model-error-response", optional = true }models_pagination = { path = "../models_pagination", optional = true }serde = { workspace = true }serde_json = { workspace = true }@@ -23,8 +33,12 @@ sqlx = { workspace = true, optional = true }thiserror = { workspace = true }tokio = { workspace = true, optional = true }tracing = { workspace = true }+utoipa = { workspace = true, optional = true }uuid = { workspace = true }[dev-dependencies]+http-body-util = { workspace = true }macro_db_migrator = { path = "../macro_db_migrator" }+macro_user_id = { path = "../macro_user_id" }tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }+tower = { workspace = true }diff --git a/rust/cloud-storage/foreign_entity/src/domain/models.rs b/rust/cloud-storage/foreign_entity/src/domain/models.rsindex 8df5009955..f5b9b4a595 100644--- a/rust/cloud-storage/foreign_entity/src/domain/models.rs+++ b/rust/cloud-storage/foreign_entity/src/domain/models.rs@@ -6,6 +6,7 @@ use uuid::Uuid;/// Identifies an internal source that can grant access to foreign entities.#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Hash)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]#[serde(rename_all = "camelCase")]pub struct SourceId {/// Internal entity identifier, stored in `foreign_entity.stored_for_id`.@@ -41,6 +42,7 @@ impl SourceId {/// A persisted mapping to an entity owned by an external system.#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]#[serde(rename_all = "camelCase")]pub struct ForeignEntity {/// Internal primary key for this foreign entity record.@@ -63,6 +65,7 @@ pub struct ForeignEntity {/// Fields required to create a foreign entity record.#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]#[serde(rename_all = "camelCase")]pub struct CreateForeignEntity {/// Identifier assigned by the external system.@@ -80,6 +83,7 @@ pub struct CreateForeignEntity {/// Optional fields for patching a foreign entity record.#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Default, PartialEq)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]#[serde(rename_all = "camelCase")]pub struct PatchForeignEntity {/// New external identifier. `None` leaves the current value unchanged.diff --git a/rust/cloud-storage/foreign_entity/src/domain/ports.rs b/rust/cloud-storage/foreign_entity/src/domain/ports.rsindex 70c5388339..97e0b45bbe 100644--- a/rust/cloud-storage/foreign_entity/src/domain/ports.rs+++ b/rust/cloud-storage/foreign_entity/src/domain/ports.rs@@ -4,6 +4,7 @@use std::future::Future;+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};use item_filters::ast::{LiteralTree, foreign_entity::ForeignEntityLiteral};use models_pagination::{Query, SimpleSortMethod};use uuid::Uuid;@@ -77,6 +78,12 @@ pub trait ForeignEntityRepository: Send + Sync + 'static {/// The service owns validation, ID generation, and mapping repository misses to/// domain errors.pub trait ForeignEntityService: Send + Sync + 'static {+ /// Fetch an authorized foreign entity record using an access receipt.+ fn get_foreign_entity(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> impl Future<Output = Result<ForeignEntity, ForeignEntityError>> + Send;+/// Fetch a foreign entity record by its internal primary key.fn get_foreign_entity_by_id(&self,diff --git a/rust/cloud-storage/foreign_entity/src/domain/service.rs b/rust/cloud-storage/foreign_entity/src/domain/service.rsindex cc6b9a5506..eefc8e9dc6 100644--- a/rust/cloud-storage/foreign_entity/src/domain/service.rs+++ b/rust/cloud-storage/foreign_entity/src/domain/service.rs@@ -3,6 +3,7 @@#[cfg(test)]mod tests;+use entity_access::domain::models::{EntityAccessReceipt, EntityType, ViewAccessLevel};use uuid::Uuid;use super::models::{@@ -30,6 +31,28 @@ impl<R> ForeignEntityService for ForeignEntityServiceImpl<R>whereR: ForeignEntityRepository,{+ #[tracing::instrument(err, skip(self))]+ async fn get_foreign_entity(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ let entity = receipt.entity();+ if entity.entity_type != EntityType::ForeignEntity {+ return Err(ForeignEntityError::BadRequest(format!(+ "expected ForeignEntity receipt, got {:?}",+ entity.entity_type+ )));+ }++ let id = Uuid::parse_str(&entity.entity_id).map_err(|_| {+ ForeignEntityError::BadRequest(+ "foreign entity receipt id must be a valid UUID".to_string(),+ )+ })?;++ self.get_foreign_entity_by_id(id).await+ }+#[tracing::instrument(err, skip(self))]async fn get_foreign_entity_by_id(&self,diff --git a/rust/cloud-storage/foreign_entity/src/domain/service/tests.rs b/rust/cloud-storage/foreign_entity/src/domain/service/tests.rsindex 43a7da57fd..35c6e65f37 100644--- a/rust/cloud-storage/foreign_entity/src/domain/service/tests.rs+++ b/rust/cloud-storage/foreign_entity/src/domain/service/tests.rs@@ -2,6 +2,7 @@ use std::collections::HashMap;use std::sync::{Arc, Mutex};use chrono::{DateTime, Utc};+use entity_access::domain::models::{EntityAccessReceipt, EntityType, ViewAccessLevel};use models_pagination::{Query, SimpleSortMethod};use serde_json::json;use uuid::Uuid;@@ -210,6 +211,17 @@ fn listing_query(sort_method: SimpleSortMethod) -> ForeignEntityListQuery {Query::Sort(sort_method, None)}+fn foreign_entity_receipt(entity_id: &str) -> EntityAccessReceipt<ViewAccessLevel> {+ receipt_for_type(entity_id, EntityType::ForeignEntity)+}++fn receipt_for_type(+ entity_id: &str,+ entity_type: EntityType,+) -> EntityAccessReceipt<ViewAccessLevel> {+ EntityAccessReceipt::dangerously_assert_internal_user(entity_id, entity_type)+}+fn assert_bad_request(error: ForeignEntityError, expected_message: &str) {let ForeignEntityError::BadRequest(message) = error else {panic!("expected bad request error, got {error:?}");@@ -253,6 +265,60 @@ async fn create_persists_foreign_entity_with_generated_id() {assert_eq!(fetched, created);}+#[tokio::test]+async fn get_foreign_entity_returns_matching_record_from_receipt() {+ let service = service();+ let created = service+ .create_foreign_entity(valid_create())+ .await+ .expect("valid foreign entity should be created");++ let fetched = service+ .get_foreign_entity(foreign_entity_receipt(&created.id.to_string()))+ .await+ .expect("created foreign entity should be fetched by receipt");++ assert_eq!(fetched, created);+}++#[tokio::test]+async fn get_foreign_entity_missing_row_returns_not_found() {+ let service = service();+ let id = Uuid::new_v4();++ let error = service+ .get_foreign_entity(foreign_entity_receipt(&id.to_string()))+ .await+ .expect_err("missing foreign entity should return not found");++ assert_not_found(error, id);+}++#[tokio::test]+async fn get_foreign_entity_rejects_invalid_uuid_receipt() {+ let service = service();++ let error = service+ .get_foreign_entity(foreign_entity_receipt("not-a-uuid"))+ .await+ .expect_err("invalid receipt UUID should be rejected");++ assert_bad_request(error, "valid UUID");+}++#[tokio::test]+async fn get_foreign_entity_rejects_wrong_entity_type_receipt() {+ let service = service();+ let id = Uuid::new_v4();++ let error = service+ .get_foreign_entity(receipt_for_type(&id.to_string(), EntityType::Document))+ .await+ .expect_err("wrong receipt entity type should be rejected");++ assert_bad_request(error, "ForeignEntity");+}+#[tokio::test]async fn get_by_foreign_entity_id_returns_all_matching_records() {let service = service();diff --git a/rust/cloud-storage/foreign_entity/src/inbound/axum_router.rs b/rust/cloud-storage/foreign_entity/src/inbound/axum_router.rsnew file mode 100644index 0000000000..3206e17b4c--- /dev/null+++ b/rust/cloud-storage/foreign_entity/src/inbound/axum_router.rs@@ -0,0 +1,137 @@+//! Axum router for foreign entity endpoints.++#[cfg(test)]+mod tests;++use std::sync::Arc;++use axum::{+ Json, Router,+ extract::{FromRef, State},+ http::StatusCode,+ response::IntoResponse,+ routing::get,+};+use entity_access::{+ domain::{models::ViewAccessLevel, ports::EntityAccessService},+ inbound::axum_extractors::ForeignEntityAccessLevelExtractor,+};+use model_error_response::ErrorResponse;++use crate::domain::{+ models::{ForeignEntity, ForeignEntityError},+ ports::ForeignEntityService,+};++/// Router state for authenticated foreign entity operations.+pub struct ForeignEntityRouterState<S, AccessSvc> {+ service: Arc<S>,+ access_service: Arc<AccessSvc>,+}++impl<S, AccessSvc> Clone for ForeignEntityRouterState<S, AccessSvc> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ access_service: self.access_service.clone(),+ }+ }+}++impl<S, AccessSvc> ForeignEntityRouterState<S, AccessSvc>+where+ S: ForeignEntityService,+ AccessSvc: EntityAccessService,+{+ /// Create router state from shared service references.+ pub fn new(service: Arc<S>, access_service: Arc<AccessSvc>) -> Self {+ Self {+ service,+ access_service,+ }+ }+}++impl<S, AccessSvc> FromRef<ForeignEntityRouterState<S, AccessSvc>> for Arc<AccessSvc> {+ fn from_ref(state: &ForeignEntityRouterState<S, AccessSvc>) -> Self {+ state.access_service.clone()+ }+}++/// Build the authenticated foreign entity router.+///+/// Routes:+/// - `GET /{id}` — get a visible foreign entity by its internal ID.+pub fn foreign_entity_router<S, AccessSvc, T>(+ state: ForeignEntityRouterState<S, AccessSvc>,+) -> Router<T>+where+ S: ForeignEntityService,+ AccessSvc: EntityAccessService,+ T: Send + Sync + 'static,+{+ Router::new()+ .route("/{id}", get(get_foreign_entity_handler::<S, AccessSvc>))+ .with_state(state)+}++/// Get a visible foreign entity by its internal ID.+#[utoipa::path(+ get,+ tag = "foreign_entity",+ operation_id = "get_foreign_entity",+ path = "/foreign_entity/{id}",+ params(+ ("id" = uuid::Uuid, Path, description = "Foreign entity ID")+ ),+ responses(+ (status = 200, body = ForeignEntity),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn get_foreign_entity_handler<S, AccessSvc>(+ State(state): State<ForeignEntityRouterState<S, AccessSvc>>,+ access: ForeignEntityAccessLevelExtractor<ViewAccessLevel, AccessSvc>,+) -> Result<Json<ForeignEntity>, ForeignEntityError>+where+ S: ForeignEntityService,+ AccessSvc: EntityAccessService,+{+ let foreign_entity = state+ .service+ .get_foreign_entity(access.entity_access_receipt)+ .await?;++ Ok(Json(foreign_entity))+}++impl IntoResponse for ForeignEntityError {+ fn into_response(self) -> axum::response::Response {+ let status_code = match &self {+ ForeignEntityError::NotFound(_) => StatusCode::NOT_FOUND,+ ForeignEntityError::BadRequest(_) => StatusCode::BAD_REQUEST,+ ForeignEntityError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ if status_code.is_server_error() {+ tracing::error!(error=?self, "internal server error");+ }++ let message = match &self {+ ForeignEntityError::Internal(_) => "internal server error".to_string(),+ error => error.to_string(),+ };++ (+ status_code,+ Json(ErrorResponse {+ message: message.into(),+ }),+ )+ .into_response()+ }+}diff --git a/rust/cloud-storage/foreign_entity/src/inbound/axum_router/tests.rs b/rust/cloud-storage/foreign_entity/src/inbound/axum_router/tests.rsnew file mode 100644index 0000000000..453b7e0c3c--- /dev/null+++ b/rust/cloud-storage/foreign_entity/src/inbound/axum_router/tests.rs@@ -0,0 +1,334 @@+use std::sync::{Arc, Mutex};++use axum::{+ Router,+ body::Body,+ http::{Method, Request, StatusCode},+ response::Response,+};+use chrono::{DateTime, Utc};+use entity_access::{+ domain::{+ models::{+ AccessError, AccessLevel, CallChannelInfo, EntityAccessReceipt, EntityPermission,+ EntityType, RequiredPermission, UserTeamInfo, ViewAccessLevel,+ },+ ports::EntityAccessService,+ },+ inbound::axum_extractors::InternalUser,+};+use http_body_util::BodyExt;+use macro_user_id::{+ lowercased::Lowercase,+ user_id::{MacroUserId, MacroUserIdStr},+};+use serde_json::{Value, json};+use tower::ServiceExt;+use uuid::Uuid;++use super::{ForeignEntityRouterState, foreign_entity_router};+use crate::domain::{+ models::{+ CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity, SourceId,+ },+ ports::{ForeignEntityListQuery, ForeignEntityService},+};++#[derive(Clone)]+struct StubForeignEntityService {+ response: StubForeignEntityResponse,+ receipt_entity_ids: Arc<Mutex<Vec<String>>>,+}++#[derive(Clone)]+enum StubForeignEntityResponse {+ Entity(ForeignEntity),+ NotFound(Uuid),+}++impl StubForeignEntityService {+ fn entity(entity: ForeignEntity) -> Self {+ Self::new(StubForeignEntityResponse::Entity(entity))+ }++ fn not_found(id: Uuid) -> Self {+ Self::new(StubForeignEntityResponse::NotFound(id))+ }++ fn new(response: StubForeignEntityResponse) -> Self {+ Self {+ response,+ receipt_entity_ids: Arc::new(Mutex::new(Vec::new())),+ }+ }++ fn receipt_entity_ids(&self) -> Vec<String> {+ self.receipt_entity_ids+ .lock()+ .expect("stub foreign entity service receipt lock poisoned")+ .clone()+ }+}++impl ForeignEntityService for StubForeignEntityService {+ async fn get_foreign_entity(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ let entity = receipt.entity();+ if entity.entity_type != EntityType::ForeignEntity {+ return Err(ForeignEntityError::BadRequest(format!(+ "expected ForeignEntity receipt, got {:?}",+ entity.entity_type+ )));+ }++ self.receipt_entity_ids+ .lock()+ .expect("stub foreign entity service receipt lock poisoned")+ .push(entity.entity_id.clone());++ match &self.response {+ StubForeignEntityResponse::Entity(entity) => Ok(entity.clone()),+ StubForeignEntityResponse::NotFound(id) => Err(ForeignEntityError::NotFound(*id)),+ }+ }++ async fn get_foreign_entity_by_id(+ &self,+ _id: Uuid,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ unreachable!("router must call the receipt-based get_foreign_entity method")+ }++ async fn get_foreign_entities_by_foreign_entity_id(+ &self,+ _foreign_entity_id: &str,+ _foreign_entity_source: Option<&str>,+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {+ unreachable!("router does not list foreign entities by external ID")+ }++ async fn get_foreign_entities_for_user(+ &self,+ _source_ids: Vec<SourceId>,+ _limit: u32,+ _query: ForeignEntityListQuery,+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {+ unreachable!("router does not list foreign entities")+ }++ async fn create_foreign_entity(+ &self,+ _create: CreateForeignEntity,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ unreachable!("router does not create foreign entities")+ }++ async fn delete_foreign_entity(&self, _id: Uuid) -> Result<(), ForeignEntityError> {+ unreachable!("router does not delete foreign entities")+ }++ async fn patch_foreign_entity(+ &self,+ _id: Uuid,+ _patch: PatchForeignEntity,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ unreachable!("router does not patch foreign entities")+ }+}++#[derive(Clone)]+struct NoopEntityAccessService;++impl EntityAccessService for NoopEntityAccessService {+ async fn generate_entity_access_receipt<T: RequiredPermission>(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ _user_org_id: Option<i64>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ unreachable!("InternalUser extension should bypass real access receipt generation")+ }++ async fn get_access_level(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Option<AccessLevel>, AccessError> {+ unreachable!("InternalUser extension should bypass real access checks")+ }++ async fn check_access(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ unreachable!("InternalUser extension should bypass real access checks")+ }++ async fn check_public_access(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ unreachable!("InternalUser extension should bypass real access checks")+ }++ async fn get_entity_permission(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _user_org_id: Option<i64>,+ ) -> Result<EntityPermission, AccessError> {+ unreachable!("InternalUser extension should bypass real access checks")+ }++ async fn get_users_by_entity(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ unreachable!("foreign entity router does not list entity users")+ }++ async fn get_call_channel(+ &self,+ _call_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ unreachable!("foreign entity router does not resolve call channels")+ }++ async fn get_call_channel_by_channel_id(+ &self,+ _channel_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ unreachable!("foreign entity router does not resolve call channels")+ }++ async fn get_user_team(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ ) -> Result<Option<UserTeamInfo>, AccessError> {+ unreachable!("foreign entity router does not resolve user teams")+ }+}++fn test_router(service: Arc<StubForeignEntityService>) -> Router {+ foreign_entity_router(ForeignEntityRouterState::new(+ service,+ Arc::new(NoopEntityAccessService),+ ))+}++fn internal_get(uri: impl Into<String>) -> Request<Body> {+ let mut request = Request::builder()+ .method(Method::GET)+ .uri(uri.into())+ .body(Body::empty())+ .expect("test request should be built");++ request.extensions_mut().insert(InternalUser {+ access_level: AccessLevel::Owner,+ });++ request+}++async fn response_json(response: Response) -> Value {+ let bytes = response+ .into_body()+ .collect()+ .await+ .expect("response body should be collected")+ .to_bytes();++ serde_json::from_slice(bytes.as_ref()).expect("response body should be JSON")+}++fn fixed_time(value: &str) -> DateTime<Utc> {+ DateTime::parse_from_rfc3339(value)+ .expect("fixture timestamp should be valid")+ .with_timezone(&Utc)+}++fn foreign_entity(id: Uuid) -> ForeignEntity {+ ForeignEntity {+ id,+ foreign_entity_id: "github:pull-request:123".to_string(),+ foreign_entity_source: "github_pull_request".to_string(),+ metadata: json!({ "repository": "macro/app", "number": 123 }),+ stored_for_id: "document-123".to_string(),+ stored_for_auth_entity: "document".to_string(),+ created_at: fixed_time("2026-05-29T14:00:00Z"),+ updated_at: fixed_time("2026-05-29T15:00:00Z"),+ }+}++fn expected_foreign_entity_json(entity: &ForeignEntity) -> Value {+ json!({+ "id": entity.id.to_string(),+ "foreignEntityId": entity.foreign_entity_id,+ "foreignEntitySource": entity.foreign_entity_source,+ "metadata": entity.metadata,+ "storedForId": entity.stored_for_id,+ "storedForAuthEntity": entity.stored_for_auth_entity,+ "createdAt": serde_json::to_value(&entity.created_at).expect("created_at should serialize"),+ "updatedAt": serde_json::to_value(&entity.updated_at).expect("updated_at should serialize"),+ })+}++#[tokio::test]+async fn get_foreign_entity_returns_camel_case_json_and_forwards_receipt_id() {+ let id = Uuid::new_v4();+ let entity = foreign_entity(id);+ let service = Arc::new(StubForeignEntityService::entity(entity.clone()));+ let response = test_router(service.clone())+ .oneshot(internal_get(format!("/{id}")))+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ response_json(response).await,+ expected_foreign_entity_json(&entity)+ );+ assert_eq!(service.receipt_entity_ids(), vec![id.to_string()]);+}++#[tokio::test]+async fn get_foreign_entity_rejects_invalid_uuid() {+ let service = Arc::new(StubForeignEntityService::entity(foreign_entity(+ Uuid::new_v4(),+ )));+ let response = test_router(service.clone())+ .oneshot(internal_get("/not-a-uuid"))+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ assert!(service.receipt_entity_ids().is_empty());+}++#[tokio::test]+async fn get_foreign_entity_maps_not_found_to_404() {+ let id = Uuid::new_v4();+ let service = Arc::new(StubForeignEntityService::not_found(id));+ let response = test_router(service.clone())+ .oneshot(internal_get(format!("/{id}")))+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::NOT_FOUND);+ assert_eq!(+ response_json(response).await["message"],+ format!("foreign entity not found: {id}")+ );+ assert_eq!(service.receipt_entity_ids(), vec![id.to_string()]);+}diff --git a/rust/cloud-storage/foreign_entity/src/inbound/mod.rs b/rust/cloud-storage/foreign_entity/src/inbound/mod.rsnew file mode 100644index 0000000000..fbe9ab2003--- /dev/null+++ b/rust/cloud-storage/foreign_entity/src/inbound/mod.rs@@ -0,0 +1,4 @@+//! Inbound adapters for foreign entity APIs.++/// Axum router for foreign entity endpoints.+pub mod axum_router;diff --git a/rust/cloud-storage/foreign_entity/src/lib.rs b/rust/cloud-storage/foreign_entity/src/lib.rsindex 09c179a631..e8fc94fda7 100644--- a/rust/cloud-storage/foreign_entity/src/lib.rs+++ b/rust/cloud-storage/foreign_entity/src/lib.rs@@ -12,5 +12,9 @@pub mod domain;+/// Inbound adapters for serving foreign entity APIs.+#[cfg(feature = "inbound")]+pub mod inbound;+#[cfg(feature = "outbound")]pub mod outbound;diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rsindex 68f7c123aa..3681042aed 100644--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs@@ -21,7 +21,7 @@ use documents::domain::{},};use entity_access::domain::models::{- EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,+ EditAccessLevel, EntityAccessReceipt, EntityType, OwnerAccessLevel, ViewAccessLevel,};use foreign_entity::domain::{models::{@@ -513,6 +513,22 @@ impl GithubSyncClient for StubSyncClient {}}+fn foreign_entity_id_from_receipt(+ receipt: EntityAccessReceipt<ViewAccessLevel>,+) -> Result<uuid::Uuid, ForeignEntityError> {+ let entity = receipt.entity();+ if entity.entity_type != EntityType::ForeignEntity {+ return Err(ForeignEntityError::BadRequest(format!(+ "expected ForeignEntity receipt, got {:?}",+ entity.entity_type+ )));+ }++ uuid::Uuid::parse_str(&entity.entity_id).map_err(|_| {+ ForeignEntityError::BadRequest("foreign entity receipt id must be a valid UUID".to_string())+ })+}+struct StubForeignEntityService {foreign_entities: Mutex<Vec<ForeignEntity>>,create_calls: Mutex<Vec<CreateForeignEntity>>,@@ -542,6 +558,14 @@ impl StubForeignEntityService {}impl ForeignEntityService for StubForeignEntityService {+ async fn get_foreign_entity(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ let id = foreign_entity_id_from_receipt(receipt)?;+ self.get_foreign_entity_by_id(id).await+ }+async fn get_foreign_entity_by_id(&self,id: uuid::Uuid,diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rsindex 2e95f66b3c..cb5cba6add 100644--- a/rust/cloud-storage/soup/src/domain/service/tests.rs+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs@@ -5,6 +5,7 @@ use chrono::{DateTime, Utc};use comms::domain::models::GetChannelsRequest;use cool_asserts::assert_matches;use email::domain::models::{EnrichedEmailThreadPreview, PreviewView};+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};use filter_ast::Expr;use foreign_entity::domain::{models::{@@ -85,12 +86,35 @@ impl CallRecordQueryService for NoopCallRecordQueryService {}}+fn foreign_entity_id_from_receipt(+ receipt: EntityAccessReceipt<ViewAccessLevel>,+) -> Result<Uuid, ForeignEntityError> {+ let entity = receipt.entity();+ if entity.entity_type != EntityType::ForeignEntity {+ return Err(ForeignEntityError::BadRequest(format!(+ "expected ForeignEntity receipt, got {:?}",+ entity.entity_type+ )));+ }++ Uuid::parse_str(&entity.entity_id).map_err(|_| {+ ForeignEntityError::BadRequest("foreign entity receipt id must be a valid UUID".to_string())+ })+}use crm::domain::service::NoOpCrmService;#[derive(Clone)]struct NoopForeignEntityService;impl ForeignEntityService for NoopForeignEntityService {+ async fn get_foreign_entity(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ let id = foreign_entity_id_from_receipt(receipt)?;+ self.get_foreign_entity_by_id(id).await+ }+async fn get_foreign_entity_by_id(&self,id: Uuid,@@ -203,6 +227,14 @@ impl RecordingForeignEntityService {}impl ForeignEntityService for RecordingForeignEntityService {+ async fn get_foreign_entity(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<ForeignEntity, ForeignEntityError> {+ let id = foreign_entity_id_from_receipt(receipt)?;+ self.get_foreign_entity_by_id(id).await+ }+async fn get_foreign_entity_by_id(&self,id: Uuid,