# mulesoft Mule Gateway - Full Documentation --- product: Mule Gateway --- # Anypoint Mule Gateway > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine includes an embedded Mule Gateway. Mule Gateway enables you to add a dedicated orchestration layer on top of your backend APIs and services to help you separate orchestration from implementation. You can leverage the governance capabilities of API Manager to apply, among other capabilities, throttling, security, caching, and logging to your APIs. For example, using Mule Gateway you can: - Apply a basic authentication policy on top of a Mule application. - Enrich an incoming or outgoing message. - Add any other complex capability to an API without having to write any code. If you want to apply policies and generate analytics info, you must use either: - An API defined in a Mule application. - A Mule application that proxies your existing backend implementation. For more information, see [Mule Gateway Overview](https://docs.mulesoft.com/mule-gateway/mule-gateway-capabilities-mule4). --- product: Mule Gateway --- # Anypoint Platform Gateways > For the full documentation index, see: https://docs.mulesoft.com/llms.txt An API gateway allows you to add a dedicated orchestration layer on top of your backend APIs and services to help you separate orchestration from implementation concerns. You can then leverage the governance capabilities of API Manager to apply, among other capabilities, throttling, security, caching, and logging to your APIs. Anypoint Platform offers three different runtime options for managing and securing your APIs. ## Omni Gateway Omni Gateway is an ultrafast API gateway designed to manage and secure APIs running anywhere. Built to seamlessly integrate with DevOps and CI/CD workflows, Omni Gateway delivers the performance required for the most demanding applications and microservices while providing enterprise security and manageability across any environment. For more information, see [Getting Started with Omni Gateway](https://docs.mulesoft.com/gateway/latest/gateway-getting-started). ## Anypoint Mule Gateway Mule runtime engine includes an embedded Mule Gateway. You can leverage the governance capabilities of API Manager to apply, among other capabilities, throttling, security, caching, and logging to your APIs. For example, using Mule Gateway you can: - Apply a basic authentication policy on top of a Mule application. - Enrich an incoming or outgoing message. - Add other complex capabilities to an API without writing code. If you want to apply policies and generate analytics info, you must use either: - An API defined in a Mule application. - A Mule application that proxies your existing backend implementation. For more information, see [Mule Gateway Overview](https://docs.mulesoft.com/mule-gateway/mule-gateway-capabilities-mule4). --- product: Mule Gateway --- # API Autodiscovery > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Configuring autodiscovery allows a deployed Mule runtime engine (Mule) application to connect with API Manager to download and manage policies and to generate analytics data. Additionally, with autodiscovery, you can configure your Mule applications to act as their own API proxy. When autodiscovery is correctly configured in your Mule application, you can say that your application’s API is _tracked by_ (green dot) or _paired to_ API Manager. You can associate an API in a Mule setup with only one autodiscovery instance at a given time. > [!NOTE] The flow referenced for autodiscovery must use an > [HTTP Listener](https://docs.mulesoft.com/http-connector/1.10/http-listener-ref) component. Other connectors that use > HTTP as an underlying transport aren’t supported for policy enforcement. ## Prerequisites To [configure autodiscovery for your Mule application](https://docs.mulesoft.com/mule-gateway/mule-gateway-config-autodiscovery-mule4), ensure that: - The API exists in API Manager and is configured as either a basic endpoint, or a proxy endpoint. - The Mule application is configured to use Anypoint Platform credentials. The platform credentials give your application access to the API Configuration in API Manager. You must configure your platform credentials before starting Mule. - The autodiscovery element is configured in your Mule application. This XML element must point to the specific API in API manager which you want to pair to. ## Proxy Endpoint vs Basic Endpoint If you configured a proxy endpoint, your autogenerated proxy is already correctly configured with the autodiscovery element. Additionally, if you want to take advantage of the platform deployment capabilities, such as 1-Click deployment, the API Manager credentials are automatically set for you. ## See Also - [API Proxy](https://docs.mulesoft.com/api-manager/latest/api-proxy-landing-page) - [Configuring API Autodiscovery in a Mule 4 Application](https://docs.mulesoft.com/mule-gateway/mule-gateway-config-autodiscovery-mule4) - [Configuring Organization Credentials in Mule Runtime 4](https://docs.mulesoft.com/mule-gateway/mule-gateway-org-credentials-mule4) --- product: Mule Gateway keywords: api security, identification, correlation, api gateway, mule gateway, gateway, policy --- # API Security-Identification Header Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

API Security-Identification Header

Summary

Adds API instance identifiers as response headers for external security platform correlation

Category

Security

First Mule version available

v4.12.0

Returned Status Codes

No return codes exist for this policy.

## Summary The API Security-Identification Header policy injects organization and API instance identifiers as response headers to enable integration with external security platforms such as Akamai. The policy adds these headers in the response phase: - `x-ms-correlation-id-1`: Contains the business group ID - `x-ms-correlation-id-2`: Contains the API instance ID The policy has no configuration parameters and operates transparently without blocking traffic. If the required metadata is unavailable, the response continues without the headers and a warning is logged for each missing identifier. If the backend already returns `x-ms-correlation-id-1` or `x-ms-correlation-id-2` headers, the policy overwrites these values with the platform metadata values. ## Configuring Policy Parameters This policy has no user-configurable parameters, but the policy requires the following system properties to be configured for the Mule runtime: - `anypoint.platform.client_id`: The client ID for authenticating with Anypoint Platform - `anypoint.platform.client_secret`: The client secret for authenticating with Anypoint Platform - `anypoint.platform.base_uri`: The base URI for the Anypoint Platform API (for example, `[https://anypoint.mulesoft.com](https://anypoint.mulesoft.com)`) > [!NOTE] These properties are typically configured automatically when running Mule runtime with > Anypoint Platform. ## Logging The policy logs the following information: - **INFO level**: Organization ID retrieval status during policy initialization (for example: `OrgIdRetriever.initialise() complete — organizationId=`) - **WARN level**: When system properties are not configured or when organization ID retrieval fails during initialization ## Example Response Given the following metadata: - Organization ID: `a1b2c3d4-e5f6-7890-abcd-ef1234567890` - API instance ID: `19203842` The policy adds the following response headers: x-ms-correlation-id-1: a1b2c3d4-e5f6-7890-abcd-ef1234567890 x-ms-correlation-id-2: 19203842 --- product: Mule Gateway keywords: policy, endpoint --- # Apply a Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt For Mule Gateway, you apply included policies via **API Manager**. The following steps demonstrate this. You can apply a policy either to the entire API (default) or to specific methods and resources of an API. > [!NOTE] To apply a policy for Mule Gateway, a Mule application must first be deployed with a flow > that uses an [HTTP Listener](https://docs.mulesoft.com/http-connector/1.10/http-listener-ref) component and is linked to > the API through autodiscovery. The flow must use the HTTP Listener component specifically, not > other connectors that use HTTP as an underlying transport. To apply a policy: 1. Go to **Anypoint Platform > API Manager**. 2. In **API Administration** click the name of the API to which to apply a policy. 3. From the left navigation menu, click **Policies**. 4. Click **\+ Add policy**. 5. Select the policy to apply. 6. Configure the required configuration parameters. For policy configuration parameters, see [Included Policies Directory](https://docs.mulesoft.com/mule-gateway/policies-included-directory). 7. Click **Apply** ## Upgrade a Policy Definition To upgrade a policy in API Manager: 1. Go to **Anypoint Platform > API Manager**. 2. In **API Administration** click the name of the API with the policy to upgrade. 3. From the left navigation menu, click **Policies**. 4. Click the more options menu (![1%](/mulesoft/current/en-us/mule-gateway/_images/more-options-menu.png)) of the policy to upgrade, and then click **Edit configuration**. 5. Select the **latest** version for **Policy version**. 6. Click **Save**. > [!NOTE] You must manually check for implementation version updates only when upgrading the > **patch** version of a definition (for example, 1.0.0 to 1.0.1). For **minor** and **major** > version upgrades (for example, 1.0.0 to 1.1.0 or 1.0.0 t0 2.0.0), the implementation updates > automatically. To upgrade a policy implementation, see > [Upgrade a Policy Implementation](#upgrade-policy-implementation). ## Upgrade a Policy Implementation To upgrade a policy implementation in API Manager: 1. Go to **Anypoint Platform > API Manager**. 2. In **API Administration** click the name of the API with the policy to upgrade. 3. From the left navigation menu, click **Policies**. 4. Click the more options menu (![1%](/mulesoft/current/en-us/mule-gateway/_images/more-options-menu.png)) of the policy to upgrade, and then click **Check for implementation updates**. 5. If implementation updates are available, click **Update all**. 6. Click **Ok**. --- product: Mule Gateway --- # Applying Automated Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Users with **Organization Admin**, **Environment Admin**, or with a role to **Manage Policies** in the environment can create, edit and delete Automated Policies. ## Task Prerequisites Before you apply an automated policy, ensure that: - Mule runtime engine (Mule) is installed with [Mule Gateway capabilities](https://docs.mulesoft.com/mule-gateway/mule-gateway-capabilities-mule4) enabled. - An [API](https://docs.mulesoft.com/api-manager/latest/api-instance-landing-page) configured with a basic endpoint or a proxy endpoint exists in API Manager. - A Mule application is deployed with a [HTTP(s) based flow](https://docs.mulesoft.com/http-connector/1.10/http-listener-ref), which is linked to the API through Autodiscovery. When Autodiscovery is correctly configured in your Mule application, your application’s API is said to be tracked by or paired to API Manager. Autogenerated proxies handle these prerequisites in most cases. Mule Gateway reconciles the automated policies applied to an API in API Manager during runtime. ## Apply Automated Policy To apply an automated policy: 1. In **API Manager**, select **Automated Policies** from the left navigation menu. 2. Click **Apply new automated policy**. 3. Select the provided policy that you want to configure as a provided policy. You can configure any provided policies for Mule 4 as an automated policy. See the [list of available Provided Policies](https://docs.mulesoft.com/gateway-home/) to learn how to configure each one of them. When configuring an automated policy, at the end of the policy configuration page, there is a **Rule of Applications** sub-section. This section dictates the set of runtimes that the policy affects. Configure the following parameters: - **Version Range** You can configure a range of Mule runtime versions to inherit the automated policy. For example, if the input **From Version** is 4.1.2 and the **To** is 4.1.4, the automated policy is applied to all deployed APIs inside this range. An API deployed on 4.1.5 is not be affected by the policy. You can include values such as `4.1.x`. For example, adding a range from 4.1.1 to 4.1.x covers all runtime patch releases. An API Proxy based on 4.1.0 is not included in this range, because it’s lower than the 4.1.1. If you are configuring a type of policy that also exists as a provided policy in an API proxy affected by your rule of application, you must solve the conflict before continuing. Refer to the [Conflict Management](#conflict-management) section below for more information on how to solve them. - **Java versions** Select to apply the policy to **All Java versions** or **Choose specific Java versions**. If you choose to apply the policies to specific Java versions, chose either **Java 8**, **Java 17**, or both. 4. Click **Apply**. > [!TIP] It’s recommended to apply an automated policy in a lower environment before applying in a > production environment and ensure to review that an automated policy doesn’t affect the existing > API contracts. ## Conflict Management Since automated policies have priority over API level policies, when adding an automated policy that it is already applied as an API Level policies, on API deployed using the selected runtime range, a conflict will be detected that needs to be solved before proceeding. When a conflict is detected, a popup with the list of conflicting APIs will be displayed. A message will be shown with the first 10 APIs with conflicts and the total amount. You can use this endpoint to access the list of all APIs: ```CURL curl -X GET \ https://anypoint.mulesoft.com/xapi/v1/automated-policies/{groupId}/{assetId}/conflicting-apis \ -H 'Authorization: Bearer {token}' ``` To solve conflicts, you can either select the APIs from the list of already configured APIs and manually disable or remove the conflicting policy or choose to override all conflicting policies for the already configured APIs. If this last option is chosen the conflicting policies in the APIs will be disabled. If Automated Policy is removed, the API policy will be re-enabled automatically. ## Deploying New APIs When managing new APIs, you can see information regarding the status of the automated policies applied to your environment in the **Policies** tab. No automated policies are shown until the application is in Active status. After the application is deployed, a list of applied automated policies will be listed in the **Policies** tab of the API. Users with **View Policies** role for the environment will able to see the list of automated policies applied. If an application is deployed to an environment which has an automated policy that doesn’t cover the deployed runtime, for example with an automated policy affecting a runtime range from 4.1.2 to 4.1.4, and a user deploys to a 4.1.5 runtime, a notification will be sent to the organization, and environment administrators, to let them know of this activity. ### Viewing Coverage Status View the **Coverage status** of an API instance to see if an automated policy covers your API instance or why it doesn’t. Typically, instances are not covered due to their runtime type or runtime version. To view what API instances are covered by an automated policy: 1. Navigate to **Anypoint Platform** > **API Manager**. 2. In API Administration, click **Automated Policies**. 3. Click the more options button (![Three circles displayed horizontally, representing the More Options menu](/mulesoft/current/en-us/mule-gateway/_images/more-options-menu.png)) of the policy whose coverage you want to view, and then click **See covered APIs**. 4. View the API instance’s coverage status in the **Coverage status** column. > [!NOTE] To filter by coverage status, click the coverage status dropdown and select a coverage > status option. ## Auditing Applied Policies It is possible to audit and get a list of all affected APIs by an automated policy. Reports can be filtered by runtime version, and by an operation. To get the list of all automated policies in an environment ```curl curl -X GET \ https://anypoint.mulesoft.com/apimanager/api/v1/organizations/{organizationId}/automated-policies?environmentId={envId} \ -H 'Authorization: Bearer {token}' ``` To get the list of APIs included in the range of automated policy or APIs where the automated policy is not applied. ```curl curl -X GET \ https://anypoint.mulesoft.com/apimanager/api/v1/organizations/{organizationId}/automated-policies/{automatedPolicyId}/apis \ -H 'Authorization: Bearer {token}' ``` ## See Also - [Included Policies](https://docs.mulesoft.com/mule-gateway/policies-included-directory) --- product: Mule Gateway --- # Applying Offline Custom Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt An offline policy is applied directly to the runtime and not through API Manager. When you create a file in the offline-policies directory, Mule runtime engine (Mule) detects the presence of the file and starts applying the policy. Mule then generates the JSON and XML policy files in a new directory in `%MULE_HOME%/policies`. ## Task Prerequisites Before you apply an offline custom policy, ensure that: - Mule runtime engine (Mule) is installed with [Mule Gateway capabilities](https://docs.mulesoft.com/mule-gateway/mule-gateway-capabilities-mule4) enabled. - An [API](https://docs.mulesoft.com/api-manager/latest/api-instance-landing-page) configured with a basic endpoint or a proxy endpoint exists in API Manager. - A Mule application is deployed with a [HTTP(s) based flow](https://docs.mulesoft.com/http-connector/1.10/http-listener-ref), which is linked to the API through Autodiscovery. When Autodiscovery is correctly configured in your Mule application, your application’s API is said to be tracked by or paired to API Manager. ## Apply an Offline Custom Policy To apply an offline custom policy: 1. If you do not want to use the policy template from Exchange due to various reasons, place the template JAR in the following directory before you apply the offline policy to the API. `%MULE_HOME%/policies/policy-templates` 2. Create a JSON file in `%MULE_HOME%/policies/offline-policies` directory that defines the policy configuration. 3. Name the JSON file after the policy ID. 4. In the file, include the following configuration specifications: - Policy template information Specify the Exchange groupId, assetId, and version of the template used to deploy the offline policy definition. - IDs of the APIs that the policy will be applied to - A list of resources that the policy will be applied to - Order of the policy - Parameters if the defined template is using handlebars variables The following example shows a typical offline policy definition: { "template" : { "groupId" : "com.mulesoft.anypoint", "assetId" : "policyTemplate", "version" : "0.1.0" }, "api": \[ { "id": "1" }, { "id": "2" } \], "order": 1, "configuration" : { "payload" : "Payload" } } 5. After you apply a custom offline policy, you must manually deploy it to a Mule runtime engine (Mule) file system. ## See Also - [Removing Offline Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-offline-remove) --- product: Mule Gateway --- # Automated Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Use automated policies to enforce security and logging requirements by applying the same policies to all APIs running in Mule. With policy automation, you can quickly design, build, and deploy secure and consistent APIs. Automated policies enable you to deploy APIs with confidence because the target environment automatically enforces critical policies, resulting in reduced errors. An administrator no longer needs to remember to insert a policy to enforce common standards manually. You can configure all [included policies](https://docs.mulesoft.com/mule-gateway/policies-included-directory) and [custom policies](https://docs.mulesoft.com/mule-gateway/policies-custom-overview) as automated policies and apply them to the APIs running in an environment. ## Automated Policies in Mule The following rules apply to automated policies in Mule runtime engine (Mule): - Automated policies are available only for Mule 4 APIs using a MuleSoft-hosted control plane. - Automated policies support all runtime deployment targets (CloudHub, Runtime Fabric, and hybrid). - Automated policies have priority over the same types of policies already applied to a specific API proxy. For example, if an API proxy running Mule 4.1.2 has an IP Allowlist policy to allow only the IP range 192.168.100.0/22 (from 192.168.100.0 to 192.168.103.255), and a new IP Allowlist automated policy is created to only allow the IP range 192.168.100.14/24 (from 192.168.100.0 to 192.168.100.255) and is applied to all supported Mule versions (4.1.1 and above), then this latter automated policy prevails. Note that in the above example, the IP range changed when the automated policy was applied. Additionally, if there is an automated policy already applied, you cannot apply that specific type of policy as a provided policy in a specific API proxy. - As an administrator, you can apply policies specific to external identity providers (IdPs, such as OpenID) if the environment to which you want to apply policies includes them. The policy is then enforced only on those APIs that have the same IdPs configured. For example, if you apply the PingFederate Access Token Enforcement policy, the policy is enforced on only those APIs that are configured to use PingFederate as the IdP. > [!NOTE] [Alerts](https://docs.mulesoft.com/api-manager/latest/using-api-alerts) cannot be added to API instances > protected by automated policies. ## See Also - [Applying Automated Policies](https://docs.mulesoft.com/mule-gateway/policies-automated-applying) --- product: Mule Gateway keywords: basic authentication, ldap, api gateway, mule gateway, gateway, policy --- # Basic Authentication: LDAP Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

Basic Authentication: LDAP

Summary

Allows access based on the basic authorization mechanism, with user-password defined on LDAP

Category

Security

First Mule version available

v4.0.0

Returned Status Codes

401 - Unauthorized or invalid client application credentials

## Summary The Lightweight Directory Access Protocol (LDAP) authentication policy specifies how to restrict access to an API using LDAP authentication mechanism. This policy is available in Omni and Mule 4 or later. When an error is encountered, the Basic Authentication - LDAP policy returns an "WWW-Authenticate" HTTP header field using the format:\`WWW-Authenticate: Basic realm="mule-realm"\`. LDAP is an inverted tree, and each leaf has a username-password pair and associated metadata. Each level is like a tree branch. For more information about LDAP, see [About LDAP](https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol). ## Configuring Policy Parameters ### Mule Gateway When you apply the Basic Authentication - LDAP policy to your API from the UI, you can configure the following parameters to connect to your LDAP or Active Directory:
ParameterDescription

LDAP Server URL

The URL of your LDAP OR LDAPS server, including the port number.

LDAP User DN

The name of the user or user group with access to traverse and list users of LDAP.

LDAP User Password

The password for the user or user group. The password must be a secure value that, once specified, is not visible or retrievable.

LDAP Search Base

The starting point for the search in the directory tree.

LDAP Search Filter

The criteria for the filter for the Active Directory or the OpenLDAP model, as shown in the examples.

Note that all parameters are required to successfully configure LDAP or Active Directory. ## Example Configuration for an Active Directory You can configure Active Directory for your LDAP authentication by providing the following values:
FieldExample Literal String ValueExample Secure Property Placeholder

LDAP Server URL

ldap://174.19.33.17:389/

${ldap.server.url}

LDAP Secure Server URL (SSL)

ldaps://my-company-ldap.cloudhub.io:1010/

${ldap.server.url}

LDAP Server User DN

CN=Administrator,CN=Users,DC=my-company,DC=com

${ldap.user.dn}

LDAP User Password

somePassword

${ldap.password}

LDAP Search Base

CN=Users,DC=my-company,DC=com

${ldap.search.base}

LDAP Search Filter

(sAMAccountName={0})

${ldap.search.filter}

The search filter string in the example is specific to Active Directory applications. ## Example Configuration for OpenLDAP You can configure OpenLDAP for your LDAP authentication by providing the following values:
FieldExample Literal String ValueExample Secure Property Placeholder

LDAP Server URL

ldap://174.19.33.17:389/

${ldap.server.url}

LDAP Secure Server URL (SSL)

ldaps://my-company-ldap.cloudhub.io:1010/

${ldap.server.url}

LDAP Server User DN

cn=Manager,dc=my-company,dc=com

${ldap.user.dn}

LDAP User Password

somePassword

${ldap.password}

LDAP Search Base

ou=people,dc=my-company,dc=com

${ldap.search.base}

LDAP Search Filter

(uid={0})

${ldap.search.filter}

The search filter string in the example is specific to OpenLDAP applications. ## How This Policy Works The Basic Authentication - LDAP policy intercepts the request to the protected resource and looks for the `Authorization` HTTP header. The policy then extracts the username and password encoded in Base64 and then requests the configured LDAP instance to determine if the user credentials are correct in the provided LDAP context. You can configure the Basic Authentication: LDAP policy to credentials using the following methods: - Search for the valid username and password pair in the level specified. - Search for the valid username and password pair in the level specified, including lower levels. This search option is comprehensive, however, can result in slow performance. ### Search Scope Your search scope options differ depending on your policy version. The search scope options are one level for LDAP 1.0.0 and two levels (subtree) for LDAP 1.1.0. You can choose between `one level` and `subtree` search scopes by using the `LDAP Search in subtree` option. The `LDAP search base` is the starting point for the search in the directory. ### One-Level Search Scope With this option, the filter affects only the objects immediately subordinate to the `LDAP search base`, and not the `LDAP search base` itself. In the following example, the first level has four entries: two users and two groups. These are the only entries that are a part of any search: ![A hierarchical chart displays organizational structure and user IDs](/mulesoft/current/en-us/mule-gateway/_images/search-scope.png) If you set the search filter to `(uid={0})`, only `Jane` and `Paul` are found. The group entries are not considered. #### Subtree Search Scope With this option, the Basic Authentication - LDAP policy examines the subtree below the `LDAP search base` and also includes the `LDAP search base` level. Notice that performance is affected by this behavior. In the previous example, the analyzed area covers the entire organization. The group and user entries are considered at any level of the organization: ![A hierarchical chart displays a company’s organizational structure](/mulesoft/current/en-us/mule-gateway/_images/search-scope2.png) ## Creating Requests for APIs with Basic Authentication Policies Applied After applying the Basic Authentication - LDAP policy to the API, a request to that API must contain the following header: Authorization: Basic The `username:password` value must be a Base64-encoded string. For example on a Mac OS X or Linux system, the username and password requirement is implemented as: `echo -n ':' | base64` Mule runtime engine (Mule) separates the credentials of the header and sends the request to the LDAP server with the search filter. From the `username` and search filter, LDAP finds the registered user and then verifies credentials. The valid result is returned to Mule: ![A sequence diagram that illustrates the message flow for client authentication through an LDAP Server](/mulesoft/current/en-us/mule-gateway/_images/ldap-verification.png) The following diagram illustrates an invalid request: ![A sequence diagram that illustrates the message flow for authorization](/mulesoft/current/en-us/mule-gateway/_images/ldap-verification-invalid.png) The Basic Authentication: LDAP policy throws an HTTP 401 status code to indicate that the authorization header is malformed, not provided, or invalid. --- product: Mule Gateway keywords: basic authentication, api gateway, mule gateway, gateway, policy --- # Basic Authentication: Simple Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

Basic Authentication: Simple

Summary

Allows access based on the basic authorization mechanism, with a single user-password

Category

Security

First Mule version available

v4.0.0

Returned Status Codes

400 - Unauthorized or invalid client application credentials in WSDL API using SOAP 1.2

401 - Unauthorized or invalid client application credentials in HTTP or RAML APIs

500 - Unauthorized or invalid client application credentials in WSDL API using SOAP 1.1

## Summary The Basic Authentication: Simple policy protects an API by forcing applications to provide a username and password when making requests. The policy follows [basic HTTP authentication standards](https://datatracker.ietf.org/doc/html/rfc7617). When an error is encountered, the policy returns an "WWW-Authenticate" HTTP header field. ## Configuring Policy Parameters ### Mule Gateway When you apply the Basic Authentication: Simple policy to an API, a request to that API must contain the following header: Authorization: Basic The `username:password` value must be a base64-encoded string. For example on a Mac OS X or Linux system, the username and password requirement is implemented as: `echo -n ':' | base64` --- product: Mule Gateway --- # Caching in a Custom Policy for Mule 4 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When a value needs to be retrieved from an external system, like a token, to be used in an app or a policy, the value can be stored temporarily in the [Mule 4 Object Store](https://docs.mulesoft.com/object-store-connector/latest/). Information on the [Object Store connector is available in Anypoint Exchange](https://www.anypoint.mulesoft.com/exchange/org.mule.connectors/mule-objectstore-connector/). See also the [Object Store backend documentation](https://docs.mulesoft.com/object-store/). You can enable access to Object Store from Anypoint Platform > Runtime Manager. However, the Runtime Manager object store is only for [CloudHub](https://docs.mulesoft.com/cloudhub/) and hybrid applications. An application that stores the data in the object store can, or any of its workers, retrieve the data. The object store provides the cache for your custom policy, thus avoiding making external calls multiple times. In addition, the object store can be used by multiple policies applied in different APIs running in different instances in CloudHub. ## Caching with the Object Store Mule provides the Mule 4 Object Store connector that retrieves and stores values for up to 30 days. The following example retrieves data from an object store and if no data is found for a specific key, a new value is retrieved from the external system and stored in the object store. ```xml #[vars.myVar] ``` In this example, the `` statement executes the retrieve operation of the Object Store connector using the value token as the key to look for and assign the retrieved value to the `myVar` variable. If no value is associated with a key, an error is thrown by the retrieve operation. This is why the operation is enclosed in a `` block, so that should an error occur, it can be handled by retrieving a fresh value and storing it in the object store. The HTTP request is implemented inside the `` block. The value is obtained through an HTTP call and assigned to the `myVar` variable. Then that value is stored in the object store using the `store` operation of the Object Store connector. After this block executes, myVar contains a value that was retrieved from either the cache or the external system, and stored in the cache for later use. You can use that value for any purpose such as adding it as a new header to a request or response, or more. ## Defining an Object Store To use the Object Store connector operations, you need to first define the object store that those operations use. The following configuration defines the myObjectStore and stores the values for an hour. The object store in this example is set to be persistent so that if the runtime is restarted, the Object Store won’t be cleared. ```xml ``` The time to live (TTL) value is set to 1 hour. ## Caching in Runtime Manager When the policy is deployed to an API running in Runtime Manager and that instance also has the Object Store v2 (OSv2) enabled, then using the above persistent object store configuration results in the policy caching the values into the Cloud Object Store. However, there is a limitation, as the configured entry time to live is not honored when using it, as the Object Store connector is not able to create new stores, but rather it uses the default object store partition that has a 30 days TTL. ## Enabling an Object Store for Multiple APIs When using Object Store v2, you can share the cache between multiple API deployments. To achieve this, the object store configuration needs to have the same name attribute in every deployed policy and also the runtime needs to have a system property named `objectstore.enable.global.sharing` that is set with the value true. After enabling this, data persisted by a policy running in that instance is also available to policies running in other instances under the same environment. **Caution:** Enabling the global sharing OSv2 mode makes that object store used by the application or any other policy also shared across all your organization’s APIs. ## Reviewing full example of a Policy Caching with an Object Store This example shows a policy that adds a header to an incoming HTTP Request with a value retrieved from an external system and cached in the Mule Object Store. ```xml #[vars.myVar] #[{'new-custom-header': vars.myVar}] ``` The necessary dependencies for the example are: ```xml org.mule.connectors mule-http-connector 1.2.1 mule-plugin provided org.mule.connectors mule-objectstore-connector 1.1.1 mule-plugin com.mulesoft.anypoint mule-http-policy-transform-extension 1.1.0 mule-plugin ``` ## See Also - [Object Store backend documentation](https://docs.mulesoft.com/object-store/) --- product: Mule Gateway keywords: clientid enforcement, api gateway, mule gateway, gateway, policy --- # Client ID Enforcement Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

Client ID Enforcement

Summary

Allows access only to authorized client applications

Category

Compliance

First Mule version available

v3.8.0

Returned Status Codes

401 - Unauthorized or invalid client application credentials

500 - Bad response from authorization server, or WSDL SOAP Fault error

## Summary The Client ID Enforcement policy restricts access to a protected resource by allowing requests only from registered client applications. The policy ensures that the client credentials sent on each request have been approved to consume the API. When a client application is registered in Anypoint Platform, a pair of credentials consisting of a client ID and client secret is generated. When the client application requests access to an API, a contract is created between the application and that API. An API that is protected with a Client ID Enforcement policy is accessible only to applications that have an approved contract. When you apply a Client ID Enforcement policy, access to your API is tracked by reporting the client ID along with the analytics events. You can configure Mule runtime engine (Mule) to encrypt all sensitive information that pertains to policies, contracts, and initialization data. Default policies that internally enforce client application credentials include: - [Rate Limiting: SLA-Based Policy](https://docs.mulesoft.com/mule-gateway/policies-included-rate-limiting-sla) - [OAuth 2.0 Access Token Enforcement Using Mule OAuth Provider Policy](https://docs.mulesoft.com/mule-gateway/policies-included-oauth-access-token-enforcement) - [PingFederate OAuth 2.0 Token Enforcement Policy](https://docs.mulesoft.com/mule-gateway/policies-included-pingfederate-oauth-token-enforcement) - [OpenAM OAuth 2.0 Token Enforcement Policy](https://docs.mulesoft.com/mule-gateway/policies-included-openam-oauth-token-enforcement) - [JWT Validation Policy](https://docs.mulesoft.com/mule-gateway/policies-included-jwt-validation) Although token enforcement policies can optionally skip client validation, it is recommended that you enforce the validation to ensure that the token is associated to an approved contract. ## Configuring Policy Parameters ### Mule Gateway When you apply the policy to your API from the UI, a list of parameters are displayed based on whether your environment includes Mule or non-Mule applications. #### Configuring the Parameters For Mule applications, the following parameters are displayed:
ParameterDescriptionRequired

Credentials origin

Specifies from where in the request to extract the values:

  • HTTP Basic Authentication Header: Requires credentials as part of the authorization header. The application consuming the API must use the basic authentication scheme to send the credentials in the requests.

  • Custom Expression: Accepts a DataWeave 2.0 expression for each client ID and client secret, indicating where to extract the credentials from the request. Use this option to send the credentials in a custom header or any other format. You can leave the field blank to configure the client secret requirement as optional.

Must choose from one of the options.

Client ID Expression

The DataWeave 2.0 expression to use for obtaining the client ID from API requests.

Yes.

Client Secret Expression

The DataWeave 2.0 expression to use for obtaining the client secret from API requests.

No.

Method & Resource conditions: Apply configurations to all API methods & resources

Choose this option if you require the policy to be applied to all the methods and resources associated with the API.

Must choose from one of the options.

Method & Resource conditions: Apply configurations to specific methods & resources

Choose this option if you require the policy to be applied to only specific methods and resources associated with the API.

Must choose from one of the options.

## How This Policy Works Before a client application is allowed to consume an API protected by a Client ID Enforcement policy, the client application must request access to the API. After an approved contract exists between the client application and the API, every request must include the client application credentials in compliance with how the policy is configured. For example, if the policy is configured to expect a client ID and client secret as query parameters, the application must send those credentials in the request. To enforce this, add a `client-id-required` RAML trait to the API specification: traits: client-id-required: queryParameters: client\_id: type: string client\_secret: type: string Apply the trait to the resources or methods using the `is` RAML attribute: /example: get: is: \[client-id-required\] description: Example description ## Configuring How the Policy Obtains Credentials You can configure the policy to extract either both the client ID and client secret, or only the client ID from the HTTP request by using a variety of custom DataWeave 2.0 expressions. The following examples use a client ID of '1234' and a client secret of 'abcd'. ### Obtaining Credentials Using HTTP Headers Example request using curl: ```text curl "http://localhost/myResource" -H "client_id:1234" -H "client_secret:abcd" ``` Example DataWeave 2.0 expression to be used when configuring the policy: ```text #[attributes.headers['client_id']] #[attributes.headers['client_secret']] ``` In this example, the policy is configured to expect two headers: client\_id and client\_secret, with the pair of credentials. The policy is flexible to allow other types of headers also. This is the default configuration for the policy. ### Obtaining Credentials Using HTTP Query Parameters Example request using curl: ```text curl "http://localhost/myResource?client_id=1234&client_secret=abcd" ``` Example DataWeave 2.0 expression to be used when configuring the policy for Mule 4: ```text #[attributes.queryParams.'client_id'] #[attributes.queryParams.'client_secret'] ``` In this example, the requester must send the two specified query parameters with the request. Although this is a supported configuration, it poses possible security risks. The recommended method is to use headers. DataWeave 2.0 is fully supported in Mule 4 as wells as a subset in Omni. ### Obtaining Credentials Using HTTP Request Payload (Mule only) Example request using curl: ```text curl "http://localhost/myResource" -d '{"client_id":"1234", "client_secret":"abcd"}' -X POST ``` Example DataWeave 2.0 expression to be used when configuring the policy: ```text #[payload.client_id] #[payload.client_secret] ``` Although you can configure the policy to obtain the credentials from the request payload, this option is not recommended because it is harder to reflect in the API specification. ### Obtaining Credentials Using Basic Authorization header Example request using curl: ```text curl "http://localhost/myResource" -u 1234:abcd ``` ## Configuring API Specifications The Client ID Enforcement policy requires changes in your API specification to implement the credentials requirement. You can find the RAML or OAS snippet link containing the RAML or OAS code you need to add to the API specification in the corresponding policy. You can access this code from the list of applied policies in the Policies tab of your API specification in API Manager. ## Policy Output When an HTTP request is performed against a protected resource for which the Client ID Enforcement policy is applied, and the client application credentials are invalid or unauthorized, the HTTP response includes a WWW Authenticate header with the following values:

