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(documents): hex crate (#1488)

Will Hutchinson35a427c99b1a
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/getDocumentLocationV3Params.ts b/js/app/packages/service-clients/service-storage/generated/schemas/getDocumentLocationV3Params.ts
new file mode 100644
index 0000000000..6ba2727921
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/getDocumentLocationV3Params.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type GetDocumentLocationV3Params = {
+ /**
+ * A specific document version id to get the location for.
+ */
+ document_version_id?: number;
+ /**
+ * If true, this will return the converted docx url.
+ */
+ get_converted_docx_url?: boolean;
+};
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.ts
index 6820e529c7..19d020d6f1 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
@@ -312,6 +312,7 @@ export * from './getDocumentListResultCreatedAt';
export * from './getDocumentListResultDocumentFamilyId';
export * from './getDocumentListResultFileType';
export * from './getDocumentListResultUpdatedAt';
+export * from './getDocumentLocationV3Params';
export * from './getDocumentPermissionsResponseDataV2';
export * from './getDocumentProcessingResult';
export * from './getDocumentProcessingResultResponse';
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index 42feb2175e..c0ddf20d5d 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -1691,7 +1691,8 @@ export const getBatchPreviewHandlerResponse = zod.object({
});
/**
- * @summary Gets a particular document by its id
+ * Returns document metadata, user access level, and view location.
+ * @summary Handler for `GET /documents/:document_id`.
*/
export const getDocumentParams = zod.object({
document_id: zod.string().describe('Document ID'),
@@ -1929,18 +1930,15 @@ export const saveDocumentHandlerResponse = zod.object({
});
/**
- * @summary Deletes a specific document.
-The document will be soft deleted and appear in the user's trash for 30 days.
+ * Soft-deletes a document (only owners can delete).
+ * @summary Handler for `DELETE /documents/:document_id`.
*/
-export const deleteDocumentHandlerParams = zod.object({
+export const deleteDocumentParams = zod.object({
document_id: zod.string().describe('Document ID'),
});
-export const deleteDocumentHandlerResponse = zod.object({
- data: zod.object({
- success: zod.boolean().describe('Indicates if the request was successful'),
- }),
- error: zod.boolean().describe('Indicates if an error occurred'),
+export const deleteDocumentResponse = zod.object({
+ success: zod.boolean().describe('Indicates if the request was successful'),
});
/**
@@ -2136,6 +2134,25 @@ export const getLocationHandlerResponse = zod.union([
.describe('The presigned urls of the docx bom parts if it is a docx'),
]);
+/**
+ * Returns a presigned URL or sync service content for accessing the document.
+ * @summary Handler for `GET /documents/:document_id/location_v3`.
+ */
+export const getDocumentLocationV3Params = zod.object({
+ document_id: zod.string().describe('Document ID'),
+});
+
+export const getDocumentLocationV3QueryParams = zod.object({
+ document_version_id: zod
+ .number()
+ .optional()
+ .describe('A specific document version id to get the location for.'),
+ get_converted_docx_url: zod
+ .boolean()
+ .optional()
+ .describe('If true, this will return the converted docx url.'),
+});
+
/**
* @summary Permanently deletes a document.
*/
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 939780d3a7..7c32ac5df0 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -1370,7 +1370,8 @@
"/documents/{document_id}": {
"get": {
"tags": ["document"],
- "summary": "Gets a particular document by its id",
+ "summary": "Handler for `GET /documents/:document_id`.",
+ "description": "Returns document metadata, user access level, and view location.",
"operationId": "get_document",
"parameters": [
{
@@ -1399,7 +1400,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -1409,7 +1410,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -1419,7 +1420,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -1506,8 +1507,9 @@
},
"delete": {
"tags": ["document"],
- "summary": "Deletes a specific document.\nThe document will be soft deleted and appear in the user's trash for 30 days.",
- "operationId": "delete_document_handler",
+ "summary": "Handler for `DELETE /documents/:document_id`.",
+ "description": "Soft-deletes a document (only owners can delete).",
+ "operationId": "delete_document",
"parameters": [
{
"name": "document_id",
@@ -1525,7 +1527,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/SuccessResponse"
+ "$ref": "#/components/schemas/GenericSuccessResponse"
}
}
}
@@ -1535,7 +1537,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -1545,7 +1547,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -1555,7 +1557,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -1822,6 +1824,89 @@
}
}
},
+ "/documents/{document_id}/location_v3": {
+ "get": {
+ "tags": ["document"],
+ "summary": "Handler for `GET /documents/:document_id/location_v3`.",
+ "description": "Returns a presigned URL or sync service content for accessing the document.",
+ "operationId": "get_document_location_v3",
+ "parameters": [
+ {
+ "name": "document_id",
+ "in": "path",
+ "description": "Document ID",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "document_version_id",
+ "in": "query",
+ "description": "A specific document version id to get the location for.",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "format": "int64"
+ }
+ },
+ {
+ "name": "get_converted_docx_url",
+ "in": "query",
+ "description": "If true, this will return the converted docx url.",
+ "required": false,
+ "schema": {
+ "type": "boolean"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "410": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/documents/{document_id}/permanent": {
"delete": {
"tags": ["document"],
diff --git a/js/app/packages/service-clients/service-storage/service.ts b/js/app/packages/service-clients/service-storage/service.ts
index ad5acdfddd..8b58add12d 100644
--- a/js/app/packages/service-clients/service-storage/service.ts
+++ b/js/app/packages/service-clients/service-storage/service.ts
@@ -347,11 +347,11 @@ export const StorageService = new Svc('Document++ Storage Service API')
throws: withFetchErrors(),
})
.fn('deleteDocument', {
- description: schemas.deleteDocumentHandlerResponse.description!,
+ description: schemas.deleteDocumentResponse.description!,
args: {
- documentId: schemas.deleteDocumentHandlerParams.shape.document_id,
+ documentId: schemas.deleteDocumentParams.shape.document_id,
},
- result: schemas.deleteDocumentHandlerResponse.shape.data.shape,
+ result: schemas.deleteDocumentResponse.shape,
modifies: true,
access: { exclude: ['ai'] },
throws: withFetchErrors(),
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index a786348f9b..aa35eb6065 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2765,6 +2765,7 @@ dependencies = [
"connection_gateway",
"cool_asserts",
"document_sub_type",
+ "documents",
"dynamodb_client",
"email",
"entity_access",
@@ -2884,6 +2885,40 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "documents"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "axum",
+ "axum-extra",
+ "chrono",
+ "cloudfront_sign",
+ "document_sub_type",
+ "entity_access",
+ "futures",
+ "http-body-util",
+ "macro_db_migrator",
+ "macro_project_utils",
+ "macro_user_id",
+ "mockall",
+ "model",
+ "model-error-response",
+ "model_user",
+ "models_permissions",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "sync_service_client",
+ "thiserror 2.0.17",
+ "tokio",
+ "tower 0.5.2",
+ "tracing",
+ "urlencoding",
+ "utoipa",
+ "uuid",
+]
+
[[package]]
name = "docx_unzip_handler"
version = "0.1.0"
@@ -5203,8 +5238,6 @@ name = "macro_project_utils"
version = "0.1.0"
dependencies = [
"anyhow",
- "macro_db_client",
- "model",
"sqlx",
"tokio",
"tracing",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 4ec08699ba..ee9a73da58 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -26,6 +26,7 @@ members = [
"document_storage_service",
"document_storage_service_client",
"document_sub_type",
+ "documents",
"document_text_extractor",
"docx_unzip_handler",
"dynamodb_client",
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index 37733bd4c2..7793343d86 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -48,6 +48,7 @@ channels = { path = "../channels", features = ["inbound", "outbound"] }
comms = { path = "../comms", features = ["outbound"] }
connection_gateway = { path = "../connection_gateway" }
document_sub_type = { path = "../document_sub_type" }
+documents_hex = { path = "../documents", package = "documents" }
dynamodb_client = { path = "../dynamodb_client" }
entity_access = { path = "../entity_access", features = ["schema"] }
email = { path = "../email", features = ["outbound", "ports"] }
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index ec838576dc..9a09fef0f8 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -11,6 +11,9 @@ use comms::{
};
use comms_service::CommsHandlerState;
use connection_gateway_client::client::ConnectionGatewayClient;
+use documents_hex::domain::service::DocumentServiceImpl;
+use documents_hex::inbound::axum_router::DocumentRouterState;
+use documents_hex::outbound::pg_document_repo::PgDocumentRepo;
use dynamodb_client::DynamodbClient;
use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
@@ -63,6 +66,10 @@ type PropertiesService = PropertiesServiceImpl<
/// Type alias for the entity access service.
pub(crate) type EntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;
+/// Type alias for the documents router state.
+pub(crate) type DocumentsState =
+ DocumentRouterState<DocumentServiceImpl<PgDocumentRepo>, EntityAccessService>;
+
/// Type alias for the ChannelServiceImpl used by comms
pub(crate) type CommsChannelService =
ChannelServiceImpl<PgCommsRepo, UserRepoImpl, FrecencyPgStorage>;
@@ -98,6 +105,7 @@ pub(crate) struct ApiContext {
pub permissions_token_secret:
LocalOrRemoteSecret<comms_service::DocumentPermissionJwtSecretKey>,
pub entity_access_service: Arc<EntityAccessService>,
+ pub documents_state: DocumentsState,
pub channels_state: DssChannelsState,
}
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs b/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs
index c1aab5bb81..6dca09d999 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs
@@ -13,86 +13,14 @@ use model::response::{
};
use model::user::UserContext;
use models_permissions::share_permission::access_level::OwnerAccessLevel;
-use properties::PropertiesService;
use serde::Deserialize;
use sqs_client::search::{SearchQueueMessage, document::DocumentId};
-use uuid::Uuid;
#[derive(Deserialize)]
pub struct Params {
pub document_id: String,
}
-/// Deletes a specific document.
-/// The document will be soft deleted and appear in the user's trash for 30 days.
-#[utoipa::path(
- tag = "document",
- delete,
- path = "/documents/{document_id}",
- params(
- ("document_id" = String, Path, description = "Document ID")
- ),
- responses(
- (status = 200, body=SuccessResponse),
- (status = 401, body=GenericErrorResponse),
- (status = 404, body=GenericErrorResponse),
- (status = 500, body=GenericErrorResponse),
- )
- )]
-#[tracing::instrument(skip(state, user_context), fields(user_id=?user_context.user_id))]
-pub async fn delete_document_handler(
- access: DocumentAccessExtractor<OwnerAccessLevel>,
- State(state): State<ApiContext>,
- user_context: Extension<UserContext>,
- Path(Params { document_id }): Path<Params>,
- doc: Extension<DocumentBasic>,
-) -> impl IntoResponse {
- tracing::info!("delete document");
-
- // soft delete the document, this will remove the history and pins and mark the document as deleted
- if let Err(e) = macro_db_client::document::soft_delete_document(&state.db, &document_id).await {
- tracing::error!(error=?e, document_id=?document_id, "unable to soft delete document");
- return GenericResponse::builder()
- .message("unable to delete document")
- .is_error(true)
- .send(StatusCode::INTERNAL_SERVER_ERROR);
- }
-
- // Unlink task parent/subtasks if this is a task (no-op for non-tasks)
- if let Ok(task_id) = Uuid::parse_str(&document_id) {
- if let Err(e) = state
- .properties_service
- .link_parent_task(task_id, None)
- .await
- {
- tracing::warn!(error = ?e, "failed to unlink parent task on delete");
- }
- if let Err(e) = state
- .properties_service
- .link_subtasks(task_id, vec![])
- .await
- {
- tracing::warn!(error = ?e, "failed to unlink subtasks on delete");
- }
- }
-
- let response_data = GenericSuccessResponse { success: true };
-
- macro_project_utils::update_project_modified(
- &state.db,
- macro_project_utils::ProjectModifiedArgs {
- project_id: doc.project_id.clone(),
- old_project_id: None,
- user_id: user_context.user_id.clone(),
- },
- )
- .await;
-
- GenericResponse::builder()
- .data(&response_data)
- .send(StatusCode::OK)
-}
-
/// Permanently deletes a document.
#[utoipa::path(
tag = "document",
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/get_document.rs b/rust/cloud-storage/document_storage_service/src/api/documents/get_document.rs
index d31f7ca101..c8a6200474 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/get_document.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/get_document.rs
@@ -1,101 +1,13 @@
-use axum::{
- Extension, Json,
- extract::{Path, State},
- http::StatusCode,
- response::IntoResponse,
-};
-use macro_db_client::{
- document::get_document, user_document_view_location::get::get_user_document_view_location,
-};
-use macro_middleware::cloud_storage::ensure_access::document::DocumentAccessExtractor;
-use model::{
- document::{
- DocumentBasic,
- response::{GetDocumentResponse, GetDocumentResponseData},
- },
- response::GenericErrorResponse,
- user::UserContext,
-};
-use models_permissions::share_permission::access_level::ViewAccessLevel;
+use axum::{Extension, Json, extract::Path, http::StatusCode, response::IntoResponse};
+use model::document::DocumentBasic;
+use model::response::GenericErrorResponse;
use serde::Deserialize;
-use sqlx::PgPool;
-
-use crate::api::middleware::internal_access::InternalUser;
#[derive(Deserialize)]
pub struct Params {
pub document_id: String,
}
-/// Gets a particular document by its id
-#[utoipa::path(
- tag = "document",
- get,
- path = "/documents/{document_id}",
- operation_id = "get_document",
- params(
- ("document_id" = String, Path, description = "Document ID")
- ),
- responses(
- (status = 200, body=GetDocumentResponse),
- (status = 401, body=GenericErrorResponse),
- (status = 404, body=GenericErrorResponse),
- (status = 500, body=GenericErrorResponse),
- )
- )]
-#[tracing::instrument(skip(db, user_context, access), fields(user_id=?user_context.user_id))]
-pub async fn handler(
- State(db): State<PgPool>,
- access: axum_extra::either::Either<
- DocumentAccessExtractor<ViewAccessLevel>,
- Option<Extension<InternalUser>>,
- >,
- user_context: Extension<UserContext>,
- Path(Params { document_id }): Path<Params>,
-) -> Result<Json<GetDocumentResponse>, StatusCode> {
- let access_level = match access {
- axum_extra::either::Either::E1(DocumentAccessExtractor { access_level, .. }) => {
- access_level
- }
- axum_extra::either::Either::E2(Some(Extension(InternalUser { access_level }))) => {
- access_level
- }
- axum_extra::either::Either::E2(None) => return Err(StatusCode::UNAUTHORIZED),
- };
-
- let document_metadata = match get_document(&db, &document_id).await {
- Ok(document_metadata) => document_metadata,
- Err(e) => {
- tracing::error!(document_id=?document_id, error=?e, "unable to get document metadata");
- let mut status_code = StatusCode::INTERNAL_SERVER_ERROR;
- if e.to_string()
- .contains("no rows returned by a query that expected to return at least one row")
- {
- status_code = StatusCode::NOT_FOUND;
- }
- return Err(status_code);
- }
- };
-
- let view_location =
- match get_user_document_view_location(&db, &user_context.user_id, &document_id).await {
- Ok(view_location) => view_location,
- Err(e) => {
- tracing::error!(error=?e, "error getting view location");
- return Err(StatusCode::INTERNAL_SERVER_ERROR);
- }
- };
-
- Ok(Json(GetDocumentResponse {
- error: false,
- data: GetDocumentResponseData {
- document_metadata,
- user_access_level: access_level,
- view_location: view_location.map(|v| v.location),
- },
- }))
-}
-
/// Gets the basic document info for a document id.
#[utoipa::path(
tag = "document",
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/location.rs b/rust/cloud-storage/document_storage_service/src/api/documents/location.rs
index 655dd45c94..f7446ec4fa 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/location.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/location.rs
@@ -17,15 +17,13 @@ use axum::{
body::Body,
extract::{Path, Query, State},
http::{Response, StatusCode},
- response::{IntoResponse, Response as AxumResponse},
+ response::IntoResponse,
};
use cloudfront_sign::{SignedOptions, get_signed_url};
-use futures::{FutureExt, pin_mut, select};
use model::{
document::{
CONVERTED_DOCUMENT_FILE_NAME, DocumentBasic, FileType, FileTypeExt,
- build_cloud_storage_bucket_document_key,
- response::{LocationResponseData, LocationResponseV3},
+ build_cloud_storage_bucket_document_key, response::LocationResponseData,
},
response::{GenericErrorResponse, GenericResponse, PresignedUrl},
user::UserContext,
@@ -38,144 +36,6 @@ pub struct Params {
static DOCUMENT_DOES_NOT_EXIST: &str = "document does not exist in s3";
-/// Attempts to retrieve metadata from sync service using optimized concurrent exists/metadata checks
-async fn try_get_from_sync_service(
- sync_service_client: &sync_service_client::SyncServiceClient,
- document_id: &str,
-) -> Result<Option<model::sync_service::DocumentMetadata>, anyhow::Error> {
- let exists_fut = sync_service_client.exists(document_id).fuse();
- let metadata_fut = sync_service_client.get_metadata(document_id).fuse();
-
- pin_mut!(exists_fut, metadata_fut);
-
- // Use select to handle whichever completes first for better performance
- select! {
- exists_result = exists_fut => {
- match exists_result {
- Ok(false) => Ok(None),
- Ok(true) | Err(_) => {
- metadata_fut.await.map(Some)
- }
- }
- },
- metadata_result = metadata_fut => {
- match metadata_result {
- Ok(metadata) => Ok(Some(metadata)),
- Err(e) => {
- match exists_fut.await {
- Ok(false) => Ok(None),
- _ => Err(e),
- }
- }
- }
- }
- }
-}
-
-#[utoipa::path(
- tag = "document",
- get,
- path = "/documents/{document_id}/location_v3",
- params(
- ("document_id" = String, Path, description = "Document ID"),
- ("document_version_id" = i64, Query, description = "A specific document version id to get the location for."),
- ("get_converted_docx_url" = bool, Query, description = "If true, this will return the converted docx url.")
- ),
- responses(
- (status = 200, body=LocationResponseV3),
- (status = 401, body=GenericErrorResponse),
- (status = 404, body=GenericErrorResponse),
- (status = 410, body=GenericErrorResponse),
- (status = 500, body=GenericErrorResponse),
- )
-)]
-#[tracing::instrument(skip(user_context, document_context, state, _access), fields(user_id=?user_context.user_id))]
-pub async fn get_location_handler_v3(
- _access: DocumentAccessExtractor<ViewAccessLevel>,
- State(state): State<ApiContext>,
- user_context: Extension<UserContext>,
- Extension(document_context): Extension<DocumentBasic>,
- Path(Params { document_id }): Path<Params>,
- Query(params): Query<LocationQueryParams>,
-) -> AxumResponse {
- let file_type = document_context.try_file_type();
-
- let make_result = |response: anyhow::Result<LocationResponseV3>| {
- let response_data: LocationResponseV3 = match response {
- Ok(response_data) => response_data,
- Err(e) => {
- tracing::error!(error=?e, "unable to get document location");
- let status_code = if e.to_string() == DOCUMENT_DOES_NOT_EXIST {
- tracing::error!("document does not exist in s3");
- StatusCode::GONE
- } else {
- StatusCode::INTERNAL_SERVER_ERROR
- };
- return GenericResponse::builder()
- .message("unable to get document location")
- .is_error(true)
- .send(status_code);
- }
- };
-
- let max_age = state
- .config
- .document_storage_service_presigned_url_browser_cache_expiry_seconds;
-
- Response::builder()
- .status(StatusCode::OK)
- .header(reqwest::header::CONTENT_TYPE, "application/json")
- .header("Cache-Control", format!("max-age={}", max_age))
- .header(
- "X-custom-response-uuid",
- macro_uuid::generate_uuid_v7().to_string(),
- ) // this is used to verify if a response is cached between requests
- .body(Body::from(serde_json::to_vec(&response_data).unwrap()))
- .unwrap()
- };
-
- // do sync service check for markdown files
- if matches!(file_type, Some(FileType::Md)) {
- match try_get_from_sync_service(&state.sync_service_client, &document_id).await {
- Ok(Some(sync_service_metadata)) => {
- let data = LocationResponseV3::SyncServiceContent {
- metadata: document_context,
- sync_service_metadata,
- };
- return make_result(Ok(data)).into_response();
- }
- Ok(None) => {
- // Document doesn't exist in sync service, continue to check S3
- }
- Err(e) => {
- tracing::error!(error=?e, "sync service failed");
- return StatusCode::INTERNAL_SERVER_ERROR.into_response();
- }
- }
- }
-
- let response_data = get_presigned_url_by_type(
- &state,
- document_context.owner.as_ref(),
- &document_id,
- file_type,
- params.document_version_id,
- params.get_converted_docx_url.unwrap_or(false),
- )
- .await
- .map(|response| match response {
- LocationResponseData::PresignedUrl(url) => LocationResponseV3::PresignedUrl {
- presigned_url: url,
- metadata: document_context,
- },
- LocationResponseData::PresignedUrls(urls) => LocationResponseV3::PresignedUrls {
- presigned_urls: urls,
- metadata: document_context,
- },
- });
- make_result(response_data).into_response()
-}
-
/// Gets the presigned url(s) for the document. aka location
#[utoipa::path(
tag = "document",
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs b/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs
index 4c3808194e..ca0d4f5e8b 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs
@@ -117,10 +117,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
"/:document_id/location",
get(location::get_location_handler).layer(ensure_document_exists_middleware.clone()),
)
- .route(
- "/:document_id/location_v3",
- get(location::get_location_handler_v3).layer(ensure_document_exists_middleware.clone()),
- )
+ // NOTE: /:document_id/location_v3 is now served by the documents hex crate router
.route(
"/:document_id/text",
get(get_document_text::handler).layer(ensure_document_exists_middleware.clone()),
@@ -148,10 +145,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
)),
),
)
- .route(
- "/:document_id",
- get(get_document::handler).layer(ensure_document_exists_middleware.clone()),
- )
+ // NOTE: GET /:document_id is now served by the documents hex crate router
.route(
"/:document_id/views",
get(get_document_views::get_document_views_handler)
@@ -185,11 +179,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
"/:document_id/simple_save",
put(simple_save::handler).layer(ensure_document_exists_middleware.clone()),
)
- .route(
- "/:document_id",
- delete(delete_document::delete_document_handler)
- .layer(ensure_document_exists_middleware.clone()),
- )
+ // NOTE: DELETE /:document_id is now served by the documents hex crate router
.route(
"/:document_id/permanent",
delete(delete_document::permanently_delete_document_handler)
diff --git a/rust/cloud-storage/document_storage_service/src/api/entity/get_entity_permission.rs b/rust/cloud-storage/document_storage_service/src/api/entity/get_entity_permission.rs
index b5f952b245..5cd174dcce 100644
--- a/rust/cloud-storage/document_storage_service/src/api/entity/get_entity_permission.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/entity/get_entity_permission.rs
@@ -38,7 +38,7 @@ pub async fn handler(
Ok(ext) => (
StatusCode::OK,
Json(EntityPermissionResponse::Access {
- permission: ext.permission,
+ permission: *ext.entity_access_receipt.entity_permission(),
}),
)
.into_response(),
diff --git a/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs b/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs
index e9bd88779c..d6755c995c 100644
--- a/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs
@@ -1,5 +1,5 @@
use super::{
- context::ApiContext,
+ context::{ApiContext, EntityAccessService},
documents::{export_document, get_document_version},
history::upsert_history,
permissions,
@@ -24,6 +24,8 @@ use axum::{
Router,
routing::{delete, get, post, put},
};
+use documents_hex::domain::service::DocumentServiceImpl;
+use documents_hex::outbound::pg_document_repo::PgDocumentRepo;
use macro_middleware::{
auth::ensure_user_exists,
cloud_storage::{document::ensure_document_exists, thread::ensure_thread_exists},
@@ -51,7 +53,11 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
// Document routes
.route(
"/documents/:document_id",
- get(get_document::handler).layer(ensure_document_exists_middleware.clone()),
+ get(documents_hex::inbound::axum_router::get_document_handler::<
+ DocumentServiceImpl<PgDocumentRepo>,
+ EntityAccessService,
+ >)
+ .layer(ensure_document_exists_middleware.clone()),
)
.route(
"/documents/:document_id/basic",
@@ -77,7 +83,13 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
)
.route(
"/documents/:document_id/location_v3",
- get(location::get_location_handler_v3).layer(ensure_document_exists_middleware.clone()),
+ get(
+ documents_hex::inbound::axum_router::get_location_v3_handler::<
+ DocumentServiceImpl<PgDocumentRepo>,
+ EntityAccessService,
+ >,
+ )
+ .layer(ensure_document_exists_middleware.clone()),
)
.route(
"/documents/:document_id/permissions",
diff --git a/rust/cloud-storage/document_storage_service/src/api/middleware/internal_access.rs b/rust/cloud-storage/document_storage_service/src/api/middleware/internal_access.rs
index b13f0a241d..05414a1e92 100644
--- a/rust/cloud-storage/document_storage_service/src/api/middleware/internal_access.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/middleware/internal_access.rs
@@ -8,6 +8,7 @@ use axum::{
middleware::Next,
response::{IntoResponse, Response},
};
+pub(crate) use entity_access::inbound::axum_extractors::InternalUser;
use model::user::UserContext;
use models_permissions::share_permission::access_level::AccessLevel;
use reqwest::header::ToStrError;
@@ -17,12 +18,6 @@ use tracing::Level;
#[cfg(test)]
mod tests;
-/// marker struct which denotes that this is an internal user via the [MACRO_DOCUMENT_STORAGE_SERVICE_AUTH_HEADER_KEY]
-#[derive(Debug, Clone)]
-pub(crate) struct InternalUser {
- pub access_level: AccessLevel,
-}
-
#[derive(Debug, Error)]
pub(crate) enum InternalAccessErr {
#[error(
diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rs
index 7ad52248dd..d733814169 100644
--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs
@@ -91,9 +91,13 @@ fn api_router(state: ApiContext) -> Router {
let internal_router = Router::new()
.nest(
"/documents",
- documents::router(state.clone()).layer(ServiceBuilder::new().layer(
- axum::middleware::from_fn(macro_middleware::connection_drop_prevention_handler),
- )),
+ documents::router(state.clone())
+ .merge(documents_hex::inbound::axum_router::documents_router(
+ state.documents_state.clone(),
+ ))
+ .layer(ServiceBuilder::new().layer(axum::middleware::from_fn(
+ macro_middleware::connection_drop_prevention_handler,
+ ))),
)
.nest(
"/history",
diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
index c39b9fa33a..29fbf3fb1e 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -139,19 +139,20 @@ use utoipa::OpenApi;
// documents
documents::get_user_documents::get_user_documents_handler,
- documents::get_document::handler,
+ documents_hex::inbound::axum_router::get_document_handler,
documents::get_document_version::handler,
documents::create_document::create_document_handler,
documents::copy_document::copy_document_handler,
documents::save_document::save_document_handler,
documents::pre_save::presave_document_handler,
documents::edit_document::edit_document_handler_v2,
- documents::delete_document::delete_document_handler,
+ documents_hex::inbound::axum_router::delete_document_handler,
documents::delete_document::permanently_delete_document_handler,
documents::get_document_list::get_document_list_handler,
documents::get_document_permissions::get_document_permissions_handler_v2,
documents::get_document_views::get_document_views_handler,
documents::location::get_location_handler,
+ documents_hex::inbound::axum_router::get_location_v3_handler,
documents::simple_save::handler,
documents::initialize_user_documents::handler,
documents::get_batch_preview::get_batch_preview_handler,
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 82c9441551..c6d6e9a712 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -17,6 +17,10 @@ use comms::{
};
use config::{Config, Environment};
use connection_gateway_client::client::ConnectionGatewayClient;
+use documents_hex::domain::models::CloudFrontConfig;
+use documents_hex::domain::service::DocumentServiceImpl;
+use documents_hex::inbound::axum_router::DocumentRouterState;
+use documents_hex::outbound::pg_document_repo::PgDocumentRepo;
use dynamodb_client::DynamodbClient;
use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
@@ -244,6 +248,39 @@ async fn main() -> anyhow::Result<()> {
// Create the CommsRouterState for comms_service routes
let comms_state = CommsRouterState::new(channel_service_for_comms);
+ let entity_access_service = Arc::new(
+ entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(db.clone()),
+ ),
+ );
+
+ let document_repo = PgDocumentRepo::new(db.clone());
+ let cloudfront_config = CloudFrontConfig {
+ distribution_url: config
+ .vars
+ .document_storage_service_cloudfront_distribution_url
+ .as_ref()
+ .to_string(),
+ signer_public_key_id: config
+ .vars
+ .document_storage_service_cloudfront_signer_public_key_id
+ .as_ref()
+ .to_string(),
+ signer_private_key: config
+ .document_storage_service_cloudfront_signer_private_key
+ .as_ref()
+ .to_string(),
+ presigned_url_expiry_seconds: config.document_storage_service_presigned_url_expiry_seconds,
+ browser_cache_expiry_seconds: config
+ .document_storage_service_presigned_url_browser_cache_expiry_seconds,
+ };
+ let document_service = DocumentServiceImpl::new(
+ document_repo,
+ cloudfront_config,
+ sync_service_client.clone(),
+ db.clone(),
+ );
+
let api_context = ApiContext {
soup_router_state: SoupRouterState::new(
SoupImpl::new(
@@ -278,11 +315,12 @@ async fn main() -> anyhow::Result<()> {
frecency_storage,
comms_state,
permissions_token_secret: comms_permissions_token_secret,
- entity_access_service: Arc::new(
- entity_access::domain::service::EntityAccessServiceImpl::new(
- entity_access::outbound::PgAccessRepository::new(db.clone()),
- ),
- ),
+ entity_access_service: entity_access_service.clone(),
+ documents_state: DocumentRouterState {
+ service: Arc::new(document_service),
+ access_service: entity_access_service,
+ pool: db.clone(),
+ },
channels_state: ChannelsRouterState::new(ChannelMessagesServiceImpl::new(
PgChannelMessagesRepo::new(db.clone()),
)),
diff --git a/rust/cloud-storage/documents/.sqlx/query-28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281.json b/rust/cloud-storage/documents/.sqlx/query-28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281.json
new file mode 100644
index 0000000000..98ceb2aeec
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE \"Project\" SET \"updatedAt\" = NOW() WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-3ebdc4ec5d9a7b08d21f6e249d5c72d10d42e25aa07353aa47ebd3f1ad4f56a7.json b/rust/cloud-storage/documents/.sqlx/query-3ebdc4ec5d9a7b08d21f6e249d5c72d10d42e25aa07353aa47ebd3f1ad4f56a7.json
new file mode 100644
index 0000000000..dc0ac30179
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-3ebdc4ec5d9a7b08d21f6e249d5c72d10d42e25aa07353aa47ebd3f1ad4f56a7.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT bp.sha\n FROM \"BomPart\" bp\n WHERE bp.\"documentBomId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sha",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "3ebdc4ec5d9a7b08d21f6e249d5c72d10d42e25aa07353aa47ebd3f1ad4f56a7"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-49b6375ff01eeccbeecacee87258d2b4c354daa345b9c838adc1fadbc6a1cbb5.json b/rust/cloud-storage/documents/.sqlx/query-49b6375ff01eeccbeecacee87258d2b4c354daa345b9c838adc1fadbc6a1cbb5.json
new file mode 100644
index 0000000000..32e2bdf85e
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-49b6375ff01eeccbeecacee87258d2b4c354daa345b9c838adc1fadbc6a1cbb5.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT location\n FROM \"UserDocumentViewLocation\"\n WHERE user_id = $1 AND document_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "location",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "49b6375ff01eeccbeecacee87258d2b4c354daa345b9c838adc1fadbc6a1cbb5"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-530dbf9753f99470bd1928f17721031cd3fcee89685f44afc0d0305ec6231093.json b/rust/cloud-storage/documents/.sqlx/query-530dbf9753f99470bd1928f17721031cd3fcee89685f44afc0d0305ec6231093.json
new file mode 100644
index 0000000000..dea819c66a
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-530dbf9753f99470bd1928f17721031cd3fcee89685f44afc0d0305ec6231093.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n di.id,\n d.uploaded\n FROM \"DocumentInstance\" di\n JOIN \"Document\" d ON di.\"documentId\" = d.id\n WHERE di.\"documentId\" = $1\n ORDER BY di.\"createdAt\" DESC\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "uploaded",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "530dbf9753f99470bd1928f17721031cd3fcee89685f44afc0d0305ec6231093"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-6d419ad1a1c53be5ee3edf5667c55489e99232e1dbd25cbb3f31746b4b9614ab.json b/rust/cloud-storage/documents/.sqlx/query-6d419ad1a1c53be5ee3edf5667c55489e99232e1dbd25cbb3f31746b4b9614ab.json
new file mode 100644
index 0000000000..6c45bc7756
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-6d419ad1a1c53be5ee3edf5667c55489e99232e1dbd25cbb3f31746b4b9614ab.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM \"Pin\" WHERE \"pinnedItemId\" = $1 AND \"pinnedItemType\" = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "6d419ad1a1c53be5ee3edf5667c55489e99232e1dbd25cbb3f31746b4b9614ab"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-76ca09231164d0c838d59d477f6406b67ddfeaea2b6fe078c30927277b6d3fa0.json b/rust/cloud-storage/documents/.sqlx/query-76ca09231164d0c838d59d477f6406b67ddfeaea2b6fe078c30927277b6d3fa0.json
new file mode 100644
index 0000000000..0a9bbbd734
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-76ca09231164d0c838d59d477f6406b67ddfeaea2b6fe078c30927277b6d3fa0.json
@@ -0,0 +1,70 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n d.id as \"document_id\",\n d.owner,\n d.name as \"document_name\",\n d.\"branchedFromId\" as \"branched_from_id\",\n d.\"branchedFromVersionId\" as \"branched_from_version_id\",\n d.\"documentFamilyId\" as \"document_family_id\",\n d.\"fileType\" as \"file_type\",\n d.\"projectId\" as \"project_id\",\n d.\"deletedAt\"::timestamptz as \"deleted_at\"\n FROM\n \"Document\" d\n WHERE\n d.id = $1\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "document_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "document_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "branched_from_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "branched_from_version_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 5,
+ "name": "document_family_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 6,
+ "name": "file_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true,
+ null
+ ]
+ },
+ "hash": "76ca09231164d0c838d59d477f6406b67ddfeaea2b6fe078c30927277b6d3fa0"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-76e487efe2d8f383ac8e7688892624be4d81662c6f82f6aa16ba2e752dcabd94.json b/rust/cloud-storage/documents/.sqlx/query-76e487efe2d8f383ac8e7688892624be4d81662c6f82f6aa16ba2e752dcabd94.json
new file mode 100644
index 0000000000..4d075c448f
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-76e487efe2d8f383ac8e7688892624be4d81662c6f82f6aa16ba2e752dcabd94.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT bp.sha\n FROM \"BomPart\" bp\n JOIN \"DocumentBom\" db ON bp.\"documentBomId\" = db.id\n WHERE db.\"documentId\" = $1\n AND db.id = (\n SELECT db_inner.id\n FROM \"DocumentBom\" db_inner\n WHERE db_inner.\"documentId\" = $1\n ORDER BY db_inner.\"updatedAt\" DESC\n LIMIT 1\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sha",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "76e487efe2d8f383ac8e7688892624be4d81662c6f82f6aa16ba2e752dcabd94"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-ab394ab1dcafaff117ba75dd454c9ef5dc894f2a86012e54c8bd5e085458a89d.json b/rust/cloud-storage/documents/.sqlx/query-ab394ab1dcafaff117ba75dd454c9ef5dc894f2a86012e54c8bd5e085458a89d.json
new file mode 100644
index 0000000000..b80b95917b
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-ab394ab1dcafaff117ba75dd454c9ef5dc894f2a86012e54c8bd5e085458a89d.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE \"Document\"\n SET \"deletedAt\" = NOW()\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ab394ab1dcafaff117ba75dd454c9ef5dc894f2a86012e54c8bd5e085458a89d"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-af5bcc105de6d97d360513479747e8f32d4045c3e2baa01c7100ba834dcf80e4.json b/rust/cloud-storage/documents/.sqlx/query-af5bcc105de6d97d360513479747e8f32d4045c3e2baa01c7100ba834dcf80e4.json
new file mode 100644
index 0000000000..45ed60c4d2
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-af5bcc105de6d97d360513479747e8f32d4045c3e2baa01c7100ba834dcf80e4.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n COALESCE(db.id, di.id) as \"id!\",\n d.uploaded\n FROM\n \"Document\" d\n LEFT JOIN LATERAL (\n SELECT\n i.id\n FROM\n \"DocumentInstance\" i\n WHERE\n i.\"documentId\" = d.id\n ORDER BY\n i.\"createdAt\" ASC\n LIMIT 1\n ) di ON d.\"fileType\" IS DISTINCT FROM 'docx'\n LEFT JOIN LATERAL (\n SELECT\n b.id\n FROM\n \"DocumentBom\" b\n WHERE\n b.\"documentId\" = d.id\n ORDER BY\n b.\"createdAt\" ASC\n LIMIT 1\n ) db ON d.\"fileType\" = 'docx'\n WHERE\n d.id = $1\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "uploaded",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null,
+ false
+ ]
+ },
+ "hash": "af5bcc105de6d97d360513479747e8f32d4045c3e2baa01c7100ba834dcf80e4"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-d86be6e3a5bac69df99498b43dfc645a882c4f965226e71fc300d84a081ad30d.json b/rust/cloud-storage/documents/.sqlx/query-d86be6e3a5bac69df99498b43dfc645a882c4f965226e71fc300d84a081ad30d.json
new file mode 100644
index 0000000000..86f183fae7
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-d86be6e3a5bac69df99498b43dfc645a882c4f965226e71fc300d84a081ad30d.json
@@ -0,0 +1,127 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n d.id as \"document_id\",\n d.owner as \"owner\",\n COALESCE(db.id, di.id) as \"document_version_id!\",\n d.name as \"document_name\",\n d.\"branchedFromId\" as \"branched_from_id\",\n d.\"branchedFromVersionId\" as \"branched_from_version_id\",\n d.\"documentFamilyId\" as \"document_family_id\",\n d.\"createdAt\"::timestamptz as \"created_at\",\n d.\"updatedAt\"::timestamptz as \"updated_at\",\n d.\"fileType\" as \"file_type\",\n db.bom_parts as \"document_bom?\",\n di.modification_data as \"modification_data?\",\n d.\"projectId\" as \"project_id\",\n p.name as \"project_name?\",\n di.sha as \"sha?\",\n dt.sub_type as \"sub_type?: DocumentSubType\",\n d.\"deletedAt\"::timestamptz as \"deleted_at\"\n FROM\n \"Document\" d\n LEFT JOIN document_sub_type dt ON dt.document_id = d.id\n LEFT JOIN LATERAL (\n SELECT\n i.id,\n i.sha,\n i.\"createdAt\",\n (\n SELECT\n imod.\"modificationData\"\n FROM\n \"DocumentInstanceModificationData\" imod\n WHERE\n imod.\"documentInstanceId\" = i.id\n ) as modification_data,\n i.\"updatedAt\"\n FROM\n \"DocumentInstance\" i\n WHERE\n i.\"documentId\" = d.id\n ORDER BY\n i.\"createdAt\" DESC\n LIMIT 1\n ) di ON true\n LEFT JOIN LATERAL (\n SELECT\n b.id,\n (\n SELECT\n json_agg(\n json_build_object(\n 'id', bp.id,\n 'sha', bp.sha,\n 'path', bp.path\n )\n )\n FROM\n \"BomPart\" bp\n WHERE\n bp.\"documentBomId\" = b.id\n ) as bom_parts\n FROM\n \"DocumentBom\" b\n WHERE\n b.\"documentId\" = d.id\n ORDER BY\n b.\"createdAt\" DESC\n LIMIT 1\n ) db ON d.\"fileType\" = 'docx'\n LEFT JOIN LATERAL (\n SELECT\n p.name\n FROM \"Project\" p\n WHERE p.id = d.\"projectId\"\n ) p ON d.\"projectId\" IS NOT NULL\n WHERE\n d.id = $1\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "document_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "document_version_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "document_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "branched_from_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "branched_from_version_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 6,
+ "name": "document_family_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "file_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "document_bom?",
+ "type_info": "Json"
+ },
+ {
+ "ordinal": 11,
+ "name": "modification_data?",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 12,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
+ "name": "project_name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 14,
+ "name": "sha?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
+ "name": "sub_type?: DocumentSubType",
+ "type_info": {
+ "Custom": {
+ "name": "document_sub_type_value",
+ "kind": {
+ "Enum": [
+ "task"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 16,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ false,
+ true,
+ true,
+ true,
+ null,
+ null,
+ true,
+ null,
+ null,
+ true,
+ false,
+ false,
+ false,
+ null
+ ]
+ },
+ "hash": "d86be6e3a5bac69df99498b43dfc645a882c4f965226e71fc300d84a081ad30d"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-fb8a9157d4c7546ced9440b417c693bcaa3226934fedb2a4348a24ca9568c4ed.json b/rust/cloud-storage/documents/.sqlx/query-fb8a9157d4c7546ced9440b417c693bcaa3226934fedb2a4348a24ca9568c4ed.json
new file mode 100644
index 0000000000..9bee89e00f
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-fb8a9157d4c7546ced9440b417c693bcaa3226934fedb2a4348a24ca9568c4ed.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM \"UserHistory\" WHERE \"itemId\" = $1 AND \"itemType\" = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "fb8a9157d4c7546ced9440b417c693bcaa3226934fedb2a4348a24ca9568c4ed"
+}
diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.toml
new file mode 100644
index 0000000000..cff8ee17b4
--- /dev/null
+++ b/rust/cloud-storage/documents/Cargo.toml
@@ -0,0 +1,62 @@
+[package]
+edition = "2024"
+name = "documents"
+publish = false
+version = "0.1.0"
+
+[features]
+default = ["ports", "inbound", "outbound", "axum"]
+ports = ["dep:tokio"]
+inbound = ["axum", "ports"]
+outbound = ["ports"]
+axum = [
+ "dep:axum",
+ "dep:axum-extra",
+ "dep:model_user",
+ "dep:model-error-response",
+ "dep:utoipa",
+ "entity_access/axum",
+]
+
+[dependencies]
+# Core
+anyhow = { workspace = true }
+chrono = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+thiserror = { workspace = true }
+tracing = { workspace = true }
+uuid = { workspace = true }
+
+# Domain models (always included)
+document_sub_type = { path = "../document_sub_type" }
+entity_access = { path = "../entity_access" }
+macro_user_id = { path = "../macro_user_id" }
+model = { path = "../model" }
+models_permissions = { path = "../models_permissions" }
+
+# Async runtime (for ports)
+tokio = { workspace = true, optional = true }
+
+# Axum dependencies (for inbound)
+axum = { workspace = true, optional = true }
+axum-extra = { workspace = true, optional = true }
+model_user = { path = "../model_user", optional = true, features = ["axum"] }
+model-error-response = { path = "../model-error-response", optional = true }
+utoipa = { workspace = true, optional = true }
+
+# Outbound dependencies
+cloudfront_sign = { workspace = true }
+futures = { workspace = true }
+macro_project_utils = { path = "../macro_project_utils" }
+sqlx = { workspace = true }
+sync_service_client = { path = "../sync_service_client" }
+urlencoding = { workspace = true }
+
+[dev-dependencies]
+http-body-util = { workspace = true }
+macro_db_migrator = { path = "../macro_db_migrator" }
+mockall = { workspace = true }
+serde_json = { workspace = true }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+tower = { workspace = true }
diff --git a/rust/cloud-storage/documents/fixtures/documents_test_data.sql b/rust/cloud-storage/documents/fixtures/documents_test_data.sql
new file mode 100644
index 0000000000..51dfc40b7f
--- /dev/null
+++ b/rust/cloud-storage/documents/fixtures/documents_test_data.sql
@@ -0,0 +1,68 @@
+INSERT INTO
+ public."Organization" ("id", "name") (
+ SELECT
+ 1,
+ 'organization-one'
+ );
+
+INSERT INTO
+ public."User" (
+ "id",
+ "email",
+ "stripeCustomerId",
+ "organizationId"
+ ) (
+ SELECT
+ 'stripe_id',
+ 1
+ );
+
+INSERT INTO
+ public."Document" ("id", "name", "fileType", "owner") (
+ SELECT
+ 'document-one',
+ 'test_document_name',
+ 'txt',
+ );
+
+INSERT INTO
+ public."DocumentInstance" ("revisionName", "documentId", "sha") (
+ SELECT
+ 'test_document_name',
+ 'document-one',
+ 'sha-one'
+ );
+
+INSERT INTO
+ public."DocumentInstanceModificationData" ("documentInstanceId", "modificationData") (
+ SELECT
+ 1,
+ '{"testing": true}'
+ );
+
+INSERT INTO
+ public."Document" ("id", "name", "fileType", "owner") (
+ SELECT
+ 'document-two',
+ 'test_document_name',
+ 'pdf',
+ );
+
+INSERT INTO
+ public."DocumentBom" ("revisionName", "documentId") (
+ SELECT
+ 'test_document_name',
+ 'document-two'
+ );
+
+INSERT INTO
+ public."Project" ("id", "name", "userId") (
+ SELECT
+ 'new-project',
+ 'test_project_name',
+ );
diff --git a/rust/cloud-storage/documents/justfile b/rust/cloud-storage/documents/justfile
new file mode 100644
index 0000000000..d5a52bc432
--- /dev/null
+++ b/rust/cloud-storage/documents/justfile
@@ -0,0 +1,6 @@
+DATABASE_URL := "postgres://user:password@localhost:5432/macrodb"
+
+mod sqlx '../sqlx.just'
+
+prepare_db:
+ just sqlx::prepare_db {{ DATABASE_URL }}
diff --git a/rust/cloud-storage/documents/src/domain.rs b/rust/cloud-storage/documents/src/domain.rs
new file mode 100644
index 0000000000..a947d9653b
--- /dev/null
+++ b/rust/cloud-storage/documents/src/domain.rs
@@ -0,0 +1,9 @@
+//! Domain layer: models, ports (trait interfaces), and service implementation.
+
+pub mod models;
+
+#[cfg(feature = "ports")]
+pub mod ports;
+
+#[cfg(feature = "ports")]
+pub mod service;
diff --git a/rust/cloud-storage/documents/src/domain/models.rs b/rust/cloud-storage/documents/src/domain/models.rs
new file mode 100644
index 0000000000..d4259444cb
--- /dev/null
+++ b/rust/cloud-storage/documents/src/domain/models.rs
@@ -0,0 +1,41 @@
+//! Domain models for the documents crate.
+
+/// Errors that can occur during document operations.
+#[derive(Debug, thiserror::Error)]
+pub enum DocumentError {
+ /// The requested document was not found.
+ #[error("document not found: {0}")]
+ NotFound(String),
+ /// The user is not authorized to perform this action.
+ #[error("unauthorized")]
+ Unauthorized,
+ /// The document does not exist in storage (S3/sync service).
+ #[error("document does not exist in storage")]
+ Gone,
+ /// An internal error occurred.
+ #[error("{0}")]
+ Internal(#[from] anyhow::Error),
+}
+
+/// Configuration for CloudFront presigned URL generation.
+pub struct CloudFrontConfig {
+ /// The CloudFront distribution URL.
+ pub distribution_url: String,
+ /// The public key ID for the CloudFront signer.
+ pub signer_public_key_id: String,
+ /// The private key for the CloudFront signer.
+ pub signer_private_key: String,
+ /// Number of seconds before a presigned URL expires.
+ pub presigned_url_expiry_seconds: u64,
+ /// Number of seconds for browser cache expiry (Cache-Control max-age).
+ pub browser_cache_expiry_seconds: u64,
+}
+
+/// Query parameters for the location_v3 endpoint.
+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug)]
+pub struct LocationQueryParams {
+ /// A specific document version id to get the location for.
+ pub document_version_id: Option<i64>,
+ /// If true, this will return the converted docx url.
+ pub get_converted_docx_url: Option<bool>,
+}
diff --git a/rust/cloud-storage/documents/src/domain/ports.rs b/rust/cloud-storage/documents/src/domain/ports.rs
new file mode 100644
index 0000000000..a6c83be438
--- /dev/null
+++ b/rust/cloud-storage/documents/src/domain/ports.rs
@@ -0,0 +1,104 @@
+//! Port definitions for the documents domain.
+//!
+//! These traits define the contracts that adapters must implement.
+
+use std::future::Future;
+
+use entity_access::domain::models::EntityAccessReceipt;
+use model::document::response::{GetDocumentResponseData, LocationResponseV3};
+use model::document::{DocumentBasic, DocumentMetadata};
+
+use super::models::{DocumentError, LocationQueryParams};
+
+/// Repository for accessing document data from the database.
+///
+/// All methods perform database operations — SQL queries are written
+/// directly in the outbound adapter implementation.
+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
+pub trait DocumentRepo: Send + Sync + 'static {
+ /// The error type returned by repository operations.
+ type Err: Into<anyhow::Error> + Send;
+
+ /// Get full document metadata (including latest version, BOM, project info).
+ fn get_document_metadata(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<DocumentMetadata, Self::Err>> + Send;
+
+ /// Get a user's last view location within a document.
+ fn get_user_view_location(
+ &self,
+ user_id: &str,
+ document_id: &str,
+ ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;
+
+ /// Get basic document info (used by middleware and access checks).
+ fn get_basic_document(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<DocumentBasic, Self::Err>> + Send;
+
+ /// Soft-delete a document (remove pins/history, set deletedAt).
+ fn soft_delete_document(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Get the latest document version ID (for editable files: js, py).
+ /// Returns (version_id, uploaded).
+ fn get_latest_document_version_id(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<(i64, bool), Self::Err>> + Send;
+
+ /// Get the document version ID (for static files: pdf, images).
+ /// Returns (version_id, uploaded).
+ fn get_document_version_id(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<(i64, bool), Self::Err>> + Send;
+
+ /// Get document SHAs for a specific document version (BOM parts).
+ fn get_document_shas(
+ &self,
+ document_version_id: i64,
+ ) -> impl Future<Output = Result<Vec<String>, Self::Err>> + Send;
+
+ /// Get document SHAs by document ID (latest BOM).
+ fn get_document_shas_by_document_id(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<Vec<String>, Self::Err>> + Send;
+}
+
+/// Service interface for document operations.
+///
+/// Orchestrates business logic using the repository and external services.
+pub trait DocumentService: Send + Sync + 'static {
+ /// Gets the basic document ignoring access checks
+ fn internal_get_basic_document(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<DocumentBasic, DocumentError>> + Send;
+
+ /// Get a document with metadata, access level, and view location.
+ fn get_document(
+ &self,
+ entity_access_receipt: EntityAccessReceipt,
+ ) -> impl Future<Output = Result<GetDocumentResponseData, DocumentError>> + Send;
+
+ /// Get the location (presigned URL or sync service content) for a document.
+ fn get_document_location(
+ &self,
+ document_context: &DocumentBasic,
+ entity_access_receipt: EntityAccessReceipt,
+ params: LocationQueryParams,
+ ) -> impl Future<Output = Result<LocationResponseV3, DocumentError>> + Send;
+
+ /// Soft-delete a document and update project modified timestamp.
+ fn delete_document(
+ &self,
+ entity_access_receipt: EntityAccessReceipt,
+ project_id: Option<String>,
+ ) -> impl Future<Output = Result<(), DocumentError>> + Send;
+}
diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rs
new file mode 100644
index 0000000000..dfab316b99
--- /dev/null
+++ b/rust/cloud-storage/documents/src/domain/service.rs
@@ -0,0 +1,405 @@
+//! Document service implementation.
+
+#[cfg(test)]
+mod tests;
+
+use std::str::FromStr;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use anyhow::anyhow;
+use cloudfront_sign::{SignedOptions, get_signed_url};
+use entity_access::domain::models::{EntityAccessAuth, EntityAccessReceipt};
+use model::document::response::{
+ GetDocumentResponseData, LocationResponseData, LocationResponseV3,
+};
+use model::document::{
+ CONVERTED_DOCUMENT_FILE_NAME, DocumentBasic, FileType, FileTypeExt,
+ build_cloud_storage_bucket_document_key,
+};
+use model::response::PresignedUrl;
+use sqlx::PgPool;
+use tracing;
+
+use super::models::{CloudFrontConfig, DocumentError, LocationQueryParams};
+use super::ports::{DocumentRepo, DocumentService};
+
+/// The concrete document service implementation.
+pub struct DocumentServiceImpl<R: DocumentRepo> {
+ repo: R,
+ cloudfront_config: CloudFrontConfig,
+ sync_service_client: sync_service_client::SyncServiceClient,
+ db: PgPool,
+}
+
+impl<R: DocumentRepo> DocumentServiceImpl<R> {
+ /// Create a new document service.
+ pub fn new(
+ repo: R,
+ cloudfront_config: CloudFrontConfig,
+ sync_service_client: sync_service_client::SyncServiceClient,
+ db: PgPool,
+ ) -> Self {
+ Self {
+ repo,
+ cloudfront_config,
+ sync_service_client,
+ db,
+ }
+ }
+
+ fn get_signed_options(&self) -> SignedOptions {
+ let current_unix_timestamp = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs();
+ let date_less_than =
+ current_unix_timestamp + self.cloudfront_config.presigned_url_expiry_seconds;
+
+ SignedOptions {
+ key_pair_id: self.cloudfront_config.signer_public_key_id.clone(),
+ date_less_than,
+ private_key: self.cloudfront_config.signer_private_key.clone(),
+ ..Default::default()
+ }
+ }
+
+ fn make_presigned_url(&self, key: &str) -> anyhow::Result<String> {
+ let constructed_url = format!("{}/{}", self.cloudfront_config.distribution_url, key);
+ let options = self.get_signed_options();
+ let signed_url = get_signed_url(&constructed_url, &options)?;
+ Ok(signed_url)
+ }
+
+ async fn get_editable_url(
+ &self,
+ owner: &str,
+ document_id: &str,
+ document_version_id: Option<i64>,
+ file_type: &str,
+ ) -> anyhow::Result<LocationResponseData> {
+ let url_encoded_owner = urlencoding::encode(owner);
+ let document_version_id = if let Some(id) = document_version_id {
+ id
+ } else {
+ self.repo
+ .get_latest_document_version_id(document_id)
+ .await
+ .map_err(Into::into)?
+ .0
+ };
+
+ let document_key = build_cloud_storage_bucket_document_key(
+ &url_encoded_owner,
+ document_id,
+ document_version_id,
+ Some(file_type),
+ );
+
+ let signed_url = self.make_presigned_url(&document_key)?;
+ Ok(LocationResponseData::PresignedUrl(signed_url))
+ }
+
+ async fn get_static_url(
+ &self,
+ owner: &str,
+ document_id: &str,
+ file_type: &Option<FileType>,
+ ) -> anyhow::Result<LocationResponseData> {
+ let url_encoded_owner = urlencoding::encode(owner);
+ let (document_version_id, _) = self
+ .repo
+ .get_document_version_id(document_id)
+ .await
+ .map_err(Into::into)?;
+
+ let file_type_str = file_type.as_ref().map(|s| s.as_str());
+ let document_key = build_cloud_storage_bucket_document_key(
+ &url_encoded_owner,
+ document_id,
+ document_version_id,
+ file_type_str,
+ );
+
+ let signed_url = self.make_presigned_url(&document_key)?;
+ Ok(LocationResponseData::PresignedUrl(signed_url))
+ }
+
+ async fn get_converted_docx_url(
+ &self,
+ owner: &str,
+ document_id: &str,
+ ) -> anyhow::Result<LocationResponseData> {
+ let url_encoded_owner = urlencoding::encode(owner);
+ let document_key = format!(
+ "{}/{}/{}.pdf",
+ url_encoded_owner, document_id, CONVERTED_DOCUMENT_FILE_NAME
+ );
+
+ let signed_url = self.make_presigned_url(&document_key)?;
+ Ok(LocationResponseData::PresignedUrl(signed_url))
+ }
+
+ async fn get_docx_urls(
+ &self,
+ document_id: &str,
+ document_version_id: Option<i64>,
+ ) -> anyhow::Result<LocationResponseData> {
+ let shas: Vec<String> = if let Some(version_id) = document_version_id {
+ self.repo
+ .get_document_shas(version_id)
+ .await
+ .map_err(Into::into)?
+ } else {
+ self.repo
+ .get_document_shas_by_document_id(document_id)
+ .await
+ .map_err(Into::into)?
+ };
+
+ let options = self.get_signed_options();
+ let distribution_url = &self.cloudfront_config.distribution_url;
+
+ let presigned_urls: Vec<PresignedUrl> = shas
+ .iter()
+ .filter_map(|sha| {
+ let constructed_url = format!("{}/{}", distribution_url, sha);
+ match get_signed_url(&constructed_url, &options) {
+ Ok(url) => Some(PresignedUrl {
+ presigned_url: url,
+ sha: sha.to_string(),
+ }),
+ Err(e) => {
+ tracing::error!(error=?e, sha=?sha, "unable to generate presigned url");
+ None
+ }
+ }
+ })
+ .collect();
+
+ if shas.len() != presigned_urls.len() {
+ return Err(anyhow!("unable to generate presigned urls"));
+ }
+
+ Ok(LocationResponseData::PresignedUrls(presigned_urls))
+ }
+
+ async fn get_presigned_url_by_type(
+ &self,
+ owner: &str,
+ document_id: &str,
+ file_type: Option<FileType>,
+ document_version_id: Option<i64>,
+ get_converted_docx: bool,
+ ) -> anyhow::Result<LocationResponseData> {
+ match file_type {
+ None => self.get_static_url(owner, document_id, &None).await,
+ Some(ft) => {
+ if ft == FileType::Docx && get_converted_docx {
+ self.get_converted_docx_url(owner, document_id).await
+ } else if ft == FileType::Docx && !get_converted_docx {
+ self.get_docx_urls(document_id, document_version_id).await
+ } else if ft.is_static() {
+ self.get_static_url(owner, document_id, &Some(ft)).await
+ } else {
+ self.get_editable_url(owner, document_id, document_version_id, ft.as_str())
+ .await
+ }
+ }
+ }
+ }
+
+ async fn try_get_from_sync_service(
+ &self,
+ document_id: &str,
+ ) -> Result<Option<model::sync_service::DocumentMetadata>, anyhow::Error> {
+ use futures::{FutureExt, pin_mut, select};
+
+ let exists_fut = self.sync_service_client.exists(document_id).fuse();
+ let metadata_fut = self.sync_service_client.get_metadata(document_id).fuse();
+
+ pin_mut!(exists_fut, metadata_fut);
+
+ select! {
+ exists_result = exists_fut => {
+ match exists_result {
+ Ok(false) => Ok(None),
+ Ok(true) | Err(_) => {
+ metadata_fut.await.map(Some)
+ }
+ }
+ },
+ metadata_result = metadata_fut => {
+ match metadata_result {
+ Ok(metadata) => Ok(Some(metadata)),
+ Err(e) => {
+ match exists_fut.await {
+ Ok(false) => Ok(None),
+ _ => Err(e),
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+impl<R: DocumentRepo> DocumentService for DocumentServiceImpl<R> {
+ #[tracing::instrument(err, skip(self))]
+ async fn get_document(
+ &self,
+ entity_access_receipt: EntityAccessReceipt,
+ ) -> Result<GetDocumentResponseData, DocumentError> {
+ let document_id = entity_access_receipt.entity().entity_id.clone();
+ // get access level
+ // check if >= view
+ // do work
+ let document_metadata = self
+ .repo
+ .get_document_metadata(&document_id)
+ .await
+ .map_err(|e| {
+ let err: anyhow::Error = e.into();
+ if err.to_string().contains(
+ "no rows returned by a query that expected to return at least one row",
+ ) {
+ DocumentError::NotFound(document_id.clone())
+ } else {
+ DocumentError::Internal(err)
+ }
+ })?;
+
+ let view_location = match entity_access_receipt.auth() {
+ EntityAccessAuth::Authenticated(user_id) => self
+ .repo
+ .get_user_view_location(user_id.as_ref(), &document_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))?,
+ EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => None,
+ };
+
+ let access_level = match entity_access_receipt.entity_permission() {
+ entity_access::domain::models::EntityPermission::AccessLevel { access_level } => {
+ access_level
+ }
+ _ => unreachable!(),
+ };
+
+ Ok(GetDocumentResponseData {
+ document_metadata,
+ user_access_level: *access_level,
+ view_location,
+ })
+ }
+
+ #[tracing::instrument(err, skip(self, document_context))]
+ async fn get_document_location(
+ &self,
+ document_context: &DocumentBasic,
+ entity_access_receipt: EntityAccessReceipt,
+ params: LocationQueryParams,
+ ) -> Result<LocationResponseV3, DocumentError> {
+ let file_type = document_context
+ .file_type
+ .as_deref()
+ .and_then(|f| FileType::from_str(f).ok());
+
+ let document_id = entity_access_receipt.entity().entity_id.clone();
+
+ // For markdown files, check sync service first
+ if matches!(file_type, Some(FileType::Md)) {
+ match self.try_get_from_sync_service(&document_id).await {
+ Ok(Some(sync_service_metadata)) => {
+ return Ok(LocationResponseV3::SyncServiceContent {
+ metadata: document_context.clone(),
+ sync_service_metadata,
+ });
+ }
+ Ok(None) => {
+ // Continue to S3 check
+ }
+ Err(e) => {
+ tracing::error!(error=?e, "sync service failed");
+ return Err(DocumentError::Internal(e));
+ }
+ }
+ }
+
+ let owner = document_context.owner.as_ref();
+ let response_data = self
+ .get_presigned_url_by_type(
+ owner,
+ &document_id,
+ file_type,
+ params.document_version_id,
+ params.get_converted_docx_url.unwrap_or(false),
+ )
+ .await
+ .map(|response| match response {
+ LocationResponseData::PresignedUrl(url) => LocationResponseV3::PresignedUrl {
+ presigned_url: url,
+ metadata: document_context.clone(),
+ },
+ LocationResponseData::PresignedUrls(urls) => LocationResponseV3::PresignedUrls {
+ presigned_urls: urls,
+ metadata: document_context.clone(),
+ },
+ })
+ .map_err(|e| {
+ if e.to_string() == "document does not exist in s3" {
+ DocumentError::Gone
+ } else {
+ DocumentError::Internal(e)
+ }
+ })?;
+
+ Ok(response_data)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn delete_document(
+ &self,
+ entity_access_receipt: EntityAccessReceipt,
+ project_id: Option<String>,
+ ) -> Result<(), DocumentError> {
+ self.repo
+ .soft_delete_document(&entity_access_receipt.entity().entity_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))?;
+
+ match entity_access_receipt.auth() {
+ EntityAccessAuth::Authenticated(macro_user_id) => {
+ macro_project_utils::update_project_modified(
+ &self.db,
+ macro_project_utils::ProjectModifiedArgs {
+ project_id,
+ old_project_id: None::<String>,
+ user_id: macro_user_id.as_ref().to_string(),
+ },
+ )
+ .await;
+ }
+ EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => (),
+ }
+
+ Ok(())
+ }
+
+ async fn internal_get_basic_document(
+ &self,
+ document_id: &str,
+ ) -> Result<DocumentBasic, DocumentError> {
+ self.repo
+ .get_basic_document(document_id)
+ .await
+ .map_err(|e| {
+ let err: anyhow::Error = e.into();
+ if err.to_string().contains(
+ "no rows returned by a query that expected to return at least one row",
+ ) {
+ DocumentError::NotFound(document_id.to_string())
+ } else {
+ DocumentError::Internal(err)
+ }
+ })
+ }
+}
diff --git a/rust/cloud-storage/documents/src/domain/service/tests.rs b/rust/cloud-storage/documents/src/domain/service/tests.rs
new file mode 100644
index 0000000000..836ecc2c0b
--- /dev/null
+++ b/rust/cloud-storage/documents/src/domain/service/tests.rs
@@ -0,0 +1,90 @@
+use macro_user_id::cowlike::CowLike;
+use model::document::DocumentMetadata;
+
+use crate::domain::ports::MockDocumentRepo;
+
+use super::*;
+
+fn make_test_metadata() -> DocumentMetadata {
+ DocumentMetadata {
+ document_id: "doc-1".to_string(),
+ document_version_id: 1,
+ owner: macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ document_name: "test_doc".to_string(),
+ file_type: Some("txt".to_string()),
+ sha: Some("sha-1".to_string()),
+ project_id: Some("project-1".to_string()),
+ project_name: Some("Test Project".to_string()),
+ branched_from_id: None,
+ branched_from_version_id: None,
+ document_family_id: None,
+ document_bom: None,
+ modification_data: None,
+ created_at: None,
+ updated_at: None,
+ deleted_at: None,
+ sub_type: None,
+ }
+}
+
+fn make_mock_repo() -> MockDocumentRepo {
+ MockDocumentRepo::new()
+}
+
+#[tokio::test]
+async fn test_get_document_happy_path() {
+ let mut repo = make_mock_repo();
+ let metadata = make_test_metadata();
+ let metadata_clone = metadata.clone();
+
+ repo.expect_get_document_metadata()
+ .withf(|id| id == "doc-1")
+ .returning(move |_| Box::pin(std::future::ready(Ok(metadata_clone.clone()))));
+
+ repo.expect_get_user_view_location()
+ .withf(|uid, did| uid == "user-1" && did == "doc-1")
+ .returning(|_, _| Box::pin(std::future::ready(Ok(Some("page-3".to_string())))));
+
+ // We can't easily construct the full service because it needs SyncServiceClient + PgPool.
+ // Instead, test the repo interaction directly via the trait.
+ let result = repo.get_document_metadata("doc-1").await.unwrap();
+ assert_eq!(result.document_id, "doc-1");
+ assert_eq!(result.document_name, "test_doc");
+
+ let view_loc = repo
+ .get_user_view_location("user-1", "doc-1")
+ .await
+ .unwrap();
+ assert_eq!(view_loc, Some("page-3".to_string()));
+}
+
+#[tokio::test]
+async fn test_get_document_not_found() {
+ let mut repo = make_mock_repo();
+
+ repo.expect_get_document_metadata()
+ .withf(|id| id == "nonexistent")
+ .returning(|_| {
+ Box::pin(std::future::ready(Err(anyhow!(
+ "no rows returned by a query that expected to return at least one row"
+ ))))
+ });
+
+ let result = repo.get_document_metadata("nonexistent").await;
+ assert!(result.is_err());
+ assert!(result.unwrap_err().to_string().contains("no rows returned"));
+}
+
+#[tokio::test]
+async fn test_soft_delete_document() {
+ let mut repo = make_mock_repo();
+
+ repo.expect_soft_delete_document()
+ .withf(|id| id == "doc-1")
+ .returning(|_| Box::pin(std::future::ready(Ok(()))));
+
+ let result = repo.soft_delete_document("doc-1").await;
+ assert!(result.is_ok());
+}
diff --git a/rust/cloud-storage/documents/src/inbound.rs b/rust/cloud-storage/documents/src/inbound.rs
new file mode 100644
index 0000000000..45c679928b
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound.rs
@@ -0,0 +1,4 @@
+//! Inbound adapters for the documents domain.
+
+#[cfg(feature = "axum")]
+pub mod axum_router;
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router.rs b/rust/cloud-storage/documents/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..ffc4b85feb
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/axum_router.rs
@@ -0,0 +1,278 @@
+//! Axum router for document endpoints.
+//!
+//! Provides three routes:
+//! - `GET /:document_id` — get document metadata
+//! - `GET /:document_id/location_v3` — get document content location (presigned URL)
+//! - `DELETE /:document_id` — soft-delete a document
+
+#[cfg(test)]
+mod tests;
+
+use std::sync::Arc;
+
+use axum::{
+ Extension, Json, Router,
+ body::Body,
+ extract::{FromRef, Path, Query, State},
+ http::{HeaderMap, Request, StatusCode},
+ middleware::{self, Next},
+ response::IntoResponse,
+};
+use entity_access::domain::ports::EntityAccessService;
+use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
+use model::document::response::GetDocumentResponse;
+use model::document::{DocumentBasic, response::LocationResponseV3};
+use model::response::GenericSuccessResponse;
+use model::user::UserContext;
+use model_error_response::ErrorResponse;
+use models_permissions::share_permission::access_level::{OwnerAccessLevel, ViewAccessLevel};
+use serde::Deserialize;
+use sqlx::PgPool;
+
+use crate::domain::models::{DocumentError, LocationQueryParams};
+use crate::domain::ports::DocumentService;
+
+impl IntoResponse for DocumentError {
+ fn into_response(self) -> axum::response::Response {
+ let status_code = match &self {
+ DocumentError::NotFound(_) => StatusCode::NOT_FOUND,
+ DocumentError::Unauthorized => StatusCode::UNAUTHORIZED,
+ DocumentError::Gone => StatusCode::GONE,
+ DocumentError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ if status_code.is_server_error() {
+ tracing::error!(error=?self, "internal server error");
+ }
+
+ let message = self.to_string();
+ (status_code, Json(ErrorResponse { message: &message })).into_response()
+ }
+}
+
+/// Router state containing the document service, entity access service, and DB pool.
+pub struct DocumentRouterState<T, Svc> {
+ /// The document service implementation.
+ pub service: Arc<T>,
+ /// The entity access service for authorization.
+ pub access_service: Arc<Svc>,
+ /// The database pool (used by middleware for document lookups).
+ pub pool: PgPool,
+}
+
+// Manual Clone impl so T and Svc don't need to be Clone (they're behind Arc).
+impl<T, Svc> Clone for DocumentRouterState<T, Svc> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ access_service: self.access_service.clone(),
+ pool: self.pool.clone(),
+ }
+ }
+}
+
+impl<T, Svc> FromRef<DocumentRouterState<T, Svc>> for Arc<Svc> {
+ fn from_ref(state: &DocumentRouterState<T, Svc>) -> Self {
+ state.access_service.clone()
+ }
+}
+
+/// Path parameters for document endpoints (document_id extraction).
+#[derive(Deserialize)]
+pub struct Params {
+ document_id: String,
+}
+
+/// Build the documents router with all three endpoints.
+pub fn documents_router<T, Svc, S>(state: DocumentRouterState<T, Svc>) -> Router<S>
+where
+ T: DocumentService,
+ Svc: EntityAccessService,
+ S: Send + Sync + 'static,
+{
+ Router::new()
+ .route(
+ "/:document_id",
+ axum::routing::get(get_document_handler::<T, Svc>)
+ .delete(delete_document_handler::<T, Svc>),
+ )
+ .route(
+ "/:document_id/location_v3",
+ axum::routing::get(get_location_v3_handler::<T, Svc>),
+ )
+ .layer(middleware::from_fn_with_state(
+ state.clone(),
+ ensure_document_exists,
+ ))
+ .with_state(state)
+}
+
+/// Path parameters for document endpoints.
+pub struct DocumentIdPathParams {
+ /// The document ID.
+ pub document_id: String,
+}
+
+/// Middleware that loads [`DocumentBasic`] into request extensions.
+///
+/// Extracts `document_id` from the path and queries the database.
+/// Returns 404 if the document does not exist.
+#[tracing::instrument(skip(state, request, next))]
+async fn ensure_document_exists<T: DocumentService, Svc: EntityAccessService>(
+ State(state): State<DocumentRouterState<T, Svc>>,
+ Path(Params { document_id }): Path<Params>,
+ request: Request<Body>,
+ next: Next,
+) -> impl IntoResponse {
+ let document_basic = match state
+ .service
+ .internal_get_basic_document(&document_id)
+ .await
+ {
+ Ok(doc) => doc,
+ Err(e) => {
+ match e {
+ DocumentError::NotFound(_) => {
+ return (
+ StatusCode::NOT_FOUND,
+ Json(ErrorResponse {
+ message: &format!("document with id \"{}\" was not found", document_id),
+ }),
+ )
+ .into_response();
+ }
+ _ => {
+ // Only other type that we return here is DocumentError::Internal
+ tracing::error!(error=?e, document_id=?document_id, "unable to check if document exists");
+ return (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unknown error occurred",
+ }),
+ )
+ .into_response();
+ }
+ }
+ }
+ };
+
+ let mut request = request;
+ request.extensions_mut().insert(document_basic);
+ next.run(request).await.into_response()
+}
+
+/// Handler for `GET /documents/:document_id`.
+///
+/// Returns document metadata, user access level, and view location.
+#[utoipa::path(
+ tag = "document",
+ get,
+ path = "/documents/{document_id}",
+ operation_id = "get_document",
+ params(
+ ("document_id" = String, Path, description = "Document ID")
+ ),
+ responses(
+ (status = 200, body = GetDocumentResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(state, access), err)]
+pub async fn get_document_handler<T: DocumentService, Svc: EntityAccessService>(
+ State(state): State<DocumentRouterState<T, Svc>>,
+ access: DocumentAccessExtractor<ViewAccessLevel, Svc>,
+ user_context: Extension<UserContext>,
+ Path(Params { document_id }): Path<Params>,
+) -> Result<Json<GetDocumentResponse>, DocumentError> {
+ let response_data = state
+ .service
+ .get_document(access.entity_access_receipt)
+ .await?;
+
+ Ok(Json(GetDocumentResponse {
+ error: false,
+ data: response_data,
+ }))
+}
+
+// entity access
+// do work
+
+/// Handler for `GET /documents/:document_id/location_v3`.
+///
+/// Returns a presigned URL or sync service content for accessing the document.
+#[utoipa::path(
+ tag = "document",
+ get,
+ path = "/documents/{document_id}/location_v3",
+ operation_id = "get_document_location_v3",
+ params(
+ ("document_id" = String, Path, description = "Document ID"),
+ ("document_version_id" = Option<i64>, Query, description = "A specific document version id to get the location for."),
+ ("get_converted_docx_url" = Option<bool>, Query, description = "If true, this will return the converted docx url.")
+ ),
+ responses(
+ (status = 200),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 410, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(state, access, document_context), err)]
+pub async fn get_location_v3_handler<T: DocumentService, Svc: EntityAccessService>(
+ access: DocumentAccessExtractor<ViewAccessLevel, Svc>,
+ State(state): State<DocumentRouterState<T, Svc>>,
+ Extension(document_context): Extension<DocumentBasic>,
+ Path(Params { document_id }): Path<Params>,
+ Query(params): Query<LocationQueryParams>,
+) -> Result<(HeaderMap, Json<LocationResponseV3>), DocumentError> {
+ let response_data = state
+ .service
+ .get_document_location(&document_context, access.entity_access_receipt, params)
+ .await?;
+
+ let mut header_map = HeaderMap::new();
+ header_map.append("content-type", "application/json".parse().unwrap());
+ header_map.append("Cache-Control", "max-age-300".parse().unwrap());
+
+ Ok((header_map, Json(response_data)))
+}
+
+/// Handler for `DELETE /documents/:document_id`.
+///
+/// Soft-deletes a document (only owners can delete).
+#[utoipa::path(
+ tag = "document",
+ delete,
+ path = "/documents/{document_id}",
+ operation_id = "delete_document",
+ params(
+ ("document_id" = String, Path, description = "Document ID")
+ ),
+ responses(
+ (status = 200, body = GenericSuccessResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(state, access, doc), err)]
+pub async fn delete_document_handler<T: DocumentService, Svc: EntityAccessService>(
+ access: DocumentAccessExtractor<OwnerAccessLevel, Svc>,
+ State(state): State<DocumentRouterState<T, Svc>>,
+ user_context: Extension<UserContext>,
+ doc: Extension<DocumentBasic>,
+ Path(Params { document_id }): Path<Params>,
+) -> Result<Json<GenericSuccessResponse>, DocumentError> {
+ tracing::info!("delete document");
+
+ state
+ .service
+ .delete_document(access.entity_access_receipt, doc.project_id.clone())
+ .await?;
+
+ Ok(Json(GenericSuccessResponse { success: true }))
+}
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/tests.rs b/rust/cloud-storage/documents/src/inbound/axum_router/tests.rs
new file mode 100644
index 0000000000..bd65af6757
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/tests.rs
@@ -0,0 +1,4 @@
+// Placeholder for handler integration tests.
+// Full integration tests would require mocking the entity access service
+// and document service, constructing a test router, and making HTTP requests.
+// For now, the core logic is tested via the domain service and outbound repo tests.
diff --git a/rust/cloud-storage/documents/src/lib.rs b/rust/cloud-storage/documents/src/lib.rs
new file mode 100644
index 0000000000..5e3204d472
--- /dev/null
+++ b/rust/cloud-storage/documents/src/lib.rs
@@ -0,0 +1,19 @@
+//! Documents hexagonal architecture crate.
+//!
+//! Encapsulates document CRUD operations using a ports-and-adapters pattern.
+//!
+//! # Architecture
+//!
+//! - **domain**: Contains domain models, ports (traits), and the service implementation
+//! - **outbound**: Contains adapters for external dependencies (PostgreSQL)
+//! - **inbound**: Contains adapters for incoming requests (Axum handlers)
+
+#![deny(missing_docs)]
+
+pub mod domain;
+
+#[cfg(feature = "inbound")]
+pub mod inbound;
+
+#[cfg(feature = "outbound")]
+pub mod outbound;
diff --git a/rust/cloud-storage/documents/src/outbound.rs b/rust/cloud-storage/documents/src/outbound.rs
new file mode 100644
index 0000000000..e028988102
--- /dev/null
+++ b/rust/cloud-storage/documents/src/outbound.rs
@@ -0,0 +1,3 @@
+//! Outbound adapters for the documents domain.
+
+pub mod pg_document_repo;
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
new file mode 100644
index 0000000000..69e0d758df
--- /dev/null
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
@@ -0,0 +1,354 @@
+//! PostgreSQL implementation of the [`DocumentRepo`] port.
+//!
+//! All SQL queries are written directly here (not delegated to `macro_db_client`).
+
+#[cfg(test)]
+mod tests;
+
+use document_sub_type::DocumentSubType;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use model::document::{DocumentBasic, DocumentMetadata};
+use sqlx::PgPool;
+
+use crate::domain::ports::DocumentRepo;
+
+/// PostgreSQL-backed document repository.
+#[derive(Clone)]
+pub struct PgDocumentRepo {
+ pool: PgPool,
+}
+
+impl PgDocumentRepo {
+ /// Create a new repository backed by the given connection pool.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl DocumentRepo for PgDocumentRepo {
+ type Err = sqlx::Error;
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_document_metadata(
+ &self,
+ document_id: &str,
+ ) -> Result<DocumentMetadata, Self::Err> {
+ sqlx::query!(
+ r#"
+ SELECT
+ d.id as "document_id",
+ d.owner as "owner",
+ COALESCE(db.id, di.id) as "document_version_id!",
+ d.name as "document_name",
+ d."branchedFromId" as "branched_from_id",
+ d."branchedFromVersionId" as "branched_from_version_id",
+ d."documentFamilyId" as "document_family_id",
+ d."createdAt"::timestamptz as "created_at",
+ d."updatedAt"::timestamptz as "updated_at",
+ d."fileType" as "file_type",
+ db.bom_parts as "document_bom?",
+ di.modification_data as "modification_data?",
+ d."projectId" as "project_id",
+ p.name as "project_name?",
+ di.sha as "sha?",
+ dt.sub_type as "sub_type?: DocumentSubType",
+ d."deletedAt"::timestamptz as "deleted_at"
+ FROM
+ "Document" d
+ LEFT JOIN document_sub_type dt ON dt.document_id = d.id
+ LEFT JOIN LATERAL (
+ SELECT
+ i.id,
+ i.sha,
+ i."createdAt",
+ (
+ SELECT
+ imod."modificationData"
+ FROM
+ "DocumentInstanceModificationData" imod
+ WHERE
+ imod."documentInstanceId" = i.id
+ ) as modification_data,
+ i."updatedAt"
+ FROM
+ "DocumentInstance" i
+ WHERE
+ i."documentId" = d.id
+ ORDER BY
+ i."createdAt" DESC
+ LIMIT 1
+ ) di ON true
+ LEFT JOIN LATERAL (
+ SELECT
+ b.id,
+ (
+ SELECT
+ json_agg(
+ json_build_object(
+ 'id', bp.id,
+ 'sha', bp.sha,
+ 'path', bp.path
+ )
+ )
+ FROM
+ "BomPart" bp
+ WHERE
+ bp."documentBomId" = b.id
+ ) as bom_parts
+ FROM
+ "DocumentBom" b
+ WHERE
+ b."documentId" = d.id
+ ORDER BY
+ b."createdAt" DESC
+ LIMIT 1
+ ) db ON d."fileType" = 'docx'
+ LEFT JOIN LATERAL (
+ SELECT
+ p.name
+ FROM "Project" p
+ WHERE p.id = d."projectId"
+ ) p ON d."projectId" IS NOT NULL
+ WHERE
+ d.id = $1
+ LIMIT 1
+ "#,
+ document_id,
+ )
+ .try_map(|row| {
+ Ok(DocumentMetadata {
+ document_id: row.document_id,
+ document_version_id: row.document_version_id,
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ document_name: row.document_name,
+ file_type: row.file_type,
+ sha: row.sha,
+ project_id: row.project_id,
+ project_name: row.project_name,
+ branched_from_id: row.branched_from_id,
+ branched_from_version_id: row.branched_from_version_id,
+ document_family_id: row.document_family_id,
+ document_bom: row.document_bom,
+ modification_data: row.modification_data,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ sub_type: row.sub_type,
+ deleted_at: row.deleted_at,
+ })
+ })
+ .fetch_one(&self.pool)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_user_view_location(
+ &self,
+ user_id: &str,
+ document_id: &str,
+ ) -> Result<Option<String>, Self::Err> {
+ let row = sqlx::query!(
+ r#"
+ SELECT location
+ FROM "UserDocumentViewLocation"
+ WHERE user_id = $1 AND document_id = $2
+ "#,
+ user_id,
+ document_id,
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+
+ Ok(row.map(|r| r.location))
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_basic_document(&self, document_id: &str) -> Result<DocumentBasic, Self::Err> {
+ sqlx::query!(
+ r#"
+ SELECT
+ d.id as "document_id",
+ d.owner,
+ d.name as "document_name",
+ d."branchedFromId" as "branched_from_id",
+ d."branchedFromVersionId" as "branched_from_version_id",
+ d."documentFamilyId" as "document_family_id",
+ d."fileType" as "file_type",
+ d."projectId" as "project_id",
+ d."deletedAt"::timestamptz as "deleted_at"
+ FROM
+ "Document" d
+ WHERE
+ d.id = $1
+ LIMIT 1
+ "#,
+ document_id,
+ )
+ .try_map(|row| {
+ Ok(DocumentBasic {
+ document_id: row.document_id,
+ document_name: row.document_name,
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ file_type: row.file_type,
+ branched_from_id: row.branched_from_id,
+ branched_from_version_id: row.branched_from_version_id,
+ document_family_id: row.document_family_id,
+ project_id: row.project_id,
+ deleted_at: row.deleted_at,
+ })
+ })
+ .fetch_one(&self.pool)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn soft_delete_document(&self, document_id: &str) -> Result<(), Self::Err> {
+ let mut transaction = self.pool.begin().await?;
+
+ // Delete pins
+ sqlx::query!(
+ r#"
+ DELETE FROM "Pin" WHERE "pinnedItemId" = $1 AND "pinnedItemType" = $2
+ "#,
+ document_id,
+ "document",
+ )
+ .execute(&mut *transaction)
+ .await?;
+
+ // Delete from history
+ sqlx::query!(
+ r#"
+ DELETE FROM "UserHistory" WHERE "itemId" = $1 AND "itemType" = $2
+ "#,
+ document_id,
+ "document",
+ )
+ .execute(&mut *transaction)
+ .await?;
+
+ // Soft delete the document
+ sqlx::query!(
+ r#"
+ UPDATE "Document"
+ SET "deletedAt" = NOW()
+ WHERE id = $1
+ "#,
+ document_id,
+ )
+ .execute(&mut *transaction)
+ .await?;
+
+ transaction.commit().await?;
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_latest_document_version_id(
+ &self,
+ document_id: &str,
+ ) -> Result<(i64, bool), Self::Err> {
+ sqlx::query!(
+ r#"
+ SELECT
+ di.id,
+ d.uploaded
+ FROM "DocumentInstance" di
+ JOIN "Document" d ON di."documentId" = d.id
+ WHERE di."documentId" = $1
+ ORDER BY di."createdAt" DESC
+ LIMIT 1
+ "#,
+ document_id,
+ )
+ .map(|row| (row.id, row.uploaded))
+ .fetch_one(&self.pool)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_document_version_id(&self, document_id: &str) -> Result<(i64, bool), Self::Err> {
+ sqlx::query!(
+ r#"
+ SELECT
+ COALESCE(db.id, di.id) as "id!",
+ d.uploaded
+ FROM
+ "Document" d
+ LEFT JOIN LATERAL (
+ SELECT
+ i.id
+ FROM
+ "DocumentInstance" i
+ WHERE
+ i."documentId" = d.id
+ ORDER BY
+ i."createdAt" ASC
+ LIMIT 1
+ ) di ON d."fileType" IS DISTINCT FROM 'docx'
+ LEFT JOIN LATERAL (
+ SELECT
+ b.id
+ FROM
+ "DocumentBom" b
+ WHERE
+ b."documentId" = d.id
+ ORDER BY
+ b."createdAt" ASC
+ LIMIT 1
+ ) db ON d."fileType" = 'docx'
+ WHERE
+ d.id = $1
+ LIMIT 1
+ "#,
+ document_id,
+ )
+ .map(|row| (row.id, row.uploaded))
+ .fetch_one(&self.pool)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_document_shas(&self, document_version_id: i64) -> Result<Vec<String>, Self::Err> {
+ sqlx::query!(
+ r#"
+ SELECT bp.sha
+ FROM "BomPart" bp
+ WHERE bp."documentBomId" = $1
+ "#,
+ document_version_id,
+ )
+ .map(|r| r.sha)
+ .fetch_all(&self.pool)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_document_shas_by_document_id(
+ &self,
+ document_id: &str,
+ ) -> Result<Vec<String>, Self::Err> {
+ sqlx::query!(
+ r#"
+ SELECT bp.sha
+ FROM "BomPart" bp
+ JOIN "DocumentBom" db ON bp."documentBomId" = db.id
+ WHERE db."documentId" = $1
+ AND db.id = (
+ SELECT db_inner.id
+ FROM "DocumentBom" db_inner
+ WHERE db_inner."documentId" = $1
+ ORDER BY db_inner."updatedAt" DESC
+ LIMIT 1
+ )
+ "#,
+ document_id,
+ )
+ .map(|r| r.sha)
+ .fetch_all(&self.pool)
+ .await
+ }
+}
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs
new file mode 100644
index 0000000000..d3cb81f403
--- /dev/null
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs
@@ -0,0 +1,103 @@
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::{Pool, Postgres};
+
+use crate::domain::ports::DocumentRepo;
+use crate::outbound::pg_document_repo::PgDocumentRepo;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_get_document_metadata(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool);
+
+ // Document exists
+ let metadata = repo.get_document_metadata("document-one").await.unwrap();
+ assert_eq!(metadata.document_id, "document-one");
+ assert_eq!(metadata.document_name, "test_document_name");
+ assert_eq!(metadata.owner.as_ref(), "macro|[email protected]");
+ assert_eq!(metadata.document_version_id, 1);
+ assert_eq!(metadata.file_type, Some("txt".to_string()));
+
+ // Document does not exist
+ let result = repo.get_document_metadata("nonexistent").await;
+ assert!(result.is_err());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_get_basic_document(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool);
+
+ let basic = repo.get_basic_document("document-one").await.unwrap();
+ assert_eq!(basic.document_id, "document-one");
+ assert_eq!(basic.document_name, "test_document_name");
+ assert_eq!(basic.owner.as_ref(), "macro|[email protected]");
+ assert_eq!(basic.file_type, Some("txt".to_string()));
+
+ // Not found
+ let result = repo.get_basic_document("nonexistent").await;
+ assert!(result.is_err());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_soft_delete_document(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+
+ repo.soft_delete_document("document-one").await.unwrap();
+
+ // Verify deleted_at is set
+ let row = sqlx::query!(
+ r#"SELECT "deletedAt"::timestamptz as deleted_at FROM "Document" WHERE id = $1"#,
+ "document-one"
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert!(row.deleted_at.is_some());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_get_latest_document_version_id(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool);
+
+ let (version_id, _uploaded) = repo
+ .get_latest_document_version_id("document-one")
+ .await
+ .unwrap();
+ assert_eq!(version_id, 1);
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_get_document_version_id(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool);
+
+ let (version_id, _uploaded) = repo.get_document_version_id("document-one").await.unwrap();
+ assert_eq!(version_id, 1);
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_get_user_view_location(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool);
+
+ // No view location exists
+ let location = repo
+ .get_user_view_location("macro|[email protected]", "document-one")
+ .await
+ .unwrap();
+ assert!(location.is_none());
+}
diff --git a/rust/cloud-storage/entity_access/src/domain/models.rs b/rust/cloud-storage/entity_access/src/domain/models.rs
index 43b760eb75..566aa2874f 100644
--- a/rust/cloud-storage/entity_access/src/domain/models.rs
+++ b/rust/cloud-storage/entity_access/src/domain/models.rs
@@ -1,5 +1,6 @@
//! Domain models for entity access.
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use serde::{Deserialize, Serialize};
pub use model_entity::EntityType;
@@ -53,6 +54,54 @@ pub enum ChannelRoleResult {
NotFound,
}
+/// A given entity
+#[derive(Debug)]
+pub struct Entity {
+ /// The id of the entity
+ pub entity_id: String,
+ /// The type of the entity
+ pub entity_type: EntityType,
+}
+
+/// The entity access auth type
+#[derive(Debug)]
+pub enum EntityAccessAuth {
+ /// The user is authenticated
+ Authenticated(MacroUserId<Lowercase<'static>>),
+ /// The user is unauthenticated
+ Unauthenticated,
+ /// Internally authenticated
+ Internal,
+}
+
+/// Represents that a given user has a given permission for the provided id.
+#[derive(Debug)]
+pub struct EntityAccessReceipt {
+ /// The entity access authentication method
+ pub(crate) auth: EntityAccessAuth,
+ /// The entity that was requested access
+ pub(crate) entity: Entity,
+ /// The permission for the user on the entity
+ pub(crate) entity_permission: EntityPermission,
+}
+
+impl EntityAccessReceipt {
+ /// Getter for auth
+ pub fn auth(&self) -> &EntityAccessAuth {
+ &self.auth
+ }
+
+ /// Getter for entity
+ pub fn entity(&self) -> &Entity {
+ &self.entity
+ }
+
+ /// Getter for entity permission
+ pub fn entity_permission(&self) -> &EntityPermission {
+ &self.entity_permission
+ }
+}
+
/// Errors that can occur during access checking.
#[derive(Debug, thiserror::Error)]
pub enum AccessError {
diff --git a/rust/cloud-storage/entity_access/src/domain/ports.rs b/rust/cloud-storage/entity_access/src/domain/ports.rs
index c41037f434..cf8984d699 100644
--- a/rust/cloud-storage/entity_access/src/domain/ports.rs
+++ b/rust/cloud-storage/entity_access/src/domain/ports.rs
@@ -20,7 +20,7 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
fn get_document_access(
&self,
document_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
/// Get the highest access level a user has for a chat.
@@ -30,7 +30,7 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
fn get_chat_access(
&self,
chat_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
/// Get the highest access level a user has for a project.
@@ -40,7 +40,7 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
fn get_project_access(
&self,
project_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
/// Get the highest access level a user has for an email thread.
@@ -50,7 +50,7 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
fn get_thread_access(
&self,
thread_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
/// Check if a user is a member of the specified channels.
@@ -58,7 +58,7 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
/// Returns the subset of channel_ids that the user is a participant of.
fn check_user_channel_membership(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
channel_ids: &[Uuid],
) -> impl Future<Output = Result<Vec<Uuid>, AccessError>> + Send;
@@ -71,7 +71,7 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
fn get_channel_role(
&self,
channel_id: &Uuid,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
user_org_id: Option<i64>,
) -> impl Future<Output = Result<ChannelRoleResult, AccessError>> + Send;
}
@@ -85,7 +85,7 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {
/// Returns `None` if the user has no access to the entity.
fn get_access_level(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
entity_id: &str,
entity_type: EntityType,
) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
@@ -96,7 +96,18 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {
/// Returns an error if the user does not have sufficient access.
fn check_access(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ entity_id: &str,
+ entity_type: EntityType,
+ required_level: AccessLevel,
+ ) -> impl Future<Output = Result<AccessLevel, AccessError>> + Send;
+
+ /// Check if the public access level is at least the required access level for an entity.
+ ///
+ /// Returns the actual access level if access is granted.
+ /// Returns an error if there is not sufficient access.
+ fn check_public_access(
+ &self,
entity_id: &str,
entity_type: EntityType,
required_level: AccessLevel,
@@ -110,7 +121,7 @@ pub trait EntityAccessService: Clone + Send + Sync + 'static {
/// Returns `AccessError::Unauthorized` if the user has no access.
fn get_entity_permission(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
entity_id: &str,
entity_type: EntityType,
user_org_id: Option<i64>,
diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rs
index d7be83b1f1..7dce57bf96 100644
--- a/rust/cloud-storage/entity_access/src/domain/service.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service.rs
@@ -33,7 +33,7 @@ where
async fn get_optimized_access(
&self,
entity_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
entity_type: EntityType,
) -> Result<Option<AccessLevel>, AccessError> {
match entity_type {
@@ -51,7 +51,7 @@ where
async fn get_channel_access(
&self,
channel_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, AccessError> {
let channel_uuid = Uuid::from_str(channel_id)
.map_err(|_| AccessError::BadRequest("Invalid channel ID format"))?;
@@ -76,7 +76,7 @@ where
#[tracing::instrument(err, skip(self))]
async fn get_access_level(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
entity_id: &str,
entity_type: EntityType,
) -> Result<Option<AccessLevel>, AccessError> {
@@ -97,7 +97,7 @@ where
#[tracing::instrument(err, skip(self))]
async fn check_access(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
entity_id: &str,
entity_type: EntityType,
required_level: AccessLevel,
@@ -113,10 +113,25 @@ where
}
}
+ #[tracing::instrument(err, skip(self))]
+ async fn check_public_access(
+ &self,
+ entity_id: &str,
+ entity_type: EntityType,
+ required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ let access_level = self.get_access_level(None, entity_id, entity_type).await?;
+
+ match access_level {
+ Some(level) if level >= required_level => Ok(level),
+ Some(_) | None => Err(AccessError::Unauthorized),
+ }
+ }
+
#[tracing::instrument(err, skip(self))]
async fn get_entity_permission(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
entity_id: &str,
entity_type: EntityType,
user_org_id: Option<i64>,
diff --git a/rust/cloud-storage/entity_access/src/domain/service/test.rs b/rust/cloud-storage/entity_access/src/domain/service/test.rs
index 9d9cf0d881..3d72bc2432 100644
--- a/rust/cloud-storage/entity_access/src/domain/service/test.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service/test.rs
@@ -64,7 +64,7 @@ impl AccessRepository for MockRepo {
async fn get_document_access(
&self,
_document_id: &str,
- _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, AccessError> {
Ok(*self.document_access.lock().await)
}
@@ -72,7 +72,7 @@ impl AccessRepository for MockRepo {
async fn get_chat_access(
&self,
_chat_id: &str,
- _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, AccessError> {
Ok(*self.chat_access.lock().await)
}
@@ -80,7 +80,7 @@ impl AccessRepository for MockRepo {
async fn get_project_access(
&self,
_project_id: &str,
- _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, AccessError> {
Ok(*self.project_access.lock().await)
}
@@ -88,14 +88,14 @@ impl AccessRepository for MockRepo {
async fn get_thread_access(
&self,
_thread_id: &str,
- _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, AccessError> {
Ok(*self.thread_access.lock().await)
}
async fn check_user_channel_membership(
&self,
- _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
_channel_ids: &[Uuid],
) -> Result<Vec<Uuid>, AccessError> {
Ok(self.channel_membership.lock().await.clone())
@@ -104,7 +104,7 @@ impl AccessRepository for MockRepo {
async fn get_channel_role(
&self,
_channel_id: &Uuid,
- _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
_user_org_id: Option<i64>,
) -> Result<ChannelRoleResult, AccessError> {
Ok(*self.channel_role.lock().await)
@@ -122,7 +122,7 @@ async fn test_get_document_access_returns_level_from_repo() {
let user_id = test_user_id();
let result = service
- .get_access_level(&user_id, "doc-1", EntityType::Document)
+ .get_access_level(Some(&user_id), "doc-1", EntityType::Document)
.await;
assert_eq!(result.unwrap(), Some(AccessLevel::Edit));
@@ -135,7 +135,7 @@ async fn test_get_chat_access_returns_level_from_repo() {
let user_id = test_user_id();
let result = service
- .get_access_level(&user_id, "chat-1", EntityType::Chat)
+ .get_access_level(Some(&user_id), "chat-1", EntityType::Chat)
.await;
assert_eq!(result.unwrap(), Some(AccessLevel::View));
@@ -148,7 +148,7 @@ async fn test_get_project_access_returns_level_from_repo() {
let user_id = test_user_id();
let result = service
- .get_access_level(&user_id, "proj-1", EntityType::Project)
+ .get_access_level(Some(&user_id), "proj-1", EntityType::Project)
.await;
assert_eq!(result.unwrap(), Some(AccessLevel::Owner));
@@ -161,7 +161,7 @@ async fn test_get_thread_access_returns_level_from_repo() {
let user_id = test_user_id();
let result = service
- .get_access_level(&user_id, "thread-1", EntityType::EmailThread)
+ .get_access_level(Some(&user_id), "thread-1", EntityType::EmailThread)
.await;
assert_eq!(result.unwrap(), Some(AccessLevel::Comment));
@@ -176,7 +176,7 @@ async fn test_get_channel_access_for_member_returns_view() {
let result = service
.get_access_level(
- &user_id,
+ Some(&user_id),
"11111111-1111-1111-1111-111111111111",
EntityType::Channel,
)
@@ -193,7 +193,7 @@ async fn test_get_channel_access_for_non_member_returns_none() {
let result = service
.get_access_level(
- &user_id,
+ Some(&user_id),
"11111111-1111-1111-1111-111111111111",
EntityType::Channel,
)
@@ -209,7 +209,7 @@ async fn test_get_channel_access_with_invalid_uuid_returns_error() {
let user_id = test_user_id();
let result = service
- .get_access_level(&user_id, "not-a-uuid", EntityType::Channel)
+ .get_access_level(Some(&user_id), "not-a-uuid", EntityType::Channel)
.await;
assert!(matches!(result, Err(AccessError::BadRequest(_))));
@@ -222,7 +222,12 @@ async fn test_check_access_sufficient_level_returns_actual_level() {
let user_id = test_user_id();
let result = service
- .check_access(&user_id, "doc-1", EntityType::Document, AccessLevel::View)
+ .check_access(
+ Some(&user_id),
+ "doc-1",
+ EntityType::Document,
+ AccessLevel::View,
+ )
.await;
assert_eq!(result.unwrap(), AccessLevel::Edit);
@@ -235,7 +240,12 @@ async fn test_check_access_insufficient_level_returns_unauthorized() {
let user_id = test_user_id();
let result = service
- .check_access(&user_id, "doc-1", EntityType::Document, AccessLevel::Edit)
+ .check_access(
+ Some(&user_id),
+ "doc-1",
+ EntityType::Document,
+ AccessLevel::Edit,
+ )
.await;
assert!(matches!(result, Err(AccessError::Unauthorized)));
@@ -248,7 +258,12 @@ async fn test_check_access_no_access_returns_unauthorized() {
let user_id = test_user_id();
let result = service
- .check_access(&user_id, "doc-1", EntityType::Document, AccessLevel::View)
+ .check_access(
+ Some(&user_id),
+ "doc-1",
+ EntityType::Document,
+ AccessLevel::View,
+ )
.await;
assert!(matches!(result, Err(AccessError::Unauthorized)));
@@ -262,17 +277,17 @@ async fn test_unsupported_entity_type_returns_none() {
// Email, Team, and User entity types don't have access checks implemented
let result = service
- .get_access_level(&user_id, "email-1", EntityType::Email)
+ .get_access_level(Some(&user_id), "email-1", EntityType::Email)
.await;
assert_eq!(result.unwrap(), None);
let result = service
- .get_access_level(&user_id, "team-1", EntityType::Team)
+ .get_access_level(Some(&user_id), "team-1", EntityType::Team)
.await;
assert_eq!(result.unwrap(), None);
let result = service
- .get_access_level(&user_id, "user-1", EntityType::User)
+ .get_access_level(Some(&user_id), "user-1", EntityType::User)
.await;
assert_eq!(result.unwrap(), None);
}
@@ -286,7 +301,7 @@ async fn test_get_entity_permission_document_returns_access_level() {
let user_id = test_user_id();
let result = service
- .get_entity_permission(&user_id, "doc-1", EntityType::Document, None)
+ .get_entity_permission(Some(&user_id), "doc-1", EntityType::Document, None)
.await
.unwrap();
@@ -305,7 +320,7 @@ async fn test_get_entity_permission_document_no_access_returns_unauthorized() {
let user_id = test_user_id();
let result = service
- .get_entity_permission(&user_id, "doc-1", EntityType::Document, None)
+ .get_entity_permission(Some(&user_id), "doc-1", EntityType::Document, None)
.await;
assert!(matches!(result, Err(AccessError::Unauthorized)));
@@ -319,7 +334,7 @@ async fn test_get_entity_permission_channel_returns_role() {
let result = service
.get_entity_permission(
- &user_id,
+ Some(&user_id),
"11111111-1111-1111-1111-111111111111",
EntityType::Channel,
None,
@@ -343,7 +358,7 @@ async fn test_get_entity_permission_channel_no_access_returns_unauthorized() {
let result = service
.get_entity_permission(
- &user_id,
+ Some(&user_id),
"11111111-1111-1111-1111-111111111111",
EntityType::Channel,
None,
@@ -361,7 +376,7 @@ async fn test_get_entity_permission_channel_not_found_returns_not_found() {
let result = service
.get_entity_permission(
- &user_id,
+ Some(&user_id),
"11111111-1111-1111-1111-111111111111",
EntityType::Channel,
None,
@@ -378,7 +393,7 @@ async fn test_get_entity_permission_invalid_channel_uuid_returns_bad_request() {
let user_id = test_user_id();
let result = service
- .get_entity_permission(&user_id, "not-a-uuid", EntityType::Channel, None)
+ .get_entity_permission(Some(&user_id), "not-a-uuid", EntityType::Channel, None)
.await;
assert!(matches!(result, Err(AccessError::BadRequest(_))));
@@ -391,8 +406,82 @@ async fn test_get_entity_permission_unsupported_type_returns_bad_request() {
let user_id = test_user_id();
let result = service
- .get_entity_permission(&user_id, "email-1", EntityType::Email, None)
+ .get_entity_permission(Some(&user_id), "email-1", EntityType::Email, None)
.await;
assert!(matches!(result, Err(AccessError::BadRequest(_))));
}
+
+// --- Public (unauthenticated) access tests ---
+
+#[tokio::test]
+async fn test_public_access_with_sufficient_level_returns_level() {
+ let repo = MockRepo::new().with_document_access(AccessLevel::View);
+ let service = EntityAccessServiceImpl::new(repo);
+
+ let result = service
+ .check_public_access("doc-1", EntityType::Document, AccessLevel::View)
+ .await;
+
+ assert_eq!(result.unwrap(), AccessLevel::View);
+}
+
+#[tokio::test]
+async fn test_public_access_with_insufficient_level_returns_unauthorized() {
+ let repo = MockRepo::new().with_document_access(AccessLevel::View);
+ let service = EntityAccessServiceImpl::new(repo);
+
+ let result = service
+ .check_public_access("doc-1", EntityType::Document, AccessLevel::Edit)
+ .await;
+
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
+
+#[tokio::test]
+async fn test_public_access_with_no_access_returns_unauthorized() {
+ let repo = MockRepo::new();
+ let service = EntityAccessServiceImpl::new(repo);
+
+ let result = service
+ .check_public_access("doc-1", EntityType::Document, AccessLevel::View)
+ .await;
+
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
+
+#[tokio::test]
+async fn test_get_access_level_with_none_user_id() {
+ let repo = MockRepo::new().with_document_access(AccessLevel::View);
+ let service = EntityAccessServiceImpl::new(repo);
+
+ let result = service
+ .get_access_level(None, "doc-1", EntityType::Document)
+ .await;
+
+ assert_eq!(result.unwrap(), Some(AccessLevel::View));
+}
+
+#[tokio::test]
+async fn test_check_access_with_none_user_id_and_sufficient_level() {
+ let repo = MockRepo::new().with_project_access(AccessLevel::View);
+ let service = EntityAccessServiceImpl::new(repo);
+
+ let result = service
+ .check_access(None, "proj-1", EntityType::Project, AccessLevel::View)
+ .await;
+
+ assert_eq!(result.unwrap(), AccessLevel::View);
+}
+
+#[tokio::test]
+async fn test_check_access_with_none_user_id_and_no_access() {
+ let repo = MockRepo::new();
+ let service = EntityAccessServiceImpl::new(repo);
+
+ let result = service
+ .check_access(None, "doc-1", EntityType::Document, AccessLevel::View)
+ .await;
+
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/chat.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/chat.rs
index 535f9a8554..867ba18a47 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/chat.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/chat.rs
@@ -9,13 +9,15 @@ use axum::{
http::request::Parts,
};
-use super::{ExtractorError, RequiredAccessLevel};
+use super::{ExtractorError, InternalUser, RequiredAccessLevel};
use crate::domain::{
- models::{AccessLevel, EntityType},
+ models::{
+ AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
+ },
ports::EntityAccessService,
};
use model::chat::ChatBasic;
-use model_user::axum_extractor::MacroUserExtractor;
+use model_user::axum_extractor::OptionalMacroUserExtractor;
/// Validates that the user has at least the required access level to a chat.
///
@@ -24,12 +26,11 @@ use model_user::axum_extractor::MacroUserExtractor;
///
/// # Prerequisites
///
-/// - User must be authenticated (MacroUserExtractor in extensions)
/// - Chat context must be loaded (ChatBasic in extensions)
#[derive(Debug)]
pub struct ChatAccessLevelExtractor<T, Svc> {
- /// The actual access level the user has.
- pub access_level: AccessLevel,
+ /// The entity access receipt
+ pub entity_access_receipt: EntityAccessReceipt,
_marker: PhantomData<(T, Svc)>,
}
@@ -47,7 +48,7 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let MacroUserExtractor { macro_user_id, .. } = parts
+ let OptionalMacroUserExtractor { macro_user_id, .. } = parts
.extract()
.await
.map_err(|_| ExtractorError::Internal)?;
@@ -57,33 +58,86 @@ where
.await
.map_err(|_| ExtractorError::Internal)?;
- // Owner always has full access
- if chat_context.user_id == macro_user_id {
+ let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {
+ parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?
+ } else {
+ None
+ };
+
+ if internal_user.is_some() {
return Ok(Self {
- access_level: AccessLevel::Owner,
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: chat_context.id.clone(),
+ entity_type: EntityType::Chat,
+ },
+ auth: EntityAccessAuth::Internal,
+ entity_permission: EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ },
+ _marker: PhantomData,
+ });
+ }
+
+ // Check ownership only if authenticated
+ if let Some(ref user_id) = macro_user_id
+ && chat_context.user_id == *user_id
+ {
+ return Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: chat_context.id.clone(),
+ entity_type: EntityType::Chat,
+ },
+ auth: EntityAccessAuth::Authenticated(user_id.clone().0),
+ entity_permission: EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ },
_marker: PhantomData,
});
}
// Deleted items are only accessible by owner
if chat_context.deleted_at.is_some() {
- return Err(ExtractorError::Unauthorized);
+ return Err(ExtractorError::UnauthorizedWithMessage(
+ "only owner can access deleted resource",
+ ));
}
- // Check access via service
let required_level = T::required_level();
- let access_level = service
- .check_access(
- &macro_user_id,
- &chat_context.id,
- EntityType::Chat,
- required_level,
- )
- .await
- .map_err(ExtractorError::from)?;
+ // Check access based on auth state
+ let access_level: AccessLevel = match macro_user_id.as_ref() {
+ Some(macro_user_id) => service
+ .check_access(
+ Some(macro_user_id),
+ &chat_context.id,
+ EntityType::Chat,
+ required_level,
+ )
+ .await
+ .map_err(ExtractorError::from)?,
+ None => service
+ .check_public_access(&chat_context.id, EntityType::Chat, required_level)
+ .await
+ .map_err(ExtractorError::from)?,
+ };
Ok(Self {
- access_level,
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: chat_context.id.clone(),
+ entity_type: EntityType::Chat,
+ },
+ auth: macro_user_id
+ .map(|m| EntityAccessAuth::Authenticated(m.0))
+ .unwrap_or(EntityAccessAuth::Unauthenticated),
+ entity_permission: EntityPermission::AccessLevel { access_level },
+ },
_marker: PhantomData,
})
}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/document.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/document.rs
index a2566aa326..d281c75428 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/document.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/document.rs
@@ -10,12 +10,18 @@ use axum::{
};
use super::{ExtractorError, RequiredAccessLevel};
-use crate::domain::{
- models::{AccessLevel, EntityType},
- ports::EntityAccessService,
+use crate::{
+ domain::{
+ models::{
+ AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission,
+ EntityType,
+ },
+ ports::EntityAccessService,
+ },
+ inbound::axum_extractors::InternalUser,
};
use model::document::DocumentBasic;
-use model_user::axum_extractor::MacroUserExtractor;
+use model_user::axum_extractor::OptionalMacroUserExtractor;
/// Validates that the user has at least the required access level to a document.
///
@@ -28,8 +34,8 @@ use model_user::axum_extractor::MacroUserExtractor;
/// - Document context must be loaded (DocumentBasic in extensions)
#[derive(Debug)]
pub struct DocumentAccessExtractor<T, Svc> {
- /// The actual access level the user has.
- pub access_level: AccessLevel,
+ /// The entity access receipt
+ pub entity_access_receipt: EntityAccessReceipt,
_marker: PhantomData<(T, Svc)>,
}
@@ -47,20 +53,58 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let MacroUserExtractor { macro_user_id, .. } = parts
+ let OptionalMacroUserExtractor { macro_user_id, .. } = parts
.extract()
.await
- .map_err(|_| ExtractorError::Unauthorized)?;
+ .map_err(|_| ExtractorError::Internal)?;
let document_context: Extension<DocumentBasic> = parts
.extract()
.await
.map_err(|_| ExtractorError::Internal)?;
- // Owner always has full access
- if document_context.owner == macro_user_id {
+ let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {
+ parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?
+ } else {
+ None
+ };
+
+ if internal_user.is_some() {
+ return Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: document_context.document_id.clone(),
+ entity_type: EntityType::Document,
+ },
+ auth: EntityAccessAuth::Internal,
+ entity_permission: EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ },
+ // access_level: AccessLevel::Owner,
+ _marker: PhantomData,
+ });
+ }
+
+ // Check ownership only if authenticated
+ if let Some(ref user_id) = macro_user_id
+ && document_context.owner == *user_id
+ {
return Ok(Self {
- access_level: AccessLevel::Owner,
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: document_context.document_id.clone(),
+ entity_type: EntityType::Document,
+ },
+ auth: EntityAccessAuth::Authenticated(user_id.clone().0),
+ entity_permission: EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ },
+ // access_level: AccessLevel::Owner,
_marker: PhantomData,
});
}
@@ -72,20 +116,42 @@ where
));
}
- // Check access via service
let required_level = T::required_level();
- let access_level = service
- .check_access(
- &macro_user_id,
- &document_context.document_id,
- EntityType::Document,
- required_level,
- )
- .await
- .map_err(ExtractorError::from)?;
+ // Check access based on auth state
+ let access_level: AccessLevel = match macro_user_id.as_ref() {
+ Some(macro_user_id) => service
+ .check_access(
+ Some(macro_user_id),
+ &document_context.document_id,
+ EntityType::Document,
+ required_level,
+ )
+ .await
+ .map_err(ExtractorError::from)?,
+ None => {
+ // Unauthenticated user: check public access only
+ service
+ .check_public_access(
+ &document_context.document_id,
+ EntityType::Document,
+ required_level,
+ )
+ .await
+ .map_err(ExtractorError::from)?
+ }
+ };
Ok(Self {
- access_level,
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: document_context.document_id.clone(),
+ entity_type: EntityType::Document,
+ },
+ auth: macro_user_id
+ .map(|m| EntityAccessAuth::Authenticated(m.0))
+ .unwrap_or(EntityAccessAuth::Unauthenticated),
+ entity_permission: EntityPermission::AccessLevel { access_level },
+ },
_marker: PhantomData,
})
}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/entity_permission.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/entity_permission.rs
index d33e117b9e..ac11381864 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/entity_permission.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/entity_permission.rs
@@ -4,17 +4,19 @@ use std::marker::PhantomData;
use std::sync::Arc;
use axum::{
- RequestPartsExt, async_trait,
+ Extension, RequestPartsExt, async_trait,
extract::{FromRef, FromRequestParts, Path},
http::request::Parts,
};
-use super::ExtractorError;
+use super::{ExtractorError, InternalUser};
use crate::domain::{
- models::{EntityPermission, EntityType},
+ models::{
+ AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
+ },
ports::EntityAccessService,
};
-use model_user::axum_extractor::MacroUserExtractor;
+use model_user::axum_extractor::OptionalMacroUserExtractor;
/// Path parameters for entity permission routes.
#[derive(serde::Deserialize)]
@@ -29,8 +31,8 @@ struct EntityPermissionParams {
/// the user's permission via `EntityAccessService::get_entity_permission`.
#[derive(Debug)]
pub struct EntityPermissionExtractor<Svc> {
- /// The resolved permission.
- pub permission: EntityPermission,
+ /// The entity access receipt
+ pub entity_access_receipt: EntityAccessReceipt,
_marker: PhantomData<Svc>,
}
@@ -47,7 +49,7 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let MacroUserExtractor {
+ let OptionalMacroUserExtractor {
macro_user_id,
user_context,
..
@@ -64,15 +66,64 @@ where
.map_err(|_| ExtractorError::BadRequest("Missing entity_type or entity_id in path"))?;
let parsed_type = parse_entity_type(&entity_type)?;
+
+ let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {
+ parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?
+ } else {
+ None
+ };
+
+ if internal_user.is_some() {
+ return Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id,
+ entity_type: parsed_type,
+ },
+ auth: EntityAccessAuth::Internal,
+ entity_permission: EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ },
+ _marker: PhantomData,
+ });
+ }
+
let user_org_id = user_context.organization_id.map(|id| id as i64);
- let permission = service
- .get_entity_permission(&macro_user_id, &entity_id, parsed_type, user_org_id)
- .await
- .map_err(ExtractorError::from)?;
+ let permission = match macro_user_id.as_ref() {
+ Some(macro_user_id) => service
+ .get_entity_permission(Some(macro_user_id), &entity_id, parsed_type, user_org_id)
+ .await
+ .map_err(ExtractorError::from)?,
+ None => {
+ // For unauthenticated users, check public access at View level
+ let access_level = service
+ .check_public_access(
+ &entity_id,
+ parsed_type,
+ crate::domain::models::AccessLevel::View,
+ )
+ .await
+ .map_err(ExtractorError::from)?;
+ EntityPermission::AccessLevel { access_level }
+ }
+ };
Ok(Self {
- permission,
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id,
+ entity_type: parsed_type,
+ },
+ auth: macro_user_id
+ .map(|m| EntityAccessAuth::Authenticated(m.0))
+ .unwrap_or(EntityAccessAuth::Unauthenticated),
+ entity_permission: permission,
+ },
_marker: PhantomData,
})
}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/history.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/history.rs
index bab468267c..0918b0947d 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/history.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/history.rs
@@ -4,17 +4,19 @@ use std::marker::PhantomData;
use std::sync::Arc;
use axum::{
- RequestPartsExt, async_trait,
+ Extension, RequestPartsExt, async_trait,
extract::{FromRef, FromRequestParts, Path},
http::request::Parts,
};
-use super::{ExtractorError, RequiredAccessLevel};
+use super::{ExtractorError, InternalUser, RequiredAccessLevel};
use crate::domain::{
- models::{AccessLevel, EntityType},
+ models::{
+ AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
+ },
ports::EntityAccessService,
};
-use model_user::axum_extractor::MacroUserExtractor;
+use model_user::axum_extractor::OptionalMacroUserExtractor;
/// Path parameters for history routes.
#[derive(serde::Deserialize)]
@@ -28,10 +30,10 @@ pub struct HistoryParams {
/// Validates the user has access to view the history of a particular item.
///
/// Extracts both item_id and item_type from the path parameters.
-#[derive(Clone, Debug)]
+#[derive(Debug)]
pub struct HistoryAccessExtractor<T, Svc> {
- /// The actual access level the user has.
- pub access_level: AccessLevel,
+ /// The entity access receipt
+ pub entity_access_receipt: EntityAccessReceipt,
_marker: PhantomData<(T, Svc)>,
}
@@ -49,7 +51,7 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let MacroUserExtractor { macro_user_id, .. } = parts
+ let OptionalMacroUserExtractor { macro_user_id, .. } = parts
.extract()
.await
.map_err(|_| ExtractorError::Internal)?;
@@ -64,15 +66,55 @@ where
.parse()
.map_err(|_| ExtractorError::BadRequest("Invalid item_type"))?;
- // Check access via service
+ let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {
+ parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?
+ } else {
+ None
+ };
+
+ if internal_user.is_some() {
+ return Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: item_id,
+ entity_type,
+ },
+ auth: EntityAccessAuth::Internal,
+ entity_permission: EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ },
+ _marker: PhantomData,
+ });
+ }
+
let required_level = T::required_level();
- let access_level = service
- .check_access(&macro_user_id, &item_id, entity_type, required_level)
- .await
- .map_err(ExtractorError::from)?;
+ // Check access based on auth state
+ let access_level: AccessLevel = match macro_user_id.as_ref() {
+ Some(macro_user_id) => service
+ .check_access(Some(macro_user_id), &item_id, entity_type, required_level)
+ .await
+ .map_err(ExtractorError::from)?,
+ None => service
+ .check_public_access(&item_id, entity_type, required_level)
+ .await
+ .map_err(ExtractorError::from)?,
+ };
Ok(Self {
- access_level,
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: item_id,
+ entity_type,
+ },
+ auth: macro_user_id
+ .map(|m| EntityAccessAuth::Authenticated(m.0))
+ .unwrap_or(EntityAccessAuth::Unauthenticated),
+ entity_permission: EntityPermission::AccessLevel { access_level },
+ },
_marker: PhantomData,
})
}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/internal_entity_access.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/internal_entity_access.rs
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
index 9c582f5f31..a72983f931 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
@@ -22,6 +22,15 @@ use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use model_error_response::ErrorResponse;
+/// Marker struct for internal service-to-service requests.
+///
+/// Middleware inserts this into request extensions for authenticated internal callers.
+#[derive(Debug, Clone)]
+pub struct InternalUser {
+ /// The access level granted to the internal user.
+ pub access_level: AccessLevel,
+}
+
/// Trait to convert a unit struct marker into an [`AccessLevel`].
///
/// This allows extractors to be parameterized by required access level.
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs
index dba83f7fc0..c14e3de853 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/project.rs
@@ -10,13 +10,15 @@ use axum::{
};
use serde::de::DeserializeOwned;
-use super::{ExtractorError, RequiredAccessLevel};
+use super::{ExtractorError, InternalUser, RequiredAccessLevel};
use crate::domain::{
- models::{AccessLevel, EntityType},
+ models::{
+ AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
+ },
ports::EntityAccessService,
};
use model::project::BasicProject;
-use model_user::axum_extractor::MacroUserExtractor;
+use model_user::axum_extractor::OptionalMacroUserExtractor;
/// Validates that the user has at least the required access level to a project.
///
@@ -25,12 +27,11 @@ use model_user::axum_extractor::MacroUserExtractor;
///
/// # Prerequisites
///
-/// - User must be authenticated (MacroUserExtractor in extensions)
/// - Project context must be loaded (BasicProject in extensions)
#[derive(Debug)]
pub struct ProjectAccessLevelExtractor<T, Svc> {
- /// The actual access level the user has.
- pub access_level: AccessLevel,
+ /// The entity access receipt
+ pub entity_access_receipt: EntityAccessReceipt,
_marker: PhantomData<(T, Svc)>,
}
@@ -48,7 +49,7 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let MacroUserExtractor { macro_user_id, .. } = parts
+ let OptionalMacroUserExtractor { macro_user_id, .. } = parts
.extract()
.await
.map_err(|_| ExtractorError::Internal)?;
@@ -58,10 +59,46 @@ where
.await
.map_err(|_| ExtractorError::Internal)?;
- // Owner always has full access
- if project_context.user_id == macro_user_id {
+ let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {
+ parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?
+ } else {
+ None
+ };
+
+ if internal_user.is_some() {
return Ok(Self {
- access_level: AccessLevel::Owner,
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: project_context.id.clone(),
+ entity_type: EntityType::Project,
+ },
+ auth: EntityAccessAuth::Internal,
+ entity_permission: EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ },
+ _marker: PhantomData,
+ });
+ }
+
+ // Check ownership only if authenticated
+ if let Some(ref user_id) = macro_user_id
+ && project_context.user_id == *user_id
+ {
+ return Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: project_context.id.clone(),
+ entity_type: EntityType::Project,
+ },
+ auth: EntityAccessAuth::Authenticated(user_id.clone().0),
+ entity_permission: EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ },
_marker: PhantomData,
});
}
@@ -73,20 +110,35 @@ where
));
}
- // Check access via service
let required_level = T::required_level();
- let access_level = service
- .check_access(
- &macro_user_id,
- &project_context.id,
- EntityType::Project,
- required_level,
- )
- .await
- .map_err(ExtractorError::from)?;
+ // Check access based on auth state
+ let access_level: AccessLevel = match macro_user_id.as_ref() {
+ Some(macro_user_id) => service
+ .check_access(
+ Some(macro_user_id),
+ &project_context.id,
+ EntityType::Project,
+ required_level,
+ )
+ .await
+ .map_err(ExtractorError::from)?,
+ None => service
+ .check_public_access(&project_context.id, EntityType::Project, required_level)
+ .await
+ .map_err(ExtractorError::from)?,
+ };
Ok(Self {
- access_level,
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: project_context.id.clone(),
+ entity_type: EntityType::Project,
+ },
+ auth: macro_user_id
+ .map(|m| EntityAccessAuth::Authenticated(m.0))
+ .unwrap_or(EntityAccessAuth::Unauthenticated),
+ entity_permission: EntityPermission::AccessLevel { access_level },
+ },
_marker: PhantomData,
})
}
@@ -149,8 +201,8 @@ pub enum ProjectBodyAccessLevelExtractor<T, V, Svc> {
project: ProjectOrParentId,
/// Marker for the desired access level.
desired: PhantomData<(T, Svc)>,
- /// The actual access level the user has.
- access_level: AccessLevel,
+ /// The entity access receipt
+ entity_access_receipt: EntityAccessReceipt,
/// The parsed body.
body: V,
},
@@ -187,11 +239,19 @@ where
async fn from_request(mut req: Request, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let MacroUserExtractor { macro_user_id, .. } = req
+ let OptionalMacroUserExtractor { macro_user_id, .. } = req
.extract_parts()
.await
.map_err(|_| ExtractorError::Internal)?;
+ let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {
+ req.extract_parts()
+ .await
+ .map_err(|_| ExtractorError::Internal)?
+ } else {
+ None
+ };
+
let Json(json) = req
.extract::<Json<serde_json::Value>, _>()
.await
@@ -210,19 +270,53 @@ where
});
};
+ if internal_user.is_some() {
+ return Ok(Self::FoundProject {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: project.id().to_owned(),
+ entity_type: EntityType::Project,
+ },
+ auth: EntityAccessAuth::Internal,
+ entity_permission: EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ },
+ project,
+ desired: PhantomData,
+ body: cb()?,
+ });
+ }
+
let required_level = T::required_level();
- let access_level = service
- .check_access(
- &macro_user_id,
- project.id(),
- EntityType::Project,
- required_level,
- )
- .await
- .map_err(ExtractorError::from)?;
+ // Check access based on auth state
+ let access_level: AccessLevel = match macro_user_id.as_ref() {
+ Some(macro_user_id) => service
+ .check_access(
+ Some(macro_user_id),
+ project.id(),
+ EntityType::Project,
+ required_level,
+ )
+ .await
+ .map_err(ExtractorError::from)?,
+ None => service
+ .check_public_access(project.id(), EntityType::Project, required_level)
+ .await
+ .map_err(ExtractorError::from)?,
+ };
Ok(Self::FoundProject {
- access_level,
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: project.id().to_owned(),
+ entity_type: EntityType::Project,
+ },
+ auth: macro_user_id
+ .map(|m| EntityAccessAuth::Authenticated(m.0))
+ .unwrap_or(EntityAccessAuth::Unauthenticated),
+ entity_permission: EntityPermission::AccessLevel { access_level },
+ },
project,
desired: PhantomData,
body: cb()?,
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs
index 97b1ef3467..21f49ba372 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs
@@ -9,13 +9,15 @@ use axum::{
http::request::Parts,
};
-use super::{ExtractorError, RequiredAccessLevel};
+use super::{ExtractorError, InternalUser, RequiredAccessLevel};
use crate::domain::{
- models::{AccessLevel, EntityType},
+ models::{
+ AccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
+ },
ports::EntityAccessService,
};
use model::thread::EmailThreadPermission;
-use model_user::axum_extractor::MacroUserExtractor;
+use model_user::axum_extractor::OptionalMacroUserExtractor;
/// Validates that the user has at least the required access level to an email thread.
///
@@ -24,12 +26,11 @@ use model_user::axum_extractor::MacroUserExtractor;
///
/// # Prerequisites
///
-/// - User context must be available (UserContext in extensions)
/// - Thread context must be loaded (EmailThreadPermission in extensions)
#[derive(Debug)]
pub struct ThreadAccessLevelExtractor<T, Svc> {
- /// The actual access level the user has.
- pub access_level: AccessLevel,
+ /// The entity access receipt
+ pub entity_access_receipt: EntityAccessReceipt,
_marker: PhantomData<(T, Svc)>,
}
@@ -47,7 +48,7 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let service = <Arc<Svc>>::from_ref(state);
- let MacroUserExtractor { macro_user_id, .. } = parts
+ let OptionalMacroUserExtractor { macro_user_id, .. } = parts
.extract()
.await
.map_err(|_| ExtractorError::Internal)?;
@@ -57,20 +58,64 @@ where
.await
.map_err(|_| ExtractorError::Internal)?;
- // Check access via service
+ let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {
+ parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Internal)?
+ } else {
+ None
+ };
+
+ if internal_user.is_some() {
+ return Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: thread_context.thread_id.clone(),
+ entity_type: EntityType::EmailThread,
+ },
+ auth: EntityAccessAuth::Internal,
+ entity_permission: EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ },
+ _marker: PhantomData,
+ });
+ }
+
let required_level = T::required_level();
- let access_level = service
- .check_access(
- &macro_user_id,
- &thread_context.thread_id,
- EntityType::EmailThread,
- required_level,
- )
- .await
- .map_err(ExtractorError::from)?;
+ // Check access based on auth state
+ let access_level: AccessLevel = match macro_user_id.as_ref() {
+ Some(macro_user_id) => service
+ .check_access(
+ Some(macro_user_id),
+ &thread_context.thread_id,
+ EntityType::EmailThread,
+ required_level,
+ )
+ .await
+ .map_err(ExtractorError::from)?,
+ None => service
+ .check_public_access(
+ &thread_context.thread_id,
+ EntityType::EmailThread,
+ required_level,
+ )
+ .await
+ .map_err(ExtractorError::from)?,
+ };
Ok(Self {
- access_level,
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: thread_context.thread_id.clone(),
+ entity_type: EntityType::EmailThread,
+ },
+ auth: macro_user_id
+ .map(|m| EntityAccessAuth::Authenticated(m.0))
+ .unwrap_or(EntityAccessAuth::Unauthenticated),
+ entity_permission: EntityPermission::AccessLevel { access_level },
+ },
_marker: PhantomData,
})
}
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
index 533ee8b8bb..379d2f9139 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/mod.rs
@@ -30,7 +30,7 @@ impl AccessRepository for PgAccessRepository {
async fn get_document_access(
&self,
document_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, AccessError> {
Ok(queries::document_access::get_document_access(&self.pool, document_id, user_id).await?)
}
@@ -39,7 +39,7 @@ impl AccessRepository for PgAccessRepository {
async fn get_chat_access(
&self,
chat_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, AccessError> {
Ok(queries::chat_access::get_chat_access(&self.pool, chat_id, user_id).await?)
}
@@ -48,7 +48,7 @@ impl AccessRepository for PgAccessRepository {
async fn get_project_access(
&self,
project_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, AccessError> {
Ok(queries::project_access::get_project_access(&self.pool, project_id, user_id).await?)
}
@@ -57,7 +57,7 @@ impl AccessRepository for PgAccessRepository {
async fn get_thread_access(
&self,
thread_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, AccessError> {
Ok(queries::thread_access::get_thread_access(&self.pool, thread_id, user_id).await?)
}
@@ -65,7 +65,7 @@ impl AccessRepository for PgAccessRepository {
#[tracing::instrument(err, skip(self))]
async fn check_user_channel_membership(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
channel_ids: &[Uuid],
) -> Result<Vec<Uuid>, AccessError> {
Ok(queries::channel_membership::check_user_channel_membership(
@@ -80,13 +80,13 @@ impl AccessRepository for PgAccessRepository {
async fn get_channel_role(
&self,
channel_id: &Uuid,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
user_org_id: Option<i64>,
) -> Result<ChannelRoleResult, AccessError> {
Ok(queries::channel_role::get_channel_role(
&self.pool,
channel_id,
- user_id.as_ref(),
+ user_id.map(AsRef::as_ref).unwrap_or(""),
user_org_id,
)
.await?)
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_membership.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_membership.rs
index e7b9593010..1410477aa0 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_membership.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_membership.rs
@@ -10,10 +10,10 @@ use uuid::Uuid;
#[tracing::instrument(err, skip(pool))]
pub async fn check_user_channel_membership(
pool: &PgPool,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
channel_ids: &[Uuid],
) -> Result<Vec<Uuid>, sqlx::Error> {
- let user_id = user_id.as_ref();
+ let user_id = user_id.map(AsRef::as_ref).unwrap_or("");
let channels = sqlx::query_scalar!(
r#"
SELECT c.id
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs
index 938f31177b..141cec0b33 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs
@@ -13,9 +13,9 @@ use std::str::FromStr;
pub async fn get_chat_access(
pool: &PgPool,
chat_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, sqlx::Error> {
- let user_id = user_id.as_ref();
+ let user_id = user_id.map(AsRef::as_ref).unwrap_or("");
let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(
r#"
WITH RECURSIVE project_hierarchy AS (
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/document_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/document_access.rs
index 9089ddc830..7c8fdd40fb 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/document_access.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/document_access.rs
@@ -13,9 +13,9 @@ use std::str::FromStr;
pub async fn get_document_access(
pool: &PgPool,
document_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, sqlx::Error> {
- let user_id = user_id.as_ref();
+ let user_id = user_id.map(AsRef::as_ref).unwrap_or("");
let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(
r#"
WITH RECURSIVE project_hierarchy AS (
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/project_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/project_access.rs
index 54d7d43711..8393c38e7d 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/project_access.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/project_access.rs
@@ -13,9 +13,9 @@ use std::str::FromStr;
pub async fn get_project_access(
pool: &PgPool,
project_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, sqlx::Error> {
- let user_id = user_id.as_ref();
+ let user_id = user_id.map(AsRef::as_ref).unwrap_or("");
let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(
r#"
-- CTE to recursively find all parent projects, starting from the given project.
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
index a1f4eabeb6..3faa125425 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
@@ -13,9 +13,9 @@ use std::str::FromStr;
pub async fn get_thread_access(
pool: &PgPool,
thread_id: &str,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, sqlx::Error> {
- let user_id = user_id.as_ref();
+ let user_id = user_id.map(AsRef::as_ref).unwrap_or("");
let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(
r#"
-- CTE to recursively find all parent projects for the given email thread.
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index c0b989b039..19c1accf81 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -82,6 +82,7 @@ setup_test_envs:
echo "DATABASE_URL={{ MACRODB }}" >> ./saved_views/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./channels/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./comms_service/.env
+ echo "DATABASE_URL={{ MACRODB }}" >> ./documents/.env
setup_macrodb:
just macro_db_client/create_db
diff --git a/rust/cloud-storage/macro_project_utils/.sqlx/query-28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281.json b/rust/cloud-storage/macro_project_utils/.sqlx/query-28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281.json
new file mode 100644
index 0000000000..98ceb2aeec
--- /dev/null
+++ b/rust/cloud-storage/macro_project_utils/.sqlx/query-28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE \"Project\" SET \"updatedAt\" = NOW() WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281"
+}
diff --git a/rust/cloud-storage/macro_project_utils/Cargo.toml b/rust/cloud-storage/macro_project_utils/Cargo.toml
index be0c1709d6..6f1d82966e 100644
--- a/rust/cloud-storage/macro_project_utils/Cargo.toml
+++ b/rust/cloud-storage/macro_project_utils/Cargo.toml
@@ -6,8 +6,6 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
-macro_db_client = { path = "../macro_db_client" }
-model = { path = "../model" }
sqlx = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/macro_project_utils/justfile b/rust/cloud-storage/macro_project_utils/justfile
new file mode 100644
index 0000000000..d5a52bc432
--- /dev/null
+++ b/rust/cloud-storage/macro_project_utils/justfile
@@ -0,0 +1,6 @@
+DATABASE_URL := "postgres://user:password@localhost:5432/macrodb"
+
+mod sqlx '../sqlx.just'
+
+prepare_db:
+ just sqlx::prepare_db {{ DATABASE_URL }}
diff --git a/rust/cloud-storage/macro_project_utils/src/lib.rs b/rust/cloud-storage/macro_project_utils/src/lib.rs
index cc706b32ee..c6a835f944 100644
--- a/rust/cloud-storage/macro_project_utils/src/lib.rs
+++ b/rust/cloud-storage/macro_project_utils/src/lib.rs
@@ -36,7 +36,7 @@ pub async fn update_project_modified<T>(
&& !old_project_id.is_empty()
{
tracing::trace!(project_id=?old_project_id, "updating project modified date");
- let _ = macro_db_client::projects::update_project_modified_date(&db, &old_project_id).await.inspect_err(|e| {
+ let _ = update_project_modified_date(&db, &old_project_id).await.inspect_err(|e| {
tracing::error!(error=?e, project_id=?old_project_id, "unable to update project modified date");
});
}
@@ -46,10 +46,24 @@ pub async fn update_project_modified<T>(
{
tracing::trace!(project_id=?project_id, "updating project modified date");
- let _ = macro_db_client::projects::update_project_modified_date(&db, &project_id).await.inspect_err(|e| {
+ let _ = update_project_modified_date(&db, &project_id).await.inspect_err(|e| {
tracing::error!(error=?e, project_id=?project_id, "unable to update project modified date");
});
}
}
});
}
+
+async fn update_project_modified_date(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ project_id: &str,
+) -> anyhow::Result<()> {
+ sqlx::query!(
+ r#"UPDATE "Project" SET "updatedAt" = NOW() WHERE id = $1"#,
+ project_id,
+ )
+ .execute(db)
+ .await?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/sync_service_client/src/exists.rs b/rust/cloud-storage/sync_service_client/src/exists.rs
index d219a345bf..16e97dfa45 100644
--- a/rust/cloud-storage/sync_service_client/src/exists.rs
+++ b/rust/cloud-storage/sync_service_client/src/exists.rs
@@ -3,6 +3,7 @@ use anyhow::Result;
use reqwest::StatusCode;
impl SyncServiceClient {
+ #[tracing::instrument(skip(self), err)]
pub async fn exists(&self, document_id: &str) -> Result<bool> {
let full_url = format!("{}/document/{}/exists", self.url, document_id);
let res = self.client.head(&full_url).send().await?;
diff --git a/rust/cloud-storage/sync_service_client/src/metadata.rs b/rust/cloud-storage/sync_service_client/src/metadata.rs
index b70b40ce17..7aa0b21bb3 100644
--- a/rust/cloud-storage/sync_service_client/src/metadata.rs
+++ b/rust/cloud-storage/sync_service_client/src/metadata.rs
@@ -4,6 +4,7 @@ use super::SyncServiceClient;
use anyhow::Result;
impl SyncServiceClient {
+ #[tracing::instrument(skip(self), err)]
pub async fn get_metadata(&self, document_id: &str) -> Result<DocumentMetadata> {
let full_url = format!("{}/document/{}/metadata", self.url, document_id);
let res = self.client.get(&full_url).send().await?;