Nav

Custom Policy Reference

This policy definition YAML and policy configuration XML files make up a custom policy.

Policy Definition YAML File

The policy definition file defines the high level properties of the policy, the configurable parameters, labels, and tips that are visible as a UI when implementing the policy.

The following example shows the IP White List policy definition YAML file:


         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
id: ip-whitelist
name: IP whitelist
description: Limits all service calls to a defined set of IP addresses.
category: Security
standalone: true
requiresConnectivity: false
resourceLevelSupported: true
providedCharacteristics:
  - IP filtered
requiredCharacteristics: []
configuration:
  - propertyName: ipExpression
    name: IP expression
    description: |
      Mule Expression for extracting the IP address from this API request.
      for example, #[message.inboundProperties['http.headers']['X-Forwarded-For']]
    type: expression
    defaultValue:
    optional: true
    sensitive: false
    allowMultiple: false
  - propertyName: ips
    name: Whitelist
    description: Limited list of IP addresses allowed API access
    type: ipaddress
    optional: false
    sensitive: false
    allowMultiple: true

New properties you define have values based on what you want users to configure when they apply a policy. The IP White List policy example requires values for the ipExpression and ips properties. The Policy Configuration XML file references these properties. Users are prompted to assign values to them.

The following policy definition values are related to the new policy:

Parameter Description

name

string - Policy name

description

string - A description that displays in the policy details when applying it

category

string - Category of the policy

standalone

boolean - True if the policy can work on its own or false if the policy can be applied only as part of another policy.

providedCharacteristics

array - A list of optional characteristics that are fulfilled by applying this policy.

resourceLevelSupported

boolean - True means the user can apply the policy to specific API resources; False means the policy applies to all API resources. (Mule 3.8.1 and later)

requiredCharacteristics

array - A list of required characteristics that are fulfilled before this policy can be applied. Required characteristics can be fulfilled by applying other policies that provide these. This allows dependencies between policies. Any string input is valid as a characteristic name as long as at least one other policy provides this characteristic, these are case sensitive.

configuration

array - A set of configurable properties associated with your policy, details on the parameters for each property below.

ramlSnippet

string - A security scheme described in the RAML 0.08 specification.

ramlV1Snippet

string - A security scheme described in the RAML 1.0 specification.

providedCharacterics Parameter

Typically, you set providedCharacteristics to avoid clashes between policies that cannot be applied at the same time. For example, only one OAuth 2.0 policy can be applied at a time. Use the OAuth 2.0 protected to specify only one OAuth 2.0 policy.

The list of existing characteristics is:

  • Client ID required

  • CORS enabled

  • Baseline Rate Limiting

  • SLA Rate Limiting

  • Requires authentication

  • IP filtered

  • JSON threat protected

  • Security manager

  • OAuth 2.0 protected

  • OAuth 2.0 provider

  • XML threat protected

This list is unlimited: any string input is valid as a characteristic name. The list items are case sensitive.

configuration Parameter

The configuration parameter lists a set of properties. Each can contain the following parameters:

Parameter Description

propertyName

string - Property name for internal reference

name

string - Property name to display in configuration window

description

string - Property description to display in configuration window

type

string - Data type: string, boolean, int, ipaddress, expression (in MEL)

optional

boolean - True if assigning a value for it is optional.

sensitive

boolean - True if the information contained by this field is sensitive (typically used for passwords and tokens). When policy information is requested from the server, these sensitive fields are filtered out.

allowMultiple

boolean - True if multiple values can be assigned. Only valid if type is ipaddress.

minimumValue

int - Only for values of type int

maximumValue

int - Only for values of type int

defaultValue

Only for properties of type int, boolean, string and expression

propertyName Syntax

The following snippets show how to use define propertyName parameters of the following types:

  • Integer

  • Boolean

  • String

Integer


           
        
1
2
3
4
5
6
7
8
9
10
configuration:
 - propertyName: aint
   name: Test Int single between 5 and 10
   description: Some Description
   type: int
   minimumValue: 5
   maximumValue: 10
   optional: true
   sensitive: false
   allowMultiple: false

Boolean


           
        
1
2
3
4
5
6
7
8
9
configuration:
 - propertyName: aboolean
   name: Test Boolean single
   description: Some Description
   type: boolean
   optional: true
   sensitive: false
   allowMultiple: false
   defaultValue: false