Custom mode

Header 'WWW-Authenticate'='Client-ID-Enforcement'

Basic Auth mode

Header 'WWW-Authenticate'='Basic realm="mule-realm"

For SOAP applications, the response is a SOAP error. ## See Also - [Rate Limiting: SLA-Based Policy](https://docs.mulesoft.com/mule-gateway/policies-included-rate-limiting-sla) - [OAuth 2.0 Access Token Enforcement Using Mule OAuth Provider Policy](https://docs.mulesoft.com/mule-gateway/policies-included-oauth-access-token-enforcement) - [PingFederate OAuth 2.0 Token Enforcement Policy](https://docs.mulesoft.com/mule-gateway/policies-included-pingfederate-oauth-token-enforcement) - [OpenAM OAuth 2.0 Token Enforcement Policy](https://docs.mulesoft.com/mule-gateway/policies-included-openam-oauth-token-enforcement) - [JWT Validation Policy](https://docs.mulesoft.com/mule-gateway/policies-included-jwt-validation) - [Managing API Instance Contracts on API Manager](https://docs.mulesoft.com/api-manager/latest/manage-client-apps-latest-task) - [Getting Client ID and Client Secret of a Registered Client App](https://docs.mulesoft.com/api-manager/latest/access-client-app-id-task) - [OpenID Connect OAuth 2.0 Token Enforcement Policy](https://docs.mulesoft.com/mule-gateway/policies-included-openid-token-enforcement) - [Mule Gateway Startup Encryption](https://docs.mulesoft.com/mule-gateway/mule-gateway-encryption-mule4) --- product: Mule Gateway --- # Collecting Mule Gateway Metrics > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule Gateway is enabled, by default, to collect relevant usage data for improving user experience. MuleSoft uses this data to analyze and better understand the Mule Gateway capabilities uniformly for all customers. The metrics collected by Mule Gateway include: - Number and types of applications, APIs, and policies deployed - Mule Gateway-related configuration parameters - Statistics about the number of requests processed Note that sensitive information, such as credentials and policy configuration parameters, is not collected. This feature is included in the 3.9.5, 4.2.2, and 4.3.0 versions of Mule runtime engine. ## Disable Mule Gateway Metrics Collection Even though no sensitive information is collected using this configuration, you might still want to disable it for some reason. To disable the configuration, add the following entry in the `wrapper.conf` file: `anypoint.platform.metrics_enabled=false` ## Log Analytics Event Data Mule Gateway provides `INFO` API analytics event logging to capture data about incoming API requests. > [!NOTE] API analytics event logging is only supported in Mule runtime versions 4.4.x and 4.5.x > released after Feb 1, 2024 and Mule runtime versions 4.6.0 and later. By default, `anypoint.platform.log_analytics_events=false`. Enable event logging by adding the following entry to the `wrapper.conf` file: ```conf anypoint.platform.log_analytics_events=true ``` > [!IMPORTANT] Due to additional log generation, events logging might affect the performance of the > request processing. Logs appear in the following format: com.mulesoft.mule.runtime.gw.analytics.logger.AnalyticsHttpEventsLogger: {"api\_id":XX,"api\_version\_id":XX,"org\_id":"XXX","host\_id":"XXXX","client\_id":XXX,"transaction\_id":XXX,"received\_ts":"XXX","replied\_ts":"XXX","client\_ip":"XX","verb":"GET","path":"/backend","status\_code":200,"user\_agent":"XXX","request\_bytes":0,"response\_bytes":150,"request\_disposition":"XXX","policy\_violation":null,"event\_id":"XXX","deployment\_type":null} ## Manage Logs and Troubleshoot If an error occurs during the metrics collection process, your Mule application’s ability to complete other tasks is not affected. Additionally, all entries related to the metrics collection is logged as `DEBUG` in the `com.mulesoft.mule.runtime.gw.metrics` package to avoid cluttering the log files. If you encounter issues with this feature: 1. Contact MuleSoft Support and supply them with the metrics logs listed in the previous section. 2. Disable the configuration until Support is able to resolve your issue. # Configure URI Template Regex You can specify a regular expression (regex) to include multiple paths when you apply a policy to a subset of resources exposed by an API. The **URI template regex** field in the policy enables you to specify this expression. When configuring **URI template regex**, you must consider the base path of the Mule runtime engine (Mule) application that implements (or proxies) the API. This is because Mule 4 resource-level policies depend on where an API is deployed. This diagram displays the list of methods used to specify the resource subset to apply to a policy: ![A list shows API endpoints and their corresponding GET and POST methods](/mulesoft/current/en-us/mule-gateway/_images/configure-regex-resources-list.png) Imagine that this API specification is implemented in the following Mule application: ```xml ``` In this example, `http:listener-config` defines both a `basePath` attribute and an additional path, v1, before the trailing **in the path `v1/`**. The concatenation of these two paths is referred to as the _base path_, which is `/api/v1`. To invoke the first resource of the API `resource-1`, you must use the base path in combination with the resource path `resource-1: [http://localhost:80/api/v1/resource-1](http://localhost:80/api/v1/resource-1)`. Subsequently, if you want to protect `resource-1` with a policy, you must use a resource-level policy. Therefore, the **URI template regex** that you specify when applying the policy must also include the base path in it: The diagram illustrates how to configure a **URI template regex**: ![A form that allows you to apply configurations to specific API methods and resources](/mulesoft/current/en-us/mule-gateway/_images/configure-uri-regex-example.png) If the API is of RAML or OAS type, the `Preview Resource Matching` option does not indicate that any resource is being matched, which differs from the actual runtime behavior. You can also use a regex to avoid having to explicitly specify the base path, for example, `.*/resource-1`. However, if you have resources with the same name at different levels of the API definition, the regex will match all of them, resulting in issues. This is because the regex will match with both `/api/v1/resource-1`, and `/api/v1/resources/resource-1`, which makes it an indecisive solution. ## [](#when-to-use-ignorebasepath)When to Use ignoreBasePath Including the base path in the full path of the resource when applying resource-level policies forces a coupling between the API in design time and the API in runtime. This is because you are required to know the base path where the API is going to reside when applying resource-level policies. To avoid this coupling issue, Mule 4.3.0 includes a new configuration that allows the Mule policy engine to ignore the base path of the API resource when matching the incoming HTTP request with the policy’s **URI template regex**. The configuration is exposed on the Mule application implementing the API: ```xml ``` When the `ignoreBasePath` attribute is set to `true`, the base path where the API is deployed is not considered anymore. ## [](#feature-prerequisites)Feature Prerequisites To implement this feature, ensure that your Mule application: - Is running in Mule 4.3.0 - Contains the Anypoint Connector for HTTP (HTTP Connector) 1.5.15 or later To achieve backward compatibility, this feature is disabled unless the attribute is explicitly set to `true`. If your Mule applications are running in Mule versions prior to 4.3.0 and have resource-level policies correctly configured, you do not need to make any changes to migrate to Mule 4.3.0 or later. The latest versions of API proxies available in API Manager are preconfigured to ignore the base path. To avoid breaking existing resource-level policies that are implemented using previous versions of API proxies, the following major versions of API proxies are released with this feature: - HTTP Proxy 2.0.0 - HTTP Proxy 3.0.0

Because resource-level policies work in compatibility mode in Mule versions 4.2.x and 4.1.x, deploying these proxy versions is not recommended. If you deploy these proxy versions, you will be required to update the URI Template configurations before migrating to Mule 4.3.x.

## [](#feature-limitations)Feature Limitations ### [](#base-path-requirements)Base Path Requirements The root path of an API must be well-defined to calculate the base path of the API. Make sure that the path attribute of the HTTP Listener in the Mule application ends with `*`. Otherwise, resource-level policy matching works as if `ignoreBasePath` is set to `false`. ### [](#query-parameter-exclusion)Query Parameter Exclusion The regex matches only against the URI path component of the request, and query parameters aren’t considered. For example, a regex pattern like `/api/products.*123` matches `/api/products/123` but won’t match `/api/products?id=123`. ## [](#see-also)See Also - [Policy Overview](https://docs.mulesoft.com/mule-gateway/policies-policy-overview) --- product: Mule Gateway --- # Configuring Mule Gateway API Autodiscovery in a Mule 4 Application > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To configure API Autodiscovery in your Mule 4.x application, you must meet the following requirements: ## Making your API Available in API Manager The API to which you want to pair your Mule application must be available in API Manager. You can either: - Publish your API in Exchange and import it from there to API Manager. See [To Manage an API from Exchange](https://docs.mulesoft.com/api-manager/latest/create-instance-task-mule). - Import it directly from your machine. See [To Import an API Instance](https://docs.mulesoft.com/api-manager/latest/api-instance-landing-page) for more details. API Manager generates an "API ID" identifier for every imported API: ![An HTTP API instance with API Instance ID highlighted](/mulesoft/current/en-us/mule-gateway/_images/api-id.png) This API ID is required by the Autodiscovery element to identify the API to which you want to pair your application. ## Configuring API Manager This step is necessary to instruct API Manager to use your deployed Mule application as the API proxy itself. 1. For Managing type, select Basic Endpoint. 2. Add the Implementation URI that points to the deployed Mule application. 3. Select the checkmark `Check this box if you are managing this API in Mule 4 or above`. ## Configuring Anypoint Platform Organization Credentials in Mule Runtime To use Autodiscovery in a Mule application, Mule runtime engine must start with Anypoint Platform credentials already configured. Learn how to configure your organization credentials based on your deployment target in [Configuring Organization Credentials in Mule Runtime 4](https://docs.mulesoft.com/mule-gateway/mule-gateway-org-credentials-mule4). ## Configuring the Autodiscovery Element in Your Mule Application Within the code of your Mule application, you must configure the `api-gateway:Autodiscovery` element. The Autodiscovery element points to the specific API in API Manager to which you want to pair. > [!TIP] If you configured a proxy endpoint for your API, your autogenerated proxy will already be > correctly configured with the Autodiscovery element. XML element ```xml (2) ```
1Configure the apiId with the API ID that API Manager assigned to your API.
2Set the flowRef element to point to the flow that you want to pair to the API in API Manager. The referenced flow must use an HTTP Listener component. Other connectors that use HTTP as an underlying transport aren’t supported for policy enforcement.
You can either replace `${apiId}` with your specific value, or you can create a `config.properties` file where you define it in a key-value fashion: `apiId=[your-specific-value]` and reference it as `${apiId}` in this configuration. You can also configure this using Anypoint Studio’s UI: 1. In your existing flow, select the Global Elements tab in your Mule Configuration File editor. 2. Click the Create button, and look for the API Autodiscovery global element. ![A form for configuring global elements, with API Autodiscovery selected in a dropdown labeled Component configurations](/mulesoft/current/en-us/mule-gateway/_images/auto-discovery-studio-7.png) 3. Set the API ID and Flow Reference. ![A form displaying auto-discovery settings for an API](/mulesoft/current/en-us/mule-gateway/_images/auto-discovery-api-config.png) You can also choose to use the `${apiId}` value and reference it from a `config.properties` file. After the element is defined in the application, and the runtime is configured with your Anypoint Platform credentials, Mule Runtime will automatically track and keep up to date with the API configuration. defined in API Manager. ## Autodiscovery Configuration In Mule 4, the API is identified by the API Id and a reference to a Flow where the HTTP listener is defined using the `.` element. ## See Also - [Reviewing Mule Gateway API Autodiscovery concepts](https://docs.mulesoft.com/mule-gateway/mule-gateway-autodiscovery-overview) --- product: Mule Gateway --- # Configuring Organization Credentials in Mule Runtime 4 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Organization credentials provide a way to uniquely identify a specific environment, an organization, or a business group when linking Mule runtime engine (Mule) to an organization using Anypoint Platform. Credentials for environments, organizations, and business groups consist of two keys: the client ID and a client secret. Mule uses these credentials to connect to and access your organization. The recommended way to link Mule to Anypoint API Manager (API Manager), is by using the environment client ID and secret. You may also use the organization client ID and secret, or even business group credentials if you want to track APIs defined in business groups linked to Mule or belonging to a parent business group linked to Mule. When you use environment credentials, you can manage APIs that are specific to only that environment. If your APIs are in different environments of Anypoint Platform, you must specify instead the credentials of the organization that contains both environments. You can also use parent organization credentials to manage child organization APIs. For example, if ACME is the parent organization and Logistics is a business group (child organization) within ACME, your API Administrator can track APIs created in Logistics using the credentials of either Logistics or of ACME. You can identify client applications with client ID and secret. However, it is recommended that client application credentials not be used in place of organization credentials. Otherwise Mule is not linked correctly to the organization. You can only successfully pair Mule to your organization if Mule is started using Anypoint Platform credentials that are already configured. If you provision an adapter with organization credentials, you can manage APIs on only that specific adapter of your organization. ## Obtaining Credentials Because you are required to provide credentials from time to time when using API Manager, you might need to obtain these credentials for various client applications. You can obtain environment and organization credentials using the procedures explained in this section. ### Obtaining Environment Credentials (Recommended) To obtain environment credentials: 1. Log in to Anypoint Platform as an administrator, and click **Access Management**. 2. Click the **Environments** tab and click the name of your environment within your desired organization. ![The credentials for the environment in Mule 4](/mulesoft/current/en-us/mule-gateway/_images/environment-api-manager.png) Remember that environment credentials are only available in the post-crowd (November 2017) release version of the platform. ### Obtaining Organization Credentials To obtain organization credentials: 1. Log in to Anypoint Platform as an administrator, and click **Access Management**. 2. Click the **Organization** tab and click on the name of your organization or corresponding Business Group. ![A form displays organization information, including names, IDs, and a client secret in Mule 4](/mulesoft/current/en-us/mule-gateway/_images/orgid-api-manager.png) ## Configuring Credentials for Standalone Deployments ### Automatic Runtime Manager Agent Setup Mechanism If you are setting up a stand alone instance, and you would like to register the Runtime Manager agent: 1. Log in to Anypoint Platform as an administrator, and click **Runtime Manager**. 2. Click the **Servers** tab, then **Add Server**. 3. Run the command you are prompted to run. This command looks similar to this: ```text /bin/./amc_setup -H bb123456-789c-1234-9fd3-58f4b5e2d82e---123 server-name ``` Where `MULE_HOME` is a variable holding the root directory of the Mule installation. For example, `/opt/Mule/mule-enterprise-standalone/`. Executing this command configures your runtime agent, and the automatically adds the correct organization credentials to your Mule with the correct organization credentials and URLs, so your Mule is linked to a specific organization. After registering the agent, the wrapper.conf file is modified with the required data so configuration changes are made persistent. ### Manual Configuration If you are setting up an on premises instance to point to a specific organization, you need to add your credentials in the `wrapper.conf` file (persistent approach) or specifying the credentials data using the command line. #### Using the Wrapper.conf File The configuration file is placed in the `/conf` directory, where MULE\_HOME is a variable holding the root directory of the Mule installation. 1. Navigate to your $MULE\_HOME directory. 2. Open the file located in `/conf/wrapper.conf`. 3. Add your Anypoint Platform Organization credentials like shown below: ```text wrapper.java.additional.=-Danypoint.platform.client_id=XXXXXXXX wrapper.java.additional.=-Danypoint.platform.client_secret=XXXXXXXX ``` `` must be a unique number, not used by any other entry in that file. We recommend you to use the next incremental value over the previous entries in the list. If two or more lines use the same `` identifier, only the first value with that number is taken into account. If your organization is defined in the EU control plane, you need to define two additional keys: ```text wrapper.java.additional.=-Danypoint.platform.base_uri=https://eu1.anypoint.mulesoft.com wrapper.java.additional.=-Danypoint.platform.analytics_base_uri=https://analytics-ingest.eu1.anypoint.mulesoft.com ``` #### Using the Command Line You can pass your credentials at start up time by using the following arguments: Mac OS X / Linux ```console MULE_HOME/bin/mule \ -M-Danypoint.platform.client_id=XXXXXXXX \ -M-Danypoint.platform.client_secret=XXXXXXXX ``` Windows ```console MULE_HOME\bin\mule.bat -M-Danypoint.platform.client_id=XXXXXXXX -M-Danypoint.platform.client_secret=XXXXXXXX ``` If your organization is defined in the EU control plane, you should define the base URLS by adding two additional keys: Mac OS X / Linux ```console MULE_HOME/bin/mule \ -M-Danypoint.platform.client_id=XXXXXXXX \ -M-Danypoint.platform.client_secret=XXXXXXXX \ -M-Danypoint.platform.base_uri=https://eu1.anypoint.mulesoft.com \ -M-Danypoint.platform.analytics_base_uri=https://analytics-ingest.eu1.anypoint.mulesoft.com ``` Windows ```console MULE_HOME\bin\mule.bat -M-Danypoint.platform.client_id=XXXXXXXX -M-Danypoint.platform.client_secret=XXXXXXXX -M-Danypoint.platform.base_uri=https://eu1.anypoint.mulesoft.com -M-Danypoint.platform.analytics_base_uri=https://analytics-ingest.eu1.anypoint.mulesoft.com ``` The same applies if you are pointing at an organization defined in a Private Cloud Edition. You would need to provide the URLs for your Private Cloud Edition installation. ## Configuring Credentials for Anypoint Studio 7 You can configure Studio 7 to work with your Anypoint Platform organization for testing connectivity and governance applied to endpoints. 1. In Anypoint Studio, click **Anypoint Studio** from the top menu bar, and **Preferences**. 2. Under Anypoint Studio, click **API Manager** 3. Type in the client ID and secret under **Environment Credentials**: ![A form that enables the input of API platform and analytics URIs](/mulesoft/current/en-us/mule-gateway/_images/configure-autodiscovert-4-studio.png) If your organization is defined in the EU control plane, then you must also specify the base URL for that plane: ![A form for entering Anypoint Platform API pairing properties with fields for API platform, analytics URIs, and client credentials](/mulesoft/current/en-us/mule-gateway/_images/api-gateway-enabling-0cbca.png) The same applies if you are pointing at an organization defined in a Private Cloud Edition. You would need to provide the URLs for your Private Cloud Edition installation. ## Configuring Credentials in Runtime Manager for your Deployed Application ### Automatic Auto-generated Proxy Deploy Mechanism You can deploy an auto-generated proxy from your API directly to Cloudhub. 1. Log in to Anypoint Platform as an administrator, and click **API Manager**. 2. From the list of available APIs, click the API version of the API from which you want to auto-generate a proxy. 3. Click the **Settings** tab, and navigate to the **Deployment Configuration**. 4. Configure your runtime version and your proxy application name, and click **Deploy**. When you deploy a proxy using this mechanism, the system automatically configures the organization credentials (and URLs, if applicable) for you. You may take a look at them in Runtime Manager → → Settings → Properties. ### Manual Configuration 1. Navigate to **Runtime Manager** in Anypoint Platform. 2. Access the **Properties** section of the deployed application. If the application is being deployed for the first time, the Properties section will appear during the deployment configuration. 3. In the Properties section, add the following properties: ```text anypoint.platform.client_id=XXXXXXXX anypoint.platform.client_secret=XXXXXXXX ``` If your organization is defined in the EU control plane or using a Mule Private Cloud Edition, you should define the base URLS by adding two additional keys: ```text anypoint.platform.client_id=XXXXXXXX anypoint.platform.client_secret=XXXXXXXX anypoint.platform.base_uri=https://eu1.anypoint.mulesoft.com anypoint.platform.analytics_base_uri=https://analytics-ingest.eu1.anypoint.mulesoft.com ``` The same applies if you are pointing at an organization defined in a Private Cloud Edition. You would need to provide the URLs for your Private Cloud Edition installation. ## See Also - [Configuring Mule Gateway API Autodiscovery in a Mule 4 Application](https://docs.mulesoft.com/mule-gateway/mule-gateway-config-autodiscovery-mule4) --- product: Mule Gateway keywords: policy, endpoint --- # Configuring the Java Version of a Custom Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule Gateway custom policies can support different Java versions. To upgrade your custom policy to a newer version of Java, ensure that all policy dependencies support the new Java version and add the new Java version to your policy’s implementation metadata YAML file. After you upgrade the policy: 1. [Package the custom policy](https://docs.mulesoft.com/mule-gateway/policies-custom-package). 2. [Republish the custom policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange). 3. [Upgrade your applied policies to the new policy version](https://docs.mulesoft.com/general/upgrade-policies-proxies). ## Before You Begin Before upgrading the Java version of your policy, ensure all dependencies are compatible with that Java version: - If your policy is using custom connectors, see [Custom Connectors Java Support](https://docs.mulesoft.com/general/java-support#custom-connectors) to upgrade them. - If your policy uses extensions provided by Mule API Gateway, update the version of the dependency in your `pom.xml` file to a version that supports your new Java version. For an example of how to use extensions in your custom policy, see [HTTP Policy Transform Extension](https://docs.mulesoft.com/mule-gateway/policies-custom-http-transform). To find the first Java 17-compatible version of the extension, see the following table. All versions support Java 8:

Extension artifact ID

First Java 17-compatible version

mule-client-id-enforcement-extension

1.2.0

mule-cors-extension

1.3.0

mule-event-authentication-extension

1.1.0

mule-federation-extension

1.4.0

mule-http-policy-transform-extension

3.2.0

mule-http-proxy-extension

1.2.0

mule-ip-filter-extension

2.1.0

mule-json-threat-protection-extension

1.2.0

mule-jwt-extension

1.3.0

mule-rest-validator-extension

2.3.0

mule-soap-fault

2.1.0

mule-throttling-extension

3.1.0

mule-tokenization-extension

1.2.0

mule-wsdl-functions-extension

1.2.0

mule-xml-threat-protection-extension

1.2.0

## Configure the Java Version of Your Policy For your policy to support different Java versions, you must modify the implementation metadata file to include the `supportedJavaVersions` field. The `supportedJavaVersions` supports the Java versions `8`, `11`, and `17`. If you do not include the `supportedJavaVersions` field, your policy supports only Java 8. As specified in [Before You Begin](#before-you-begin), all policy dependencies must also support the listed Java versions. For newer custom policies, your implementation metadata file and definition metadata file are split into two separate `YAML` files. However, for older policies, your implementation metadata file and definition metadata file might be included in the same `YAML` file. See the following sections the add the `supportedJavaVersions` to your relevant file structure: - [Split Model Policies](#split-model-policies) - [Non-Split Model Policies](#non-split-model-policies) ### Split Model Policies For split model policies, add the `supportedJavaVersions` field to the implementation metadata `YAML`, for example: ```yaml #%Policy Implementation 1.0 name: Basic Authentication - Simple - Mule4 technology: mule4 supportedJavaVersions: ["8", "11", "17"] minRuntimeVersion: 4.1.0 releaseNotes: | * Java 17 compatibility. ``` ### Non-Split Model Policies For older policies where implementation and definition metadata are found in the same `YAML` file, add the `supportedJavaVersions` field as follows: ```yaml id: basic-authentication-simple name: Basic authentication - Simple supportedPoliciesVersions: ">=v1" description: Enforces HTTP Basic authentication according to the details configured in the policy. category: Security violationCategory: authentication type: system resourceLevelSupported: true encryptionSupported: true standalone: true supportedJavaVersions: ["8", "11", "17"] requiredCharacteristics: [] providedCharacteristics: - Requires authentication configuration: - propertyName: username name: User Name type: string optional: false sensitive: false allowMultiple: false - propertyName: password name: User Password type: string optional: false sensitive: true allowMultiple: false ``` ## See Also - [Java Support](https://docs.mulesoft.com/general/java-support) - [Upgrading Java for Policies and API Proxies](https://docs.mulesoft.com/general/upgrade-policies-proxies) --- product: Mule Gateway keywords: cross origin resource sharing, cors, api gateway, mule gateway, gateway, policy --- # Cross-Origin Resource Sharing (CORS) Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy name

Cross-Origin Resource Sharing (CORS)

Summary

Enables access to resources residing in external domains

Category

Compliance

First Mule version available

v4.1.1

Returned Status Codes

No return codes exist for this policy

## Summary CORS is a mechanism by which a web application can access resources that are defined in another domain. Browsers implement this standard by default. The CORS policy complies with the [CORS W3C recommendation](https://fetch.spec.whatwg.org/) standards. ## Configuring Policy Parameters ### Mule Gateway When you apply the policy to your API from the UI, the following parameters are displayed:
ElementDescriptionRequired?

Public resource

Whether the CORS configuration is to be applied as a public resource (default)

Yes

Default group

Whether the CORS configuration is to be applied only to specific resources (requires unselecting Public resource)

No

Support credentials

Whether the policy supports credentials, such as cookies, authorization headers, and TLS client certificates

No

