Nav

Creating a Custom Policy

If you want an API policy that isn’t included in the default set of policies, you can create your own custom policy. In Studio 6.1 and later, you can use the Studio custom policy editor (Beta) to create the required files:

A custom policy requires the following files:

  • Policy Definition - YAML file that describes the policy and its configurable parameters

  • Policy Configuration - XML file with the backend processes that implement the policy

A custom policy also must contain a pointcut declaration.

You can create a custom policy if you use one of the following runtimes:

  • Mule 3.8 or later unified runtime

  • API Gateway runtime 1.3 or later

Limitations

Custom policies must be self-contained. From a custom policy, do not reference another dependent policy, a connector on the app, nor a shared connector.

You create a custom policy by leveraging the elements in Mule Runtime to evaluate and process HTTP calls and responses. The policy filters calls to an API and matches one of the query parameters in the request to a configurable, regular expression. Unmatched requests are rejected. You set the HTTP status and the payload to indicate an error whenever a request does not match the conditions of the filter.

The following procedure shows how to perform these tasks:

  • Create a custom policy definition to filter calls to an API.

  • Create the policy configuration file.

  • Load the new policy into Anypoint Platform.

  • Apply the new policy to an API.

Prerequisites

The prerequisites for creating a custom policy are:

  • An API created on one of the following supported releases to which you apply the custom policy

    • An API created on premises and deployed through API Gateway Runtime 1.3 or later to Anypoint Platform

    • An API created on premises and deployed through the Mule 3.8 unified runtime

  • Membership in the Organization Administrators Role

Create the Custom Policy Definition

In this procedure, you create a YAML file that contains the policy definition file. The YAML file defines required properties for a policy. These properties map to the elements that appear in a dialog in Anypoint Platform when you click the policies tab in the lower section of the API version page:

policy+yaml+mapping

Next, to filter calls to the API, the policy definition includes a query parameter and a regular expression to filter the query parameter. Unmatched requests are rejected. The following illustration shows how the properties map to the elements in the Apply "mypolicy" dialog:

policy+yaml+mapping2

To create the policy definition file:

  1. Open a new text file, and define the required properties for a policy in Anypoint Platform or download the mypolicy.yaml example definition file:

    
                
             
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    ---
    id: query-param-filter
    name: Query Param Filter
    description: Filters query parameters
    category: Security
    type: custom
    standalone: true
    requiresConnectivity: false
    providedCharacteristics: []
    requiredCharacteristics: []
  2. Add a configuration element and two propertyName fields having the values regexFilter and queryParam.

  3. Add properties to define the regular expression to filter the parameter and to name and define the query parameter that must be evaluated.

    
                
             
    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
    
    id: query-param-filter
    name: Query Param Filter
    description: Filters query parameters
    category: Security
    type: custom
    standalone: true
    requiresConnectivity: false
    providedCharacteristics: []
    requiredCharacteristics: []
    configuration:
      - propertyName: regexFilter
        name: Regex Filter
        description: A regular expression to filter a query parameter. Rejects unmatched requests.
        type: string
        defaultValue:
        optional: true
        sensitive: false
        allowMultiple: false
      - propertyName: queryParam
        name: Query Parameter
        description: Name of a query parameter to filter by a regular expression.
        type: string
        defaultValue:
        optional: false
        sensitive: false
        allowMultiple: false
  4. Save the file using a .yaml extension. For example, save the file as mypolicy.yaml.

For more information about the policy definition YAML file, see Custom Policy Reference.

Create the Policy Configuration File

The policy configuration is an XML file that implements the execution of the policy. The configuration leverages the elements available when creating a Mule application. You can use all Mule application elements in a custom policy, as described in the policy configuration documentation.