String


           
        
1
2
3
4
5
6
7
8
configuration:
 - propertyName: astring
   name: Test String single
   description: Some Description
   type: string
   optional: true
   sensitive: false
   allowMultiple: false

ramlSnippet and ramlV1Snippet Parameters

In the YAML of the custom policy, you can include the ramlSnippet and ramlV1Snippet parameters. When you add the custom policy to Anypoint Platform, links for the RAML .80 or RAML 1 snippets show up in the Applied Policies list.

The following snippet shows ramlSnippet and ramlV1Snippet parameters in a snippet of the YAML file of the out-of-the-box Throttling-SLA based policy:

id: test
name: test
description: Rosario Central
...
configuration:
  - propertyName: omar
    name: arnaldo
...
  - propertyName: rosario
    name: central
...
ramlSnippet: |
  traits:
  - client-id-required:
      queryParameters:
        client_id:
          type: string
        client_secret:
          type: string
  ...
  /products:
  get:
    is: [client-id-required]
    description: Gets a list of all the inventory products.
ramlV1Snippet: |
  traits:
  client-id-required:
    queryParameters:
      client_id:
        type: string
      client_secret:
        type: string
  ...
  /products:
  get:
    is: [client-id-required]
    description: Gets a list of all the inventory products.

Policy Configuration XML File

The policy configuration is an XML file that implements the actual execution of the policy. The configuration achieves this by leveraging the elements in a flow when creating a Mule Runtime application. All of the elements usable in Mule Runtime can be used in a custom policy.

The policy configuration defines the actual processes that carry out the implementation of the policy. Structured like a Mule app, you wrap content in the following tags:


         
      
1
2
<policy>
</policy>

The opening <policy> tag includes references to all of the Mule XSD files used in the policy. Some of the Mule elements you can add require adding the corresponding XSD reference too.

In the API Gateway runtime 2.0 and later and Mule 3.8 unified runtime, add properties id and policyName to the <policy> element parameters to gather data about the API for analytics.

By default, when you create a custom policy, you have access to the following default configuration properties that you can reference in the configuration XML file:

Property Description

policyId

A unique ID for the current policy

endpointUri

The full URI for the inbound endpoint of the API

apiId

Unique ID number for the API

apiVersionId

Unique ID number for the API version

apiName

Name of the API

isRamlEndpoint

Boolean that determines if the endpoint is linked to a RAML definition file

isWsdlEndpoint

Boolean that determines if the endpoint is linked to a WSDL definition file

isHttpEndpoint

Boolean that determines if the endpoint follows the HTTP protocol

In addition to these default properties, you can specify new ones in the policy definition YAML file and reference them in the policy configuration XML file.

Referencing Properties

In the configuration XML, you can access the default set of properties for a policy definition and properties defined in the Policy Template YAML file. To reference a property, type its name enclosed in two curly brackets as follows:

{{propertyName}}

Order Property in Policy Tag

You can set the order of execution of a policy using the order property, however setting the order of policy execution in a message processor takes precedence over setting the order of execution in the policy tag. Set the order to an integer greater than 2 because the order values 0 - 2 are reserved for CORS, Throttling, and Rate Limit policies, respectively. These policies must execute before others. The following example shows how to set the order property in the <policy> tag:


          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<policy id="7777"
        policyName="A"
        order="3"
        xmlns="http://www.mulesoft.org/schema/mule/policy"
        xmlns:mule="http://www.mulesoft.org/schema/mule/core"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:api-platform-gw="http://www.mulesoft.org/schema/mule/api-platform-gw"
        xsi:schemaLocation="http://www.mulesoft.org/schema/mule/policy http://www.mulesoft.org/schema/mule/policy/current/mule-policy.xsd
              http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
              http://www.mulesoft.org/schema/mule/api-platform-gw http://www.mulesoft.org/schema/mule/api-platform-gw/current/mule-api-platform-gw.xsd">

    <before>
         <mule:logger level="INFO" message="POLICY A" />
    </before>

    <pointcut>
        <api-platform-gw:api-pointcut apiName="Leagues API" apiVersion="1.0.0"/>
    </pointcut>
</policy>

Order Property in Before or After Tags

Alternatively, you can set the order of execution of policies in the <before></before>and <after></after> tags. Setting the order `property in the `before and after tags takes precedence over any order setting in the policy tag. Set order to an integer greater than 2. For example:


          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