## Configuration of CORS for non-API Gateway Mule Environments If your Mule runtime engine (Mule) is not enabled with API gateway capabilities and you need to implement the CORS functionality, you can use the CORS Interceptor. The CORS Interceptor is an element in the HTTP Listener configuration made available in Mule 4.0. The CORS configuration differs based on whether you leverage the CORS policy capabilities as a public resource or as a selected group of origins. For the Selected Group of Origins structure, the following example shows the elements that might be configured: ```XML (collection of origins) ... ... ... ``` For the Public Resource structure, the following example shows the elements that might be configured: ```XML ``` ## Why CORS CORS enables you to achieve web page security and web integrity in your environment. To know why you might need to apply the CORS policy to your backend, you must first understand _origins_, _cookies_, and how they can be manipulated to violate web page integrity. ### Introduction to the Web Origin Concept Origin is a header that specifies the request that initiated the fetch. The origin header includes only the server name (no path information). At a very basic level, an origin consists of: - URI scheme: `http://` - Host name: `www.example.com` - Port number: `8080` For requests between any two [origin](#origins) to be approved, the origins must be equal. Origins are considered equal only if all these three parameters match. For more information, see [RFC 6454 - The Web Origin Concept](https://datatracker.ietf.org/doc/html/rfc6454). ### HTTP Cookies Websites use HTTP cookies to retain stateful information. Most commonly, web servers use authentication cookies to know whether a user is logged in, and to know which account users are logged in to. For more information, see [RFC 6265](https://www.ietf.org/rfc/rfc6265.txt). SOP (same-origin policy) deters malicious attackers from exploiting cookies when one web page invokes another. For example, you might log in to your bank’s web page using a cookie that an attacker might be able to obtain and exploit to query the bank’s API on your behalf. With the SOP, scripts can access data from a target web page only if it has the same origin as the caller web page. For more information about origins, see [Wikipedia](https://en.wikipedia.org/wiki/Same-origin_policy). The following example illustrates the origin of the web page, `http://www.example.com:8080`: ![A table shows URL comparison results, including outcome and reason](/mulesoft/current/en-us/mule-gateway/_images/cors-policy-sop-example.png) Because the SOP is highly restrictive, access from one suborigin to another or to external hyperlinks do not work on web pages. For example, if an origin `www.testapply.com` has two suborigins, `www.eng.testapply.com` and `www.docs.testapply.com`, communication between the two suborigins is denied. Additionally, any hyperlinks to external websites from any of the suborigins is also denied. To circumvent this problem, web browsers implemented the CORS standard, which validates the web server and accepts the request if the validation is successful. For example, if your bank implements the CORS server-side protocol on its login server, you can query data only directly from the bank’s web page. Any attempt to query the login API from an external (non-bank) domain is denied. ## How CORS Works When your web pages request data, the browser detects whether the request is from within same origin and determines whether to apply the CORS algorithm. If you query data from a web page that is not in your origin, then the CORS policy is applied. The CORS algorithm works on the web server and on the client-side for the web page that requested the information. The client-side algorithm in the CORS policy is implemented by: - Determining whether the request is complex (and potentially dangerous) and sending a preliminary _preflight_ request to verify whether the server accepts the origin. - Executing the actual request and validating that the server responds correctly and accepts the origin. A _preflight_ is a preliminary request (using OPTIONS as the HTTP method) from the web browser to the backend server to test the identity (origin and a few other headers) of the web page that is trying to perform the request. If the backend does not accept the origin, the backend server responds to the request without a specific header (Access-Control-Allow-Origin). The client then understands that the page’s origin is not allowed in that server and does not execute the actual request. The following diagram shows the XMLHttpRequest (XHR) in a JavaScript flow for determining whether to execute the actual request: ![A flowchart illustrating the process of standard latency and added latency for Javascript cross-domain XHR calls](/mulesoft/current/en-us/mule-gateway/_images/cors-policy-xhr-diagram.png) As illustrated in the diagram, the request is validated based on the communication between the browser and the server: - If the request is considered to be complex (see the previous client-side diagram for XHR), then a preflight request is executed. If the server does not return the proper CORS response headers for the preflight, the client library (XHR in the previous example) is not allowed to perform the actual request. - If the preflight response is correct and complete, then the client library executes the actual request, which includes certain CORS headers. The client library then validates the CORS headers of the response. If some of the required headers are missing, then again the client library is obliged to block the response from reaching the client, which is usually a web page. ## CORS Components You can configure various components of the CORS policy, such as request headers, response headers, public resources and groups, ordering, and wildcards. ### CORS Request Headers - Origin: The origin making the cross origin request. - Access-Control-Request-Method: The method that is invoked in the actual request. This header is sent in the preflight request. - Access-Control-Request-Headers: Custom headers that are sent in the actual request. This header is sent in the preflight request. For the GET or HEAD methods, the standard defines a specific list of headers that are considered simple enough to not require a preflight. For custom headers, a preflight is executed for GET and HEAD requests (see the previous XHR example to validate the path in which the client does not have to perform a preflight). ### CORS Response Headers The headers included in a response depend on whether the request is a preflight or an actual request: - `Access-Control-Allow-Origin`: Obligatory in every response. If this header is not present in the response, the browser or client library blocks the response from reaching the web page. The wildcard “\*” can be used to represent any origin. - `Access-Control-Allow-Methods`: Allowed methods that can be executed. This header is returned in the OPTIONS request (preflight). The server might respond with a list of allowed methods, delegating the validation task to the client. - `Access-Control-Allow-Headers`: Allowed headers in the actual request. This header works in a manner similar to how Access-Control-Allow-Methods works . - `Access-Control-Allow-Credentials`: Notifies the client whether the actual request can be made with a cookie. The `Access-Control-Allow-Credentials` returns a Boolean value. - `Access-Control-Expose-Headers`: Provides the browser or client library with a list of headers that can be accessed by the web page that executed the request. The HTTP library performing the CORS request exposes only the headers to the web page, providing further privacy and security. - `Access-Control-Max-Age`: Specifies the duration (in seconds) in which the browser can avoid performing a second preflight on a request. ### Public Resources and Groups If you need to bypass the browser SOP, Mulesoft provides you an option to configure a public resource that enables the API gateway policy to mirror the preflight data in the response. This ensures that the actual request is correctly updated with all the CORS headers so that the browser accepts the response. If the public resource option is not secure enough for your environment, define multiple groups for the different origins that query your API. Each group applies to a list of origins and can specify different methods, headers, preflight caching time, and expose headers. ### Ordering The CORS policy is always applied first by the API gateway, before any other policies can be applied. If a protected request using OPTIONS is sent to an application that has the CORS policy applied, the request does not reach the protected resource. According to the [CORS specification](https://fetch.spec.whatwg.org/#resource-preflight-requests), all OPTIONS requests are considered preflight. ### Configuration Wildcards Wildcards (`*`) are accepted in the Origins and Headers sections of a group configuration. Use wildcards when you need a public resource, but must restrict the accepted HTTP methods. If you have configured multiple groups and one of the groups uses a wildcard origin, the non-wildcard settings override the wildcard configurations. ## FAQs **The CORS policy does not seem to be applied.** If you use tools such as curl or Postman to test the CORS policy for a complex request, the CORS request headers are not added and the preflight does not occur. If no CORS headers are sent or improper headers are used in the request, the API gateway CORS policy does not add any CORS response headers, giving the impression that the policy is not applied. Ensure that you use the libraries that implement the CORS protocol specific to your environment, or review the specification to ensure that you are configuring the correct headers. --- product: Mule Gateway --- # Custom Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Policies enforce regulations to help manage security, control traffic, and improve API adoption. For example, a policy can control authentication, access, and service level agreements (SLAs). You can create custom policies based on your specific business requirements and apply them to APIs to extend existing functionality or define new ones. The workflow to create custom policies for Mule 4 and earlier in Anypoint API Manager has not changed. Continue to use the process of developing the policy, packaging the custom policy, uploading it to Exchange, and applying the policy to an API through Anypoint API Manager as described in the Anypoint API Manager documentation. For more information, refer to the following: - [Publish a Mule 4 Custom Policy](https://docs.mulesoft.com/mule-gateway/policies-custom-mule-getting-started) - [Mule 4 Custom Policy Workflow](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started) - [Managing Offline Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-manage-offline) --- product: Mule Gateway --- # Custom Policy Development Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule 4 engine provides powerful capabilities for building custom policies through its architecture and XML schema language. We use Maven to build and deploy Mule 4 policies. Policies consist of two files: 1. A deployable JAR file that contains the policy implementation. 2. A YAML Configuration File, where the policy parameters and metadata are defined. To package a policy in Maven, the development project must be composed of the following files - An XML template It contains the implementation of the policy using Mule’s XML schema language. - A YAML file It defines the configurable parameters of the policy. Anypoint API Manager uses this file to render the UI to display inputs for the policy. - The template’s `pom.xml` file It defines policy dependencies. The packaging type needs to be `mule-policy`. The `pom.xml` file may define any other Maven plugin that helps to manage the development lifecycle of the Maven project. - Resources Optional files that the policy depends on, such as certificates and configuration properties files. - The mule-artifact.json descriptor > [!NOTE] Policies cannot export resources nor packages such as Java classes. ## Basic XML structure Below is an example of the basic structure of a policy configuration: ```xml (1) (2) … (3) (4) … (5) ```
1The definition of a policy starts with the http-policy:proxy element with a name argument. The http-policy:proxy element must contain http-policy:source or a http-policy:operation element. In this example, http-policy:source is used.
2The http-policy:source block contains the actual instructions to execute, relative to the Mule flow the policy is configured to handle. The http-policy:source block can inject instructions before an HTTP Listener event fires at the start of a flow, and inject instructions after the flow completes.
3Any Mule Event operation that is defined before the execute-next element will be executed before the start of a flow with an HTTP Listener.
4The http-policy:execute-next element is required to continue the Mule Event processing. The http-policy:execute-next element can trigger other policies or the application flow. Any policy can stop the Mule Event processing chain by not executing http-policy:execute-next.
5Mule Event operations defined after the http-policy:execute-next element will be executed after the flow completes. These Mule Event processors will be able to process the Mule Event returned from the flow.
### Understanding execution order Consider the case where a Mule application contains two policies, A and B. Policy A has order 1 and Policy B has order 2. Policy A is defined by the following configuration: ```xml ``` And policy B config is: ```xml ``` A flow is defined as: ```xml ``` When an HTTP Request arrives at the Mule application’s endpoint, the execution order follows the diagram below: → → → → The policy with the lower order executes first. The flow will always execute in the middle of the policy operations. With this model, the Mule Event processing chain can be controlled with the presence or absence of the `http-policy:execute-next` element. For example, by placing the `http-policy:execute-next` element inside a `choice` element, the next Mule Event execution can continue or stop, depending on the choice condition. In the example below, the flow will only execute when the incoming request has a header named `myHeader` and its value is `someValue`. A message is logged if the incoming request does not satisfy the constraint. ```xml ``` ## Using extensions Policies, just like Mule applications, can make use of Mule extensions or plugins to extend the Mule Core capabilities. For example, a policy is required to add additional headers to the HTTP Response from a flow’s HTTP Listener. The first step is to add a Maven dependency that can modify an HTTP Request object. The `mule-http-policy-transform-extension` Mule plugin can modify HTTP Requests. ```xml com.mulesoft.anypoint mule-http-policy-transform-extension 1.0.0 mule-plugin ``` These examples are developed using Mule extension v1.0.0. Using a different version of the extension might cause the examples to not work as expected. To update your Mule extension version, see [HTTP Policy Transform Extension](https://docs.mulesoft.com/mule-gateway/policies-custom-http-transform). Next, the XML `http-transform` namespace must be added to expose the operations in the above dependency. ```xml #[{'policyHeader': 'policyHeaderValue'}] ``` If a policy needs to use custom code, the policy can either: 1. Import a custom Mule plugin programmed with the Java or XML SDK Extension 2. Use the `` element to add in custom scripts The recommended method is to use the SDK Extensions. > [!CAUTION] Custom policies can’t use connectors that export resources or packages such as Java > classes. For example, custom policies can’t use the Java or Spring connectors. ## Outbound policies Policies can be applied to outbound HTTP Requests within a flow as well. This capability enables policies to inject additional headers and other information into outbound HTTP traffic through an HTTP Requester defined in a flow. Below is an example of a policy that contains source and operation blocks: ```xml (1) … … (2) ```
1One http-policy:proxy element is used for both types of policy blocks. Both source and operation blocks may be present. When both blocks are present, each block can share variables to keep state throughout the policy execution.
2This policy block contains code to be executed after the flow’s HTTP Requester returns an HTTP response. If the flow does not contain an HTTP Requester element, then this block is never executed.
In general, the `http-policy:operation` block allows a policy to inject code before Mule execution reaches an HTTP Requester and after an HTTP Requester returns an HTTP response. The operation block can contain an `http-policy:execute-next` element to control operations before and after an HTTP Request in a flow. **Execution order example** There are two policies, A and B. Policy A has order 1 and Policy B has order 2. Policy A is defined by the following configuration: ```xml ``` And policy B config is: ```xml ``` A flow is defined as: ```xml ``` When Mule runtime receives an HTTP Request, the execution order is as shown in this diagram: → → → → → → → → → → Operation policies are only injected around the `http:request` operation. ## Error Handling Mule 4 policies can handle errors thrown by 1. The policy 2. A flow within the Mule application 3. Other policies Error handling can be accomplished using Mule 4’s `try` and `error-handler` elements. Once an error is caught by an `error-handler`, the error is either, propagated up the Mule Event processing chain, or handled, where normal Mule event process execution continues. For example, consider the following policy and flow: ```xml ``` ```xml ``` ### Scenario 1 Assume `` raises an error. The execution order follows the diagram below: → → → `` is not executed, and processing continues into the flow’s error-handler. Since the flow’s error-handler is configured not to propagate errors, `` will return to the policy and `` executes instead of the policy’s `error-handler`. ### Scenario 2 Assume `` raises an error. The execution order follows the diagram below: → From the example above, the flow never executes. ### Scenario 3 Assume now that the flow’s error handler propagates errors. ```xml ``` Assume `` raises an error. The execution order follows the diagram below: → → → The error gets propagated back to the policy, and the policy’s error handler continues handling the error. In summary, error handlers provide an alternative method to conditionally execute a flow within a policy. ## Classloading isolation ### Between policies Policies contain the same classloading isolation architecture seen in Mule 4 applications: any resource or library that a policy defines is not visible to other policies. ### Between a Policy and an Application Classloading between policies and Mule 4 applications is not completely isolated. This scenario is similar to classloading isolation between applications and domains: Any plugin, library, or resource visible to the application is also visible to any policy applied to that application. However, any plugin, library, or resource visible to a policy is **not** visible to the application applied. ### Dependency resolution If a policy and an application use different versions of the same dependency, the application’s dependency version will be used by the policy. You can read more on classloading isolation in the [Classloading Isolation](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation) topic. ## Variables and Event Scope A policy can define any number of variables. Variables within a policy scope can be shared between policy blocks. For example, a variable `maxCount` defined in a `http-policy:source` block is available in a subsequent `http-policy:operation` block. However, any variables defined in a policy are **not** available to other policies and to the application. Furthermore, variables defined by the application are not available to any policy. ## Mule message propagation in source policies Policies can make changes to the Mule message, but the changes may not get propagated, depending on where the Mule message changes are made relative to the `http-policy:execute-next` element. For source policies, any modification to a Mule Message made after the `http-policy:execute-next` element, will continue propagation throughout the rest of the Mule event processing chain. The below policy and flow illustrates this concept: ```xml ``` ```xml ``` The final response back to the client will be an HTTP Response that contains "Policy Message" as the body. However, modifications made before the `execute-next` element, are not propagated to the next policy or application by default. Consider the below policy and flow: ```xml ``` ```xml ``` The final response back to the client will be an HTTP Response that contains an empty body. Furthermore, the logger in the flow will log an empty payload. ### Propagating the Mule message Within the `http-policy:source` tag, set the attribute `propagateMessageTransformations` to `true` to enable propagation. ```xml ``` ```xml ``` The final response back to the client will be an HTTP Response that contains "Policy Message" as the body. The logger within the flow will log "Policy Message." This design prevents unintentional modifications that can affect the application. ## Mule message propagation in operation policies Mule message propagation is similar to source policies but in the opposite direction. In operation policies, modifications made before the `execute-next` element are always propagated. Modifications made after the `execute-next` element, are not propagated by default. Propagation can be enabled using the same attribute `propagateMessageTransformations` in the operation policy definition: ```xml … … ``` In summary, variables cannot be used to share information from a policy to other policies or Mule applications. However, Mule messages can be used to share information from a policy to other policies or Mule applications. Dependent on where the Mule message is set within a policy block, the attribute `propagateMessageTransformations` may need to be set to true to enable Mule message propagation. ## Authentication (Security Context) User authentication can be exposed through the Authentication object within the Security context object. If a policy sets the Authentication object, it will be available to other policies and to the application. The Authentication object can be accessed using DataWeave: #\[authentication.principal\] #\[authentication.password\] #\[authentication.properties.someProperty\] The only method to set the Authentication object is through a dependency using the SDK Mule extension. Refer to the [Authentication Handler](https://docs.mulesoft.com/mule-sdk/latest/authentication-handler) article to learn how to set the authentication object. Mule 4 Provided Policies use this exact method to propagate client information. ## YAML Configuration File Mule 4’s policies use YAML files to store metadata and user parameters. This flexible design allows a policy to work across multiple APIs that require different user parameters and configurations. For example, the Rate Limit Policy allows for different configurations based on user parameters: a user may want to allow up to 100 requests per minute on one API, and allow 5000 per minute on a different API. To allow user parameters, policy developers define user input in the YAML Configuration file. The file is then used by API Manager to render the UI for user input. **Example of a Client ID enforcement YAML file** ```yaml id: openam-access-token-enforcement (1) name: OpenAM access token enforcement (2) supportedPoliciesVersions: '>=v4' (3) supportedJavaVersions: ["8", "11", "17"] (4) description: Enforces access tokens by OpenAM. (5) category: Security (6) violationCategory: authentication (7) type: system (8) resourceLevelSupported: true (9) standalone: true (10) identityManagement: (11) type: OpenAM - OAuth 2.0 protected configuration: (12) - propertyName: scopes name: Scopes description: A space-separated list of supported scopes type: string optional: true sensitive: false allowMultiple: false - propertyName: exposeHeaders name: Expose Headers description: In a proxy scenario, defines if headers should be exposed in the request to the backend. The headers that may be sent are the user properties returned by the federation server when validating the access token with a 'X-AGW-' prefix. type: boolean optional: true defaultValue: true allowMultiple: false ```
1Unique ID within your organization of the policy. Required
2User friendly name that is used for displaying the policy name in API Manager’s UI. Required
3Deprecated property. Value should be set to ‘>=v1’ for now. Required
4Java versions supported by the policy. Required for Java 17 runtime support. Without this field, the policy won’t appear in API Manager for Java 17 runtimes. Optional
5Description of what the policy does. Also used in API Manager’s UI. Required
6Category to which the policy belongs. Used to group and filter policies in API Manager’s UI, any String value is valid. Required
7Value used by Edge to show metrics about different types of policy violations. Required
8Deprecated property. Value should be set to ‘system’. Required
9Whether resource level pointcuts should be enabled when applying the policy. Required
10Deprecated property. Value should be set to ‘true’. Required
11Whether policy requires information about an identity management that’s configured for the API’s Organization. Optional
12Where the policy parameters are defined. Every parameter listed here will be rendered as an expected user input in API Manager’s UI. It expects an array of values. Required
Below is the syntax for defining the above policy’s parameters: ```yaml propertyName: scopes (1) name: Scopes (2) description: A space-separated list of supported scopes (3) type: string (4) defaultValue: some String (5) optional: true (6) sensitive: false (7) allowMultiple: false (8) ```
1Internal name of the parameter. Must be unique within the policy.
2User friendly name of the parameter. Used for displaying in API Manager’s UI.
3Description of the parameter. Also, used for displaying in API Manager’s UI.
4Type of the parameter.
5Default value for the parameter.
6Whether is mandatory for the user to enter this value or not.
7Whether this property should be masked when entering in API Manager’s UI.
8Whether multiple values should be allowed for this parameter.
### Parameter types Depending of the type of the parameter, the UI will render a different type of input such as: - text boxes - radio buttons - checkboxes Some rendered elements require additional configurations. The list of elements that require additional configurations are: - **String**: Any string expected. - **Expression**: A DataWeave expression starting with #\[ and finished with \] is expected. - **Boolean**: true or false. - **Int**: A number is expected. This type requires additional properties: ```yaml minimumValue: -1 (1) maximumValue: 2147483647 (2) ```
1Minimum value allowed for the parameter.
2Maximum value allowed for the parameter.
- **Radio**: One value of a group of options. This type requires additional properties: ```yaml options: (1) - name: HTTP Basic Authentication Header value: httpBasicAuthenticationHeader - name: Custom Expression value: customExpression ```
1List of options for the user to choose. Each option has a name for displaying in the UI and an internal value used in the policy.
- **Keyvalues**: Collection of Key-Value pairs. ## HandleBars Policies support Handlebars, a templating engine for resolving the configurable parameters of the policy and implementing semantic logic, such as conditionals. This is the preferred method of using user inputs in the policies. Each policy parameter defined in a YAML Configuration file will be available as a HandleBars variable for resolving the final policy configuration. > [!NOTE] Handlebars is an extension of Mustache, which was used in earlier versions of Mule > policies. Depending on the parameter type defined in the YAML, the variable will be of a different HandleBars type. String, Expression, Radio, Int, and Boolean are primitive types in HandleBars. The primitive types can be referenced from the policy template using curly brackets: `{{{myproperty}}}` Keyvalues are complex types in HandleBars. Complex types have inner properties, and those can be referenced as follows: {{{keyvalue.key}}} {{{keyvalue.value}}} There are some properties that are available to use in policies without being defined in the YAML Configuration file: - **policyId** id of the policy, useful for logging or naming a policy - **isWsdlEndpoint** indicates whether the API where the policy is being applied is a WSDL API. When an Identity Management is defined for the organization where the API is being applied, then the following properties are also available: **identityManagementTokenUrl** introspection endpoint of the identity management. **identityManagementClientId** client Id for authenticating to the introspection endpoint. **identityManagementClientSecret** client secret for authenticating to the introspection endpoint. ## Pointcuts In earlier versions, the pointcut element was required to configure a custom policy. Pointcuts specified the API that the policy operates. In Mule 4, there is no need to configure the pointcut element. Information about the API on which the custom policy operates is provided by API Manager when a policy is applied. See offline policies for configuration guidelines when a policy is not applied online. ## Advanced topics - [Reviewing HTTP Policy Transform Extension](https://docs.mulesoft.com/mule-gateway/policies-custom-http-transform) - [Removing HTTP Caching Custom Policy example](https://docs.mulesoft.com/mule-gateway/policies-custom-mule-4-caching) ## See also - [Packaging a Custom Policy](https://docs.mulesoft.com/mule-gateway/policies-custom-package) - [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange) --- product: Mule Gateway --- # Custom Policy Examples > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To better understand how to develop and implement custom policies for various events and scenarios, see the following examples: - [Create a custom response policy](https://docs.mulesoft.com/mule-gateway/policies-custom-response-example) - [Create a custom policy using Event Authentication extension](https://docs.mulesoft.com/mule-gateway/policies-custom-set-authentication-example) --- product: Mule Gateway keywords: detokenization, api gateway, mule gateway, policy --- # Detokenization Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

Detokenization

Summary

Returns a tokenized value to its original value. This policy is designed to work only for Anypoint Runtime Fabric deployments.

Category

Security

First Mule version available

v4.1.1

Returned Status Codes

400

The provided expression is invalid or returns no result to detokenize.

NOTE: You can configure the status code to be returned.

502 - Connection to the tokenization service is unavailable or not configured.

## Summary Detokenization is the process of returning the previously masked sensitive data back into its original value to reduce the risk of compromising sensitive information. You can tokenize your data to replace sensitive information with tokens to reduce the risk of compromising sensitive information. For example, an application can require the bank account number or the credit card number for generating monthly credit card statements. Detokenized sensitive data must always be read under strict security controls. ## Prerequisites To apply and manage the Detokenization policy, you must have: - Obtained the **Manage Policies** permission - To configure and use the tokenization service, you must have: - Installed Runtime Fabric - Obtained the **Manage Tokenization Services** permission - An operating tokenization service ## Scope and Considerations Before you apply this policy, review the following considerations: - One instance of the policy supports only one tokenization service. All the formats that you configured must be contained in the same tokenization service. - You can use one instance of the policy to tokenize a value either in the request or the response, but not in both. - If you deleted your tokenization service or if it is not operational, the policy cannot establish communication with it. This causes all the requests to fail until the service is available again. - During policy configuration, the services menu displays only the tokenization services that are ready to use. If you do not see the service you want, check to see if it is already deployed. ## Configuring Policy Parameters ### Mule Gateway When you apply this policy to your API, the following fields are displayed in the UI:
ElementDescriptionRequired

Direction

Whether the values to detokenize are extracted from the request or the response (default).

Yes

Fail on unmatched expressions

If selected, requests fail when the expression and tokens do not match.

No

Services

The tokenization services available for the current organization and environment. Select the service that you need from the list. Note that the formats available depend on the service that you choose.

Yes

Expression

A selector expression to be used to extract the information that will be detokenized.

For example:

#[payload.people.creditCardNumber]

Only expressions using dots as field separators are allowed. While [payload.people.creditCardNumber] is valid, #[payload[‘people’]] is not.

No
If you do not specify a selector expression, the policy is applied but does not detokenize anything from the payload.

Format

Type of information that will be detokenized. Formats may vary depending on the selected service. Choose one format from the list.

If you don’t see any formats in the list, verify that the tokenization service selected contains at least one format.

No
If you do not specify a format, the policy is applied but nothing is detokenized from the payload.

## How This Policy Works The Detokenization policy returns tokenized information within the payload to its original values. To define which data in the payload is detokenized, you must provide a selector expression. **Examples** If the payload that receives the policy contains the following structure: ```JSON { "name":"Amun Ra", "socialSecurityNumber":"167-47-9268" } ``` If you want to detokenize the social security number, you can use the following selector expression to specify which piece of information the policy should tokenize: ```expression #[payload.socialSecurityNumber] ``` Using this selector, every time the policy receives a request containing a `socialSecurityNumber` key in its top level, it extracts all the tokens that match the expression you indicated, establishes a connection with the tokenization service, and replaces the tokenized values in your payload with the original values. If the detokenized value for the Social Security Number in the example were _365-93-2738_, your application would receive the following payload: ```json { "name": "Amun Ra", "socialSecurityNumber": "365-93-2738" } ``` You can configure the detokenization policy to detokenize values in the request or response of your payload. ### Detokenizing Requests The following events occur when detokenizing requests: ![A diagram shows a data flow between security, tokenization, and a Mule application](/mulesoft/current/en-us/mule-gateway/_images/policy-mule4-tokenization-67b25.png) 1. A user performs a request to the application protected by the policy. 2. The request goes first to Anypoint Security and then to the application Detokenization policy. 3. The Detokenization policy extracts the tokens from the payload using the selector expression. 4. The detokenization service receives the tokens, returns them to their original sensitive values, and sends the result to the policy. 5. The policy replaces the tokenized payload with the detokenized values and forwards it to the Mule application. 6. The Mule application processes the request and returns the result. ### Detokenizing Responses The following events occur when detokenizing responses: ![A diagram shows a data flow of a tokenization service](/mulesoft/current/en-us/mule-gateway/_images/policy-mule4-tokenization-9347d.png) 1. A user performs a request to the application protected by the policy. 2. The request goes first to Anypoint Security and then to the application Detokenization policy. 3. The Detokenization policy redirects the request without extracting anything from the payload. 4. The Mule application processes the request and returns the result. 5. The detokenization policy extracts the tokens from the payload using the selector expression. 6. The detokenization service receives the tokens, returns them to their original sensitive values, and sends the result to the policy. 7. The policy sends the response back to the user with the detokenized values in the payload. --- product: Mule Gateway --- # Developing a Custom Policy Using the Event Authentication Extension > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can use an Event Authentication Extension to propagate a client ID property, using the authentication data of the Mule event. To develop and implement a custom policy using the Event Authentication Extension, you must understand the steps involved: 1. Evaluate your use case based on the [use case](#use_case) provided. 2. [Set up your project](#set-up-the-project). 3. [Create the YAML configuration file](#create_the_YAML). 4. [Implement your custom policy](#implement_the_policy). 5. [Upload your custom policy to Exchange](#upload_to_exchange). 6. [Apply your custom policy](#apply_custom_policy). ## The Use Case ProTeams is a sports-management application that enables its users to manage team and sports activities. ProTeams users can perform actions on behalf of their teams, such as participating in chats with other teams, organizing exhibitions or friendly matches, and confirming tournament dates. Each team has a client application in Anypoint Platform, and uses a Client ID Enforcement policy to validate requests to their site. To keep the team management tasks hidden from the players, separate IDs are created for managers and for players. Team owners and managers can proxy for the players for specific tasks if required. Players can also perform tasks for the team, such as setting up practice matches or initiate chat messages with team members. Because every user ID is mapped to the team’s client ID, it is propagated with every transaction made by any user ID. When the client ID is injected into the authentication data of the Mule event, Mule generates analytics data for the client application. ProTeams uses this application analytics to review the team transactions in the application. To create this player ID and team client ID mapping, the team owners need to develop a new custom policy that retrieves the user IDs from a header called `userId` on the request. The user IDs can also be obtained using query parameters. The policy then performs the mapping. ProTeams uses this example as a starting point and then adds their own mapping logic to it. ## Setting Up the Project ProTeams develops a custom policy by first creating a [custom policy archetype project](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started). Then ProTeams runs the archetype, replacing the values shown in this example. Then ProTeams copies the directory to their workspace, and replaces the `groupId` and `artifactId` values in the `pom.xml` file to match their own: - Replace `_YOUR_GROUP_ID_` with the ProTeams Organization ID, which in this case is `Group2234`. - Replace `_set-authentication-policy_` with the required Artifact ID, which in this case is `map-to-authentication-policy`. Additionally, you can add or modify other elements, such as version and dependencies, if required. ## Creating the YAML Configuration File After ProTeams sets up the project, they start by defining the input parameters of the policy to be configured in API Manager. The following code snippet shows an example YAML file for the policy UI: ```YAML id: Map To Authentication name: Map To Authentication description: Maps input user identifier to the associated Client ID, and propagates it via the authentication data category: Custom type: custom resourceLevelSupported: true encryptionSupported: false standalone: true requiredCharacteristics: [] providedCharacteristics: [] configuration: - propertyName: userIdExpression name: User Identifier Expression description: Mule Expression used to extract the user identifier value from API requests type: expression defaultValue: "#[attributes.headers['fks_user_id']]" optional: false sensitive: false allowMultiple: false ``` In the example, the YAML file contains just one configuration property, which is a DataWeave expression field, to determine from which request attribute to extract the user ID. The `name` and `description` parameters are the display title and description of the property, respectively. The `type` parameter indicates that the field value must be a DataWeave expression, and the `defaultValue` parameter specifies the suggested field value in API Manager when configuring the policy. The `optional` parameter is set to `false`, indicating that this field is mandatory. For more information about how to set up of the YAML file, see [YAML Configuration File](https://docs.mulesoft.com/mule-gateway/policies-custom-mule-4-reference#yaml-configuration-file). ## Implementing the Policy After ProTeams has defined the input parameters for their policy, they can start implementing their policy by: 1. [Adding a new server in their Maven `settings.xml` file](#add-server_in-settings). 2. [Adding extra dependencies in the `pom.xml` file.](#add_dependencies_in_pom) 3. [Adding conditions in the `template.xml` file.](#add_conditions_in_template) The Event Authentication Extension is available in the Mule EE Nexus repository. The POM file in the example already holds a reference to the repository, and is configured with a credentials alias named `releases-ee`. You can rename this alias if required. ### Add a Server in the settings.xml File To have access to the repository, ProTeams needs to add the corresponding server in their Maven settings file: ```XML releases-ee your_username your_password ``` ### Add Dependencies in the pom.xml File After adding a new server in their Maven `settings.xml` file, ProTeams then adds dependencies such as the Event Authentication and the HTTP Policy Transform extensions to the `pom.xml` file, for the policy to perform specific actions: ```XML com.mulesoft.anypoint mule-event-authentication-extension ${authenticationExtensionVersion} mule-plugin com.mulesoft.anypoint mule-http-policy-transform-extension ${httpPolicyTransformVersion} mule-plugin org.mule.connectors mule-http-connector ``` For more information about how to create your own connector in Java, see [Getting Started with the Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started). ### Add Conditions in the template.xml File ProTeams now needs to add functionality logic to the `template.xml file` to enable the policy to perform tasks, such as the ID mapping for ProTeams. Because ProTeams value mapping is not available in a Mule extension, ProTeams must create and add their own custom module. ## Uploading to Exchange To upload the custom policy to Exchange, ProTeams must verify that their `pom.xml` file is correctly configured for their organization. ### Task Prerequisites Before uploading their policy to Exchange, ProTeams must verify that: - A new server is created in their Maven `settings.xml` file, with a unique ID, and username and password of the Exchange credentials for their organization. - The URL matches their region. **Warning:** When you perform similar actions to create your own custom policy, note that the template uses the URL that corresponds to the US region. If your account does not belong to this region, change this value. - The repository ID matches the one from the Maven settings. You can define an alias to that repository using the name tag. To upload the policy to Exchange: 1. ProTeams goes to their policy `pom.xml` file\` and locates the `distributionManagement` section: ```XML your_server_id My Repository ${exchange.url} default ``` 2. After ProTeams verifies the server configuration, they begin uploading their policy to Exchange using the following command: ```console > mvn deploy ``` The custom policy that ProTeams developed is now uploaded to Exchange. ## Applying the Policy ProTeams next applies a custom policy the same way as they apply a default policy. When they go to API Manager, they can see the new policy available and ready to configure and use. To view the full custom policy example, see the Github repository [custom policies examples](https://github.com/mulesoft/api-gateway-custom-policies-examples). --- product: Mule Gateway --- # Developing a Custom Response Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When you are ready to develop your custom policy, follow the "Good Weather company" example to learn how to plan, develop, and implement your own policy later. Creating a policy involves the following steps: 1. Evaluate your use case based on the [use case](#use_case) provided. 2. [Set up your project](#set-up-the-project). 3. [Create the YAML configuration file](#create_the_YAML). 4. [Implement your custom policy](#implment_the_policy). 5. [Upload your custom policy to Exchange](#upload_to_exchange). 6. [Apply your custom policy](#apply_custom_policy). ## The Use Case To better understand how to implement a custom policy, imagine an example "Good Weather" company that is in the business of forecasting weather for a given location and time. Good Weather collects quantitative data about the current state of the atmosphere at a given place and, using meteorology, predicts how that current state will change over time. Based on the current weather patterns, Good Weather wants to provide the capability to add custom responses to the weather forecast in the consuming application. The application must be able to manipulate the status code and response message based on a series of conditions that are evaluated on each request. Telstra is an IT company that develops operating systems and applications for mobile and home computing technologies. Telstra wants to integrate with Good Weather to display daily weather forecasts on mobiles and PCs. Good Weather uses an HTTP proxy with a Basic Authentication policy applied to it. Each time a request arrives, the policy checks the bearer token and performs one of the following tasks: - Allow the request to reach the backend, or - Reject the request, if validation is not successful, with a 401 Unauthorized Status code. But what if, in case of unauthorized access, Telstra wants to include a different message each time it receives a 401 error. Developing a custom response policy allows Telstra to change the response message and status code based on a series of different conditions. For example,Telstra can state that if the response contains an Unauthorized status code, they modify the response payload accordingly. However, if Telstra requires the application to provide its users with a custom response in case of a failed validation based on specific conditions, no default policy can work. For example, imagine that Telstra wants its application to not just return an error code but also provide additional response payload. In such a scenario, Telstra needs to create a custom policy. ## Setting Up the Project Telstra starts developing a custom policy by first creating a [custom policy archetype project](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started). Then Telstra runs the archetype, replacing the parameters shown here in bold with their own parameters. - `DgroupId` is Telstra Organization ID. - `DartifactId` is the `custom-response-policy` value. You can set it to any other value as required. - `Dversion` is 1.0.0. Note that `DartifactId` and `Dversion` do not have any restrictions. ```console mvn -Parchetype-repository archetype:generate \ -DarchetypeGroupId=org.mule.tools \ -DarchetypeArtifactId=api-gateway-custom-policy-archetype \ -DarchetypeVersion=1.2.0 \ -DgroupId= \ -DartifactId=custom-response-policy \ -Dversion=1.0.0 \ -Dpackage=mule-policy ``` ## Creating the YAML Configuration File After Telstra sets up a project, they start adding dependencies and components to customize it. They start by defining the input parameters of the policy to configure in API Manager: 1. Specify the conditions used to evaluate the request and response. 2. If conditions are parametric, then DataWeave expressions are created. 3. API Manager verifies whether the conditions are met at the same time. 4. If the conditions are met, the status code is set. 5. If the conditions are met, the payload is set. The following code snippet shows an example YAML file for the policy UI: ```YAML id: Custom Response name: Custom Response description: Modifies the payload and/or the status code when some condition is met. category: Custom type: custom resourceLevelSupported: true encryptionSupported: false standalone: true requiredCharacteristics: [] providedCharacteristics: [] configuration: - propertyName: evaluateInRequest name: Evaluate in the request description: If the condition should be evaluated in the request. type: boolean optional: true defaultValue: false - propertyName: requestCondition name: Request Condition description: Dataweave expression that will be evaluated to define if the request should be modified. type: expression optional: true sensitive: false allowMultiple: false dependsOnKey: evaluateInRequest dependsOnValue: true - propertyName: evaluateInResponse name: Evaluate in the response description: If the condition should be evaluated in the response. type: boolean optional: true defaultValue: false - propertyName: responseCondition name: Response Condition description: Dataweave expression that will be evaluated to define if the request should be modified. type: expression optional: true sensitive: false allowMultiple: false dependsOnKey: evaluateInResponse dependsOnValue: true - propertyName: mergeBothConditions name: Merge both conditions description: Check if both request and response conditions need to be met. type: boolean optional: true defaultValue: false - propertyName: statusCode name: Status Code type: int minimumValue: 0 maximumValue: 999 description: Status code to return when the condition is met. optional: true sensitive: false allowMultiple: false - propertyName: payload name: Payload type: expression description: Expression that sets the payload to return when the condition is met. optional: true sensitive: false allowMultiple: false ``` In the example, the `dependsOnKey` and `dependsOnValue` parameters specify that the key indicated in `dependsOnKey` must be set to the value indicated in `dependsOnValue`, to display the fields `responseCondition` or `requestCondition`. > [!NOTE] Parameters using the `dependsOnKey` must be `optional: true`. In the UI, this translates to a checkbox in `evaluateInTheRequest` or `evaluateInTheResponse` that causes either the `requestCondition` or the `responseCondition` field to appear, depending on the value of the checkbox. For more information about how to set up of the YAML file, see [YAML Configuration File](https://docs.mulesoft.com/mule-gateway/policies-custom-mule-4-reference#yaml-configuration-file). Based on the example, the UI is generated as: ![A form that modifies the response payload and status code when a condition is met](/mulesoft/current/en-us/mule-gateway/_images/custom-response-policy-ui.png) The following screenshot illustrates the `dependsOnKey` and `dependsOnValue` parameters: ![Two checkboxes allow the user to evaluate the condition in the request or the response](/mulesoft/current/en-us/mule-gateway/_images/depends-on-key-demo.png) ## Implementing the Policy After Telstra has defined the input parameters for their policy, they can start implementing their policy as follows: 1. Add dependencies in the `pom.xml` file. 2. Add conditions in the `template.xml` file. ### Add Dependencies in pom.xml File To transform the custom response with the new status code and payload, Telstra must create an extension. This helps them to avoid developing the boilerplate code to transform the response message: 1. In the `pom.xml`, Telstra includes all the dependencies that they need to use. In this case, they need only the [http-policy-transform-extension](https://docs.mulesoft.com/mule-gateway/policies-custom-http-transform), which helps them to easily modify the response information. 2. In the `` section of the policy `pom.xml` file, Telstra includes the following dependencies: ```XML com.mulesoft.anypoint mule-http-policy-transform-extension ${httpPolicyTransformVersion} mule-plugin ``` For more information about how to create your own connector in Java, see [Getting Started with the Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started). ### Add Conditions in template.xml File Telstra must now associate the YAML file with the Handlebars. The YAML file, is used to complete the fields in the XML, for example, to create the expressions that will be used, or to add an entire block of code. In the `template.xml` file, Telstra must include the following code: ```XML {{#if evaluateInRequest}} {{/if}} {{#if evaluateInResponse}} {{/if}} ``` Note that the pieces of code in double braces ({{}}) correspond to [Handlebars](https://docs.mulesoft.com/mule-gateway/policies-custom-mule-4-reference#handlebars) syntax, which uses a template engine to compose the policy template with the configuration defined in the YAML file. The values used to configure the template must be the keys defined earlier in the YAML configuration file. Both values must match. Misspelling in any of the parameters can generate errors. In the previous example, the parameters `evaluateInRequest` and `evaluateInResponse` define elements that will hold the value of the condition to be evaluated, defined in `requestCondition` and `responseCondition`. For example, when you configure your policy, you want to validate that a particular header is present in the request. However, you do not want to check anything in the response. In this case, your policy configuration looks like this: ![A form with checkboxes and a text field for a DataWeave expression](/mulesoft/current/en-us/mule-gateway/_images/custom-response-configuration.png) When deployed, the template is resolved as displayed in the following code example. Because you did not specify any response condition, the Handlebars do not include it in the resolved template. ```XML ``` Telstra then completes the logic of their template file with the following code: ```XML {{#if mergeBothConditions}} {{#if statusCode}} {{/if}} {{#if payload}} {{/if}} #[vars.payload default payload] #[attributes.headers] {{else}} {{#if statusCode}} {{/if}} {{#if payload}} {{/if}} #[vars.payload default payload] #[attributes.headers] {{/if}} ``` To modify the payload and the status code, if set, Telstra uses the `http-policy-transform-extension` parameter that is included in the [dependencies](#add_dependencies_in_pom). Notice how Handlebars is used to resolve pieces of the template, as described earlier. Telstra’s Custom Response policy is now ready to be uploaded to Exchange and tested. ## Uploading to Exchange To upload a custom policy to Exchange, Telstra must verify that their `pom.xml` file is correctly configured for their organization. ### Task Prerequisites Before Telstra uploads their policy to Exchange, they verify that: - A new server is created in their Maven `settings.xml` file. - A unique ID is assigned, and the username and password of the Exchange credentials exist. - The URL matches their region. **Warning:** When you perform similar actions to create your own custom policy, note that the template uses the URL that corresponds to the US region. If your account does not belong to this region, change this value. - The repository ID matches the one from the Maven settings. **Tip:** You can define an alias to that repository using the name tag. ```XML your_server_id your_username your_password ``` Next, Telstra goes to their policy `pom.xml` file and locates the `distributionManagement` section: ```XML your_server_id My Repository ${exchange.url} default ``` After Telstra checks the configuration of the servers, they begin uploading their policy to Exchange using the following command: ```console > mvn deploy ``` The custom policy that Telstra developed is now uploaded to Exchange. ## Applying the Policy Telstra next applies a custom policy the same way as they apply a Default policy. When they go to API Manager, they can see the new policy available and ready to use: ![A custom response setting with version 1.0.0 selected](/mulesoft/current/en-us/mule-gateway/_images/custom-response-policy-platform.png) --- product: Mule Gateway keywords: policy, outbound-policies, resource-level --- # Disable Outbound Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, you can apply policies to both outgoing and incoming HTTP requests. Policies applied to outgoing HTTP requests are known as outbound policies. You implement them by defining an `http-policy:operation` block in the policy template, specifying the execution components. Mule runtime engine then applies the operation block of every policy that is applied to an API to every HTTP requester element defined in a Mule application. In the case of the HTTP proxy, there is only one HTTP Requester defined to which an outbound policy is applied. Because Mule applications that implement APIs might invoke several external services, you can define more than one HTTP Requester for such APIs. In that case, outbound policies are applied to each one of the HTTP requests that the application performs. The following example illustrates a Mule application flow implementing an API: Every time the Mule application is invoked, two HTTP requests to external services are executed. In this next example, a Mule policy is applied to the previous example by adding a header to the HTTP request: #\[{'new-header': 'the-value'}\] Every time the Mule application is invoked, the Mule policy is executed twice: once when invoking `service-1` and again when invoking `service-2`. Each HTTP request includes an additional header called `new-header`, which is added by the policy. Now imagine a scenario in which `service-1` needs the additional header for authentication, but `service-2` rejects incoming requests that have unexpected headers. In Mule 4.3.0, you can meet these requirements by specifying the annotation `api-gateway:disablePolicies="true"` in any of the Mule application’s HTTP requesters, resulting in the Mule policy engine not executing policies for that annotated requester. When using the annotation `api-gateway:disablePolicies="true"`, you must specify the following namespace in the application: `xmlns:api-gateway="http://www.mulesoft.org/schema/mule/api-gateway"` As a result, your application flow looks like the following: By specifying the annotation on the HTTP requester that invokes `service-2`, the policy is not applied. Therefore, the additional header is not appended to that particular HTTP request. If a Mule application with the annotation is deployed to a Mule version prior to 4.3.0, the annotation has no effect and the policies are not disabled. However, the application is still deployed. ## See Also - [Policies for Mule 4](https://docs.mulesoft.com/mule-gateway/policies-included-overview) --- product: Mule Gateway keywords: runtime, gateway, gatekeeper, security, policy, policies --- # Enhancing Security with Gatekeeper > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When you deploy an application, the tracked resources exposed by the application might become accessible for a short amount of time due to a lapse in security. Because the policies for those resources are not yet applied, the API might receive unwanted traffic. GateKeeper prevents this situation by blocking the tracked resource until all policies are retrieved and applied without errors. Starting with CloudHub 4.2.2, Mule runtime engine (Mule) keep APIs blocked until the contracts of the API are successfully downloaded from the Management plane in case the policy requires contracts and if Gatekeeper is enabled. Gatekeeper waits until contracts are available to unblock the API. In earlier versions of Mule, APIs were unblocked after the runtime successfully applied all the policies. For example, if the API had the Client ID Enforcement policy applied, a request with valid credentials was rejected. This CloudHub update behaves the same way with `strict` and `flexible` Gatekeeper modes. Contracts are considered available if they are downloaded from the Contracts Service before or after Mule is restarted. Out of the box policies that might require contracts include: - [Client ID Enforcement Policy](https://docs.mulesoft.com/mule-gateway/policies-included-client-id-enforcement) - [Rate Limiting SLA Policy](https://docs.mulesoft.com/mule-gateway/policies-included-rate-limiting-sla) - [JWT Validation Policy](https://docs.mulesoft.com/mule-gateway/policies-included-jwt-validation) - [PingFederate OAuth 2.0 Token Enforcement Policy](https://docs.mulesoft.com/mule-gateway/policies-included-pingfederate-oauth-token-enforcement) - [OpenID Connect OAuth 2.0 Token Enforcement Policy](https://docs.mulesoft.com/mule-gateway/policies-included-openid-token-enforcement) - [Mule OAuth 2.0 Access Token Enforcement](https://docs.mulesoft.com/mule-gateway/policies-included-oauth-access-token-enforcement) ## How Gatekeeper Works The Gatekeeper mechanism is engaged only when you restart the runtime or redeploy a tracked resource that is linked with an API instance when automatically discovered. When Gatekeeper is engaged, each tracked resource is blocked, resulting in a `503 - Service Unavailable` HTTP status code, until all API instance policies are applied in API Manager without errors. Resources not linked to an API instance when automatically discovered are ignored by Gatekeeper. Additionally, you cannot apply any policies to these resources, and no analytics information is generated. If you lose connectivity after the Mule instance is restarted or the tracked Mule application is redeployed, you use cached policies, configuration, and contracts, even if Gatekeeper is not enabled. When Gatekeeper is engaged, if a tracked resource has a malformed or incorrectly defined policy applied, the tracked resource is blocked, resulting in a `503 - Service Unavailable` HTTP status code\`. The resource reamains blocked until the offending policy is removed from API Manager. Mule runtime caches all policies and active contracts locally. ## Security Levels To enable or disable Gatekeeper functionality, you can configure the following property with a specific security level: anypoint.platform.gatekeeper For example, to configure the `flexible` security level, you must specify the following property: anypoint.platform.gatekeeper=flexible - Valid Values for Mule 4 Security Levels - `strict` - `flexible` - `disabled` For Mule runtime versions 4.8.0 or later. Gatekeeper blocks requests when editing the policy configurations. The Gatekeeper does not block requests when editing policy order. To disable Gatekeeper during editing, set the `anypoint.platform.gatekeeper` property to `false`: anypoint.platform.gatekeeper.block\_edit=false ### Security Level Definitions You can apply `false`, `disabled`, `true`, `strict`, or `flexible` security levels to Gatekeeper, as explained in the following table:

