← Wiki

Return Address in Mule: the invoice goes to the system that asked for it

  • 9 min read
On this page

Code

Two systems ask invoicing for an order’s invoice: checkout, when the customer completes the purchase, and the back office, when an agent reissues the invoice. Invoicing replies asynchronously and needs to know, for each request, where to send the invoice. Having the request say where the reply goes is the problem Return Address solves. In Mule, the address arrives in an HTTP header and becomes the path of an HTTP Request, which accepts an expression.

The problem

On the Request-Reply page, the warehouse always replies to the same channel, fixed in the configuration. That works while there is a single requestor. With two, invoicing would have to know each one’s channel and choose between them, and every new requestor would force a change to invoicing. Checkout and the back office have nothing in common except asking for the same invoice; only the requestor knows where it wants the reply.

The pattern in the book

The book asks how the replier knows where to send the reply. The solution is for the request to contain a Return Address that indicates where to send the reply (Return Address). That way the replier does not need to know where to reply: it asks the request. If different requests to the same replier want replies in different places, the replier knows the destination of each. The knowledge of which channels to use stays with the requestor and does not have to be fixed in the replier. The book puts the Return Address in the message header, because it is not part of the data being transmitted.

The diagram redraws the book’s sketch (CC BY 4.0) in the orders scenario:

Checkout sends Invoicing the request with reply to: checkout. Back office sends Invoicing the request with reply to: back office. Invoicing sends the invoice to the checkout channel, which delivers it to Checkout, and the invoice to the back office channel, which delivers it to Back office.

In Mule

The HTTP Listener puts the request body in the payload and the rest of the HTTP data, headers included, in the attributes (Configure HTTP Listener Source). The reply address arrives in the X-Reply-To header, which the flow reads from attributes.headers, and becomes the path of the HTTP Request, a parameter that accepts an expression (Configure HTTP Request Operation). Invoicing answers 202 and sends the invoice from inside an Async scope, which runs in parallel with the main flow (Async Scope).

Mule already has implicit return addresses. The HTTP Listener replies on the same connection the request arrived on, and the VM Connector’s Publish Consume waits for the reply on a temporary reply-to queue that it creates (VM Connector Reference). With JMS, the listener does more: when the incoming message declares a destination in the ReplyTo header and the flow ends without an error, it produces and publishes the reply itself (Listen for New Messages Using the JMS Connector). That is the book’s Return Address done by the connector, in a listener that acts as an Event-Driven Consumer. The example makes the address explicit because the reply is asynchronous and goes over HTTP, where no open connection is waiting.

The endpoint POST /eip/invoice-requests, with the X-Reply-To header, goes to the decision X-Reply-To in /eip/requestors/{r}/invoice-replies?. If not, it answers 400. If so, it answers 202 ACCEPTED and, asynchronously, issues the invoice; an http:request with path = X-Reply-To delivers the invoice to the requestor’s inbox.

The Return Address says where the reply goes; it does not say which request it belongs to. When the requestor has several pending requests and needs to match each reply, the pattern is the Correlation Identifier. Here the invoice carries the orderId, which is enough for the example.

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule does not list the Return Address. The closest row is Request-Reply’s, which points to the request and reply connectors in general; the address in the X-Reply-To header and the allowlist of paths are decisions of this page’s flow, not of a component.

The example

Invoicing reads the header and validates the request and the address before accepting:

<set-variable doc:name="SET vReplyTo" variableName="vReplyTo" value="#[attributes.headers['x-reply-to'] default '']" />
<choice doc:name="Validate Invoice Request">
	<when expression="#[(not (payload is Object)) or isEmpty(payload.orderId) or not (payload.amount is Number)]">
		<raise-error doc:name="Raise BAD_REQUEST Error - Missing fields" type="APP:BAD_REQUEST" description="orderId and amount (number) are required" />
	</when>
	<when expression="#[not (vars.vReplyTo matches /^\/eip\/requestors\/[A-Za-z0-9-]+\/invoice-replies$/)]">
		<logger doc:name="WARN: Log rejected reply address" level="WARN" message="#['Invoice request for orderId=' ++ payload.orderId ++ ' rejected, X-Reply-To not allowed: ' ++ vars.vReplyTo ++ ', correlationId=' ++ correlationId]" />
		<raise-error doc:name="Raise BAD_REQUEST Error - Bad reply address" type="APP:BAD_REQUEST" description="X-Reply-To must be a path of the form /eip/requestors/{requestor}/invoice-replies" />
	</when>
</choice>

In the repository: src/main/mule/eip/return-address/return-address.xml

The regular expression is the allowlist of paths: only a path of this application in the form /eip/requestors/{requestor}/invoice-replies gets through. A missing header, an absolute URL or another path of the application gets 400.

After accepting, the invoice leaves from inside the Async for the address that came with the request:

<async doc:name="Async Reply To Return Address">
	<ee:transform doc:name="Issue Invoice">
		<ee:message>
			<ee:set-payload><![CDATA[%dw 2.0
output application/java
---
{
	orderId: vars.vInvoiceRequest.orderId,
	invoiceId: "INV-" ++ uuid(),
	amount: vars.vInvoiceRequest.amount,
	issuedAt: now() as String
}]]></ee:set-payload>
		</ee:message>
	</ee:transform>
	<http:request doc:name="POST Invoice To Return Address" config-ref="eip-self-http-request-config" method="POST" path="#[vars.vReplyTo]">
		<http:body><![CDATA[#[output application/json --- payload]]]></http:body>
	</http:request>
	<logger doc:name="INFO: Log invoice sent" level="INFO" message="#['Invoice for orderId=' ++ vars.vInvoiceRequest.orderId ++ ' sent to ' ++ vars.vReplyTo ++ ', correlationId=' ++ correlationId]" />
</async>

Only the path comes from the request. The host is in the eip-self-http-request-config configuration, in eip-global.xml, fixed to localhost and the application’s port. Each requestor has its own channel in the same flow, POST /eip/requestors/{requestor}/invoice-replies, which stores the invoice in an Object Store under the key requestor|orderId; the GET on the same path lists only that requestor’s invoices.

Caveats

  • The return address is an input from the caller. A replier that calls any URL it receives can be led to call anything. OWASP calls this Server-Side Request Forgery and lists user-supplied webhooks and callback URLs among the typical cases (Server-Side Request Forgery Prevention Cheat Sheet). The example accepts only paths of one form and keeps the host fixed in the configuration. This page’s recommendation, which OWASP also makes: to send the reply to another host, use an allowlist of hosts, checked before the call.
  • A host in an expression creates one HTTP client per value. DataWeave expressions in the HTTP Request configuration make the configuration dynamic: at each use, Mule evaluates the expressions and creates and initializes a new instance of the configuration for each distinct set of values (Configure HTTP Request Operation). Putting the X-Reply-To host in the configuration would make each new requestor create one more client. The example puts the expression only in the operation’s path, which is not in the configuration.
  • With JMS, the automatic reply may be unwanted. Because the JMS listener replies on its own when there is a ReplyTo, a flow that only consumes the message also publishes a reply. The documentation shows how to turn that off with Ignore Jms replyTo Header (Listen for New Messages Using the JMS Connector), and the release notes record the option as new in JMS Connector 1.7.0 (JMS Connector Release Notes).
  • An invoice that fails to go out is lost. The Async does not inherit the main flow’s error handling (Async Scope). As in Request-Reply, the example has no retry: if the POST to the return address fails, the requestor does not receive the invoice and is not told.

When not to use it

With a single requestor, a fixed address in the replier’s configuration is simpler and does not open the door to arbitrary addresses; that is the design of the Request-Reply page. And in a synchronous HTTP reply, the return address is already the open connection: sending an X-Reply-To on a call that waits for the response only duplicates the path.

Running the example and the tests

git clone https://github.com/brunosouzas/mulesoft-patterns-examples.git
cd mulesoft-patterns-examples
mvn clean test

The project needs Java 17, Maven 3.9+ and the Mule 4.9 runtime. MUnit runs on the Enterprise runtime, so Maven needs access to the MuleSoft Enterprise repository (credentials in ~/.m2/settings.xml).

The return-address-test-suite.xml suite pins the behavior, observed on Mule 4.9.17 with MUnit 3.7.1:

Test What it proves
ra-each-requestor-gets-the-reply-at-its-own-address Checkout and the back office request invoices with different X-Reply-To values, and each receives only its own
ra-request-without-return-address-returns-400 A request without X-Reply-To gets 400 and no reply goes out
ra-return-address-outside-the-allowed-paths-returns-400 An absolute URL or another application path as X-Reply-To gets 400, and the replier calls neither

The last test sends a URL on another host and the application’s payment callback path, and checks that neither was called. The same test also checks the 400 for a request without amount and for a reply without orderId:

<munit-tools:assert-that doc:name="Absolute URL 400" expression="#[vars.vAbsolute.status]" is="#[MunitTools::equalTo(400)]" />
<munit-tools:assert-that doc:name="Other path 400" expression="#[vars.vOtherPath.status]" is="#[MunitTools::equalTo(400)]" />
<munit-tools:assert-that doc:name="No amount 400" expression="#[vars.vNoAmount.status]" is="#[MunitTools::equalTo(400)]" />
<munit-tools:assert-that doc:name="Reply without orderId 400" expression="#[vars.vBadReply.status]" is="#[MunitTools::equalTo(400)]" />
<munit-tools:verify-call doc:name="Rejected addresses logged" processor="logger" times="2">
	<munit-tools:with-attributes>
		<munit-tools:with-attribute attributeName="doc:name" whereValue="WARN: Log rejected reply address" />
	</munit-tools:with-attributes>
</munit-tools:verify-call>
<munit-tools:verify-call doc:name="No reply sent" processor="http:request" times="0">
	<munit-tools:with-attributes>
		<munit-tools:with-attribute attributeName="doc:name" whereValue="POST Invoice To Return Address" />
	</munit-tools:with-attributes>
</munit-tools:verify-call>

In the repository: src/test/munit/eip/return-address-test-suite.xml

To call the endpoints, run the application in Anypoint Studio (port 8081) and use the Return Address entries in requests.http:

### EIP return address — the invoice goes to the address in X-Reply-To
POST {{base}}/eip/invoice-requests
Content-Type: application/json
X-Reply-To: /eip/requestors/checkout/invoice-replies

{ "orderId": "ORD-4201", "amount": 72.5 }

###
POST {{base}}/eip/invoice-requests
Content-Type: application/json
X-Reply-To: /eip/requestors/backoffice/invoice-replies

{ "orderId": "ORD-4202", "amount": 30 }

###
GET {{base}}/eip/requestors/checkout/invoice-replies

In the repository: requests.http

Checkout’s GET lists only the invoice for ORD-4201. The other patterns are in the catalog of integration patterns in Mule and, by component name, in the index by component.

Code for this page