<policy id="2"
       ...

    <before order="4">
       <mule:set-payload value=" before cust2 "/>
       <mule:logger level="INFO" message="#[payload]" />
    </before>

    <before order="3">
       <mule:set-payload value=" before cust2.1 "/>
       <mule:logger level="INFO" message="#[payload]" />
    </before>

Before and After Tags

Enclosed within the main element of the configuration file are two fundamental structures you can add: <before></before> and <after></after> tags. Both are optional, but your policy must have at least one of them if you want it to perform any action at all.

As shown in the following flow, content between the before tags executes every time there’s an incoming request to your API, as soon as the request reaches the inbound endpoint, and before your API executes any of the remaining message processors in your flows. Content between the after tags likewise executes every time there’s a request to your API, right before reaching the outbound endpoint in your API, and after having executed every other one of the message processors in your flows.

basic+flow

In addition to the <before></before> and <after></after> tags, you can also add <mule:processor-chain></mule:processor-chain> tags as additional flows where you can perform more procedures. These flows don’t execute on their own, they must be referenced one way or another by either the before or the after sections of your policy. When writing a policy, unlike when writing a Mule application, you must add a mule: suffix to the name of the element.


          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<policy>
    <before>
        <!-- Elements automatically executed at the start -->
    </before>
    <after>
        <!-- Elements automatically executed at the end -->
    </after>
 
    <mule:processor-chain name="chain1">
        <!-- This flow may be called to be executed by the others -->
    </mule:processor-chain>
 
    <mule:processor-chain name="chain2">
        <!-- This flow may be called to be executed by the others -->
    </mule:processor-chain>
</policy>

The "Using Pointcuts" section of this document covers enabling resource level policies. The following example runs versions earlier than Mule 3.8.4 and does not support resource level policies.


          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?xml version="1.0" encoding="UTF-8"?>
<policy id="4444"
        policyName="HTTP Basic Authentication"
        xmlns="http://www.mulesoft.org/schema/mule/policy"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:spring="http://www.springframework.org/schema/beans"
        xmlns:mule-ss="http://www.mulesoft.org/schema/mule/spring-security"
        xmlns:ss="http://www.springframework.org/schema/security"
        xmlns:api-platform-gw="http://www.mulesoft.org/schema/mule/api-platform-gw"
        xsi:schemaLocation="http://www.mulesoft.org/schema/mule/policy http://www.mulesoft.org/schema/mule/policy/current/mule-policy.xsd
              http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
              http://www.mulesoft.org/schema/mule/spring-security http://www.mulesoft.org/schema/mule/spring-security/current/mule-spring-security.xsd
              http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-current.xsd
              http://www.mulesoft.org/schema/mule/api-platform-gw http://www.mulesoft.org/schema/mule/api-platform-gw/current/mule-api-platform-gw.xsd">
    <!-- HTTP BASIC AUTH POLICY -->
    <!-- The HTTP basic auth policy adds a validation that requires -->
    <!-- all requests to contain the Authorization HTTP header, -->
    <!-- in case it doesn't send back a challenge. -->
    <!-- The policy consists of two parts. -->
    <!-- The first part is the configuration of a security manager, -->
    <!-- which in this case is using a mocked up one with a single -->
    <!-- hardcoded user. -->
    <spring:beans>
        <ss:authentication-manager alias="example-authentication-manager">
            <ss:authentication-provider>
                <ss:user-service id="userService">
                    <ss:user name="admin" password="admin" authorities="ROLE_ADMIN"/>
                </ss:user-service>
            </ss:authentication-provider>
        </ss:authentication-manager>
    </spring:beans>
    <mule-ss:security-manager name="example-security-manager">
        <mule-ss:delegate-security-provider name="example-security-provider" delegate-ref="example-authentication-manager" />
    </mule-ss:security-manager>
    <!-- The second part is the injection of the filter itself, that uses the previously configured security manager. -->
    <!-- Notice that the injection happens according to the pointcut criteria specified below. -->
    <before>
        <mule-ss:http-security-filter securityManager-ref="example-security-manager" realm="mule-realm" />
    </before>
    <!-- The following provides a custom trait to the RAML of the API if it uses APIkit. Otherwise it is ignored. -->
    <raml-security-scheme id="basic"><![CDATA[
        description: Resource access is protected using basic authentication.
        type: Basic Authentication
        describedBy:
            headers:
                Authorization:
                    description: |
                       Sends username and password encoded in RFC2045-MIME variant of Base64.
                    type: string
                    example: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
            responses:
                403:
                    description: |
                        Invalid username and password
    ]]></raml-security-scheme>
    <!-- Pointcuts specify where this policy takes effect. 
         The pointcut refers to a specific API and Version. -->
    <pointcut>
        <api-platform-gw:api-pointcut apiName="sampleApi" apiVersion="1.0.0"/>
    </pointcut>