The custom policy in this example needs the following elements and other constructs:

  • <policy>, id, and policyName elements.

    In the Mule 3.8 unified runtime and API Gateway version 2.0 and later these elements track the policy for analytics.

  • before section to execute on every request to the API before the actual API services are called.

    The after section is not needed; return results need no processing. 

  • A filter element in the before section references an element named Expression. This filter element has a name property that matches the referenced element.

    The expression parameter contains a MEL expression that specifies the filtering conditions and the targeted element to filter. The YAML file defined these parameters, which are wrapped in {{curly brackets}} in the XML configuration file:

    • {{regexFilter}} is used as the filtering condition.

    • {{queryParamm}} is used to construct expression that references the desired query parameter.

  • A message filter, which is a standard Mule element, to filter the incoming request.

    This element does not actually define the filter logic, but references the Expression element that specifies the filter’s behavior.

  • An onUnaccepted property in the opening tag of the filter element in the before section references the policyViolation element

  • An onUnaccepted property in the opening tag of the mule:message-filter element. When the criteria specified by the filter is not matched, this property calls and executes the referenced element.

To create the policy configuration file:

  1. Open a new text file, and create policy, before, and pointcut elements as described in the Using Pointcuts or download the mypolicy.xml example policy configuration file.

    The following example policy configuration file shows these elements.

    
                 
              
    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
    
    <policy xmlns="http://www.mulesoft.org/schema/mule/policy"
            id="{{policyId}}"
            policyName="Regex Filter"
            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">
    
      <!-- This element defines the details of the filter -->
      <!--   implemented in the "before" section. -->
      <mule:expression-filter xmlns:mule="http://www.mulesoft.org/schema/mule/core" expression="#[regex('{{regexFilter}}',message.inboundProperties['http.query.params']['{{queryParam}}'] )]" name="Expression"/>
      <!-- This section builds response messages when the policy fails. -->
      <mule:processor-chain xmlns:mule="http://www.mulesoft.org/schema/mule/core" name="policyViolation">
        <!-- Set the HTTP status code to 403: -->
        <mule:set-property propertyName="http.status" value="403"/>
        <mule:set-property propertyName="Content-Type" value="application/json"/>
        <!-- Set the payload to the description of the violation: -->
        <mule:set-payload value="You shall not pass!"/>
      </mule:processor-chain>
    
       <!-- This executes right after the inbound endpoint of the application -->
      <before>
        <mule:message-filter xmlns:mule="http://www.mulesoft.org/schema/mule/core"
          onUnaccepted="policyViolation">
          <mule:filter ref="Expression"/>
        </mule:message-filter>
      </before>
    
      <!-- Pointcut defines where a policy implements. -->
       <pointcut>
           <api-platform-gw:api-pointcut apiName="{{ apiName }}" apiVersion="{{ apiVersionName }}"/>
       </pointcut>
    </policy>
  2. Save the file using a .xml extension. For example, save the file as mypolicy.xml.

For more information about the tags in the configuration XML file, see Custom Policy Reference.

Creating a New Policy

After you have created the YAML and XML files, or downloaded the files, you use them to create a new custom policy.

To create a new policy:

  1. Sign in to Anypoint Platform.

  2. Click API Manager.

  3. From the menu on the right, click Custom policies.

    ApiGwy_CustomPolicies

  4. Click Add custom policy.

    The Add custom policy dialog appears.

  5. Give the new policy a name, for example myPolicy.

  6. Browse to and select the YAML and XML files you created or downloaded.

    creting+queryparamfilter

Applying the Policy

After creating a policy, you can apply the policy.

  1. Navigate to the policies tab of an API.

    applying+queryparamfilter

    The properties you set in the policy description YAML file, such as description and category, display in this dialog.

  2. Click the Apply button.

    The Apply "mypolicy" dialog appears.

  3. Enter search for the query parameter.

    applying+queryparamfilter+2

    The proxy expects all calls to APIs to contain a query parameter named "search" that has a single lowercase letter as its value.

  4. Click Apply.

    If you deploy the proxy on premises using a .zip file that you downloaded from Anypoint Platform, then the new policy applies on-premises automatically. Even if the proxy was already deployed on-premises before creating the policy, there’s no need to re-download or re-deploy anything. The new policy automatically downloads to the /policies folder, in the location where the API Gateway or Mule 3.8 unified runtime is installed.

  5. Configure your organization’s Client ID and Token in the wrapper.conf file.