Security level

Description

disabled

Gatekeeper does not apply any security. With this setting, the API might receive unwanted traffic during the period while the policies are being applied.

strict

Gatekeeper security is set to its maximum level. When the Mule instance is restarted, the API is blocked with a 503 error until policies for each tracked resource are correctly applied. If connectivity to Anypoint Platform is lost when Gatekeeper is engaged, the tracked resource is blocked until the connection is reestablished.

flexible

Gatekeeper security is set to intermediate level. When the Mule instance is restarted, the API is blocked with a 503 error. If the connectivity to Anypoint Platform is lost when Gatekeeper is engaged, local cache is used to apply the policies during the outage. If cache is unavailable, the tracked resource is blocked at least until the connection is reestablished. Available in Mule 4.1.0 or later.

### Default Gatekeeper Configuration The following table illustrates a Gatekeeper configuration with default values:

Runtime version

Default security level

4.0.0

Strict

4.1.0 and later

Flexible

--- product: Mule Gateway --- # Gateway Startup Encryption in Mule 4 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule Gateway startup encryption enables you to encrypt sensitive information stored by Mule runtime engine (Mule), such as policies, contracts, and the credentials required to configure the connection between your Mule application and Anypoint Platform. This feature is supported in Mule 4.2.0 and later. If a [policy that supports encryption](#policies-that-support-encryption), such as Basic Authentication 1.2.0, is applied to an API that is running in Mule versions earlier than 4.2.0, the policy configuration is not encrypted. ## Encrypting Your Anypoint Platform Credentials Using the Agent Configuring encryption through Anypoint Runtime Manager agent is the fastest way to secure your client credentials. You add the encryption key when creating an agent server. The agent then encrypts the properties encryption for you. To learn how to configure encryption through the agent, see [Install and Configure the Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/installing-and-configuring-runtime-manager-agent). ## Encrypting the Client ID and Client Secret You can manually encrypt your properties even though you are using an agent. The most common way is using the [secure properties tools](https://docs.mulesoft.com/mule-runtime/latest/secure-configuration-properties#secure-properties-tool). When you use encrypted properties, Mule Gateway assumes that you are using the AES algorithm in CBC Mode. ### Example Let us assume that your client ID is `bb458e566cba4e2ea5a826d27b46031a`, and you choose the encryption key to be the 128 bits string `MyEncryptionKey1`. To encrypt these properties, you must run the following command: ```console > java -jar secure-properties-tool.jar \ string \ (1) encrypt \ (2) AES \ (3) CBC \ MyEncryptionKey1 \ (4) bb458e566cba4e2ea5a826d27b46031a ```
1Use the string parameter to encrypt a single value.
2Set the tool to encrypt the value.
3Use AES with CBC Mode.
This is important because Mule uses this configuration to decrypt the value later.
4And finally, specify the encryption key-value pair that you want to encrypt.
This command outputs your encrypted client ID: ```none > smzbg+aV2HbiC9Fv8KBsZpD5PlXiplsfhZ42RWNEbHhUeZ9ZIDftljUx6sYpuQ+b ``` ## Passing Your Encrypted Client ID and Client Secret After encrypting your credentials, you must configure your encrypted values in your `wrapper.conf` file, which is located inside the `conf` directory in the root folder of your Mule environment: ```none wrapper.java.additional.=-Danypoint.platform.client_id=![_encrypted client ID_] wrapper.java.additional.=-Danypoint.platform.anypoint.platform.client_secret=![_encryptedclient secret_] wrapper.java.additional.=-Danypoint.platform.proxy_password=![_encrypted password_] ``` Replace with the unique number within the property `wrapper.java.additional` file. > [!CAUTION] If you add `wrapper.java.additional.n` entries to the configuration file, you must > change each instance of `` to a consecutive number. otherwise, Java does not parse the > properties correctly. Based on this example, your `client_id` would appear as: ```none wrapper.java.additional.100=-Danypoint.platform.client_id=![smzbg+aV2HbiC9Fv8KBsZpD5PlXiplsfhZ42RWNEbHhUeZ9ZIDftljUx6sYpuQ+b] ``` > [!NOTE] The required `![` prefix and `]` suffix indicate to Mule runtime that the enclosed value > is encrypted. When starting Mule runtime, you must pass your secret key, using the `anypoint.platform.encryption_key` property: ```none $MULE_HOME/bin/mule start -M-Danypoint.platform.encryption_key=MyEncryptionKey1 ``` Mule runtime uses the encryption key passed in the `anypoint.platform.encryption_key` property to decrypt the properties. ### How It Works You can encrypt your Anypoint Platform credentials (client ID, client secret, and your proxy password) and add those encrypted values, along with your encryption key to the `wrapper.conf` file of your Mule environment. When Mule Gateway capability starts, it checks for an encryption key. The client ID and client secret values are then obtained from its `wrapper.conf` file. If any of the values in that file are enclosed within encryption indicators (`![` and `]`), Mule runtime uses the encryption key that it loaded earlier to decrypt the values and use its original content. ## Debugging Startup Encryption You can configure your runtime Log4J logger to display information about the encryption mechanism during startup. In `$MULE_HOME/conf/log4j2.xml`, set up an asynchronous logger for your gateway deployment: ```XML ... ... ``` When you provide a key, the Mule environment displays the following message: An encryption key is present. Policies and API contracts will be encrypted. If not, Mule runtime starts with: No encryption key provided. Policies and API contracts will not be encrypted. If the decryption process fails, the Mule environment displays an error: Client ID cannot be decrypted If your credentials cannot be decrypted, you cannot establish a connection with Anypoint Platform, nor can you subsequently download policies or contracts or generate analytics information for tracked APIs. ## Troubleshooting Credentials If you encounter issues when passing your encrypted credentials to Anypoint Platform, MuleSoft recommends you verify that the provided credentials are valid. You can use the Secure Properties Tool to decrypt the values back to the original and compare them with the ones displayed in Anypoint Platform: 1. Run the Secure Properties Tool to decrypt your credentials: ```none > java -jar secure-properties-tool.jar string decrypt AES CBC ``` 2. Compare the decrypted value with the one in Anypoint Platform. See [Obtaining Credentials](https://docs.mulesoft.com/mule-gateway/mule-gateway-org-credentials-mule4#obtaining-credentials) for information on how to verify your Anypoint Platform’s credentials. ## Supported Properties The following `wrapper.conf` properties support encryption:
PropertyProperty KeyDescription

Client ID

anypoint.platform.client_id

Your Anypoint Platform client ID

Client secret

anypoint.platform.client_secret

Your Anypoint Platform client secret

Proxy password

anypoint.platform.proxy_password

Password of the proxy configuration to connect to Anypoint Platform

## Policies Encryption The configuration for your API policies is stored in the `policies` directory. Some policies may contain sensitive information that you want to hide from unauthorized parties, such as the password field for the `Basic Authentication` header. Sensitive values in your provided API policies are marked as such in the API Manager UI for policy configuration. When creating a custom policy, you can define which values are sensitive. ## Configuring Policy Encryption To enable encryption in policies, you must provide two system properties in your `wrapper.conf` file: - `anypoint.platform.encryption_key` The encryption key for your policy. > [!CAUTION] If you restart Mule runtime without an encryption key, all policies are downloaded > again, and sensitive information is not encrypted. - `anypoint.platform.policy_encryption_mode` This property key can take two values:

FULL

All values are encrypted.

SENSITIVE_ONLY

Only values that you marked as sensitive are encrypted.
This is the default encryption mode.

If you have not configured this property, the default `SENSITIVE_ONLY` encryption mode is used. You can change the encryption mode after applying one. The files in your `policies` directory regenerates according to your new encryption mode. > [!CAUTION] If you are changing from `FULL` to `SENSITIVE_ONLY`, any parameter not marked as > `sensitive` is shown as plain text in your file system. ## Policies That Support Encryption The following list describes all policies that support encryption in their values, along with their minimum required version to support this feature. Earlier versions of these policies and policies that are not listed below will not encrypt the policy values even when the gateway capability detects an encryption key in its configuration.
PolicyVersion

Basic Authentication

1.2.0 and later.

Client ID Enforcement

1.2.0 and later.

Header Injection

1.1.0 and later.

IP Allowlist

1.0.0 and later.

IP Blocklist

1.0.0 and later.

JWT Validation

1.1.0 and later.

Open AM

1.2.0 and later.

Open ID

1.2.0 and later.

OAuth 2.0

1.2.0 and later.

Ping Federate

1.2.0 and later.

## Custom Policy Encryption The recommended way to create a new custom policy project is using the Maven archetype. When creating a new custom policy project using the archetype, you can pass the `-DencryptionSupported=true` property to enable encryption in your custom policy. See [Setting up a project with the archetype](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started#setting-up-a-project-with-the-archetype) for more detailed steps to do this. If you are developing a custom policy manually, or want to add encryption to an existing policy, perform the following steps: 1. Add the required dependencies in the policy `pom.xml` file. You must add the **Secure Configuration Property Module** dependency in your `pom.xml` file: ```XML com.mulesoft.modules mule-secure-configuration-property-module ${securePropertyModuleVersion} mule-plugin ``` 2. Add the **Secure Properties Element** to your policy’s template file. Paste the following snippet in your policy’s XML template file, after your `` element: ```XML {{#if encrypted}} {{/if}} ``` This feature supports only the AES Algorithm in CBC mode. The gateway capability takes the `anypoint.platform.encryption_key` and `encryptedPropertiesFile` values from the system properties that you set at startup time for the gateway. 3. Define the sensitive values in the policy’s YAML file. By default, the values in a custom policy are not sensitive. To specify that a value is sensitive, use the `sensitive` element. ```YAML configuration: - propertyName: username type: string sensitive: false - propertyName: password type: string sensitive: true (1) ```
1The password value in your policy is now considered sensitive.
## Offline Policies Encryption You can encrypt the configuration of your offline policies by encrypting their values using the [Secure Properties Tools](https://docs.mulesoft.com/mule-runtime/latest/secure-configuration-properties#secure-properties-tool). \> java -jar secure-properties-tool.jar \\ string \\ **(1)** encrypt \\ **(2)** AES \\ **(3)** CBC \\ MyEncryptionKey1 \\ **(4)** bb458e566cba4e2ea5a826d27b46031a 1. Use the string parameter to encrypt a single value. 2. Set the tool to encrypt the value. 3. Use AES with CBC Mode. This is important because Mule runtime uses this configuration to decrypt the value later. 4. And finally, specify the encryption key-value pair that you want to encrypt. See [Applying an Offline Policy](https://docs.mulesoft.com/mule-gateway/policies-custom-offline-apply) for more information. ## Contracts Encryption If your Mule Gateway is configured with encryption, then contracts associated with the contract enforcement policies will also be encrypted. ## Scope and Considerations In a cluster scenario, you must set the encryption properties for each node. Otherwise, you may leave some of your nodes unprotected. --- product: Mule Gateway keywords: header injection, api gateway, mule gateway, gateway, policy --- # Header Injection Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy name

Header Injection

Summary

Adds headers to a request or a response

Category

Transformation

First Mule version available

v4.1.0

Returned Status Codes

500 - The configuration includes an expression that was not evaluated.

## Summary The Header Injection policy adds HTTP headers to the request or response of a message. When you configure this policy for your API, you must specify an inbound and outbound map of the headers that you want to add in the message processing in the form of a key-value pair. ![A flow chart illustrating the process of setting header injection and removal policies for clients accessing an API through a proxy](/mulesoft/current/en-us/mule-gateway/_images/header-inject-remove-diagram.png) You can optionally include DataWeave expressions in the value or name of the header. For example, all headers matching the following configured expression are injected to the message: `“#[attributes.requestPath]”` If the injected header already exists in the message attributes, the policy creates a new header without overriding the value of the existing one. > [!NOTE] Only certain headers are restricted to support multiple values, and they will be > overwritten using configured values. These headers are: `access-control-allow-origin`, > `content-type`, `content-length`, `transfer-encoding`. > > To overwrite any other existing message header, remove it before adding your header. See the > [Header Removal](https://docs.mulesoft.com/mule-gateway/policies-included-header-removal) policy. ## Configuring Policy Parameters ### Mule Gateway When you apply the policy to your API from the UI, the following parameters are displayed:
ParameterDescription

Inbound Header Map

List of headers to be injected at the beginning of the message processing.

Inbound Header Key

String or Dataweave expression to be used as header name at the beginning of the message.

Inbound Header Value

String or Dataweave expression to be used as header value at the beginning of the message.

Outbound Header Map

List of headers to be injected at the end of the message processing.

Outbound Header Key

String or Dataweave expression to be used as header name at the end of the message processing.

Outbound Header Value

String or Dataweave expression to be used as header value at the end of the message processing.

Method & Resource conditions

The option to add configurations to only a select few or all methods and resources of the API