</policy>

The DataWeave component is not supported for use within your Custom Policies.

Using Pointcuts

A custom policy must contain a pointcut declaration. Pointcuts control the scope of a policy application and they use regular expressions to indicate what flows in the application are affected by a policy.

If you’re applying your policy to APIs that are deployed in Anypoint Platform, then set your pointcut to the default properties apiName and apiVersion. This action guarantees that your policy is applied to only the API that you’re activating the policy. This is what your pointcut should look like:


          
       
1
2
3
<pointcut>
   <api-platform-gw:api-pointcut apiName="{{ apiName }}" apiVersion="{{ apiVersionName }}"/>
</pointcut>

Setting your pointcut to a broad regular expression such as regex=”.*” may have undesirable effects.

Applying this policy to a single API through the platform, might actually affect other APIs you’re deploying as well.

If you’re using your policies in an on-site deployment, then you might want to modify the pointcut to apply your policy to multiple APIs simultaneously.

Enabling Resource Level Policies

If your API runs on Mule 3.8.4 and later, use the following code to include resource level policies:


          
       
1
2
3
4
5
6
7
8
9
10
11
12
  {{#pointcutData}}
    <pointcut>
      <api-platform-gw:api-pointcut apiName="{{apiName}}" apiVersion="{{apiVersionName}}"/>
      <resource methodRegex="{{methodRegex}}" uriTemplateRegex="{{uriTemplateRegex}}"/>
    </pointcut>
  {{/pointcutData}}
{{/pointcutData.length}}
{{^pointcutData.length}}
  <pointcut>
    <api-platform-gw:api-pointcut apiName="{{apiName}}" apiVersion="{{apiVersionName}}"/>
  </pointcut>
{{/pointcutData.length}}

Also, include the following property in the YAML: resourceLevelSupported: true

Customizing a Pointcut

In a pointcut you can reference the following kinds of elements:

  • Endpoints

  • Apps

  • Resources

If several elements are specified inside a single pointcut, then they are implemented as if you were using an AND expression.


          
       
1
2
3
4
<pointcut>
   <resource uriTemplateRegex="/items/.*" />
   <resource methodRegex="GET" />
</pointcut>

If several elements are specified in separate pointcut parent elements, they are implemented as if you were using an OR expression.

Reference Apps


           
        
1
2
3
<pointcut>
   <app regex=".*" />
</pointcut>

Reference Endpoints


          
       
1
2
3
<pointcut>
   <endpoint regex=".*" />
</pointcut> 

The following example uses values from properties:


          
       
1
2
3
<pointcut>
    <endpoint regex="http://localhost:${http.port}/gateway/.*" />
</pointcut>

This example is also valid:


          
       
1
2
3
<pointcut>
   <endpoint regex="http\:\/\/localhost:${http.port}\/gateway\/.*" />
</pointcut>

For the two previous examples to work you have to define http.port when starting Mule or in your wrapper.conf file, define something like this:

wrapper.java.additional.4=-Dhttp.port=8081

If http.port is defined at application level, a parse exception occurs when you apply the policy.

Reference Resources


          
       
1
2
3
<pointcut>
   <resource methodRegex=".*" />
</pointcut>

You can reference specific methods (GET, POST, PUT, etc.).

For example: <resource methodRegex=”P.*” /> applies to all POST, PUT and PATCH methods.

Example using defaults:


          
       
1
2
3
<pointcut>
   <resource uriTemplateRegex=".*" />
</pointcut>

In this example you can specify the path from the baseUri specified on the RAML file.

Example filtering of the first level of resources:


          
       
1
2
3
<pointcut>
    <resource uriTemplateRegex="/items/.*" />
</pointcut>

You can only use the Java classes that are provided by Mule.

Although you can use any message processor that is available in Mule to build your custom policy, you can only use the Java classes that are provided by Mule. Unlike building a Mule application, you can’t define and call a custom Java class when building a custom policy, as you have no way of bundling the custom Java class with your policy.

Minimal Policy Configuration File

You can use the following minimal policy configuration file to start building your custom policy:


         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>
<policy xmlns="http://www.mulesoft.org/schema/mule/policy"
        id="{{policyId}}"
        policyName="IP whitelist"  
        xmlns:mule="http://www.mulesoft.org/schema/mule/core"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:api-platform-gw="http://www.mulesoft.org/schema/mule/api-platform-gw"
        xsi:schemaLocation="http://www.mulesoft.org/schema/mule/policy http://www.mulesoft.org/schema/mule/policy/current/mule-policy.xsd
                            http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
                            http://www.mulesoft.org/schema/mule/api-platform-gw http://www.mulesoft.org/schema/mule/api-platform-gw/current/mule-api-platform-gw.xsd">
 
    <before>
        <mule:set-payload value="PRE" />
    </before>
 
    <after>
        <mule:set-payload value="POST" />
    </after>
 
    <pointcut>
       <api-platform-gw:api-pointcut apiName="{{ apiName }}" apiVersion="{{ apiVersionName }}"/>
    </pointcut>
 
</policy> 

Full Example of a Policy Configuration File

Below is an example of a policy configuration file that implements an IP whitelist filter that matches the previous YAML example. This XML file references several variables enclosed in curly brackets that the YAML file defines and resource level policies supported in Mule 3.8.4 and later.

The IP whitelist filter policy adds a validation that requires all requests to contain a valid IP Address based on a valid list of IPs  configured.


         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?xml version="1.0" encoding="UTF-8"?>
<policy online="true"
        id="{{policyId}}"
        policyName="IP whitelist"
        xmlns="http://www.mulesoft.org/schema/mule/policy"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:spring="http://www.springframework.org/schema/beans"
        xmlns:mule="http://www.mulesoft.org/schema/mule/core"
        xmlns:ip-filter-gw="http://www.mulesoft.org/schema/mule/ip-filter-gw"
        xsi:schemaLocation="http://www.mulesoft.org/schema/mule/policy http://www.mulesoft.org/schema/mule/policy/current/mule-policy.xsd
                            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                            http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
                            http://www.mulesoft.org/schema/mule/ip-filter-gw http://www.mulesoft.org/schema/mule/ip-filter-gw/current/mule-ip-filter-gw.xsd">
 
    <!-- This section is for building response messages when the policy fails. -->
    <mule:processor-chain name="{{policyId}}-build-response">
        <mule:set-property propertyName="http.status" value="403"/> <!-- Set HTTP status code to 403 -->
        <mule:set-property propertyName="Content-Type" value="application/json"/>
        <mule:set-payload value="#[_ipViolationMessage]"/> <!-- Set the payload to the description of the violation -->
    </mule:processor-chain>
 
    <!-- This is the element that gets injected at the beginning of every flow. According to the pointcut specified below. -->
    <before>
        <ip-filter-gw:filter ipAddress="{{ipExpression}}" onUnaccepted="{{policyId}}-build-response">   <!-- If failed, the mule:processor-chain above is executed -->
            <ip-filter-gw:whitelist>
                {{#ips}}
                <ip-filter-gw:ip>{{.}}</ip-filter-gw:ip>
                {{/ips}}
            </ip-filter-gw:whitelist>
        </ip-filter-gw:filter>
    </before>
 
    <!-- Pointcuts specify where this policy takes effect-->
    {{#pointcutData.length}}
      {{#pointcutData}}
        <pointcut>
          <api-platform-gw:api-pointcut apiName="{{apiName}}" apiVersion="{{apiVersionName}}"/>
          <resource methodRegex="{{methodRegex}}" uriTemplateRegex="{{uriTemplateRegex}}"/>
        </pointcut>
      {{/pointcutData}}
    {{/pointcutData.length}}
    {{^pointcutData.length}}
      <pointcut>
        <api-platform-gw:api-pointcut apiName="{{apiName}}" apiVersion="{{apiVersionName}}"/>
      </pointcut>
    {{/pointcutData.length}}
</policy>