Cloud storage hexagonal architecture

From macro-inc/macro · View interactive version

Cloud storage hexagonal architecture is an AI agent skill from the GitHub repository macro-inc/macro. Enforce hexagonal architecture in the Rust backend. Use before modifying crates/ or Rust services, especially inbound axum/tool/listener adapters, domain services/ports, outbound adapters, authorization, permissions, database access, or external clients.

How to use this skill

Skill file

Cloud Storage Hexagonal Architecture Guard

Use this skill whenever you add, change, or review Rust code under crates/** or services/** that touches a crate with src/domain, src/inbound, or src/outbound.

This repository follows the ports-and-adapters / hexagonal style described in _Master Hexagonal Architecture in Rust_ and the howtocodeit/hexarch 3-simple-service branch: domain models + ports + services are the center; inbound and outbound adapters are replaceable shells around that center.

Non-negotiable dependency rule

Dependencies point inward:

inbound adapters ──► domain ports/models/services ◄── outbound adapters
composition root ──► inbound + domain service + outbound implementations

Layer responsibilities

Domain (`src/domain/**`)

Put the following here:

Inbound adapters (`src/inbound/**`)

Axum handlers, AI tools, Kafka/listener handlers, lambda handlers, and CLI entrypoints are adapters. Keep them thin:

Inbound adapters must not:

Outbound adapters (`src/outbound/**`)

Put implementation details here:

Outbound adapters must not:

Authorization and `EntityAccessReceipt` rule

Authentication can happen at the edge. Entity access checks should cross the boundary as a typed capability: EntityAccessReceipt<T>.

EntityAccessReceipt<T> means the entity access layer has verified the caller has at least permission T for the entity. Inbound adapters may obtain this receipt through the standard access extractors or by calling the entity access service specifically to mint a receipt. After that, ordinary handlers/tools/listeners must pass the receipt inward instead of re-checking or branching on authorization.

Allowed in inbound:

Forbidden in ordinary inbound handlers/tools/listeners:

Correct pattern:

  1. Pick the minimum required permission type for the use case, e.g. ViewAccessLevel, EditAccessLevel, or OwnerAccessLevel.
  2. In inbound, obtain EntityAccessReceipt<RequiredLevel> using the existing entity access boundary.
  3. Pass that receipt to the domain service method.
  4. In the domain service, perform use-case-specific policy that is not captured by the minimum receipt type, e.g. owner-only share changes inside an edit operation.
  5. Return a domain error such as Unauthorized, Forbidden, or a typed policy error.
  6. Let inbound map that domain/access error to HTTP/tool/listener semantics.
  7. Unit-test allow and deny cases at the domain service level with fake receipts/ports.

Bad vs good

Bad: the handler branches on permissions and performs the protected action itself.

pub async fn edit_document_handler(
    State(state): State<DocumentRouterState>,
    Json(args): Json<EditDocumentServiceArgs>,
) -> Result<Json<EditDocumentResponse>, DocumentError> {
    let access_level = state
        .entity_access
        .get_access_level(current_user(), &args.document_id, EntityType::Document)
        .await?
        .ok_or(DocumentError::Unauthorized)?;

    if access_level < AccessLevel::Edit {
        return Err(DocumentError::Unauthorized);
    }

    if args.share_permission.is_some() && access_level != AccessLevel::Owner {
        return Err(DocumentError::Unauthorized);
    }

    state.document_repo.update_document(args).await?;
    Ok(Json(EditDocumentResponse::success()))
}

Good: inbound obtains a typed receipt and forwards it; the domain service owns policy and orchestration.

pub async fn edit_document_handler<T: DocumentService, Svc: EntityAccessService>(
    access: DocumentAccessExtractor<EditAccessLevel, Svc>,
    State(state): State<DocumentRouterState<T, Svc>>,
    document_context: LoadedDocumentBasic,
    project: ProjectBodyAccessLevelExtractor<EditAccessLevel, EditDocumentServiceArgs, Svc>,
) -> Result<Json<EditDocumentResponse>, DocumentError> {
    state
        .service
        .edit_document(
            access.entity_access_receipt,
            document_context.into_inner(),
            project.into_inner(),
        )
        .await?;

    Ok(Json(EditDocumentResponse::success()))
}
async fn edit_document(
    &self,
    receipt: EntityAccessReceipt<EditAccessLevel>,
    document_context: DocumentBasic,
    args: EditDocumentServiceArgs,
) -> Result<(), DocumentError> {
    if let EntityPermission::AccessLevel { access_level } = receipt.entity_permission() {
        if args.project_id.is_some() && *access_level != AccessLevel::Owner {
            return Err(DocumentError::Unauthorized);
        }

        if args.share_permission.is_some() && *access_level != AccessLevel::Owner {
            return Err(DocumentError::Unauthorized);
        }
    }

    let document_id = receipt.entity().entity_id.clone();
    self.repo
        .edit_document_metadata(document_id, document_context, args)
        .await
}

Pre-write checklist

Before editing code, classify each touched file:

  1. Is it domain, inbound, outbound, or composition/wiring?
  2. What use case is being added or changed?
  3. What domain command/model/error represents it?
  4. Which domain service method should inbound call?
  5. Which outbound capabilities are needed, and are they behind domain port traits?
  6. What authorization/policy decisions are needed, and where will domain service tests cover them?

If a step has no answer, stop and design that boundary before writing code.

Review checklist

For every Rust backend diff, reject or refactor if any of these are true:

Useful inspection commands

Set CRATE to the crate you are touching, for example CRATE=crates/documents.

# Domain must not know transport or concrete infrastructure.
rg -n "use (axum|http::StatusCode)|IntoResponse|Json<|Router|HeaderMap|Request<|sqlx::|PgPool|aws_sdk|redis::|reqwest|crate::inbound|crate::outbound" "$CRATE/src/domain" --glob '*.rs'

# Inbound authz/policy hits require inspection. Receipt-minting extractors are allowed;
# ordinary handlers should forward EntityAccessReceipt<T> instead of branching.
rg -n "entity_access|EntityAccessReceipt|roles_and_permissions|AccessLevel|RoleId|owner|admin|member|tenant|team|project|permission|authorize|authz|can_|ensure_.*permission|Forbidden|Unauthorized" "$CRATE/src/inbound" --glob '*.rs'

# Inbound should not do persistence or infrastructure work.
rg -n "sqlx::|query!|query_as!|PgPool|Transaction|aws_sdk|redis::|opensearch|reqwest|S3|Sqs|Dynamo" "$CRATE/src/inbound" --glob '*.rs'

# Outbound must not depend on inbound transport.
rg -n "crate::inbound|axum|IntoResponse|Json<|Router|StatusCode" "$CRATE/src/outbound" --glob '*.rs'

rg hits are not automatically failures, but every hit must be explained by layer responsibilities. When in doubt, move policy inward.

If you find an existing violation

Final response requirement

When you use this skill, explicitly state that the hexagonal boundary was checked and summarize where authz/business policy lives after your change.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.