> [!NOTE] Header keys should be compliance with > [HTTP 1.1](https://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2) standard. To use single quotes directly in a String value (for example `"default-src 'none'; frame-ancestors 'none';"`), use a DataWeave expression: #\["default-src 'none'; frame-ancestors 'none';"\] --- product: Mule Gateway keywords: header removal, api gateway, mule gateway, gateway, policy --- # Header Removal Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy name

Header Removal

Summary

Removes headers from a request or a response

Category

Transformation

Returned Status Codes

500 - The configuration includes an expression that was not evaluated.

## Summary The Header Removal policy removes all listed headers from a request or a response of a message when you specify an inbound and outbound map of the headers that you want to remove with a key-value pair. ![A flow chart illustrating the process of setting header injection and removal policies for clients accessing an API through a proxy](/mulesoft/current/en-us/mule-gateway/_images/header-inject-remove-diagram.png) You can optionally include DataWeave expressions in the value of the header. For example, all headers matching the following configured expression are injected to the message: `“#[attributes.requestPath]”` > [!NOTE] The following headers may not be removed: user-agent, accept, host, content-type, > content-length, date, transfer-encoding, connection, ## Configuring Policy Parameters ### Mule Gateway When you apply the Header Removal policy to your API from the UI, you can configure the following parameters:
ParameterDescription

Inbound Header Map

List of header names or regular expressions (comma separated) to be removed at the beginning of the message processing, for example, Cache-Control, Access-Control.*

Outbound Header Map

List of header names or regular expressions (comma separated) to be removed at the end of the message processing, for example, Access-Control-Allow-Credentials

Method & Resource conditions

The option to add configurations to only a select few or all methods and resources of the API

## How This Policy Works Because every header that matches a Header Removal policy parameter is removed from the message, you must be careful about how you configure that parameter. For example, the following parameter configuration removes any header starting with the word `Access-Control`, such as the `Access-Control-Allow-Credentials` and `Access-Control-Allow-Origin` headers from a message. The configuration also removes the `Cache-Control` header: ![Removed headers at the start of message processing](/mulesoft/current/en-us/mule-gateway/_images/remove-inbound-header.png) Figure 1. Inbound Header --- product: Mule Gateway keywords: http caching, api gateway, mule gateway, gateway, policy --- # HTTP Caching Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

HTTP caching

Summary

Caches HTTP responses from an API implementation

Category

Quality of Service

First Mule version available

v4.1.0

Returned Status Codes

No return codes exist for this policy

## Summary The HTTP Caching policy enables you to cache HTTP responses for reuse. Caching these responses speeds up the response time for user requests and reduces the load on the backend. For example, if your backend exposes an endpoint for which the responses to requests are not likely to change, you can reuse the HTTP responses and bypass the backend request processing by using the HTTP Caching policy. > [!NOTE] Policies applied after the HTTP Caching policy in the policy order are not applied to > responses served from the cache. For example, a rate limiting policy applied after the HTTP > Caching policy only limits the responses served by the upstream service but not the responses > served by the cache. Apply all policies needed for the cached response before the HTTP Caching > policy. ## Configuring Policy Parameters ### Mule Gateway When you apply the HTTP Caching policy to your API from the UI, you can configure the following parameters:
ParameterDescriptionRequired?

HTTP Caching Key

A DataWeave expression. Default value: #[attributes.requestPath]

Yes

Maximum Cache Entries

Specifies the maximum number of entries that can be stored in the cache at any given time. Default value: 10000

Yes

Entry Time To Live

Specifies the amount of time (in seconds) after which a single entry expires from the cache. Default value: 600

Yes

Distributed

Configures the cache to be distributed among different nodes in a cluster. If you are using CloudHub, ensure that you enable Object Store v2 when deploying an application. Default value: false

Yes

Persistent Cache

Configures the cache to persist between different restarts of the Mule/Omni instance. If you are using CloudHub, ensure that you enable Object Store v2 when deploying an application. Default value: false

Yes

Follow HTTP Caching directives

Enables the use of Cache-Control header directives. Default value: true

Yes

Invalidation Header

Name of the header used to invalidate a single entry or the entire cache.

No

Conditional Request Caching Expression

The DataWeave expression that is used to decide which requests are to be cached (caches the response only if the condition is true). Default value: #[attributes.method == 'GET' or attributes.method == 'HEAD']

No

Conditional Response Caching Expression

The DataWeave expression that is used to decide which responses are to be cached (caches the response only if the condition is true). Default value: #[[200, 203, 204, 206, 300, 301, 404, 405, 410, 414, 501] contains attributes.statusCode]

No

## How This Policy Works When an HTTP request reaches an endpoint, what happens next depends on whether that request does not already exist in cache (a cache miss) or whether it does (a cache hit). ### Cache Miss In a cache miss scenario, the HTTP Caching policy checks whether a response to the submitted request is already cached. The request reaches the backend and the process is initiated only when it’s a cache miss. The diagram illustrates the flow of events that occur in this scenario: ![A flowchart that illustrates the data flow between a web browser and a backend system](/mulesoft/current/en-us/mule-gateway/_images/http-policy-cache-miss.png) 1. The client (user) sends a request to the API. 2. The request proceeds through other policies in the policy chain before reaching the HTTP Caching policy. 3. The HTTP Caching policy checks if the request is already in the object store and, if not, the cache miss process is initiated. 4. The request continues throughout the chain of other remaining policies. 5. The request reaches the backend and completes all required processing. 6. The backend responds and the response travels back through the policy chain. 7. The response reaches the HTTP Caching policy. 8. Caching hits the object store again and attempts to save the [key](#key) of the request for later reuse. 9. The response continues through the remaining policies in the policy chain. 10. The response is returned to the client. ### Cache Hit In a cache hit scenario, the HTTP Caching policy searches for the key in the object store and finds that the response to a request is already cached as a [stored entry](#stored_entry). The request does not proceed any further in the policy chain toward the backend, and the cached response is reused. Subsequently, all the policies that must be executed in the policy chain after caching are not executed, in case of a cache hit: ![A flowchart illustrating the data flow from a web browser through an API gateway to the backend and the object store](/mulesoft/current/en-us/mule-gateway/_images/http-policy-cache-hit.png) 1. The client (user) sends a request to the API. 2. The request crosses other policies before reaching the HTTP Caching policy. 3. The HTTP Caching policy verifies that the request is already in the cache. 4. The [key](#key) is found in the object store and the stored response is returned. 5. The response continues through the rest of the policy chain until it reaches the last one. 6. The cached response is returned to the client. ### Stored Entries _Stored entries_ are the cached HTTP responses. The cache can store any serializable data or input streams of up to 1 MB. If that value is surpassed, then the reading stops and the value is not stored in such a case. ### HTTP Caching Key The cache works as a dictionary, where each response stored in the cache is associated with a string called _key_. For example, the expression #\[attributes.headers\['key'\]\] uses the header called `key` as the entry key. ### Cache Size and Entry Expiration The cache can hold a specified number of entries at any given time. You can configure this number using the `Maximum Cache Entries` property. Each stored entry is held in the cache memory for a specific period of time, after which the entry expires and must be processed again. This expiration time is called _time to live_ (TTL). Another condition that can trigger the expiration of an entry is when the cache reaches the maximum number of items that it can store. When this scenario occurs, the entry is removed by using the FIFO (First-In First-Out) criteria. This means that the earliest entry to reach the cache is removed, even though it hasn’t reached the TTL value yet. ### Distributed Cache Each entry in the cache can be shared between different nodes in a cluster or between several workers in Runtime Manager using the `Distributed` option (see table). If this option is not enabled, then each node is assigned its own cache memory. ### Persistent Cache A persistent cache enables the stored entries in the cache to persist if Mule runtime engine (Mule) or Omni replica is restarted. When you upgrade a version of the instance that has the HTTP Caching policy configured to use the persistent store, the policy tries to maintain the entries stored by the previous version. However in a worst-case scenario, the entries in the cache are invalidated and the cache is re-populated when new requests arrive. This manipulation of the entries in the cache occurs automatically and is invisible to the user. ## HTTP Caching Directives To obtain more control over the cache, the HTTP Caching policy interprets some of the HTTP directives from the [RFC-7234](https://datatracker.ietf.org/doc/html/rfc7234) protocol by taking the following headers into account: - `Cache-Control` - `Expires` - `Date` - `Age` ### Cache-Control The `Cache-Control` header can exist either in the request or in the response. Possible values for the header, which can be combined separated by commas, include: - In requests: - `no-cache` The response is not searched for, but is directly stored in the cache. - `no-store` The response is not stored in the cache. However, if the response is already present in the cache, the policy returns the response. - In responses: - `no-store`, `no-cache`, `private` For each value, the response is not stored in the cache. - `max-age=`, `s-maxage=` The `` placeholder must be replaced with a valid integer that indicates the time (in seconds) for which the response can remain in the cache. If both parameters are defined, `s-maxage` takes precedence over `max-age`. If a global time-to-live (TTL) value is also defined for the policy, these header values override the global TTL configured in the policy if the time specified in the headers is less than the global TTL. ### Expires If present, this header specifies the date by which the entry in the cache expires. If you specify the `max-age` directive or `s-maxage` directive, this header is ignored. You must define the header value as stated in [RFC-1123](https://datatracker.ietf.org/doc/html/rfc1123). ### Date The `date` header, as defined per [RFC-1123](https://datatracker.ietf.org/doc/html/rfc1123), specifies the date and time when the response is created. If not defined, the `date` header is added with the time when the request was received. This header is used in conjunction with the values defined in the `max-age` and `s-maxage` directives of the Cache-Control header. ### Age The `age` header indicates the time (in seconds) elapsed since the origin of the cached response specified in the date header. This header is calculated by the policy and added to each response that is retrieved from the cache. The expiration time is calculated using the `cache-control`, `date`, and `expires` headers. However, if the resulting expiration time exceeds the one imposed by the TTL value of the entry, the cache entry expires anyway. ### Invalidate The `invalidate` header, if configured in the HTTP Caching policy, invalidates the entries in the cache, thereby causing the request to be processed again. You specify the name of the header in the Invalidation Header configuration to turn on the option. The value of the header can take only one of the following options: `invalidate` This option invalidates the entry whose key matches the current request. `invalidate-all` This option invalidates all the entries from the cache. For example, imagine that the following values are configured in the policy for the request: - `HTTP Caching Key`: "#\[attributes.requestPath\]" - `Invalidation header`: "myInvalidationHeader" The following command invalidates the entry with key “/my/policy" from the cache: `curl http:///my/policy -H “myInvalidationHeader:invalidate”` The following request invalidates all entries from the cache: `curl http:///my/policy -H “myInvalidationHeader:invalidate-all”` ## Conditional Caching Conditional caching enables you to configure a set of conditions that must be met before entries are stored in the cache. If none of the conditional caching parameters are configured, the cache stores the responses for every incoming request. If configured, parameters are evaluated for each request to determine whether the response of the current request must be stored. For conditional request expressions, only the responses for incoming requests with HTTP methods `GET` or `HEAD` are cached by default. For conditional response expressions, only status codes specified by [RFC-7231](https://datatracker.ietf.org/doc/html/rfc7231) are cached by default. For more information about the default values, see [Configuring Policy Parameters](#cpp). ## FAQ **What happens when the evaluation of the key results in any error?** If the evaluation of the expression for a particular request results in an error, the policy does not take effect and the request continues to the next receptor in the policy chain. **Can I store only part of the response with this policy?** No, but you can apply a policy before this one and transform the response to something else. **What happens if one parameter is configured to search for the response in the cache and the other parameter is configured for the opposite action?** This is the same as configuring the response to be stored in the cache when there is a no-store directive in the Cache-Control header. In this situation, the response isn’t stored. You must configure both the Cache-Control header and the cache to be able to store and search for the response in the cache. **How does running the HTTP Caching policy in CloudHub differ compared with running it in Mule runtime engine?** - If the Distributed option is selected, the cache is always persistent. - The maximum cache configuration is ignored in Runtime Manager. - The edition of the TTL of the policy is not correctly reflected while using Object Store v2. To change this value, remove the HTTP Caching policy and apply a new one. **What happens if I do not define some of the optional parameters?** If you have not configured the `invalidation` header, you cannot invalidate the cache in a request. Additionally, if you have not configured the request expression or response expression, the cache is used for all requests and all the responses are stored in the cache (expression #\[true\]). **Can I modify the Invalidation header values?** No, you can modify only the header name. **If I deploy my application in an on-premise server, will it use Object Store v2?** No, Object Store v2 is not available for on-premises servers. You must use the Mule object store. For more information, see [Object Store v2 FAQs](https://docs.mulesoft.com/object-store/osv2-faq#can-i-use-object-store-v2-for-apps-deployed-to-on-premises-servers). --- product: Mule Gateway --- # HTTP Policy Transform Extension > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule version 4.1.0 and later, the HTTP Policy Transform Extension is available for use in policies. This extension simplifies the modification of HTTP requests and responses that go through the different policies. This documentation applies to HTTP Policy Transform Extension 3.0.0 and later. ## Adding the extension as a Maven dependency to a policy To use the HTTP Policy Transform Extension in a policy, first you must add the Maven dependency to the POM file of the policy. Add the following code in the dependencies section of policy’s POM file: ```xml com.mulesoft.anypoint mule-http-policy-transform-extension ${httpPolicyTransformVersion} mule-plugin org.mule.connectors mule-http-connector ``` When a policy using the HTTP Policy Transform Extension is packaged, the Mule HTTP Connector is added to the policy JAR file. To avoid double packaging the connector in both your policy and application, use the exclusion statement in the dependency to remove the Mule HTTP Connector from the policy JAR file. However, if your custom policy must perform its own outbound HTTP requests, you must either: - Remove the exclusion statement to ensure the connector is available within the policy’s own class loader. - Set `mule.enable.policy.isolation=false` so that the policy uses the application level connector. Additionally, ensure that you set the `mule-maven-plugin` parameter version to `3.3.2` or later in the POM file of the policy. ## Namespace ```xml ``` ## Operations - Add Headers Operations - Add Request Headers - Add Request Headers List (Since mule-http-policy-transform-extension 3.1.0) - Add Response Headers - Add Response Headers List (Since mule-http-policy-transform-extension 3.1.0) - Remove Headers - Set Response - Set Request ### Add Headers Operations #### Add Request Headers This operation is used to inject headers in the request. To use this operation, you must initiate a call from: - Source Policy, before the `execute-next` is invoked. - Operation Policy, before the `execute-next` is invoked. ##### Parameters - `headers` A DataWeave expression that resolves to the Map of the headers to be added to present message attributes. **Example** ```xml #[ { 'FirstHeader': 'FirstHeaderValue', 'SecondHeader': 'SecondHeaderValue', 'ThirdHeader': 'ThirdHeaderValue' } ] ``` #### Add Request Headers List > [!NOTE] This operation was added in mule-http-policy-transform-extension 3.1.0. This operation is used to inject headers in the request. To use this operation, you must initiate a call from: - Source Policy, before `execute-next` is invoked. - Operation Policy, before `execute-next` is invoked. ##### Parameters - `http-transform:new-headers` An `http-transform:header` must be added for each header. Each http-transform:header must have the `headerName` and `headerValue` attributes defined with a literal or a DataWeave expression. **Example** ```xml ``` The operation allows DataWeave expressions when the policy configuration has a property type of `keyvalues` with multiple values. **Example** ```xml ... configuration: - propertyName: requestHeaders name: Reques Headers description: Header Names and values type: keyvalues optional: true allowMultiple: true ... ``` With the above configuration shown, you can use handlebars to expand the headers to be added in the policy: ```xml ... {{#each requestHeaders}} {{/each}} ... ``` #### Add Response Headers This operation is used to inject headers in the response. To use this operation, you must initiate a call from: - Source Policy, after the `execute-next` is invoked. - Operation Policy, after the `execute-next` is invoked. ##### Parameters - `headers` A DataWeave expression that resolves to the Map of headers to be added to present message attributes. **Example** ```xml #[ { 'FirstHeader': 'FirstHeaderValue', 'SecondHeader': 'SecondHeaderValue', 'ThirdHeader': 'ThirdHeaderValue' } ] ``` #### Add Response Headers List > [!NOTE] This operation was added in mule-http-policy-transform-extension 3.1.0. This operation is used to inject headers in the response. To use this operation, you must initiate a call from: - Source Policy, after the `execute-next` is invoked. - Operation Policy, after the `execute-next` is invoked. ##### Parameters - `http-transform:new-headers` An `http-transform:header` must be added for each header. Each http-transform:header must have the `headerName` and `headerValue` attributes defined with a literal or a DataWeave expression. **Example** ```xml ``` The operation allows DataWeave expressions when the policy configuration has a property of type `keyvalues` with multiple values. **Example** ```xml ... configuration: - propertyName: responseHeaders name: Reques Headers description: Header Names and values type: keyvalues optional: true allowMultiple: true ... ``` With the above configuration shown, you can use handlebars to expand the headers to be added in the policy: ```xml ... {{#each responseHeaders}} {{/each}} ... ``` ### Remove Headers This operation removes the headers from both requests and responses of the HTTP Listener and Requester. The returned attributes are of the same type as that of the input attributes. This operation is case-insensitive. #### Parameters - `header-names` A Data-Weave expression that resolves to an array of header names to be removed. **Example** ```xml #[['FirstHeader', 'SecondHeader']] ``` ### Set Response This operation sets a complete HTTP response. You use this operation when the policy prevents the flow from being executed, thereby resulting in no HTTP response being set. #### Parameters - `statusCode`\-- An integer representing the HTTP status code of the response. - `reasonPhrase`\-- A string representing the HTTP reason phrase of the response. - `body`\-- The content of the HTTP response. - headers-- A DataWeave expression that resolves to the map of headers of the HTTP response **Example** ```xml #['policyPayload'] #[ { 'FirstHeader': 'FirstHeaderValue', 'SecondHeader': 'SecondHeaderValue', 'ThirdHeader': 'ThirdHeaderValue' } ] ``` ### Set Request This operation sets a complete HTTP request that the HTTP Requester executes. #### Parameters - `requestPath`: The path where the HTTP Request is being sent. - `body`: The content of the HTTP Request. - `headers`: A DataWeave expression that resolves to the map of headers of the HTTP request. - `uriParams`: A DataWeave expression that resolves to the map of URI params of the HTTP request. - `queryParams`: A DataWeave expression that resolves to the map of query params of the HTTP request. **Example** ```xml #['policyPayload'] #[ { 'FirstHeader': 'FirstHeaderValue', 'SecondHeader': 'SecondHeaderValue', 'ThirdHeader': 'ThirdHeaderValue' } ] #[ { 'FirstUriParam': 'FirstUriParamValue', 'SecondUriParam': 'SecondUriParamValue' } ] #[ { 'FirstQueryParam': 'FirstQueryParamValue', 'SecondQueryParam': 'SecondQueryParamValue' } ] ``` --- product: Mule Gateway --- # Included Mule Gateway Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt See the [Included Policies Directory](https://docs.mulesoft.com/mule-gateway/policies-included-directory) for descriptions of all included policies. Policies applied to APIs are the same as those in the earlier release with a few exceptions. Classloader isolation exists between the application, the runtime and connectors, and policies. To fulfill the isolation requirement, policies are self-contained and packaged to include libraries needed for execution, similar to an application. Policies are non-blocking. You can order all policies except CORS which takes precedence over all other policies. MEL expressions are replaced by DataWeave. ## Policy Management and Mule 4 In Mule 4, classloader isolation exists between application, runtime, connectors and policies. Other changes to policies are: - All policies are non-blocking, which is described in Mule 4 documentation. - All policies except CORS, which is executed first, can be ordered. - Resource level policy support, which was restricted to RAML-based APIs, is extended to any HTTP API. - You can distribute policies outside of the runtime, which simplifies upgrades. Mule 4 introduces changes to the packaging, size and scope of a policy. ## Provided Policies and Mule 4 Notable changes to policies for governing APIs are: - API Manager now provides two HTTP Basic Authentication policies, one based on the simplest technique for enforcing access control to web resources and the other on the LDAP configuration. If you upgrade APIs from the Jul 2017 to Nov 2017, the security manager setup information is no longer required. The policy incorporates the information. - Header propagation no longer occurs by default. You can configure header propagation for token enforcement and rate limiting policies by checking the Expose Headers checkbox. - You can configure the rate limiting policy to share the quota among the cluster nodes (default) or not. ## See Also - [Apply a Policy](https://docs.mulesoft.com/mule-gateway/policies-included-apply) - [Reordering Policies](https://docs.mulesoft.com/mule-gateway/policies-reorder) --- product: Mule Gateway --- # Included Policies Directory > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## Policies Included in Mule Gateway
PolicySummary

API Security-Identification Header

Adds API instance identifiers as response headers for external security platform correlation

Basic Authentication: LDAP

Allows access based on the basic authorization mechanism, with user-password defined on LDAP

Basic Authentication: Simple

Allows access based on the basic authorization mechanism, with a single user-password

Client ID Enforcement

Allows access only to authorized client applications

Cross-Origin Resource Sharing (CORS)

Enables access to resources residing in external domains

Header Injection

Adds headers to a request or a response

Header Removal

Removes headers from a request or a response

HTTP Caching

Caches HTTP responses from an API implementation

IP Allowlist

Allows a list or range of specified IP addresses to request access

IP Blocklist

Blocks a single IP address or a range of IP addresses from accessing an API endpoint

JSON Threat Protection

Protects against malicious JSON in API requests

JWT Validation

Validates a JWT

Message Logging

Logs custom messages using information from incoming requests, responses from the backend, or information from other policies applied to the same API endpoint

OAuth 2.0 Access Token Enforcement Using Mule OAuth Provider

Allows access only to authorized client applications

OpenAM OAuth 2.0 Token Enforcement

Allows access only to authorized client applications

OpenID Connect OAuth 2.0 Access Token Enforcement

Allows access only to authorized client applications

PingFederate OAuth 2.0 Token Enforcement

Allows access only to authorized client applications

Rate Limiting

Monitors access to an API by defining the maximum number of requests processed within a period of time

Rate Limiting: SLA-based

Monitors access to an API by defining the maximum number of requests processed within a timespan, based on SLAs

Spike Control

Regulates API traffic

XML Threat Protection

Protects against malicious XML in API requests

## See Also - [Policy Availability by Gateway](https://docs.mulesoft.com/gateway-home/#policy-availability-by-gateway) --- product: Mule Gateway keywords: ip, allowlist, validation, api gateway, mule gateway, gateway, policy --- # IP Allowlist Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

IP Allowlist

Summary

Allows a list or range of specified IP addresses to request access

Category

Security

First Mule version available

v4.1.0

Returned Status Codes

403 - IP is rejected

## Summary The IP Allowlist policy allows a list or a range of specified IP addresses access to a protected resource when a match is found between a source IP (specified when configuring the policy) and a list of individual IPs or range of IPs. You can specify a DataWeave 2.0 expression to define the source IP used by the policy to determine whether the IP belongs to the policy’s restricted IP list. ## Configuring Policy Parameters ### Mule Gateway When you apply the IP Allowlist policy to your API from the UI, configure the following parameters:
ParameterDescription

IP expression

The DataWeave 2.0 expression to be used for extracting the IP address from this API request.

Allowlist

The list of IP addresses allowed access to the API. You can define one IP or IP range at a time, as many times as required. For more information, see Specifying IP Addresses to Allowlist in Your Policy.

Method & Resource conditions

The option to add configurations either to a select few or to all methods and resources of the API.

## Specifying IP Addresses to Allowlist in Your Policy Specify IP addresses to allow access to your policy based on: - The IP address of the request - The origin IP address that is determined by resolving a specific DataWeave expression, such as the [x-Forwarded-For](https://en.wikipedia.org/wiki/X-Forwarded-For) header - Any other origin. ### Allowlisting Access Based on the IP address of the Request Allowlist access based on the IP address of the request in any of the following ways: - Define a specific IP address by enumerating it in the Allowlist field, for example, `192.168.1.1`. - Define a subset of addresses by identifying a subnet mask, for example, `192.168.3.1/30`, which includes the consolidated range `192.168.3.01` through `192.168.3.3`. - Define a whole range of IP addresses by stating the relevant octets of the IP address you want to permit, for example, setting `192.168`, which includes IP addresses from `192.168.0.0` through `192.168.255.255`. ### Allowlisting Access Based on the Origin IP Address of the x-Forwarded-For Header If the client connects to your API through an HTTP proxy or a load balancer, you can allowlist the client’s specific IP address (the IP address originating the request) instead of the address that appears in the request. For example, if you want to allowlist `192.168.2.3`(private IP) and the address of a client connecting through an HTTP proxy is `92.40.1.255` (public IP), the client requests appear with the public address using the proxy. Typically, applications use the `X-Forwarded-For` header to identify the origin IP addresses of a request that was redirected to your endpoint. You can use a DataWeave 2.0 expression in the policy to instruct the service to look for the IP address in the `x-Forwarded-For` header. When you insert the IP address in the IP expression field of the policy parameters, Anypoint Platform is instructed to look for the starting IP address in the concatenated values of the `x-Forwarded-For` header of the request. --- product: Mule Gateway keywords: ip, blocklist, validation, api gateway, mule gateway, gateway, policy --- # IP Blocklist Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

IP Blocklist

Summary

Blocks a single IP address or a range of IP addresses from accessing an API endpoint

Category

Security

First Mule version available

v4.1.0

Returned Status Codes

403 - IP is rejected

## Summary The IP Blocklist policy controls access to a configured API endpoint from either a single IP address or a range of IP addresses. The IP Blocklist policy restricts access to a protected resource when a match is found between a source IP (specified when configuring the policy) and either a list of individual IPs or a range of IPs. You can specify a DataWeave 2.0 expression to define the source IP to be used when the policy tries to determine whether the IP belongs to the restricted IP list defined in the policy. ## Configuring Policy Parameters ### Mule Gateway When you apply the IP Blocklist policy to your API from the UI, configure the following parameters:
ParameterDescription

IP expression

The DataWeave 2.0 expression to be used for extracting the IP address from this API request.

Blocklist

The list of IP addresses blocked from the API. You can define one IP or IP range at a time, as many times as required. For more information, see Specifying IP Addresses to Blocklist in the Policy.

Method & Resource conditions

The option to add configurations either to a select few or to all methods and resources of the API.

## Specifying IP Addresses to Blocklist in the Policy Specify IP addresses to block in your policy based on: - The IP address of the request. - The origin IP address that is determined by resolving a specific DataWeave expression, such as the [x-Forwarded-For](https://en.wikipedia.org/wiki/X-Forwarded-For) header. - Any other origin. ### Blocklist Access Based on the IP Address of the Request Blocklist access based on the IP address of the request in any of the following ways: - Define a specific IP address by enumerating it in the white space, for example, `192.168.1.1`. - Define a subset of addresses by identifying a subnet mask, for example, `192.168.3.1/30` includes the consolidated range `192.168.3.0` through `192.168.3.3`. - Define a whole range of IP addresses by specifying the relevant octets of the IP address that you want to permit, for example, setting `192.168` will include IP addresses from `192.168.0.0` through `192.168.255.255`. ### Blocklist Access Based on the Origin IP Address of the x-Forwarded-For Header If the client connects to your API through an HTTP proxy or a load balancer, you can blocklist the client’s specific IP address (the IP address originating the request) instead of the address that appears in the request For example, if you want to blocklist `192.168.2.3` and the address of a client connecting through an HTTP proxy is `92.40.1.255`, the client requests appear with the public address using the proxy. Typically, applications use the `X-Forwarded-For` header to identify the origin IP addresses of a request that was redirected to your endpoint. You can use a DataWeave 2.0 expression in the policy to instruct the service to look for the IP address in the `x-Forwarded-For` header. When you insert the IP address in the IP expression field of the policy parameters, Anypoint Platform is instructed to look for the starting IP address in the concatenated values of the `x-Forwarded-For` header of the request. --- product: Mule Gateway keywords: json threat protection, api gateway, mule gateway, gateway, policy --- # JSON Threat Protection Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

JSON Threat Protection

Summary

Protects against malicious JSON in API requests

Category

Security

First Mule version available

v3.8.0

Returned Status Codes

400 - Bad Request

## Summary > [!NOTE] The JSON Threat Protection policy does not support SOAP APIs. Applications processing JSON requests are susceptible to attacks characterized by unusual inflation of elements and nesting levels. Attackers use recursive techniques to consume memory resources. Dramatic swings in the size of the application data often signal a security problem. The JSON Threat Protection policy helps protect your applications from such intrusions. If you find that attacks on your Anypoint Platform setup are difficult to detect, design your services architecture with layers of protection in addition to JSON Threat Protection. > [!NOTE] The JSON Threat Protection policy doesn’t support multi-part form requests. ## Configuring Policy Parameters ### Mule Gateway When you apply the JSON Threat Protection policy to your API from the UI, the following parameters are displayed:

Field

Description

Default

Required

Maximum Container Depth

Specifies the maximum nested depth. JSON allows you to nest the containers (object and array) in any order to any depth

-1

false

Maximum String Value Length

Specifies the maximum length of a string value

-1

false

Maximum Object Entry Name Length

Specifies the maximum string length of an object’s entry name

-1

false

Maximum Object Entry Count

Specifies the maximum number of entries in an object

-1

false

Maximum Array Element Count

Specifies the maximum number of elements in an array

-1

false

> [!NOTE] A value of -1 indicates that the field value has no limits. ## Payload Example If your payload contains the following example JSON: { "Players":\[ { "Name":"Sachin", "Email":"sachin.tendulkar@example.com" }, { "Name":"Suryakumar", "email":"Surya@example.com" }, { "Name":"Bhuvi", "email":"bhuvi@example.com" }, { "Name":"Jonty", "Email":"jonty@example.com" } \] } The policy defines the example parameter values as follows:
ParameterValueExplanation

Maximum Container Depth

3

The depth of the Name and Email entries

Maximum String Value Length

28

The length of sachin.tendulkar@example.com

Maximum Object Entry Name Length

7

The length of the Players object entry name

Maximum Object Entry Count

2

The number of entries in each Players object

Maximum Array Element Count

4

The number of elements in the Players array

--- product: Mule Gateway keywords: jwt validation, api gateway, mule gateway, gateway, policy --- # JWT Validation Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy name

JWT Validation

Summary

Validates a JWT

Category

Security

First Mule version available

v4.1.0

Returned Status Codes

400 - Token was not provided in the request.

401

Signature was not validated, or is invalid.

Some of the required claims are not present or their validation failed.

Failed to parse the token.

## Summary JSON Web Token (JWT) is a URL-secure method of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS), or as a JSON web encryption (JWE) structure in plain text. This enables the claims to be digitally signed and integrity protected with a message authentication code (MAC). Because the token is signed, you can trust the information and its source. The JWT Validation policy validates the signature of the token and asserts the values of the claims of all incoming requests by using a JWT with JWS format. The policy does not validate JWT that uses JWE. ## Configuring Policy Parameters ### Mule Gateway When you apply the policy to your API from the UI, a list of parameters are displayed based on whether your environment includes Mule or non-Mule applications. #### Configuring the Parameters for Mule Applications For Mule applications, the following parameters are displayed based on whether your environment includes Mule applications:
ElementDescriptionExample

JWT Origin

Specifies from where in the request the JWT will be extracted: * HTTP Bearer Authentication Header * Custom Expression

If you set this field to HTTP Bearer Authentication Header, the JWT is expected as Bearer.
If you set this field to Custom Expression, provide a DataWeave expression that returns the token.

Token Expression

If you set the JWT Origin to Custom Expression, type the DataWeave expression returning the JWT here.

#[attributes.headers['jwt']]
This expression searches the JWT in the header named jwt.

JWT Signing Method

Specify the signing method expected in the incoming JWT. The policy rejects the token if the JWT has a different signing method.

RSA, HMAC, ES, None

JWT Signing Key Length

Specify the length of the key (in the case of the HMAC algorithm) or the algorithm (in the case of RSA) used for the signing method.
Ignore this field if you selected none as JWT Signing Method.

256, 384, 512

JWT Key Origin

Specifies where to obtain the key for the Signature validation.
You can provide the key in the policy by selecting the Text option or by obtaining it from a JWKS.
Ignore this field if you selected none as JWT Signing Method.

JWT Key

This field appears if you selected Text as JWT Key Origin.
Use this field to provide the key used to check the signature of the token.
Ignore this field if you selected none as JWT Signing Method.

Enter a 32, 48, or 64 character string shared secret for HMAC, a 32 character string shared secret for ES, or the PEM Public Key without the header and footer for RSA.

JWKS URL

This field appears if you selected the JWKS method as JWT Key Origin.
Ignore this field if you selected none as JWT Signing Method.

The URL to the JWKS server.

JWKS Caching Time To Live

The amount of time, in minutes, that the JKWS is valid. When the JKWS expires, the policy retrieves it again. The devault value is 60 minutes.
Ignore this field if you selected none as JWT Signing Method.

This field input is the amount of time, in minutes, during which the policy considers the JWKS valid.

JWKS Service connection timeout (milliseconds)

Sets the maximum time, in milliseconds, to wait for a response when authenticating the access token validation endpoint.
The default value is 10 seconds.

Skip Client ID Validation

If you check this field, the policy does not verify that the client ID extracted from the JWT matches a valid client application of the API.

Client ID Expression

If Skip Client Id Validation is not set, the client ID needs to be extracted from the token.

By default, the value will be extracted using the expression #[vars.claimSet.client_id] as specified in the Oauth 2.0 token exchange draft.

Validate Audience Claim

Indicates that the policy should check for the validity of the audience claim. You can set this "Mandatory" if you select Audience Claim Mandatory.

Validate Expiration Claim

Indicates that the policy should check for the validity of the expiration claim. You can set this claim as "Mandatory" by selecting Expiration Claim Mandatory.

Validate Not Before Claim

Indicates that the policy should check for the validity of the Not Before claim. You can set this claim as "Mandatory" by selecting Not Before Claim Mandatory

Validate Custom Claim

Enables the usage of custom validations in the policy. The JWT will be valid only if all DataWeave expressions are fulfilled.

The policy provides a claimSet variable that contains all the claims present in the incoming JWT. For example:

foo : #[vars.claimSet.foo == 'fooValue']

Note that all DataWeave expressions must return a boolean value or they will always fail.

## How This Policy Works The policy validates claims and signatures differently, as explained in this section. ### Validating Signatures The policy validates the signature of the JWT based on the values specified in the policy configuration. If the algorithm specified in the policy configuration does not match with the token, or if the signature of the token is invalid, all JWTs are rejected by the policy. If no algorithm is specified, the policy matches every signed and unsigned token. The algorithms that support signature verification are: - **Symmetric algorithms** - HMAC using SHA-256, SHA-384, and SHA-512. - **Asymmetric algorithms** - ES and RSA using SHA-256, SHA-384, and SHA-512. - **None** - No signature validation. For more information about the algorithms in a JWS structure, refer to the [JWA RFC standard](https://datatracker.ietf.org/doc/html/rfc7518). ### Validating Claims Claim validations enable you to choose the conditions under which a token received in the policy is rejected. The following registered claim validations are provided by default: - **aud**: The Audience validation specifies that a token must be rejected if it does not contain at least one of the values defined. - **exp**: The Expiration validation specifies that a token must be rejected if its date is past the validation date. - **nbf**: The Not before validation specifies that the token must be rejected if the validation time is before the time the token has. In addition to these _provided claims_, you can also specify other claims to use in your validations. For all claims, _Registered_ or _Custom_, you must provide the following details: - The name of the claim you want to validate. For example **iss**, for the issuer of the token. - The value used to test. You can provide a simple literal value if you only need to verify it, or you can provide a DataWeave expression for more complex comparisons. You can define each claim validation as mandatory or non-mandatory. If a claim is defined as mandatory and is not present in the incoming JWT, the policy rejects this token. If a claim is defined as non-mandatory and is not present in the incoming JWT, the policy does not reject the token for that specific validation. For both cases, if a claim is present, the policy validates the token value. If the validation fails, the JWT will be rejected. ### Propagating Claims After the policy parses and validates the JWT, the claims are propagated to downstream policies and flows through the **claims** property in the authentication object. To access the claim values you can use the following Dataweave 2.0 expression by replacing `` with the name of the desired claim to access: `#[authentication.properties.claims.]` The JWT is also propagated downstream, and you can access it by using the following Dataweave 2.0 expression: `#[authentication.properties.jwt]` ### Retry Mechanism If you selected JSON Web Key Set (JWKS) as JWT Key Origin, the policy uses a retry mechanism to handle failed JWKS fetches. Every time the cached JWKS expires or is absent and a new request is initiated, a request is sent to the JWKS service. If the request fails, a sequence of asynchronous requests with an exponential backoff delay is sent to the JWKS service until a new JWKS is obtained and cached again. Until the recaching finishes, the expired JWKS is used to process the request, and a `503` error is returned if no request is found. Using an expired JWKS enables you to apply cached values in upcoming requests, even if the previous requests failed. ## Obtain a Policy Compatible PEM Public Key If you have a preexisting RSA key in an unsupported format that you want to use, first covert the key to a PEM public key. The JWT policy uses public RSA key in PEM format. **Task Prerequisite** Before you convert your existing key: 1. Obtain the `public.pem` key. 2. Before you paste the key to the policy configuration, remove the **\-----BEGIN PUBLIC KEY-----** header and the **\-----END PUBLIC KEY-----** footer. The following table provides instructions for how to convert your existing key based on its current format:
Starting PointProcedure

No previous certificate

  1. Generate the private RSA key openssl genrsa -out key.pem 2048

  2. Extract the public key from the generated private key key.pem openssl rsa -in key.pem -outform PEM -pubout -out public.pem

  3. The public key will be in the file public.pem

PEM Certificate

  1. Extract the public key from the PEM certificate openssl x509 -inform pem -in cert.pem -pubkey -noout > public.pem

  2. The public key will be in the file public.pem

DER Certificate

  1. Extract the public key from the DER certificate openssl x509 -inform der -in cert.crt -pubkey -noout > public.pem

  2. The public key will be in the file public.pem

x5c field from JWKS

  1. Copy the first certificate from the chain and decode it echo <certificateString> | base64 -D > cert.crt (replace <certificateString> with the copied value)

  2. Extract the public key from the DER certificate openssl x509 -inform der -in cert.crt -pubkey -noout > public.pem

  3. The public key will be in the file public.pem

## See Also - [JWT Validation Policy Release Notes](https://docs.mulesoft.com/release-notes/policies/jwt-validation-release-notes) --- product: Mule Gateway keywords: policy, custom, ootb, offline --- # Managing Online Custom Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To develop and manage online custom policies, see the following topics: - [Packaging a Custom Policy](https://docs.mulesoft.com/mule-gateway/policies-custom-package) - [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange) - [Reviewing HTTP Policy Transform Extension Concepts](https://docs.mulesoft.com/mule-gateway/policies-custom-http-transform) - [Caching a Custom Policy for Mule 4](https://docs.mulesoft.com/mule-gateway/policies-custom-mule-4-caching) --- product: Mule Gateway keywords: message logging, api gateway, mule gateway, gateway, policy --- # Message Logging Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy name

Message Logging

Summary

Logs custom messages using information from incoming requests, responses from the backend, or information from other policies applied to the same API endpoint

Category

Troubleshooting

First Mule version available

v3.8.0

Returned Status Codes

No return codes exist for this policy

## Summary The Message Logging policy logs custom messages using information from incoming requests, responses from the backend, or information from other policies applied to the same API endpoint. For Mule Gateway this policy works with both Apache log4j and Apache log4j2. ## Prerequisites You must have the Anypoint Platform Organization Administrators role or have permission to create or manage APIs. ## Configuring Policy Parameters ### Mule Gateway When you use the UI to apply the Message Logging policy to your API, you can configure the following parameters: ![A form to add a new logging configuration](/mulesoft/current/en-us/mule-gateway/_images/apim-message-logging-policy-ui.png)
ParameterDescriptionRequired?

Message

A DataWeave expression to use for extracting the message to be logged Note for Mule 4 Gateway: If the payload is used as part of the message log, do not configure the Listener as non-repeatable.

Required

Conditional

A DataWeave Boolean expression used to specify whether a message is to be logged

Optional

Category

A prefix in the log message that indicates the package and class where the log is executed.

Optional

Level

Defines the level of message to log: INFO, WARN, ERROR, or DEBUG

Required

Before Calling API

Set to cause your logging policy to log messages before the API endpoint is called, taking into account the order in which this policy is applied

Optional

After Calling API

Set to cause your logging policy to log messages after the API endpoint is called, taking into account the order in which this policy is applied

Optional

#### Example of Message Logging Policy Configured from the UI To better understand how to use the Message Logging policy, consider a fictional retail clothier named Les Vetments. To successfully run its e-commerce portal, Les Vetments must audit the status code of the requests made on its website. For example, if a customer buys or returns a product, or if the company adds or removes a product from its catalog, the transactions must be logged. The IT manager at Les Vetments applies the Message Logging policy to the company APIs to enable logging and viewing any data or transaction changes without making any modifications to the code. To log the attributes of the incoming and outgoing HTTP message, Les Vetments applies the Message Logging policy to the API with the following UI configurations: - **Message**: #\[attributes\] The attributes in the payload must be logged. - **Conditional**: Blank Because Les Vetments requires all attributes, no Mule expression to filter messages is specified. - **Category**: Blank No prefix is required in the log sentence. - **Level**: Info All types of messages are to be logged. The Info log level also includes Warn, Error, or Debug log messages. - **Before Calling API**: Checked All transactions that occur before the API is called are to be logged. - **After calling API**: Checked All transactions that occur after the API is called are to be logged. Following this configuration, whenever customers access the Les Vetments catalogue or add or remove items from their carts, or when an item is added or removed from the Les Vetments catalog, logs are generated: ```text ********************************************************************** * Policy: message-logging-1351146-proxy * * OS encoding: UTF-8, Mule encoding: UTF-8 * * * ********************************************************************** 21:56:50.147 11/30/2020 Worker-0 [MuleRuntime].uber.06: [message-logging-771181-proxy].771181-message-logging.CPU_LITE @71625864 INFO event:184152a0-3370-11eb-b732-0a8c1820c088 org.mule.extension.http.api.HttpRequestAttributes { Request path=/proxy/1 Raw request path=/proxy/1 Method=GET Listener path=/proxy/* Local Address=/172.25.159.101:8081 Query String= Relative Path=/proxy/1 Masked Request Path=/1 Remote Address=/18.191.37.179:21836 Request Uri=/proxy/1 Raw request Uri=/proxy/1 Scheme=http Version=HTTP/1.1 Headers=[ host=logging-policy.us-e2.cloudhub.io x-real-ip=204.14.236.154 accept=*/* user-agent=curl/7.54.0 x-forwarded-for=204.14.236.154 x-forwarded-port=80 x-forwarded-proto=http x-sigsci-agentresponse=200 x-sigsci-mac=7caf3820a5c07d06ef827f1565678167 ] Query Parameters=[] URI Parameters=[] } 21:56:50.254 11/30/2020 Worker-0 [MuleRuntime].uber.07: [logging-policy].proxy.CPU_LITE @f0ce617 INFO event:184152a0-3370-11eb-b732-0a8c1820c088 org.mule.extension.http.api.HttpResponseAttributes { Status Code=200 Reason Phrase=OK Headers=[ date=Tue, 01 Dec 2020 00:56:50 GMT content-type=application/json; charset=utf-8 set-cookie=__cfduid=d8afa23a4627ebef39cbc54fea223cb231606784210; expires=Thu, 31-Dec-20 00:56:50 GMT; path=/; domain=.typicode.com; HttpOnly; SameSite=Lax x-powered-by=Express x-ratelimit-limit=1000 x-ratelimit-remaining=999 x-ratelimit-reset=1606784265 vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=max-age=43200 pragma=no-cache expires=-1 x-content-type-options=nosniff etag=W/"53-hfEnumeNh6YirfjyjaujcOPPT+s" via=1.1 vegur cf-cache-status=MISS accept-ranges=bytes cf-request-id=06bd666d0a0000386b7a1fc000000001 expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" report-to={"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report?s=qUAIXoQ7qqqvFzjcwGrmK2r2PcSfDZ75jFJd0Gi0BLBUMHAcnC9wJ9I%2FEHJtk%2Bra%2FXWqkA%2F5%2FlzoWoC6YS2Lew%2BqKgjhaphHqx5WrZ0CKHMalhcM9it%2Fks0qzQGwbsRzQg%3D%3D"}],"group":"cf-nel","max_age":604800} nel={"report_to":"cf-nel","max_age":604800} cf-ray=5fa8d9c1a8c6386b-IAD ] } 12:18:31.770 11/18/2020 Worker-0 agw-policy-set-deployment.01 INFO Applied policy message-logging-1351146 version 1.0.0 to API testLoggingNew-v1-v1:16481163 (16481163) in application messagelog ``` To log headers, Les Vetments uses the following code snippet in the **Message** field: `#[attributes.headers]` To customize the log messages based on the event and the action performed, Les Vetments uses the following code snippet in the **Message** field: #\['User ' ++ authentication.clientId ++ ' performed action ' ++ attributes.method ++ ' on ' ++ attributes.requestPath ++ ' with Payload: ' ++ payload\] #### Example of Message Logging Policy Configured in XML for Mule 4 The following flow shows an example logging policy: ```xml ``` ## How This Policy Works Logging a policy consists of the following sequence: 1. A request is sent to the API. 2. The message is logged if the following conditions are true: - The level and category of the log defined in the policy are included in the logger defined in the configuration file. - Either the conditional field of the policy was not set, or was set and the condition was met. 3. The API response is returned. Message Logging Policy does not interfere with the execution of any policy nor its flow. 4. The message appears in the application log. ## About the Logging Format A message log uses the following format: - Omni: ` [flex-gateway-envoy][] wasm log .default..default.svc main: [req: ] [accessLog] ` `policy-name`: displays the name of the policy binding: `api-name`: displays the name of the api instance: `request uuid`: displays a unique identifier for the request that triggered the message: - Mule: ` : ` `date` is the message logging date and timestamp. `thread name` is the name of the event thread in which the message appears. `level` is the logging level or type of the message, such as INFO, WARN, ERROR, and DEBUG. `category` typically indicates the package and class where the logging occurred. The default value is `org.mule.runtime.logging.policy-`. `message`: displays the message to be logged, for example, `the payload`: `2018-01-25 18:57:29,907 [WrapperListener_start_runner] INFO org.mule: the payload` `2022-05-04T14:50:43.035570800Z [flex-gateway-envoy][debug] wasm log ingress-http-auth.default.ingress-http.default.svc main: [req: 61c7fdcb-8d22-4cb1-852b-0d5073f23950] [accessLog] the payload` ## Logging States During Events Message logging occurs at specific intervals during a request flow: - Before logging an API flow: ![A sequence diagram that illustrates the state before logging an API flow](/mulesoft/current/en-us/mule-gateway/_images/apim-message-logging-policy-states-1.png) - After logging an API flow: ![A sequence diagram that illustrates the state after logging an API flow](/mulesoft/current/en-us/mule-gateway/_images/apim-message-logging-policy-states-2.png) - Error handler after API flow: ![A sequence diagram that illustrates the state after the error handler executes](/mulesoft/current/en-us/mule-gateway/_images/apim-message-logging-policy-states-3.png) ## See Also - [Mule Messages in Mule 4](https://docs.mulesoft.com/mule-runtime/latest/about-mule-message) --- product: Mule Gateway --- # Mule 4 Custom Policy Workflow > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Custom Policies are policies that anyone can develop and apply to their APIs, with the intention of extending existing functionality or defining new ones. The current workflow to get a working policy for Mule 4 that can be applied in Anypoint Platform consists of: 1. Develop the policy. 2. Package the policy. 3. Upload the resulting policy assets to Exchange. 4. Apply the policy to any API through API Manager. ## Setting up a project with the archetype The first step to develop a custom policy consists in setting up a project with the required files. The easiest way to gather all your required files is by using the maven archetype. This archetype creates all the necessary files for you. Then, use Maven to package your custom policy into a deployable JAR. The Maven archetype is not currently available in a Maven Central Repository, so you need to configure your Maven settings to find the archetype in one of MuleSoft’s repositories. One way to do so is by configuring Maven’s `settings.xml` with the following section: ```xml archetype-repository archetype Mule Repository https://repository.mulesoft.org/nexus/content/repositories/public true fail true warn ``` Once Maven is configured: 1. Create a new directory where the custom policy project will live. 2. Go to that directory in the command line. 3. Execute the following command: ```console mvn -Parchetype-repository archetype:generate \ -DarchetypeGroupId=org.mule.tools \ -DarchetypeArtifactId=api-gateway-custom-policy-archetype \ -DarchetypeVersion=1.2.0 \ -DgroupId=${orgId} \ -DartifactId=${policyName} \ -Dversion=1.0.0 \ -Dpackage=mule-policy ``` Replace: - `${orgId}` with the Anypoint Platform Organization Id where the policy will be uploaded. - Get your organization ID from **Access Management > Organization**: - Click the name of your organization. - Copy the UUID from the browser address. For example, copy _2a4b93c3-7899-4ea7-9374-f787744d8784_ from the URL. - `${policyName}` with the desired name for the custom policy. 4. Before finishing, Maven asks you to set up: - **policyDescription**: A brief description of your policy. - **policyName**: The identifier name of your policy. > [!TIP] You can create a policy that supports encryption by passing the > `-DencryptionSupported=true` property. > See [Custom Policy Encryption for more information](https://docs.mulesoft.com/mule-gateway/mule-gateway-encryption-mule4#custom-policy-encryption). After running the command, the project’s directory will have a structure similar to: my-custom-policy/ ├── my-custom-policy.yaml ├── mule-artifact.json ├── pom.xml └── src └── main └── mule └── template.xml Those four files are the basic ones needed for having a working policy. - **pom.xml** - `groupId` is defined as the organization ID used with the archetype. This value must remain as it is. - `mule-policy` packaging, so packager plugin can successfully build the JAR. - `distributionManagement` section is defined pointing to user’s Exchange. - `mule-maven-plugin` responsible of packaging the policy into a deployable jar - `maven-deploy-plugin` configured to deploy both the resulting jar and the YAML when uploading the policy to Exchange - **mule-artifact.json** exists for the mule-maven-plugin. This is the same file you need for Mule applications. - **my-custom-policy.yaml** renders the policy configuration UI. If this file is not provided, the policy won’t be able to be applied through API Platform’s UI. - **template.xml** where the actual logic of the policy and Mule configuration that defines the policy behavior. The archetype, by default, generates a basic policy that sets the returned HTTP Response payload to a “Hello World!” message. That is implemented with the following configuration: XML element ```xml (1) (2) (3) ```
1Basic structure for defining a policy. {{{policyId}}} refers to a HandleBars variable. HandleBars is a templating framework that allows users to create more complex policies.
2Source refers to inbound HTTP requests. The other option is to define logic for an outbound HTTP request.
3Explicit element which indicates that the next policy or flow should be executed. Any element placed before it will be executed before jumping to the next, and any element placed after that will be executed after returning from the next.
Now that the project is set, you can update the logic as necessary with your requirements. The policy engine is powerful and enables you to do things like modifying HTTP requests and responses, logging, caching, throttling, and almost any other integration that you can do with the Mule runtime engine. ## See Also - [Packaging a Custom Policy](https://docs.mulesoft.com/mule-gateway/policies-custom-package) - [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange) - [Reviewing Custom Policy concepts](https://docs.mulesoft.com/mule-gateway/policies-custom-overview) - [Custom Policy Example](https://docs.mulesoft.com/mule-gateway/policies-custom-response-example) --- product: Mule Gateway --- # Mule Gateway Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine includes an embedded Mule Gateway. Mule Gateway enables you to add a dedicated orchestration layer on top of your backend APIs and services to help you separate orchestration from implementation. You can leverage the governance capabilities of API Manager to apply, among other capabilities, throttling, security, caching, and logging to your APIs. For example, using Mule Gateway you can: - Apply a basic authentication policy on top of a Mule application. - Enrich an incoming or outgoing message. - Add any other complex capability to an API without having to write any code. ![A diagram illustrating the architecture of an API gateway, positioned between API clients and a backend API](/mulesoft/current/en-us/mule-gateway/_images/apigateway.png) If you want to apply policies and generate analytics info, you must use either: - An API defined in a Mule application. - A Mule application that proxies your existing backend implementation. ## Key Concepts ### API An API is an abstraction of a set of components. It encapsulates the complexity of your Mule application development, and it presents an easy and reusable way of accessing your assets. Pairing your API to API Manager through an Autodiscovery element enables you to apply policies to that API. Learn more [About API Autodiscovery](https://docs.mulesoft.com/mule-gateway/mule-gateway-autodiscovery-overview). #### HTTP/HTTPS API An API that you create using an HTTP Exchange asset. Mule Gateway assumes that the associated Mule application being tracked by API Manager has an HTTP or HTTPS listener defined as an implementation endpoint. **Typical usage**: REST based APIs. See [Creating an API Asset](https://docs.mulesoft.com/exchange/to-create-an-asset#creating-an-api-asset). #### RAML API An API that you create using a RAML/OAS Exchange asset. Your Mule Gateway assumes that the associated Mule application being tracked by API Manager has an HTTP or HTTPS listener with a RAML/OAS router defined as an implementation endpoint. To make this asset available in Exchange, you can design your API using API Designer and then export it to Exchange. **Typical usage**: RAML/OAS based APIs. See [Create and Publish an API Specification with the Code Editor in Design Center](https://docs.mulesoft.com/design-center/design-create-publish-api-raml-editor). #### WSDL API An API that you create using a WSDL Exchange asset. Your Mule Gateway assumes that the associated Mule application being tracked by API Manager has an HTTP or HTTPS listener with a WSDL router defined as an implementation endpoint. **Typical usage**: WSDL based APIs. ### API Autodiscovery API Autodiscovery enables API Manager to manage an API that represents an HTTP endpoint of a Mule application. Essentially, it’s the mechanism that links an HTTP resource to its API definition in API Manager. Through API Autodiscovery, Mule Gateway syncs the configuration defined in the corresponding paired API from API Manager. Mule runtime requires Anypoint Platform organization credentials to use Autodiscovery. See the [API Autodiscovery](https://docs.mulesoft.com/mule-gateway/mule-gateway-autodiscovery-overview) article for more information. ### API Proxy API proxies, also known as "autogenerated proxies", enhance the usability of API Manager in your Mule application. **Typical usage**: Either when you want to leverage Mule Gateway capabilities and your backend API is not based on Mule Runtime, or when your API is based on Mule runtime but you are unable to define the corresponding Autodiscovery element because it is a closed code. ![A technical diagram illustrating the role of an API manager in connecting clients to backend APIs](/mulesoft/current/en-us/mule-gateway/_images/api-gateway-capabilities-mule4-62bf9.png) When you configure your API to be a Proxy Endpoint, Anypoint Platform enables you to download a preconfigured Mule application. If the application is deployed to Mule runtime and you use the correct Anypoint Platform credentials, API Manager automatically tracks the API. You can deploy the application to a correctly configured Mule runtime, without knowing the details of how to create a Mule application. > [!NOTE] Anypoint Platform can deploy the proxy directly to Cloudhub or using the Mule agent, > through Runtime Manager. If you would like to use HTTPS instead of HTTP, you can follow these steps: 1. Import the autogenerated proxy into Anypoint Studio. 2. Specify the certificates to be used. 3. Deploy the application to Cloudhub or a runtime instance. The proxies that can be downloaded from API Platform are a convenient tool to speed up your Application Network development. However, you’re not restricted to using these autogenerated proxies. You can use any Mule application, with correctly configured Autodiscovery, to leverage Mule Gateway capabilities. ### Policies Policies are the tool to apply orthogonal behavior to a whole API or to a resource of it. You can create policies to enrich, filter, and control Incoming/Outgoing messages, and to apply a security layer on top of your API by, for example, enforcing token access to your API or whitelisting/blacklisting specific IP addresses. Mule Gateway provides not only Out-Of-The-Box (OOTB) policies but an engine to create your own Custom Policies. ### Analytics When the Mule Gateway is connected to API Manager, you can monitor the usage of your registered API using **API Analytics**. Mule Gateway reports API usage, including the detected policy violations. #### Pointcut Mule Gateway uses pointcuts to point a policy to the resource where it should be applied. If you are enforcing a policy in API Manager, this policy uses pointcuts to determine the endpoints of your Mule application to which it should apply. Just as the API autodiscovery element must be declared in your Mule application code, pointcuts are declared within the policies. In Mule 4, pointcuts are invisible to the user and are only managed internally by the Mule Gateway and API Manager. You can select the granularity of the pointcut when configuring most policies. You can find this configuration under the **Method & Resource conditions** of your policies. The two available options are: - **Apply configurations to all API methods & resources**. ![A form with options to apply configurations to API methods and resources](/mulesoft/current/en-us/mule-gateway/_images/api-gateway-capabilities-mule4-40081.png) When selected, the API Pointcut matches every resource and method of your API. This means that the policy being applied will be executed for every request the HTTP Listener (linked with the API via Autodiscovery) receives. - **Apply configurations to specific methods & resources**. ![A form that allows users to apply configurations to API methods and resources](/mulesoft/current/en-us/mule-gateway/_images/api-gateway-capabilities-mule4-2ed4e.png) This defines a resource-level pointcut for your API. In this example, the policy is applied to the API only when the request method is a GET. You can optionally define a matching regex for the resource for further granularity. ## Enabling Mule Gateway capabilities To take advantage of Mule Gateway capabilities, establish a communication channel between Mule runtime and an organization created in a control plane (US or EU) or Mule Private Cloud Edition. To configure Mule runtime in such a way, you must specify your Anypoint organization credentials. Depending on your implementation, there are several ways to pass organization credentials to the runtime. See [Configuring Organization Credentials in Mule Runtime 4](https://docs.mulesoft.com/mule-gateway/mule-gateway-org-credentials-mule4) to learn how to do this. ## Mule Gateway on Hyperforce All features of Mule Gateway are supported on Hyperforce. However, some API Manager Hyperforce limitations affect Mule Gateway. To learn more, see [API Manager on Hyperforce](https://docs.mulesoft.com/api-manager/latest/latest-overview-concept#APIM-hyperforce). ### Mule Gateway Proxies on Hyperforce All Mule Gateway proxies are supported on Hyperforce. See this table to find the first proxy versions that are supported on Hyperforce:
ProxyVersion

HTTP and HTTPS proxy

2.1.0

REST Proxy

2.2.1 and 3.2.1

WSDL Proxy

2.2.1 and 3.1.1

### Mule Gateway Policies on Hyperforce All Mule Gateway policies are supported on Hyperforce. See this table to find the first policy definition and implementation versions that are supported on Hyperforce:
PolicyDefinitionImplementation

Basic Authentication: LDAP

1.4.0

1.4.1

Basic Authentication: Simple

1.3.1

1.4.1

Client ID Enforcement

1.3.2

1.4.0

Cross-Origin Resource Sharing (CORS)

1.3.1

1.4.1

Header Injection

1.3.1

1.4.0

Header Removal

1.1.1

1.2.0

HTTP Caching

1.1.0

1.1.0

IP Allowlist

1.1.1

1.2.0

IP Blocklist

1.1.1

1.2.0

JSON Threat Protection

1.2.0

1.2.3

JWT Validation

1.4.0

1.4.1

Message Logging

2.0.1

2.1.1

OAuth 2.0 Access Token Enforcement Using Mule OAuth Provider

1.6.0

1.6.1

OpenAM OAuth 2.0 Token Enforcement

1.6.0

1.6.1

OpenID Connect OAuth 2.0 Access Token Enforcement

1.6.0

1.6.1

PingFederate OAuth 2.0 Token Enforcement

1.6.0

1.6.1

Rate Limiting

1.4.0

1.4.0

Rate Limiting: SLA-based

1.3.0

1.3.0

Spike Control

1.2.1

1.3.1

XML Threat Protection

1.2.0

1.2.0

## See Also - [Reviewing Mule Gateway API Autodiscovery concepts](https://docs.mulesoft.com/mule-gateway/mule-gateway-autodiscovery-overview) --- product: Mule Gateway keywords: policy, custom, ootb, offline --- # Mule Gateway Policies Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Policies enable you to enforce regulations to help manage security, control traffic, and improve adaptability of your APIs. For example, a policy can control authentication, access, allotted consumption, and service level access (SLA). You can implement these regulations with no modification to the code implementation. Policies differ based on several different factors, such as category, purpose, version, and configuration options. Carefully consider these factors before you implement them in your environment. Based on Mule runtime engine (Mule), a policy Exchange asset consists of: - A deployable JAR file that contains the policy business logic. - A YAML configuration file, in which the policy parameters and metadata are defined. ## Policy Architecture Policies are implemented through coordinated communication between the following components: - API Manager - One or more API gateway runtimes, or Mule runtime engine (Mule) - One or more API proxies or API applications Using API Manager, you can configure and apply policies to an API instance. An API version can have one or more API instances. A specific API instance can also be tied to a specific API implementation endpoint, which can then auto-generate an API proxy application. You can deploy an API proxy to a Mule runtime engine. Each API proxy application receives requests on HTTP or HTTPS URLs specified by the API. The flow referenced for autodiscovery must use an [HTTP Listener](https://docs.mulesoft.com/http-connector/1.10/http-listener-ref) component, not other connectors that use HTTP as an underlying transport. Normally requests are forwarded to the corresponding API implementation, and then the response travels through the API proxy application back to the requesting client application. ## Policy Injection and Enforcement When you deploy an API proxy application for a specific API version to Mule, any applied policies in the platform or offline policies in the runtime are injected into the API proxy. This changes the behavior of the application. When the proxy application receives a new request, all injected policies are applied to decide if, and how, the request is forwarded to the API implementation. In this way, the actual policy enforcement occurs inside the proxy application itself. This minimizes the cross talk between the API proxy, which is processing the received request, the Anypoint Platform agent, and online API Manager. The API proxy application does not require any communication with the Anypoint Platform agent running in the runtime, nor does it require any communication with API Manager. However, the Anypoint Platform agent remains connected to API Manager. After policies are reconfigured or removed from API Manager, those policies are downloaded to any connected API gateway or Mule runtime engines, which updates each runtime or policies folder. The policy changes are then again injected into each API proxy application. This allows policies to be dynamically changed without having to redeploy the API proxy application, and without having to restart the API gateway or Mule runtime engines. ## Policy Scope Policies are isolated from the application and other policies. However, there are ways to expose information from a policy. The authentication information about a policy can be propagated in the Security Context Principal object. Some policies, such as the Token Enforcement policy, allow propagation of headers, including the information related to the token. This token is used by the implementation service or by the API itself. ## Policy Size The size of a policy varies based on its dependencies. The first time, Mule polls for policies takes longer to fetch. However, after policies are retrieved, they are cached on the file system. This ensures offline availability and also reduces latency. ### Cached Policy Assets Deletion By default, Mule Gateway never deletes the JAR and YAML policy asset files, not even when the policy is unapplied in API Manager. > [!NOTE] Automatically deleting cached policy assets is only supported in Mule runtime versions > 4.4.x and 4.5.x released after Feb 1, 2024 and Mule runtime versions 4.6.0 and later. Automatically delete unused cached files when the runtime starts by adding the following entry to the `wrapper.conf` file: ```conf anypoint.platform.delete_unused_templates_on_start=true ``` ## Policies and SLAs You can configure the Rate Limiting policy to adhere to a predefined SLA. A service level access (SLA) tier is a category of user access that you define for an API. The tier definition combined with an SLA-based policy determines whether the access to the API is granted. For example, you create tiers of access depending on one of the following SLA tiers applied to the application: - A tier that limits requests to three per minute. No approval required. - A tier that limits requests to five per minute. Requires API Version owner approval of the application that needs to access the API. With SLAs, you limit access to only one API resource. Access to other resources is unlimited. When an application attempts to consume the protected resource, the policy is enforced. The request must include the expected user name and password. Repeated calls within SLA limits from the application to the API succeed. ## See Also - [Policy Categories](https://docs.mulesoft.com/mule-gateway/policies-policy-categories) - [Policy Types](https://docs.mulesoft.com/mule-gateway/policies-policy-types) --- product: Mule Gateway keywords: oauth, raml, token, validation, policy --- # OAuth 2.0 Access Token Enforcement Using Mule OAuth Provider Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

OAuth 2.0 Access Token Enforcement Using Mule OAuth Provider Policy

Summary

Allows access only to authorized client applications

Category

Security

First Mule version available

v4.1.1

Returned Status Codes

400 - Invalid token

401 - Unauthorized access or error when connecting to the authorization server

403 - Forbidden, invalid client application credentials

500 - Bad response from authorization server, or WSDL SOAP fault error.

## Summary The OAuth 2.0 Access Token Enforcement policy, which works exclusively with the Mule OAuth provider, restricts access to a protected resource to only those HTTP requests that provide a valid OAuth 2 token belonging to a client application with API access. The policy does not generate tokens but only validates them. This policy is designed to be used exclusively with [Mule OAuth provider](https://docs.mulesoft.com/api-manager/latest/mule-oauth-provider-landing-page). Using the policy with any other OAuth 2.0 provider (for example, Facebook, Google, or Microsoft Azure) is not supported. ## Configuring Policy Parameters ### Mule Gateway When you apply the policy to your API from the UI, these parameters are displayed:
ElementDescriptionExample

Scopes

Displays a space-separated list of supported scopes.

READ, WRITE, READ and WRITE

Scope Validation Criteria

Determines if the token must contain all defined scopes or just one. The values are Contains all scopes and Contains any scope.

If the ‘Contains all scopes’ value is selected, the tokens with the scopes READ and WRITE are accepted. If the ‘Contains any scopes’ value is selected, the tokens with the scopes READ, WRITE, and READ AND WRITE are accepted.

Access Token validation endpoint url

The URL of the Access Token validation endpoint of the external OAuth 2 provider.

The link to a Mule provider hosted by the client: http://client-hostetd-mule-provider-url.cloudhub.io/validate.

Validate TLS Certificate

Enables third-party authentication server TLS validation.

If selected, the communication with the token validation endpoint uses the TLS protocol.

Expose Headers

In a proxy scenario, specifies whether headers must be exposed in the request to the backend. User properties returned by the federation server are prefixed with 'X-AGW-' and sent as headers to the backend.

See Leveraging Token Validation Endpoint Information for Mule Applications for more information about this element.

Skip Client Id Validation

Skips the client application’s API contract validation.

If selected, Step 4 of the diagram in the How This Policy Works section is skipped.

Authentication request timeout

Sets the maximum time, in milliseconds, to wait for a response when authenticating with the Access Token validation endpoint.

10000

## How This Policy Works The following diagram illustrates the OAuth 2.0 Token Enforcement using Mule OAuth Provider policy workflow: ![A flowchart illustrating the process of a user engaging with an API via an OAuth policy](/mulesoft/current/en-us/mule-gateway/_images/open-id-policy-workflow.png) As shown in the diagram: 1. The user first sends an HTTP request to the API protected by the policy. 2. The policy extracts the token from the request and sends it to the validation endpoint to verify the integrity of the token. 3. The token validation endpoint returns token metadata, including the client ID of the client application. 4. Using a local database updated with contracts previously obtained from Anypoint Platform, the policy verifies whether the client ID has access to the API. 5. If all the validations are successfully completed, the request is allowed to reach the backend. ### Leveraging Token Validation Endpoint Information for Mule Applications When a token validation endpoint successfully validates a token, certain information, such as configurable fields from Mule OAuth provider, are returned to the policy. The following example illustrates the token validation response from the authorization server: ```text --- { "uid":"john.doe", "mail":"john.doe@example.com" "token_type":"Bearer", "expires_in":3600, "alias" : ["Jhon", "Jhonny", "Mr Doe"], "address" : { "city": "london", "road": “abbey road" } ``` } --- The fields returned by the OAuth provider are processed by the policy, propagated throughout the Mule flow, and finally exposed to the backend if the application requesting the access uses an HTTP requester. ### Token Caching After the system validates a token, that token is cached (by default), until it expires, thereby improving the performance of the policy. In certain cases, such as in the case of revoked tokens, you might want to minimize or even disable caching. The validation endpoint sends multiple properties to the policy, including the expiration time of the token. If the expiration information is not available, tokens are not cached. To control the time taken to cache the tokens, before you attempt revalidating against the token validation endpoint, specify the following property when starting Mule runtime engine: `anypoint.platform.max_federation_expiration_time=` Alternatively, you can specify this parameter in the `wrapper.conf` file. Setting this property caches the token for the specified amount of time or until the tokens expire, whichever occurs first. If you have enabled this property and the validation endpoint does not send the expiration information, tokens are not cached. To control the number of tokens that can be cached simultaneously, specify the following property when starting Mule runtime engine: `anypoint.platform.oauth2_cache_max_size=` Alternatively, you can specify this parameter in the `wrapper.conf` file. ## Configuring the Expose Headers Option If you configured the `Expose Headers` option in the policy and if the application (for example, out-of-the-box proxies) uses the HTTP requester, the properties are redirected to the backend as headers. For each field, the original request to the protected resource is enriched with the HTTP headers using the format X-AGW- + =. For the example response from the previous section, the following headers are added: ```text --- X-AGW-uid=john.doe X-AGW-mail=john.doe@example.com X-AGW-token_type=Bearer --- ``` The propagated properties do not include the `scope` and `expires_in` objects and arrays. For further processing within the flow, the original unparsed response from the validation endpoint is made available. The information is stored in an authentication object. For example, if a `mail` field is returned to the policy, you can access the value of this field by using the following DataWeave 2.0 expression: `#[authentication.properties.userProperties.mail]` You can obtain the client ID of the OAuth2 token by using the following DataWeave 2.0 expression: `#[authentication.principal]` ## Communicating with the Token Validation Endpoint Using a Proxy You can enable the OAuth 2.0 Access Token Enforcement using Mule OAuth Provider policy to use the gateway proxy settings by specifying the following property when starting Mule runtime engine: `anypoint.platform.external_authentication_provider_enable_proxy_settings=` When you enable this property, the policy uses the Mule proxy settings if you have configured the following parameters: - `anypoint.platform.proxy_host=localhost` - `anypoint.platform.proxy_port=8080` ## FAQs **Can I generate OAuth 2.0 tokens with the policy?** No. The policy only validates the tokens. **Can I use other OAuth providers with the policy?** No. This policy is designed to work exclusively with the [Mule OAuth provider](https://docs.mulesoft.com/api-manager/latest/mule-oauth-provider-landing-page). Using the policy with any other OAuth provider (for example, Facebook, Google, or Azure) is not supported. **What should I do if the Mule OAuth provider validation endpoint is rejecting the requests sent by the policy?** If the validation endpoint is rejecting requests, verify whether the URL configured in the policy is reachable from the machine where the policy is running and that no authentication is required to successfully complete the request. If your use case requires the validation endpoint to be protected, you can switch to the [Open ID Connect policy](https://docs.mulesoft.com/mule-gateway/policies-included-openid-token-enforcement). **Where are the OAuth tokens cached?** OAuth 2.0 tokens are cached only in memory and are never written to disk. **Does the policy communicate with Anypoint Platform on a per-request basis?** No, the policy uses client applications previously retrieved by Mule runtime engine. This enables the policy to continue working even if the connection with the management plane is lost. If you want the client application information that is written on disk to be encrypted, [configure gateway encryption in your runtime](https://docs.mulesoft.com/mule-gateway/mule-gateway-encryption-mule4). **Can I configure the Rate-Limiting SLA policy after I configure the OAuth 2.0 Access Token Enforcement using Mule OAuth Provider policy?** Yes, you can. Apply the Rate-Limiting SLA policy after the OAuth 2.0 access token enforcement using Mule OAuth provider policy and provide a `Client ID Expression` value using the following DataWeave 2.0 expression: `#[authentication.principal]` Because the identity of the requester is already validated by the OAuth 2.0 Access Token Enforcement using Mule OAuth Provider policy, you can leave the `Client Secret Expression` field empty. **Where can I find the information associated with the token after it has been validated?** The information is available in the authentication object. For more information, see [Token Validation Endpoint Information for Mule Applications](#leveraging-TVE-information). ## See Also - [Mule OAuth 2.0 Provider](https://docs.mulesoft.com/api-manager/latest/mule-oauth-provider-landing-page) - [Mule 4.x HTTP Requester Connector](https://docs.mulesoft.com/http-connector/1.10/http-documentation) - [Client Management for Federated Users and OpenID Connect Introspection Endpoint](https://docs.mulesoft.com/access-management/managing-api-clients) --- product: Mule Gateway keywords: policy, custom, offline, example --- # Offline Custom Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To manage offline custom policies, see the following topics: - [Applying Offline Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-offline-apply) - [Removing Offline Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-offline-remove) --- product: Mule Gateway keywords: openam oauth 2.0 token enforcement, api gateway, flex gateway, gateway, policy --- # OpenAM OAuth 2.0 Token Enforcement Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

OpenAM OAuth 2.0 Token Enforcement

Summary

Allows access only to authorized client applications

Category

Security

First Mule version available

v3.8.0

Returned Status Codes

400 - Invalid token

401 - Unauthorized or Connection error when connecting to the authorization server

403 - Forbidden, invalid client application credentials

500 - Bad response from authorization server, or WSDL SOAP Fault error.

> [!IMPORTANT] This policy is only available in a Federated organization configured to use OpenAM as > Client Management solution. ## Summary The OpenAM OAuth 2.0 Token Enforcement Policy restricts access to a protected resource, by only allowing HTTP requests if the token provided in such request is a valid one and, optionally, the required OAuth scopes are fulfilled. The policy validates the token, by connecting to an OpenAM authorization server. The token is obtained specifying the credentials of an [authorized client application](https://docs.mulesoft.com/api-manager/latest/api-contracts-landing-page) when performing the [OAuth dance](https://docs.mulesoft.com/api-manager/latest/oauth-dance-about). Before applying this policy, make sure that you are familiar with its [prerequisites](https://docs.mulesoft.com/api-manager/latest/about-configure-api-for-oauth) When you apply the policy, you may optionally define a space separated list of [OAuth 2.0 scopes](https://datatracker.ietf.org/doc/html/rfc6749) to be enforced by it. OAuth 2.0 scopes are a way to further limit access to a resource protected by OAuth. You may define words like READ, WRITE, or some others that make sense in the context of your organization (such as CONTRACTOR, PUBLIC, EMPLOYEES\_ONLY, etc). ## Supported Grant Types OpenAM supports two types of OAuth clients: - A Confidential Client keeps its credentials confidential and includes the following grant types: - Client Credentials - Implicit - Resource Owner - A Public Client shares its credentials with other parties and includes the following grant types: - Authorization Code - Implicit - Resource Owner Each type of client supports three of the four OAuth grant types defined by the RFC. For this reason, when configuring the OpenAM client, you can select only three of the four grant types. The other grant type is unavailable because it belongs to the other client. You determine the public or confidential property of the OpenAM client depending on the grant types you select. ## Performance To improve performance, once a token is validated, by default, the token is cached by the system until it expires. Sometimes it is desirable to reduce or even disable the caching mechanism, for example to take into account revoked token scenarios. To control token cached time (ie token cache time before retrying validation against the OAuth Provider), you may specify the following property: anypoint.platform.max\_federation\_expiration\_time= ## Communicating to the OAuth provider through a proxy To enable the OpenAM OAuth 2.0 Token Enforcement Policy to use the Gateway proxy settings, specify the following property: anypoint.platform.external\_authentication\_provider\_enable\_proxy\_settings= Setting the previous property to true makes the policy use the runtime proxy settings if specified. For example: anypoint.platform.proxy\_host=localhost anypoint.platform.proxy\_port=8080 ## Leveraging OAuth provider information When a token is successfully validated by the OAuth provider, the provider sends back to the policy who requested the token validation, some extra information, including fields that are OpenAM side configurable. Token validation response example from the authorization server: ```text { "uid":"john.doe", "mail":"john.doe@example.com", "scope":["uid","mail","cn","givenName"], "grant_type":"password", "cn":"John Doe", "realm":"/", "token_type":"Bearer", "expires_in":3600, "givenName":"John", "access_token":"fa017a0e-1bd5-214c-b19d-03efe9f9847e" } ``` The fields returned by the OAuth provider are processed by the policy, and: - For each field, the original request to the protected resource is enriched with HTTP headers in the form: `X-AGW-` + key=value - As part of the policy configuration, you may choose to not Expose Headers. In that case, the request will **not** be enriched with `X-AGW` headers. - For further processing within the flow, the original unparsed response from the provider is made available for further processing. The information is stored in an `authentication` object. Supposing that a "mail" field is returned, its value can be accessed using the following DataWeave 2.0 expression: #\[authentication.properties.userProperties.mail\] > [!TIP] You can use the extra information to further tune your business logic. ## See Also - [Client Applications and Contracts](https://docs.mulesoft.com/api-manager/latest/api-contracts-landing-page) - [OAuth 2.0 Policy Prerequisites](https://docs.mulesoft.com/api-manager/latest/about-configure-api-for-oauth) - [OAuth 2.0 Dance and OAuth 2.0 Access Token Enforcement](https://docs.mulesoft.com/api-manager/latest/oauth-dance-about) - [Applying an OAuth 2.0 Token Validation Policy](https://docs.mulesoft.com/mule-gateway/policies-included-oauth-access-token-enforcement) - [Applying a Policy](https://docs.mulesoft.com/mule-gateway/policies-included-apply) - [OpenAM](https://www.openidentityplatform.org/openam) identity provider - [SAML 2.0](https://docs.mulesoft.com/access-management/external-identity#instructions-for-saml-configuration) - [Configuring Mule Gateway API Autodiscovery in a Mule 4 Application](https://docs.mulesoft.com/mule-gateway/mule-gateway-config-autodiscovery-mule4) --- product: Mule Gateway keywords: open, id, oauth 2.0, token, enforcement, api gateway, mule gateway, gateway, policy --- # OpenID Connect OAuth 2.0 Token Enforcement Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

OpenID Connect OAuth 2.0 Token Enforcement

Summary

Allows access only to authorized client applications

Category

Security

First Mule version available

v4.1.1

Returned Status Codes

400 - Invalid token

401 - Unauthorized access or error when connecting to the authorization server

403 - Forbidden, invalid client application credentials

500 - Bad response from authorization server; or WSDL SOAP Fault error (Mule only).

## Summary The OpenID Connect Access Token Enforcement policy restricts access to a protected resource to only those HTTP requests that provide a valid Oauth2 token belonging to a client application with API access. The policy does not generate tokens but only validates them. This policy is available only to an organization that is configured to use the OpenID Connect dynamic client registration as a [client-management solution](https://docs.mulesoft.com/access-management/configure-client-management-openid-task). ## Configuring Policy Parameters ### Mule Gateway When you apply the policy to your API from the UI, these parameters are displayed:
ElementDescriptionExample

Scopes

Displays a space-separated list of supported scopes.

READ, WRITE, READ and WRITE

Scope Validation Criteria

Determines if the token must contain all defined scopes or just one. The values are Contains all scopes and Contains any scope.

For Contains all scopes, the policy only accepts tokens with both the READ and WRITE scopes. For Contains any scopes, the policy accepts tokens with at least one scope. If no scopes are defined for the Scopes parameter, the policy doesn’t validate scopes regardless of what you select for Scope Validation Criteria.

Validate TLS Certificate (Mule only)

Enables third-party authentication server TLS validation.

If selected, the communication with the token validation endpoint uses the TLS protocol.

Expose Headers

In a proxy scenario, specifies whether headers must be exposed in the request to the backend. User properties returned by the federation server are prefixed with 'X-AGW-' and sent as headers to the backend.

See Leveraging Token Validation Endpoint Information for Mule Applications for more information about this element.

Skip Client Id Validation

Skips the client application’s API contract validation.

If selected, Step 4 of the diagram in the How This Policy Works section is skipped.

Authentication request timeout

Sets the maximum time, in milliseconds, to wait for a response when authenticating with the Access Token validation endpoint.

10000

## How This Policy Works The following diagram illustrates the OpenID Connect Access Token Enforcement policy workflow: ![A flowchart illustrating the process of a user engaging with an API via an OpenID Connect policy](/mulesoft/current/en-us/mule-gateway/_images/open-id-policy-workflow.png) As shown in the diagram: 1. The user first sends an HTTP request to the API protected by the policy. 2. The policy extracts the token from the request and sends it to the validation endpoint to verify the integrity of the token. 3. The token validation endpoint returns token metadata, including the client ID of the client application. 4. Using a local database updated with contracts previously obtained from Anypoint Platform, the policy verifies whether the client ID has access to the API. 5. If all the validations are successfully completed, the request is allowed to reach the backend. ### Leveraging Token Validation Endpoint Information for Mule Applications When a token validation endpoint successfully validates a token, certain information, such as configurable fields from OpenID Connect, are returned to the policy. The following example illustrates the token validation response from the authorization server: ```text --- { "uid":"john.doe", "mail":"john.doe@example.com" "token_type":"Bearer", "exp": 1516239022 "alias" : ["Jhon", "Jhonny", "Mr Doe"], "address" : { "city": "london", "road": “abbey road" } } --- ``` The fields returned by the OAuth provider are processed by the policy, propagated throughout the Mule flow, and finally exposed to the backend if the application requesting the access uses an HTTP requester. ### Token Caching After the system validates a token, that token is cached (by default), until it expires, thereby improving the performance of the policy. In certain cases, such as in the case of revoked tokens, you might want to minimize or even disable caching. The validation endpoint sends multiple properties to the policy, including the expiration time of the token. If the expiration information is not available, tokens are not cached. To control the time taken to cache the tokens, before you attempt revalidating against the token validation endpoint, specify the following property when starting Mule runtime engine: `anypoint.platform.max_federation_expiration_time=` Alternatively, you can specify this parameter in the `wrapper.conf` file. Setting this property caches the token for the specified amount of time or until the tokens expire, whichever occurs first. If you have enabled this property and the validation endpoint does not send the expiration information, tokens are not cached. To control the number of tokens that can be cached simultaneously, specify the following property when starting Mule runtime engine: `anypoint.platform.openid_connect_cache_max_size=` Alternatively, you can specify this parameter in the `wrapper.conf` file. ### Token Validation Endpoint Authentication To complete validating the provided token, the policy sends a request to the validation endpoint. The policy then obtains the credentials from the client provider configuration in access management, per the Token Introspection Client section of the OAuth 2.0 Authorization Framework specification. These credentials are sent in the request body, as specified in the [Client Authentication section of the OAuth 2.0 Authorization Framework specification](https://datatracker.ietf.org/doc/html/rfc6749). Other authentication methods for the token validation endpoint are currently not supported. ## Configuring the Expose Headers Option If you configured the `Expose Headers` option in the policy and if the application (for example, out-of-the-box proxies) uses the HTTP requester, the properties are redirected to the backend as headers. For each field, the original request to the protected resource is enriched with the HTTP headers using the format: X-AGW- + =. For the example response from the previous section, the following headers are added: ```text --- X-AGW-uid=john.doe X-AGW-mail=john.doe@example.com X-AGW-token_type=Bearer --- ``` The propagated properties do not include the `scope`, and `exp` objects and arrays. For further processing within the flow, the original unparsed response from the validation endpoint is made available. The information is stored in an authentication object. For example, if a `mail` field is returned to the policy, you can access the value of the field by using the following DataWeave 2.0 expression: `#[authentication.properties.userProperties.mail]` You can obtain the client ID of the OAuth2 token by using the following DataWeave 2.0 expression: `#[authentication.principal]` ## Communicating with the Token Validation Endpoint Using a Proxy You can enable the OpenID Connect OAuth 2.0 Token Enforcement policy to use the gateway proxy settings by specify the following property when starting Mule runtime engine: `anypoint.platform.external_authentication_provider_enable_proxy_settings=` When you enable this property, the policy uses the Mule proxy settings, if you have specified the following parameters: - `anypoint.platform.proxy_host=localhost` - `anypoint.platform.proxy_port=8080` ## FAQs **The OpenID Connect Access Token Enforcement policy does not appear in the list of policies to apply to the API.** If the policy does not appear in the policies list, ensure that you have configured the OpenID client provider in Access Management. For information, see [Configure OpenID Connect Client Management](https://docs.mulesoft.com/access-management/configure-client-management-openid-task). If you are using [multiple client providers](https://docs.mulesoft.com/api-manager/latest/configure-multiple-credential-providers), verify that the OpenID connect client is properly configured in the API. **Can I generate OAuth 2.0 tokens with the policy?** No. The policy only validates the tokens. **What should I do if the Mule OAuth provider validation endpoint is rejecting the requests sent by the policy?** See the validation endpoint documentation provided by the OpenID connect server and verify whether the authentication method described in the [Token Validation Endpoint Authentication](#token-validation-endpoint-authentication) section is supported. **How does the policy manage the credentials to communicate with the validation endpoint?** This information is part of the policy configuration and is stored on a disk. If you want this information to be stored with encryption, [configure gateway encryption in your runtime](https://docs.mulesoft.com/mule-gateway/mule-gateway-encryption-mule4). **How are the OAuth tokens cached?** OAuth 2.0 tokens are cached only in memory and are never written to disk. **Does the policy communicate with Anypoint Platform on a per-request basis?** No, the policy uses client applications previously retrieved by the engine. This enables the policy to continue working even if the connection with the management plane is lost. If you want the client application information that is written on disk to be encrypted, [configure gateway encryption in your runtime](https://docs.mulesoft.com/mule-gateway/mule-gateway-encryption-mule4). **Can I configure the Rate-Limiting SLA policy after I configure the OpenID Connect Access Token Enforcement policy?** Yes, you can. Apply the Rate-Limiting SLA policy after the OpenID Connect Access Token Enforcement policy and provide a `Client ID Expression` value using the following DataWeave 2.0 expression: `#[authentication.principal]` Because the identity of the requester is already validated by the OpenID Connect Access Token Enforcement policy, you can leave the `Client Secret Expression` field empty. **Where can I find the information associated with the token after it has been validated?** The information is available in the authentication object. For more information, see [Token Validation Endpoint Information for Mule Applications](#leveraging-TVE-information). --- product: Mule Gateway --- # Packaging a Custom Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can use the Mule Maven Plugin to package your custom policy into a deployable JAR file that you can later apply to an API. 1. Make sure you added the Mule Maven Plugin to your pom.xml file. This is done automatically by custom policy’s Archetype ```console org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true ``` 2. From the command line in your project’s folder, run the package phase: ```console > mvn clean package ``` The packager then packages your application and creates the deployable JAR file into the target directory within your project’s folder. It will also verify that all the necessary files were provided for the packaging, and that the information provided in the mule-artifact and in the policy yaml are valid. ## See Also - [Getting started with custom policies development](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started) - [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange) - [Reviewing Custom Policy concepts](https://docs.mulesoft.com/mule-gateway/policies-custom-mule-4-reference) --- product: Mule Gateway keywords: pingfederate oauth 2.0 token enforcement, api gateway, mule gateway, gateway, policy --- # PingFederate OAuth 2.0 Token Enforcement Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

PingFederate OAuth 2.0 Token Enforcement

Summary

Allows access only to authorized client applications

Category

Security

First Mule version available

v4.1.1

Returned Status Codes

400 - Invalid token

401 - Unauthorized access or error when connecting to the authorization server

403 - Forbidden, invalid client application credentials

500 - Bad response from authorization server, or WSDL SOAP fault error.

## Summary The PingFederate OAuth 2.0 Token Enforcement policy restricts access to a protected resource to only those HTTP requests that provide a valid OAuth2 token belonging to a client application with API access. The policy does not generate tokens but only validates them. This policy is available only to an organization that is configured to use [PingFederate as a client-management solution](https://docs.mulesoft.com/access-management/conf-client-mgmt-pf-task). ## Configuring Policy Parameters ### Mule Gateway When you apply the policy to your API from the UI, a list of parameters is displayed:
ElementDescriptionExample

Scopes

Displays a space-separated list of supported scopes.

READ, WRITE, READ and WRITE

Scope Validation Criteria

Determines whether the token must contain all defined scopes or just one. The values are Contains all scopes and Contains any scope.

If the ‘Contains all scopes’ value is selected, the tokens with the scopes READ and WRITE are accepted. If the ‘Contains any scopes’ value is selected, the tokens with the scopes READ, WRITE, and READ AND WRITE are accepted.

Validate TLS Certificate

Enables third-party authentication server TLS validation.

If selected, the communication with the token validation endpoint uses the TLS protocol.

Expose Headers

In a proxy scenario, specifies whether headers must be exposed in the request to the backend. User properties returned by the federation server are prefixed with 'X-AGW-' and sent as headers to the backend.

See Leveraging Token Validation Endpoint Information for Mule Applications for more information about this element.

Skip Client Id Validation

Skips the client application’s API contract validation.

If selected, Step 4 of the diagram in the How This Policy Works section is skipped.

Authentication request timeout

Sets the maximum time, in milliseconds, to wait for a response when authenticating with the Access Token validation endpoint.

10000

## How This Policy Works The following diagram illustrates the PingFederate OAuth 2.0 Token Enforcement policy workflow: ![A flowchart illustrating the process of a user engaging with an API via a PingFederate policy](/mulesoft/current/en-us/mule-gateway/_images/open-id-policy-workflow.png) As shown in the diagram: 1. The user first sends an HTTP request to the API protected by the policy. 2. The policy extracts the token from the request and sends it to the validation endpoint to verify the integrity of the token. 3. The token validation endpoint returns token metadata, including the client ID of the client application. 4. Using a local database updated with contracts previously obtained from Anypoint Platform, the policy verifies whether the client ID has access to the API. 5. If all the validations are successfully completed, the request is allowed to reach the backend. ### Leveraging Token Validation Endpoint Information for Mule Applications When a token validation endpoint successfully validates a token, certain information, such as configurable fields from PingFederate, are returned to the policy. The following example illustrates the token validation response from the authorization server: ```text --- { "uid":"john.doe", "mail":"john.doe@example.com" "token_type":"Bearer", "expires_in":3600 "alias" : ["Jhon", "Jhonny", "Mr Doe"], "address" : { "city": "london", "road": “abbey road" } } --- ``` The fields returned by the OAuth provider are processed by the policy, propagated throughout the Mule flow, and finally exposed to the backend if the application requesting the access uses an HTTP requester. ### Token Caching After the system validates a token, that token is cached (by default), until it expires, thereby improving the performance of the policy. In certain cases, such as in the case of revoked tokens, you might want to minimize or even disable caching. The validation endpoint sends multiple properties to the policy, including the expiration time of the token. If the expiration information is not available, tokens are not cached. To control the time taken to cache the tokens, before you attempt revalidating against the token validation endpoint, specify the following property when starting Mule runtime engine: `anypoint.platform.max_federation_expiration_time=` Alternatively, you can specify this parameter in the `wrapper.conf` file. Setting this property caches the token for the specified amount of time or until the tokens expire, whichever occurs first. If you have enabled this property and the validation endpoint does not send the expiration information, tokens are not cached. To control the number of tokens that can be cached simultaneously, specify the following property when starting Mule runtime engine: `anypoint.platform.ping_federate_cache_max_size=` Alternatively, you can specify this parameter in the `wrapper.conf` file. ## Configuring the Expose Headers Option If you configured the `Expose Headers` option in the policy and if the application (for example, out-of-the-box proxies) uses the HTTP requester, the properties are redirected to the backend as headers. For each field, the original request to the protected resource is enriched with the HTTP headers using the format `X-AGW- + =`. For the example response from the previous section, the following headers are added: ```text --- X-AGW-uid=john.doe X-AGW-mail=john.doe@example.com X-AGW-token_type=Bearer --- ``` The propagated properties do not include the `scope`, and `expires_in` objects and arrays. For further processing within the flow, the original unparsed response from the validation endpoint is made available. The information is stored in an authentication object. For example, if a `mail` field is returned to the policy, you can access the value of the field by using the following DataWeave 2.0 expression: `#[authentication.properties.userProperties.mail]` You can obtain the client ID of the OAuth2 token by using the following DataWeave 2.0 expression: `#[authentication.principal]` ## Communicating with the Token Validation Endpoint Using a Proxy You can enable the PingFederate OAuth 2.0 Token Enforcement policy to use the gateway proxy settings by specifying the following property when starting Mule runtime engine: `anypoint.platform.external_authentication_provider_enable_proxy_settings=` When you enable this property, the policy uses the Mule proxy settings, if you have specified the following parameters: - `anypoint.platform.proxy_host=localhost` - `anypoint.platform.proxy_port=8080` ## FAQs **Why doesn’t the PingFederate OAuth 2.0 Token Enforcement policy appear in the list of policies to apply to the API?** If the policy does not appear in the policies list, ensure that you have configured the PingFederate client provider in Access Management. For information, see [Configure PingFederate Client Management](https://docs.mulesoft.com/access-management/conf-client-mgmt-pf-task). If you are using [multiple IdPs](https://docs.mulesoft.com/api-manager/latest/configure-multiple-credential-providers), verify that the PingFederate client is properly configured in the API. **Can I generate OAuth2 tokens with the policy?** No. The policy only validates the tokens. **How does the policy manage the credentials to communicate with the validation endpoint?** This information is part of the policy configuration and is stored on a disk. If you want this information to be stored with encryption, [configure gateway encryption in your runtime](https://docs.mulesoft.com/mule-gateway/mule-gateway-encryption-mule4). **Where are the OAuth tokens cached?** OAuth2 tokens are cached only in memory and are never written to disk. **Does the policy communicate with Anypoint Platform on a per-request basis?** No, the policy uses client applications previously retrieved by Mule runtime engine. This enables the policy to continue working even if the connection with the control plane is lost. If you want the client application information that is written on disk to be encrypted, [configure gateway encryption in your runtime](https://docs.mulesoft.com/mule-gateway/mule-gateway-encryption-mule4). **Can I configure the Rate-Limiting SLA policy after I configure the PingFederate Access Token Enforcement policy?** Yes, you can. Apply the Rate-Limiting SLA policy after the PingFederate Access Token Enforcement policy and provide a `Client ID Expression` value using the following DataWeave 2.0 expression: `#[authentication.principal]` Because the identity of the requester is already validated by the PingFederate Access Token Enforcement policy, you can leave the `Client Secret Expression` field empty. **Where can I find the information associated with the token after it has been validated?** The information is available in the authentication object. For more information, see [Token Validation Endpoint Information for Mule Applications](#leveraging-TVE-information). ## See Also - [PingFederate](https://www.pingidentity.com/en/capability/single-sign-on.html) identity provider - [SAML 2.0](https://docs.mulesoft.com/access-management/external-identity#instructions-for-saml-configuration) --- product: Mule Gateway keywords: policy, custom, ootb, offline --- # Policy Categories > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Policies are categorized by the function they perform. For example, because you resolve issues with the help of logs, the Message Logging policy is categorized as a troubleshooting policy. The following table lists included policies by its category and the function it performs:
CategoryPolicyFunction

Security

Basic Authentication - LDAP

Authenticates the LDAP credentials.

Security

Basic Authentication - Simple

Authenticates a single user password.

Security

IP Blocklist

Blocks a range of IP addresses.

Security

IP Allowlist

Allows access from only a preapproved range of IP addresses.

Security

JSON Threat Protection

Protects against a malicious JSON structure in API requests.

Security

XML Threat Protection

Protects against malicious XML elements in API requests.

Security

JWT

Validates a JWT token.

Security

OAuth 2.0 Access Token Enforcement Using Mule OAuth Provider Policy

Enforces token access using the MuleSoft OAuth Provider policy.

Security

OpenAM Access Token Enforcement

Restricts access to a protected resource using an Open AM authentication server.

Security

PingFederate Access Token Enforcement

Restricts access to a protected resource using the PingFederate authentication server.

Security

Tokenization

Transforms sensitive data into nonsensitive equivalent tokens.

Security

Detokenization

Transforms a tokenized value back to the original data.

Compliance

Client ID Enforcement

Allows access to client applications with a valid client credentials.

Compliance

CORS

Enables calls executed in a web page to interact with resources from different domains.

Transformation

Header Injection

Adds headers to the request or response message of a policy.

Transformation

Header Removal

Removes headers from the request or response message of a policy.

Quality of Service

HTTP Caching

Stores HTTP responses from an API implementation.

Quality of Service

Rate Limiting

Enables imposing a limit on the number of requests that an API can accept within a specified time.

Quality of Service

Rate Limiting, SLA-Based

Enables imposing an API request limit based on SLA tiers.

Quality of Service

Spike Control

Controls API traffic.

Troubleshooting

Message Logging

Logs a custom message when an API is invoked.

## See Also - [Included Policies Directory](https://docs.mulesoft.com/mule-gateway/policies-included-directory) --- product: Mule Gateway keywords: policy, custom, ootb, offline --- # Policy Types > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can create included, custom, or automated policies, each with its own scope, management, and usability. You can uniformly apply a policy to all APIs, or you can apply _resource-level policies_ to select APIs based on specified criteria. ## Included Mule Gateway Policies MuleSoft provides several ready-to-use policies for areas such as authentication, security management, threat protection, and tokenization. Using the API Manager from Anypoint Platform, you can apply any of these policies to any of your API endpoints. After you apply a policy, its complete lifecycle is managed by API Manager. You can apply a default policy to a specific API. To automatically apply a policy to all APIs in your environment, you must configure it as an automated policy. ## Automated Policies You can apply any default or a custom policy to all the APIs in your environment, making that policy an _automated policy_. However, you require specific access, such as API Manager Environment Administrator, to create automated policies. ## Custom Policies Although MuleSoft provides you with several ready-to-use included policies, you might want to create a custom policy to meet your specific business needs. You can either customize an existing policy, or you can create an entirely new custom policy. These policies are categorized as either online or offline. ### Online Custom Policies Online Custom policies are applied and managed by API Manager, which is the default and recommended way to apply policies. Online policies enable you to manage the policy lifecycle by leveraging Anypoint Platform. This way, the applied policies are always in sync with API Manager, and are protected by the gatekeeper mechanism at startup. ### Offline Custom Policies Offline custom policies are applied directly to the runtime and managed manually. Because they can easily become out of sync with API Manager, using this type of policy is not recommended. Offline custom policies are not protected by the Gatekeeper mechanism at startup. Additionally, client credentials validation is also not supported in offline policies. ## See Also - [Included Policies](https://docs.mulesoft.com/mule-gateway/policies-included-overview) - [Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-overview) - [Automated Policies](https://docs.mulesoft.com/mule-gateway/policies-automated-overview) - [Resource-Level Policies](https://docs.mulesoft.com/mule-gateway/policies-resource-level-overview) --- product: Mule Gateway --- # Ports, IPs, and Hostnames to Allow > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You might need to add the Anypoint Platform hostnames and ports to an allowlist in your network so that the Mule Gateway capabilities of the runtime can communicate with the online Anypoint Platform APIs and services that are managed by MuleSoft. The following table shows you the ports or IPs/hostnames to add to your allowlists to allow communication between the Runtime Manager Agent and the Runtime Manager console:
PlaneHostPort

US

anypoint.mulesoft.com

443

US

runtime-manager.anypoint.mulesoft.com

443

US

analytics-ingest.anypoint.mulesoft.com

443

US

data-authenticator.anypoint.mulesoft.com

443

US

exchange-files.anypoint.mulesoft.com

443

US

exchange2-asset-manager-kprod.s3.amazonaws.com

443

US-GOV

runtime-manager.gov.anypoint.mulesoft.com

443

US-GOV

data-authenticator.gov.anypoint.mulesoft.com

443

US-GOV

gov.anypoint.mulesoft.com

443

US-GOV

exchange-files.gov.anypoint.mulesoft.com

443

US-GOV

exchange2-asset-manager-kgprod.s3.us-gov-west-1.amazonaws.com

443

EU

eu1.anypoint.mulesoft.com

443

EU

runtime-manager.eu1.anypoint.mulesoft.com

443

EU

analytics-ingest.eu1.anypoint.mulesoft.com

443

EU

data-authenticator.eu1.anypoint.mulesoft.com

443

EU

exchange-files.eu1.anypoint.mulesoft.com

443

EU

exchange2-asset-manager-kprod-eu.s3.eu-central-1.amazonaws.com

443

## See Also - [Ports, IP Addresses, and Hostnames to Allow](https://docs.mulesoft.com/runtime-manager/rtm-agent-allowlists) --- product: Mule Gateway --- # Publish a Mule 4 Custom Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The following steps are the high-level workflow for publishing custom policies for Mule 4: 1. Create policy definition files. 2. Publish policy definition asset to Exchange. 3. Create implementation files. 4. Add policy implementation to the published policy definition. ## Before You Begin Before you can publish a custom policy for Mule 4, ensure you have administrator or contributor permission for the Anypoint Platform. ## Create Policy Definition Files A JSON and a YAML policy definition file must be created before you can upload the policy implementation. The required files are JSON and YAML. The JSON file specifies the interface for the policy using JSON schema language. The JSON file is used by API Manager to render the UI. The YAML file provides metadata regarding the policy for example, the policy category, interface scope, required characteristics, and RAML/OAS snippets. Copy the custom policy definition examples or create the files on your local system. ### Create the JSON Schema File The JSON schema file specifies the interface for the policy by identifying which properties are required or supported to configure the policy. The file also includes more annotations to refine the type for each property that enables some fields to perform a special behavior in the Anypoint platform. For example, Dataweave validations or secure handling of secrets. The JSON file must include the following fields: - Top-level @context References the vocabulary used for the extra type annotations. The aliases used to namespace the vocabulary are a optional. Commonly-used names can be `security` or `config`. Values for the security and config aliases are: - Security: `anypoint://vocabulary/policy.yaml#` - Config: `` anypoint://vocabulary/policyConfigurationsForUI.yaml#` `` - Top-level title - $schema with a link to the JSON Schema spec (see example) - Root type of `object` - Top-level description - Each property must also include: - Title The title is used by API Manager UI to render the field name. - Description The description is used by API Manager UI to describe the field. - Type Only primitive types are supported, for example `integer`, `string`, `object`, `boolean`, and `array`. Each property can include the following: - Format Options are `dataweaveExpression` and `` ipRange` ``. - Default Allows the user to enter a default value which is rendered in the UI. - @context with a @characteristics array Further refines the type with more annotations with the following options: - `config:commaSeparatedValues` The value of this field results in an array - `security:sensitive` Determines whether the property is masked when entering the property in the API Manager UI. The following code is a example of a basic authentication JSON schema: { "title": "Basic authentication - Simple", "type": "object", "description": "Enforces HTTP Basic authentication according to the details configured in the policy.", "properties": { "username": { "title": "User Name", "type": "string" }, "password": { "title": "User Password", "type": "string", "@context": { "@characteristics": \[ "security:sensitive" \] } } }, "required": \[ "username", "password" \], "unevaluatedProperties": false, "@context": { "@vocab": "anypoint://vocabulary/policy.yaml#", "security": "anypoint://vocabulary/policy.yaml#" }, "$id": "basic-authentication-simple", "$schema": "https://json-schema.org/draft/2019-09/schema" } ### Create the Definition Metadata YAML File The YAML file provides information about the policy and its requirements. The YAML file is not tied to any specific runtime or binary. The file must have these fields configured: - Header Header must be #%Policy Definition 0.1. - Name User-friendly name used for to display the policy name in API Manager UI. Must be a string value. - Description Must be a string value. - Category Category to which the policy belongs. Used to group and filter policies in API Manager UI. Any string value is valid. For example, `security`, `quality of service`, `compliance`, `troubleshooting`, and `transformation`. - Provided Characteristics A list used to define the characteristics the policy provides. Must be an array of strings. Use `providedCharacteristics: []` to leave empty. The following code is an example of a basic authentication definition YAML file: #%Policy Definition 0.1 name: Basic authentication - Simple description: Enforces HTTP Basic authentication according to the details configured in the policy. category: Security providedCharacteristics: - Requires authentication requiredCharacteristics: \[\] interfaceScope: \["api", "resource"\] interfaceTransformation: \[\] encryptionSupported: true violationCategory: authentication ## Publish Policy Definition Asset to Exchange After creating the required policy definition files (JSON and YAML), publish the policy definition asset to Exchange. See [Create a Custom Policy Definition Asset](https://docs.mulesoft.com/exchange/to-create-an-asset#create-custom-policy-definition-asset) for more information. ## Create Implementation Files The policy implementation files that are required to make the policy available in a runtime are a metadata file and a binary file. The metadata file describes what technology the binary file applies to and from which runtime version. The metadata file must be a YAML file. The binary file contains the policy logic and manages the runtime execution. The file can be a JAR file for Mule 4 runtime. ### Create the Implementation Metadata YAML File The metadata YAML file provides details about the specific implementation of the policy definition. A single policy definition can have several implementations. Each an independent asset in Exchange or different versions of the same Exchange asset. The metadata YAML file must include the following fields: - Header `#%Policy Implementation 1.0` - Technology `mule4` - Name Name of the implementation. - `minRuntimeVersion` A semantic version representing the first runtime version that the implementation binary is compatible with. For example, a mule binary might only be compatible from 4.3.0 onwards. - `supportedJavaVersions` The Java versions supported by the custom policy, either `"8"`, `"11"`, or `"17"`. You can list one or multiple versions. If `supportedJavaVersions` field is not provided, the policy supports only Java 8. The YAML file can also include `Release notes`. The following code is an example of a implementation metadata YAML file: #%Policy Implementation 1.0 minRuntimeVersion: 4.1.1 supportedJavaVersions: \["8", "11", "17"\] technology: mule4 name: Simple Auth Mule Implementation releaseNotes: "" ### Create the Implementation Binary Files The implementation binary file is a JAR file for Mule 4 policies. This file should support all of the configuration fields and function the way the definition metadata describes. ## Add Policy Implementation Files to Published Policy Definition After the custom policy definition asset is published to Exchange, the next step is to add the policy implementation files to the published policy. This step enables the policy to be available in runtime. The required implementation files are a JAR for Mule 4 runtime and a YAML metadata file. Before adding the implementation files, ensure that the policy asset is in the Stable state. ## Apply the Policy to an API from Anypoint API Manager After the implementation files are published, the policy is available to be applied to an API in API Manager. See the Anypoint API Manager documentation for information about applying the policy. --- product: Mule Gateway keywords: rate limiting, api gateway, mule gateway, gateway, policy --- # Rate Limiting Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy name

Rate Limiting

Summary

Monitors access to an API by defining the maximum number of requests processed within a period of time

Category

Quality of Service

First Mule version available

v4.1.0

Returned Status Codes

400 - Quota exceeded by WSDL APIs that use SOAP v1.2 (Mule only). Requests are blocked until the current window completes its processing.

429 - Quota exceeded, requests are blocked until the current window finishes

500 - Quota exceeded by WSDL APIs that use SOAP v1.1 (Mule only). Requests are blocked until the current window completes its processing.

## Summary The Rate Limiting policy enables you to control the incoming traffic to an API by limiting the number of requests that the API can receive within a given period of time. After the limit is reached, the policy rejects all requests, thereby avoiding any additional load on the backend API. When you configure the Rate Limiting policy, you can specify any number of pairs of quota (number of requests) and time window (time period) values. ## Configuring Policy Parameters ### Mule Gateway When you apply the Rate Limiting policy to your API from the UI, you can configure the following parameters:
ParameterDescriptionExample

Identifier

The selector key using a DataWeave or regular String

#[attributes.method] creates one group for each available method in HTTP, for example, the policy rate-limits GET requests independently from POST requests.

Number of Reqs

The quota available per window

A positive number

Time Period

The amount of time for which the quota is to be applied

A positive number

Time Unit

The time in milliseconds, seconds, minutes, or hours

Minutes

Distributed

When enabled, the quota is shared among all nodes running the API. For a Mule runtime engine target, the nodes share the quota only when the runtime runs in high-availability (HA) cluster mode. Otherwise, each node enforces the quota independently.

Checked or unchecked

Expose Headers

The option that defines whether to expose the x-ratelimit headers as part of the response

checked or unchecked

## How This Policy Works The Rate Limiting policy monitors the number of requests made in the current window (the available quota), allowing the requests to reach the backend only if the available quota is greater than zero. You can configure the policy for multiple groups of requests by using identifiers in the policy configuration. Each group has a separate available quota for its window. To understand how the Rate Limiting policy works, consider an example in which the configuration of 3 requests every 10 seconds allows or restricts incoming requests, based on the quota available in that window: ![A timeline of accepted and rejected requests in two time windows](/mulesoft/current/en-us/mule-gateway/_images/rate-limiting-generic-example.png) In the first window, because the quota is reached with the third request, all subsequent requests are rejected until the window closes. In the second window, only two of the three requests are processed and the quota remaining is dropped after the window time has elapsed. An accepted request passes through the API to the backend. Conversely, a rejected request displays 429 status for HTTP (or either 400 or 500 if the API is WSDL) and does not reach the backend. A rejected request on the other hand, displays a “429 status for HTTP, ” (or either 400 or 500 if the API is WSDL) and does not reach the backend. ## Examples Consider the previously described configuration of 3 requests every 10 seconds and how it works when the Rate Limiting policy is configured for clusters and uses identifiers. ### Configuring Identifiers by Using Regular Strings When you use the UI to add identifiers to the policy configuration, you can define groups of requests. The configured limits apply independently to each group. You can also use the identifier `#[attributes.method]` for one bucket per HTTP method in your Rate Limiting policy configuration. An `Identifier` in the UI is a non-obligatory parameter. By default, the `Identifier` has no value. Based on whether you accept the default or provide a value, the policy performs in the following ways: - Not configured (default) The Rate Limiting quota applies to every request per bucket or group. - Configured for an obligatory HTTP header Each header has its own quota. Header values are case-sensitive. Quotas are created using the _lazy creation_ strategy. - Configured for a non-obligatory HTTP header Custom header, payload, query parameter, or expression values each have their own quotas. The identifier, if not sent in the request, defaults to an empty value, having its own quota. This behavior allows the Rate Limiting policy to be applied to an API consumed by uncontrolled clients, and at the same time accommodates special buckets for the clients sending the identifier. The following example shows the order of events that occur over a period of time using the identifier `#[attributes.method]` for a limit of 3 requests every 10 seconds: ![A line chart illustrating the acceptance and rejection of GET and POST requests over time](/mulesoft/current/en-us/mule-gateway/_images/rate-limiting-configure-identifiers-example.png) In the example: - Every HTTP method is allowed 3 requests every 10 seconds (in this example, only GET and POST requests are made to the API). - The Rate Limiting policy works in a fixed-window fashion. For more information, see the fixed-window size bracket in the diagram. - The window start times are independent. - The engine uses a _lazy creation_ strategy that spools a rate-limiting algorithm whenever the first request for a method is received. ### Configuring Identifiers by Using DataWeave Expressions The rate-limiting engine, which is HTTP agnostic, depends solely on the resolution of the DataWeave expression. You can alter the `Identifier` expression in the UI to cover complex rate-limiting scenarios. For example, you can configure a Rate Limiting policy with an identifier that uses one bucket for all Class A and Class C LAN requests and another bucket for everything else. The following image illustrates the second bucket in the previous sentence, which corresponds to 3 requests per 10 seconds quota with the DataWeave expression `#[attributes.queryParam[‘customIdentifier’]]` as the policy identifier: ![A timeline that displays both accepted and rejected requests, organized by time intervals](/mulesoft/current/en-us/mule-gateway/_images/rate-limiting-configure-identifiers-dataweave.png) In the example: - All requests without the identifier are resolved to the empty identifier and therefore use a single rate-limiting algorithm. - Each different identifier uses a different bucket, each bucket with its own independent quota. This configuration creates a false or a true bucket that corresponds to the locality of the IP that made the request. The `false` and `true` values correspond to the domain of boolean values and not HTTP. Nevertheless, the policy works correctly because the engine treats the resolved expression as a String. In this case, the value is automatically cast from Boolean to String. You can explicitly define casting in DataWeave by adding `output text/plain ---` to your script. > [!NOTE] The HTTP RFC header names are case-insensitive. Anypoint Connector for MuleSoft HTTP > changes header names to lowercase characters. However, the DataWeave key is case-sensitive. > Therefore, when creating the `Identifier` expression, remember to reference headers in lowercase. ### Configuring Unbound Identifier Sets Every identifier result has one algorithm. You must carefully create a DataWeave expression that does not return an unbound or a very large co-domain, which requires hosting the same number of algorithms in memory (at least a request for every possible identifier has to be made, because algorithms are created using the _lazy creation_ strategy). For example, suppose the DataWeave expression uses the IP address as the identifier in a Mule runtime engine instance that is public to the internet. If every public IPv4 IP on the internet makes a request to this Mule instance, there will be 3,706,452,992 algorithms running in a single Mule instance. At an average of 250 bytes per algorithm, this amounts to approximately 1 terabyte in rate-limit algorithms. Therefore, use a DataWeave expression that resolves to a finite number of identifier to keep the resulting set as small as possible. ### Configuring the Policy for Clusters (Mule only) Consider the same configuration example of 3 requests and a window that starts exactly at 12:00:00, is reset every 10 seconds, and has a 2-node Mule cluster. Both nodes start and end their windows at the same time, and the cluster allows 3 requests per window in total: ![A timeline chart that tracks accepted and rejected requests for two nodes](/mulesoft/current/en-us/mule-gateway/_images/rate-limiting-configure-clusters.png) Because the policy is clusterized, the whole cluster accepts three requests. If the clusterizable policy is turned off, the Mule cluster can accept six requests per window: that is, three requests per node. To avoid distributed counters negatively impacting performance due to node synchronization needs, the policy uses caching mechanisms to predict the behavior and maximize throughput. However, some scenarios nevertheless result in higher latency, so be careful in your use of clusterizable configuration. > [!NOTE] The **Distributed** option shares the quota across nodes only when the Mule runtime engine > instance runs as part of a Mule high-availability (HA) cluster. If the runtime does not run in HA > cluster mode, enabling **Distributed** has no effect, and each node enforces the quota > independently. ## Configuring Your Rate Limiting Policy When you configure your Rate Limiting policy, you must consider certain aspects of your environment to help you derive the most value from the policy. ### Choosing Between a Cluster or a Standalone Configuration You might have decentralized processing in your environment, with the following setup: - You have more than one servers for the same API. - Each server has its own backend. - The number of requests that can be served is limited only by the backend. - You require the fastest response time. In such a scenario, you do not need to run the policy in a clustered setup. Simply set the policy limits of the policy lower than the backend capacity of the weakest of the nodes. Additionally, a load balancer might be useful in case a node goes down. Alternatively, you might have centralized processing in your environment, with the following setup: - You have more than one servers for the same API. - You have a single backend to which all of the proxies connect. - You have a load balancer in front of the proxies In such a scenario, you do not need a cluster. However, you must then configure the policy to have a value lower than the maximum capacity of the backend. If your environment does not include load balancers, use a cluster instead of a standalone instance to be certain that your nodes can manage varying levels of traffic. The Rate Limiting policy is designed to work under both balanced and unbalanced workloads. Because the backend does not receive any extra requests, its maximum capacity is not exceeded. ### Choosing Window Sizes for Cluster Nodes Configure your environment to use processing windows longer than one minute, to prevent the latency potential caused by information sharing among nodes in a cluster. This configuration recommendation applies to both Rate Limiting and Rate Limiting-SLA policies in a cluster scenario. ### Choosing Persistence for Your Rate Limiting Policy (Mule only) You can configure your Rate Limiting policy to use windows that persist as long as days, months, and years. For example, suppose you want to allow your user to consume 1 million requests per year, but you cannot ensure that the node will be up the entire period or will need maintenance, which may result in restarting Mule runtime engine. The algorithm has been running for several months, so the client will lose critical information. Persistence solves this problem by periodically saving the current policy state. In case of a redeployment or a restart, the algorithms are recreated from the last known persisted state or started from a clean state. Although persistence is enabled by default, you can turn it off by setting the following property to false: `throttling.persistence_enabled` You can also tweak the persistence frequency rate, which has a default of 10 seconds: `throttling.persistent_data_update_freq` > [!NOTE] Persistence is not available on CloudHub. Persistence provided by ObjectStore v2 on > CloudHub 2.0 is not supported. ## FAQ **When does the window start?** The window starts with the first request after the policy is successfully applied. **What type of window does the algorithm use?** It uses a fixed window. **What happens when the quota is exhausted?** The algorithm is created on demand, when the first request is received. This event fixes the time window. Each request consumes the request quota from the current window until the time expires. When the request quota is exhausted, the Rate Limiting policy rejects the request. When the time window closes, the request quota is reset and a new window of the same fixed size starts. **What happens if I define multiple limits?** The policy creates one algorithm for each Limit with the request quota per time window configuration. Therefore, when multiple limits are configured, every algorithm must have its own available quota within the current window for the request to be accepted. **What does each response header mean?** Each response header has information about the current state of the request: - X-Ratelimit-Remaining: The amount of available quota - X-Ratelimit-Limit: The maximum available requests per window - X-Ratelimit-Reset: The remaining time, in milliseconds, until a new window starts By default, the X-RateLimit headers are disabled in the response. You can enable these headers by selecting **Expose Headers** when you configure the policy. **When should I use Rate Limiting instead of Rate-Limiting SLA or Spike Control?** Use Rate Limiting and **Rate-Limiting SLA** policies for accountability and to enforce a hard limit to a group (using the identifier in Rate Limiting) or to a client application (using **Rate-Limiting SLA**). If you want to protect your backend, use the **Spike Control** policy instead. --- product: Mule Gateway keywords: rate-limiting sla, api gateway, flex gateway, gateway, policy --- # Rate Limiting: SLA-Based Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy name

Rate-limiting SLA

Summary

Monitors access to an API by defining the maximum number of requests processed within a timespan, based on SLAs

Category

Quality of Service

First Mule version available

v4.1.0

Returned Status Codes

400 - Invalid client credentials provided or quota exceeded by WSDL APIs that use SOAP v1.2 (Mule only)

401 - Request blocked due to invalid client credentials (client ID or client secret) provided

429 - Quota exceeded; requests blocked until the current window finishes

500 - Invalid client credentials provided or quota exceeded by WSDL APIs that use SOAP v1.1 (Mule only)

503 - Service Unavailable (Mule only)

## Summary The Rate-Limiting Service Level Agreement (SLA) policy enables you to control incoming traffic to an API by limiting the number of requests that the API can receive within a given timespan. When the limit is reached before the time expires, the policy rejects all requests, thereby avoiding any additional load on the backend API. To apply the Rate-Limiting SLA policy to an API, you must first create a contract between the API and a registered client application. The number of requests that an API can receive within a given time is defined in the [contracts](https://docs.mulesoft.com/api-manager/latest/manage-client-apps-latest-task) section in API Manager. Each request must be identified by a client ID and an optional client secret (depending on the policy configuration). To review how to obtain the client credentials of a registered client application, see [Obtaining Client Credentials of a Registered Application](https://docs.mulesoft.com/api-manager/latest/access-client-app-id-task). Additionally, you can configure the policy to run in a Mule runtime engine (Mule) cluster. In a clusterized policy configuration, the quota is shared among all nodes in the cluster. For more information about how these options work, see [Examples](#examples). ## Configuring Policy Parameters ### Mule Gateway When you apply the policy to your API from the UI, a list of parameters are displayed based on whether your environment includes Mule or non-Mule applications. ### Configuring Policy Parameters The following parameters are displayed:
ParameterDescriptionExample

Client ID Expression

A DataWeave expression that resolves the Client Application’s ID for a Contract of the API

Only one rate-limiting algorithm is created per ID: #[attributes.headers['client_id']] This example looks for an HTTP header called ‘client_id’ and uses its value.

Client Secret Expression

A DataWeave expression that resolves the Client application’s client secret for a contract of the API

This is an optional value. Example: #[attributes.headers['client_secret']]

Distributed

When enabled, the quota is shared among all nodes running the API. For a Mule runtime engine target, the nodes share the quota only when the runtime runs in high-availability (HA) cluster mode. Otherwise, each node enforces the quota independently.

Checked or unchecked

Expose Headers

Defines whether to expose the x-ratelimit headers, as part of the response

Checked or unchecked

> [!NOTE] The **Distributed** option shares the quota across nodes only when the Mule runtime engine > instance runs as part of a Mule high-availability (HA) cluster. If the runtime does not run in HA > cluster mode, enabling **Distributed** has no effect, and each node enforces the quota > independently. ## How This Policy Works The Rate-Limiting SLA policy monitors the number of requests made in the current window (the available quota), allowing the requests to reach the backend only if the available quota is greater than zero. Because each client defines a separate available quota for their window, the client application must define an SLA with the API (a contract). Therefore, to verify whether the request is within the SLA limit, you must define a way to obtain the client ID from the request, and optionally the client Secret. After a contract is created between a client application and an API, API gateway automatically manages these contracts by monitoring your API Manager configurations. Additionally, API gateway implements high-availability strategies in case of unexpected downtime in the Anypoint Platform management plane. To understand how the Rate-Limiting SLA policy works, consider an example in which the configuration of an SLA of 3 requests every 10 seconds for the client with ID “ID#1” allows or restricts the request, based on the quota available in that window: ![A timeline chart that displays both accepted and rejected client requests within a specified window](/mulesoft/current/en-us/mule-gateway/_images/rate-limiting-sla-general.png) In the example: - Requests of client with ID “ID#1”: In the first window, because the quota is reached with the third request, all subsequent requests are rejected until the window closes. In the second window, only two of the three requests are processed. Because the time elapses in this window, the remaining quota is unused. An accepted request passes through the API to the backend. Conversely, a rejected request displays a `429 status for HTTP` (or 400, or 500 if the API is WSDL) and does not reach the backend. - Requests of Client with ID “ID#2”: Because the client has no contract defined for the API, every request is rejected , and therefore no request is allowed. An API might have several contracts, each with its own SLA. The Rate-Limiting SLA policy independently monitors the quota (and windows) available for each client by creating one rate-limiting algorithm per contract. With the first request to the API, algorithms are created using the _lazy creation_ strategy. ## Examples Consider how the same contract of 3 requests every 10 seconds for client ID#1 works when the configuration is clusterized (Mule only). Consider an example of a window that is reset exactly at 12:00:00, is 10 seconds long, and operates in a 2-node Mule cluster. Both nodes start and end their windows at the same time, and the cluster allows 3 requests per window for client ID#1: ![Line chart showing accepted and rejected requests over time for two nodes](/mulesoft/current/en-us/mule-gateway/_images/rate-limiting-clusterizable.png) In the example: - Requests of client ID#1: Because the policy is clusterized, the whole cluster accepts three requests. If clusterization of the policy is disabled, the Mule cluster can accept six requests per window: three per node. - Requests of client ID#2: Because there is no contract defined for this client in this specific API, every request is rejected. Distributed counters impact performance due to the need for synchronization between the nodes. The policy uses caching mechanisms to predict the behavior and maximize throughput. However, in a worst case scenario, you can expect higher latency. Therefore, whether you use the clusterizable configuration must depend solely on your use case. ## Configuring the Policy When you configure your Rate-Limiting SLA policy, you must consider certain aspects of your environment to help you derive the most value from the policy. ### Choosing Between a Cluster or a Standalone Configuration If you use only one Client application as an authorization mechanism in your server, the same recommendations as in the Rate-Limiting policy applies to your use case. You might have several Mule instances and you might map different client applications to different servers in the load balancer. In such a scenario, you do not need to use a Mule cluster. Each standalone node creates a rate-limiting algorithm for the clients they exclusively serve. Conversely, you might want to achieve high availability for your servers and have several client applications configured. Mule clusters count the SLA quota for each client throughout the cluster and thus are a best fit for this use case. The Rate-Limiting SLA policy is designed to work under both balanced and unbalanced workloads. Because the backend does not receive any extra requests, its maximum capacity is not exceeded. ### Choosing Window Sizes for Cluster Nodes In a cluster configuration, the nodes must share information across the cluster for consistency. The sharing process adds latency that must be taken into account when reviewing performance. In a worst case scenario, the number of penalized requests with latency due to cluster consistency is constant and independent from the actual size of the configured quota. Consequently, the smaller the window, the greater the percentage of potentially delayed requests. Therefore, you must set up window sizes greater than one minute in Rate Limiting and Rate-Limiting SLA policy configurations only for a cluster scenario. ### Choosing Persistence for Your Rate-Limiting SLA Policy (Mule only) You can configure your Rate-Limiting SLA policy to use windows that persist as long as days, months, and years. For example, suppose you want to allow your user to consume 1 million requests per year, but you cannot ensure that the node will be up the entire period or will need maintenance, which may result in restarting Mule. The algorithm has been running for several months, so the client will lose critical information. Persistence solves this problem by periodically saving the current policy state. In case of a redeployment or a restart, the algorithms are recreated from the last known persisted state or started from a clean state. Although persistence is enabled by default, you can turn it off by setting the following property to false: `throttling.persistence_enabled` You can also tweak the persistence frequency rate, which has a default of 10 seconds: `throttling.persistent_data_update_freq` > [!NOTE] Persistence is not available on CloudHub. ## FAQ **When does the window start?** The window starts with the first request after the policy is successfully applied. **What type of window does the algorithm use?** It uses a fixed window. **What happens when the quota is exhausted?** The algorithm is created on demand, when the first request is received. This event fixes the time window. Each request consumes the request quota from the current window until the time expires. When the request quota is exhausted, the Rate-Limiting SLA policy rejects the request. When the time window closes, the request quota is reset and a new window of the same fixed size starts. **What happens if I define multiple limits within an SLA ?** The policy creates one algorithm for each Limit with the request quota per time window configuration. Therefore, when multiple limits are configured, every algorithm must have its own available quota within the current window for the request to be accepted. **What does each response header mean?** Each response header has information about the current state of the request: - X-Ratelimit-Remaining: The amount of available quota - X-Ratelimit-Limit: The maximum available requests per window - X-Ratelimit-Reset: The remaining time, in milliseconds, until a new window starts By default, the X-RateLimit headers are disabled in the response. You can enable these headers by selecting **Expose Headers** when you configure the policy. **Can I configure a Mule Cluster in CloudHub?** No, the feature is available only for Runtime Fabric, hybrid and standalone Mule setups. **When should I use Rate Limiting instead of Rate-Limiting SLA or Spike Control?** Use Rate Limiting and Rate-Limiting SLA policies for accountability and to enforce a hard limit to a group (using the identifier in Rate Limiting) or to a client application (using Rate Limiting-SLA). If you want to protect your backend, use the Spike Control policy instead. --- product: Mule Gateway --- # Removing Offline Custom Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To remove an offline policy, you need to delete the JSON file you created in the offline-policies directory. Deleting the automatically created folder in the policies directory does _not_ remove the offline policy. ## See Also - [Applying Offline Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-offline-apply) --- product: Mule Gateway --- # Reordering Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule Gateway, to execute certain policies before others, you can configure the order of execution of included and custom API level policies. However, you cannot configure API level policies to execute before automated policies. You reorder policies via API Manager. > [!IMPORTANT] You cannot configure the execution order of the > [Cross-Origin Resource Sharing (CORS) policy](https://docs.mulesoft.com/mule-gateway/policies-included-cors). In Mule Gateway, the CORS > policy executes before automated and API level policies. ## Reorder Policies To reorder policies in Mule Gateway: 1. Go to **Anypoint Platform > API Manager**. 2. In **API Administration** click the name of the API whose policies you want to reorder. 3. From the left navigation menu, click **Policies**. 4. From the top of the list of the applied policies, click **Reorder policies**. 5. From the **Reorder Applied Policies** section, use the up and down arrows to rearrange the order of policies. 6. Click **Apply order**. ## Apply Duplicate Policies Mule Gateway supports applying duplicate policies. Automated, API-level, and resource-level policies all support duplicate policy application. When applying duplicate policies: - Add a label to the duplicated policies to differentiate them. - Consider if it makes sense to apply duplicated policies. For example, the duplicated IP allowlist policies allow only IPs that are allowed by both policies. Rather than applying duplicated policies, configure the IPs in one policy. ## See Also - [Included Policies Directory](https://docs.mulesoft.com/mule-gateway/policies-included-directory) --- product: Mule Gateway keywords: policy, custom, ootb, offline, resource level --- # Resource-Level Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Unless otherwise configured, policies are by default applied to the entire API. However, you can implement an additional level of policy granularity, one in which access is controlled based on a criteria. Policies with this granularity are called _resource-level policies_. At the resource level of granularity, policies are applied to only those requests that match the criteria. All policies, except the Cross-Origin Resource Sharing (CORS) policy, are resource-level. In Mule 4, resource-level policies support HTTP-based APIs in addition to RAML APIs. You can apply multiple conditions to filter your resources and HTTP methods using the [URI template regex](https://docs.mulesoft.com/mule-gateway/policies-resource-level-config-uri-regex) to any number of methods in your API. ## Usage Scenarios for Implementing Resource-Level Policies You can use resource-level policies in many ways. Here are just a few: - Apply policies to specific resources. - Secure a subset of an API. - Set different limits on resources. If you have a RAML or OAS specification attached to your API, you can use the **Preview Resource Matching** option to determine which resources are affected by your filters: ![API requests related to user permissions and the corresponding HTTP methods allowed for each](/mulesoft/current/en-us/mule-gateway/_images/users-api-cropped.png) A resource-level policy supports Java regular expressions. For example, you can use a wildcard to apply a policy to multiple resources. When you apply the policy to the API, specify the resources to which it applies. ## Guidelines for Implementing Resource-Level Policies When implementing resource-level policies: - Do not use a placeholder, such as {userid}, in the regular expression. Using a placeholder in an expression fails because the placeholder does not match the actual node. In the example placeholder {userid}, the node looks something like this: `/api/users/671962fc-f076-4b19-bc38-45ba3a4e4095/permissions/1234` 671962fc-f076-4b19-bc38-45ba3a4e4095 is the user ID. 1234 is the ID of a permission. To apply a policy to resource `/api/users/{userid}` that represents a single user and all resource nodes, use the following expression: The `userid` represents a single user and all resource nodes: `/api/users/.*` To apply a policy to only the permissions resources `/api/users/{userId/permissions}` and `/api/users/{userid}/permissions/{permissionId}`, use the following expression: `/api/users/.**/permissions.**` ## See Also - [Configure URI Template Regex](https://docs.mulesoft.com/mule-gateway/policies-resource-level-config-uri-regex) - [Disable Outbound Policies](https://docs.mulesoft.com/mule-gateway/policies-resource-level-disable-outbound) --- product: Mule Gateway --- # Route Mule Gateway Traffic Through a Proxy Server > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure Mule Gateway to route traffic through the proxy server to API Manager if your Mule runtime engine runs inside a firewall that restricts external communication through a proxy server. Mule Gateway supports Basic, NTLM, and Kerberos v5 (via SPNEGO) authentication schemes for proxied communication. ## Configure the Proxy Server To configure Mule Gateway to connect through a proxy server, set up your proxy server configuration by adding the following properties in a `$MULE_HOME/conf/wrapper.conf` file: - `wrapper.java.additional.=-Danypoint.platform.proxy_host={hostname}` - `wrapper.java.additional.=-Danypoint.platform.proxy_port={port}` - `wrapper.java.additional.=-Danypoint.platform.proxy_username={username}` - `wrapper.java.additional.=-Danypoint.platform.proxy_password={password}` > [!IMPORTANT] The parameters are additional options passed to Java during launch. The `` element > refers to the number of additional parameters in the configuration. Start from `1` and increment > sequentially without skipping numbers. With the provided credentials, Mule Gateway prioritizes Basic Authentication over NTLM. If Basic Authentication fails, Mule Gateway attempts to authenticate with NTLM. ### Using Kerberos for Proxy Authentication To authenticate using Kerberos, add the parameters from [Configure the Proxy Server](#configure-the-proxy-server) and the following new properties: - `wrapper.java.additional.=-Danypoint.platform.proxy_kerberos_krb5_path={/path/to/krb5.conf}` - `wrapper.java.additional.=-Danypoint.platform.proxy_kerberos_jaas_path={/path/to/kerberos.jaas}` > [!NOTE] Kerberos authentication is only supported in Mule runtime versions 4.3.x and 4.4.x > released after July 2, 2024 and Mule runtime versions 4.6.5, 4.7.1 and later. #### Kerberos KRB5 Path The property `anypoint.platform.proxy_kerberos_krb5_path` specifies the path to the `krb5.conf` file used to locate the KRB5 server. An example of this file is: ```text [libdefaults] kdc_realm = service.ws.apache.org default_realm = service.ws.apache.org udp_preference_limit = 1 kdc_tcp_port = 64718 [realms] service.ws.apache.org = { kdc = localhost:64718 } ``` #### Kerberos JAAS Path The property `anypoint.platform.proxy_kerberos_jaas_path` specifies the path to the JAAS file for authentication. An example of this file is: ```text alice { com.sun.security.auth.module.Krb5LoginModule required refreshKrb5Config=true useKeyTab=false keyTab="/my/krbwd/alice.keytab" principal="alice"; }; com.sun.security.jgss.login { com.sun.security.auth.module.Krb5LoginModule required useKeyTab=true storeKey=true keyTab="/my/krbwd/alice.keytab" principal="alice"; }; com.sun.security.jgss.initiate { com.sun.security.auth.module.Krb5LoginModule required useKeyTab=true storeKey=true keyTab="/my/krbwd/alice.keytab" principal="alice"; }; com.sun.security.jgss.accept { com.sun.security.auth.module.Krb5LoginModule required useKeyTab=true storeKey=true keyTab="/my/krbwd/alice.keytab" principal="alice"; }; ``` IMPORTANT: Set `useKeyTab` to `false` for the principal being authenticated (in this example, `alice`), so that Mule Gateway uses the credentials specified for `anypoint.platform.proxy_username` and `anypoint.platform.proxy_password`. ## See Also - [Connect the Agent Through a Proxy Server](https://docs.mulesoft.com/runtime-manager/rtm-agent-proxy-config). --- product: Mule Gateway keywords: spike control, api gateway, mule gateway, gateway, policy --- # Spike Control Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

Spike Control

Summary

Regulates API traffic

Category

Quality of Service

First Mule version available

v4.1.0

Returned Status Codes

429 - The number of requests by HTTP APIs exceeded the configured limit. Request rejected after specified number of reattempts.

400 - The number of requests by WSDL APIs that use SOAP v1.2 exceeded the configured limit. Request rejected after specified number of reattempts (Mule only).

500 - The number of requests by WSDL APIs that use SOAP v1.1 exceeded the configured limit. Request rejected after specified number of reattempts (Mule only).

## Summary The Spike Control policy regulates your API request traffic by limiting the number of messages processed by an API. The policy ensures that the number of messages processed within a specified time does not exceed the limit that you configure. If the number is exceeded, the request is queued for retry based on you have configured the policy. ## Configuring Policy Parameters The Spike Control policy does not perform quota enforcement. The configuration parameters are restricted to protect the API and backend. Therefore, to ensure maximum performance, configure these parameters to the lowest possible value. ### Mule Gateway When you apply the policy to your API from the UI, the following parameters are displayed:
ElementDescriptionRequired

Number of Reqs

The number of requests allowed (in milliseconds) in the specified window

Yes

Time Period

The number of milliseconds, within which a request must be processed

Yes

Delay Time in Milliseconds

The amount of time for which each request is retained before retrying (in milliseconds) in case there is no quota remaining

Yes

Delay Attempts

The number of times a request is retried before it is rejected

Yes

Queuing Limit

The number of requests that can be queued at the any given time

No

Expose Headers

Enable it only for internal APIs, allows the policy to return information about the algorithm behavior in the X-RateLimit headers

No

Method & Resource conditions

The option to add configurations to only a select few or all methods and resources of the API

Yes

To enforce request quotas, see the [Rate-Limiting SLA policy](https://docs.mulesoft.com/mule-gateway/policies-included-rate-limiting-sla) and [Rate Limiting policy](https://docs.mulesoft.com/mule-gateway/policies-included-rate-limiting). ## How This Policy Works The Spike Control policy uses a _Sliding Window Algorithm_ which reduces spikes in traffic and protects the gateway instance. The window self-adjusts its display size to accommodate results over time. If the current window has no remaining request quota, without closing the connection to the client, the Spike Control policy allows requests to be queued for processing later. For your policy to queue the requests, you must configure the policy parameters, as shown in the following example: - `Time Period`: 1 second - `Number of Reqs`: 2 - `Delay Time in Milliseconds`: 499 milliseconds - `Delay Attempts`: 1 - `Queuing Limit`: 5 Queuing a request requires retaining a thread and an HTTP connection. When you specify a `Queuing Limit` for the policy, the parameter protects the gateway from running out of resources and ensures that the API does not fail in case of an attack. ## Request Timelines The following diagram illustrates the lifespan of each request accepted by the algorithm, using the configuration defined in the previous section: ![A timeline that shows accepted, rejected, and queued requests](/mulesoft/current/en-us/mule-gateway/_images/spike-control.png) 1. The first two requests are accepted and the available quota is now 0. The quota increases to 1 after one second (the `window size` value) passes from request #1. 2. Request #3 arrives. Because no quota is available, the request is queued for 499 milliseconds. 3. Request #4 arrives. Because there still is no quota available, the request is queued for 499 milliseconds. 4. Shortly before request #3 is retried, request #1 ages a second and its quota is released because it falls out of the window. 5. Quota is now 1, and request #3 is reprocessed successfully. Quota returns to 0 until request #2 ages 1 second. 6. Request #4 delay concludes and it must be reprocessed. Request #4 is rejected. Requests #2 and #3 have not aged a second yet and there is no quota available. Request #4 have no more delays. 7. Request #5 arrives. Because request #2 has already aged more than a second, the request is accepted. This example illustrates request delays and how queuing regulates spikes in traffic. In high-contention scenarios, the backend continues to function properly (it serves no more than X requests in the last Y milliseconds). Users querying the API might still see their requests being served, but with higher latency. The exact configuration for the policy depends exclusively on your API and its throughput. ## FAQ **When does the sliding window start?** The window starts with the first request after the policy is successfully applied. **What type of window does the algorithm use?** The algorithm uses a sliding window that monitors transactions for the amount of time that you configure in the policy. **What happens when the quota is exhausted?** When the request quota is exhausted, the Spike Control policy queues the request and retries as configured. The request is rejected if no quota is remaining after several retries. Quota for other requests is available only after the first request exceeds the time limit configured in the policy; in this way, requests are processed in cycles. **Can I configure multiple windows?** No. The Spike Control policy ensures that the backend server does not serve more requests than it can handle. If you need accountability, use either Rate-Limiting SLA or Rate Limit policies instead. **What does each response header mean?** Each response header has information about the current state of the request: - X-Ratelimit-Remaining: The amount of quota currently available - X-Ratelimit-Limit: The maximum available requests per window - X-Ratelimit-Reset: The remaining time, in milliseconds, until the oldest request ages enough to fall outside of the sliding window. If quota is still available, the header is set to 0 (zero) because the algorithm can still serve new requests. By default, the X-RateLimit headers are disabled in the response. You can enable these headers by selecting **Expose Headers** when you configure the policy. **Can I configure Spike Control in a Mule cluster?** No, the policy protects a gateway instance. If you have a Mule cluster in your architecture, use the Spike Control policy to protect each instance separately. **When should I use Rate Limiting instead of Rate Limiting SLA or Spike Control?** Use Rate Limiting and Rate-Limiting SLA policies for accountability and to enforce a hard limit to a group (using the identifier in Rate Limiting) or to a client application (using Rate Limiting-SLA). If you want to protect your backend, use the Spike Control policy instead. --- product: Mule Gateway keywords: tokenization, api gateway, mule gateway, gateway, policy --- # Tokenization Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy name

Tokenization

Summary

Transforms sensitive data into a nonsensitive equivalent, named token

Category

Security

First Mule version available

v4.1.1

Returned Status Codes

400

A token is invalid, or the tokenization failed.

The provided expression is invalid or returns no result to tokenize.

The status code to be returned can be configured.

502 - Connection to the tokenization service is unavailable or not configured.

## Summary Tokenization is the process of masking a value or piece of information that can be considered sensitive data into a token that can be mapped back to its original value using detokenization concepts. If your API contains sensitive data, the tokenization policy is a highly effective way to protect it. The data is displayed in the same format as the original value, but its actual value is not revealed initially. > [!NOTE] This policy is designed to work only for Anypoint Runtime Fabric deployments. Tokenization minimizes the risk of matching the sensitive data to the original value, in case a third party accesses the data. For example, you can use this policy to hide credit card numbers, personally identifiable information (PII), protected health information (PHI), and similar sensitive data. ## Prerequisites To apply and manage the Tokenization policy, you must have: - Obtained the **Manage Policies** permission. - To configure and run the tokenization service, you must have: - Installed Runtime Fabric - Obtained the **Manage Tokenization Services** permission - An operating tokenization service ## Scope and Considerations Before you apply this policy, review the following considerations: - One instance of the policy supports only one tokenization service. All the formats that you configured need to be contained in the same tokenization service. - You can use one instance of the policy to tokenize a value either in the request or in the response, but not in both. - The policy is not aware of the state of the tokenization service until runtime. If you deleted your tokenization service or if it is not operational, the policy cannot establish communication with it. This causes all the requests to fail until the service is available again. During policy configuration, the services menu displays only the tokenization services that are ready to use. If you do not see the service you want, verify if it is already deployed. ## Configuring Policy Parameters ### Mule Gateway When you apply the policy to your API from the UI, the following parameters are displayed:
ElementDescriptionRequired

Direction

Whether the values to tokenize are extracted from the request or the response (default).

Yes

Fail on unmatched expressions

If selected, requests fail when the expression and tokens do not match.

No

Services

The tokenization services available for the current organization and environment. Select the service that you need from the list. Note that the formats available depend on the service that you choose.

Yes

Expression

A selector expression that extracts the information to be tokenized.

For example:

#[payload.people.creditCardNumber]

Only expressions using dots as field separators are allowed. While #[payload.people.creditCardNumber] is valid, #[payload[‘people’]] is not.

No.
If you do not specify a selector expression, the policy is applied, but does not tokenize anything from the payload.

Format

Type of information to be tokenized. Formats vary depending on the selected service.

If you do not see any formats in the list, verify that the tokenization service that you selected contains at least one.

No
If you do not specify a format, the policy is applied but does not tokenize anything from the payload.

## How This Policy Works The Tokenization policy replaces sensitive parts of a message payload with tokenized values. To define which information is tokenized, you must provide a selector expression. ### Examples Suppose that the payload that receives the policy contains the following structure: ```JSON { "name":"Amun Ra", "socialSecurityNumber":"365-93-2738" } ``` If you want to tokenize the social security number, you can use the following selector expression: ```expression #[payload.socialSecurityNumber] ``` Now, every time the policy receives a request containing a `socialSecurityNumber` key in its top level, it will extract all the tokens that match the expression you indicated, it will establish a connection with the tokenization service, and finally it will replace the tokenized values in your payload with the ones provided by the service. If the tokenized value for the Social Security Number in the example were 167-47-9268, your application will receive the following payload: ```json { "name": "Amun Ra", "socialSecurityNumber": "167-47-9268" } ``` You can configure the Tokenization policy to tokenize values in your payload request or response. ### Tokenize Requests The following events occur when you tokenize requests: ![A diagram shows a data flow between security, tokenization, and a Mule application](/mulesoft/current/en-us/mule-gateway/_images/policy-mule4-tokenization-67b25.png) 1. A user performs a request to the application protected by the policy. 2. The request goes first to Anypoint Security and then to the application Tokenization policy. 3. The Tokenization policy extracts all tokens that match the selector expression. 4. The tokenization service receives the tokens, transforms them, and returns the result to the policy. 5. The policy replaces the payload with the tokenized values and forwards it to the Mule application. 6. The Mule application processes the request and returns the result. ### Tokenize Responses The following events occur when you tokenize responses: ![A diagram shows a data flow of a tokenization service](/mulesoft/current/en-us/mule-gateway/_images/policy-mule4-tokenization-9347d.png) 1. A user performs a request to the application protected by the policy. 2. The request goes first to Anypoint Security and then to the application Tokenization policy. 3. The tokenization policy tokenizes the Mule response and redirects the request without extracting anything from the payload. 4. The Mule application processes the request and returns the result. 5. The Tokenization policy extracts the tokens from the payload using the selector expression. 6. The tokenization service receives the tokens, transforms them, and returns the result to the policy. 7. The Tokenization policy sends the response back to the user with the tokenized values in the payload. --- product: Mule Gateway keywords: custom policy, upload, Exchange --- # Uploading a Custom Policy to Exchange > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Exchange provides an API to publish or consume assets using a Maven client. You must have a unique artifact name and organization ID to publish your asset. API Manager lists custom policies published as assets of your organization. For more information about the Exchange Maven Facade asset, see [Exchange Maven Facade](https://anypoint.mulesoft.com/exchange/portals/anypoint-platform/f1e97bc6-315a-4490-82a7-23abe036327a.anypoint-platform/exchange-maven-facade-api-http/). ## Prerequisites To upload a custom policy to Exchange, you must have the Exchange Contributors role. ## Deploying a Policy Created Using the Maven Archetype If you create your custom policy project using the provided Maven archetype, the plugins necessary to upload the policy to Exchange are already defined for you. See [Setting Up a Project with the Archetype](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started#setting-up-a-project-with-the-archetype). To deploy a policy created using the Maven archetype: 1. In your Maven `.m2` directory, update the `settings.xml` file with your Exchange credentials. ```xml exchange-server myusername mypassword ``` > [!NOTE] For information about how to authenticate using a token rather than using credentials, > see > [Publish and Consume Federated Assets](https://docs.mulesoft.com/exchange/to-publish-assets-maven#publish-and-consume-federated-assets). 2. Run `mvn clean deploy` to publish the policy to Exchange. The custom policy is now available for you to apply to APIs that belong to the specified organization. > [!NOTE] For Java 17 support, add `supportedJavaVersions: ["8", "11", "17"]` to the policy > definition YAML. See > [YAML Configuration File](https://docs.mulesoft.com/mule-gateway/policies-custom-mule-4-reference#yaml-configuration-file). ## Deploying a Policy Created Without Using the Maven Archetype If you did not create your custom policy project using the provided Maven archetype, you must manually define the Exchange deployment configuration. To deploy a policy created without using the Maven archetype: 1. In Anypoint Platform, find the organization ID to use as follows: 1. Go to **Access Management > Organization**. 2. Click the name of your organization. 3. Copy the UUID from the browser address. For example, copy _2a4b93c3-7899-4ea7-9374-f787744d8784_ from the URL. 2. Update your `pom.xml` file as follows: 1. Replace the `groupId` value with the organization ID from the preceding step: ```XML {orgId} ``` 2. Add the following properties and replace `{orgId}` with the organization ID from the preceding step: ```XML https://maven.anypoint.mulesoft.com/api/v3/organizations/{OrgId}/maven 3.2.0 ``` 3. Define Exchange as a repository: ```XML exchange-server MuleSoft Exchange Environment ${exchange.url} true ``` 4. Set up your Exchange server as a distribution management repository: ```XML exchange-server Corporate Repository ${exchange.url} default ``` 5. Add the following build plugins: - Mule Maven plugin: Verifies that all necessary files are present and that all requirements are met to correctly package the policy. - Maven Deploy plugin: Communicates with the Exchange repository and uploads the policy JAR and YAML files. ```XML org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true org.apache.maven.plugins maven-deploy-plugin upload-template deploy deploy-file exchange-server ${exchange.url} ${project.basedir}/${project.artifactId}.yaml false ${project.groupId} ${project.artifactId} ${project.version} yaml policy-definition ``` 6. Add the following plugin repository: ```XML mule-plugin Mule Repository https://repository.mulesoft.org/nexus/content/repositories/public/ ``` 3. In your Maven `.m2` directory, update the settings.xml file with your Exchange credentials: ```XML exchange-server myusername mypassword ``` > [!NOTE] For information about how to authenticate using a token rather than using credentials, > see > [Publish and Consume Federated Assets](https://docs.mulesoft.com/exchange/to-publish-assets-maven#publish-and-consume-federated-assets). 4. Deploy the policy using the `mvn clean deploy` command. > [!NOTE] The IDs defined for your Exchange repositories must match. The custom policy is now available for you to apply to APIs that belong to the specified organization. > [!NOTE] For Java 17 support, add `supportedJavaVersions: ["8", "11", "17"]` to the policy > definition YAML. See > [YAML Configuration File](https://docs.mulesoft.com/mule-gateway/policies-custom-mule-4-reference#yaml-configuration-file). ## See Also - [Packaging a Custom Policy](https://docs.mulesoft.com/mule-gateway/policies-custom-package) - [Reviewing Custom Policy Concepts](https://docs.mulesoft.com/mule-gateway/policies-custom-mule-4-reference) --- product: Mule Gateway keywords: xml threat protection, api gateway, flex gateway, gateway, policy --- # XML Threat Protection Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Policy Name

XML Threat Protection

Summary

Protects against malicious XML in API requests

Category

Security

First Mule version available

v3.8.0

Returned Status Codes

400 - Bad Request

## Summary Applications processing XML requests are susceptible to attacks characterized by unusual inflation of elements, attributes, and nesting levels. Attackers use recursive techniques to consume memory resources. Dramatic increases in the size of the application data often signal a security problem. The XML Threat Protection policy helps protect your applications from such intrusions. If you find that attacks on your Anypoint Platform setup are difficult to detect, design your services architecture with layers of protection in addition to XML Threat Protection. ## Configuring Policy Parameters ### Mule Gateway When you apply the XML Threat Protection policy to your API from the UI, the following parameters are displayed:

Field

Description

Default

Required

Maximum Node Depth

Specifies the maximum node depth of an XML document.

-1

false

Maximum Attribute Count Per Element

Specifies the maximum number of attributes in an element. Note that attributes used for defining namespaces are not counted.

-1

false

Maximum Child Count

Specifies the maximum number of children of an element in the XML document.

-1

false

Maximum Text Length

Specifies the maximum length (in characters) of text nodes in the XML document.

-1

false

Maximum Attribute Length

Specifies the maximum length (in characters) of an attribute in the XML document.

-1

false

Maximum Comment Length

Specifies the maximum number of comment characters in the XML document.

-1

false

> [!NOTE] A value of -1 indicates that the field value has no limits. ## Example The following screenshot shows an example of the parameters configured for the XML Threat Protection policy: ![xml threat policy](/mulesoft/current/en-us/mule-gateway/_images/xml-threat-policy.png)