Chapter 6. APIcast Policies

APIcast policies are units of functionality that modify how APIcast operates. Policies can be enabled, disabled, and configured to control how they modify APIcast. Use policies to add functionality that is not available in a default APIcast deployment. You can create your own policies, or use standard policies provided by Red Hat 3scale.

Control policies for a service with a policy chain. Policy chains do the following:

  • specify what policies APIcast uses
  • provide configuration information for policies 3scale uses
  • specify the order in which 3scale loads policies
Note

Red Hat 3scale provides a method for adding custom policies, but does not support custom policies.

In order to modify APIcast behavior with custom policies, you must do the following:

  • Add custom policies to APIcast
  • Define a policy chain that configures APIcast policies
  • Add the policy chain to APIcast

6.1. APIcast Standard Policies

Red Hat 3scale provides a number of standard policies:

  • Authentication Caching
  • CORS
  • Echo
  • Headers
  • Token Introspection
  • SOAP
  • Upstream
  • URL rewriting

You can enable and configure standard policies in the 3scale API Management.

6.1.1. Authentication caching

The authentication caching policy caches authentication calls made to APIcast. You can select an operating mode to configure the cache operations.

Authentication caching is available in the following modes:

1. Strict - Cache only authorized calls.

"Strict" mode only caches authorized calls. If a policy is running under the "strict" mode and if a call fails or is denied, the policy invalidates the cache entry. If the backend becomes unreachable, all cached calls are rejected, regardless of their cached status.

2. Resilient – Authorize according to last request when backend is down.

The "Resilient" mode caches both authorized and denied calls. If the policy is running under the "resilient" mode, failed calls do not invalidate an existing cache entry. If the backend becomes unreachable, calls hitting the cache continue to be authorized or denied based on their cached status.

3. Allow - When backend is down, allow everything unless seen before and denied.

The "Allow" mode caches both authorized and denied calls. If the policy is running under the "allow" mode, cached calls continue to be denied or allowed based on the cached status. However, any new calls are cached as authorized.

Important

Operating in the "allow" mode has security implications. Consider these implications and exercise caution when using the "allow" mode.

4. None - Disable caching.

The "None" mode disables caching. This mode is useful if you want the policy to remain active, but do not want to use caching.

Configuration properties

propertydescriptionvaluesrequired?

caching_type

The caching_type property allows you to define which mode the cache will operate in.

data type: enumerated string [resilient, strict, allow, none]

yes

Policy object example

{
  "name": "caching",
  "version": "builtin",
  "configuration": {
    "caching_type": "allow"
  }
}

For information on how to configure policies, see the Creating a policy chain section of the documentation.

6.1.2. APIcast CORS request handling Policy

The Cross Origin Resource Sharing (CORS) request handling policy allows you to control CORS behavior by allowing you to specify:

  • allowed headers
  • allowed methods
  • allow credentials
  • allowed origin headers

The CORS request handling policy will block all unspecified CORS requests.

Configuration properties

propertydescriptionvaluesrequired?

allow_headers

The allow_headers property is an array in which you can specify which CORS headers APIcast will allow.

data type: array of strings, must be a CORS header

no

allow_methods

The allow_methods property is an array in which you can specify which CORS methods APIcast will allow.

data type: array of enumerated strings [GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, CONNECT]

no

allow_origin

The allow_origin property allows you to specify an origin domain APIcast will allow

data type: string

no

allow_credentials

The allow_credentials property allows you to specify whether APIcast will allow a CORS request with credentials

data type: boolean

no

Policy object example

{
  "name": "cors",
  "version": "builtin",
  "configuration": {
    "allow_headers": [
      "App-Id", "App-Key",
      "Content-Type", "Accept"
    ],
    "allow_credentials": true,
    "allow_methods": [
      "GET", "POST"
    ],
    "allow_origin": "https://example.com"
  }
}

For information on how to configure policies, refer to the Creating a policy chain section of the documentation.

6.1.3. Echo

The echo policy prints an incoming request back to the client, along with an optional HTTP status code.

Configuration properties

propertydescriptionvaluesrequired?

status

The HTTP status code the echo policy will return to the client

data type: integer

no

exit

Specifies which exit mode the echo policy will use. The request exit mode stops the incoming request from being processed. The set exit mode skips the rewrite phase.

data type: enumerated string [request, set]

yes

Policy object example

{
  "name": "echo",
  "version": "builtin",
  "configuration": {
    "status": 404,
    "exit": "request"
  }
}

For information on how to configure policies, refer to the Creating a policy chain section of the documentation.

6.1.4. APIcast Headers Policy

The APIcast Headers policy allows you to modify existing headers or define additional headers to add to or remove from an incoming request or response. You can modify both response and request headers.

Configuration properties

propertydescriptionvaluesrequired?

op

The op property allows you to specify which operation to apply. The add operation adds a value to an existing header. The set operation creates a header and value, and will overwrite an existing header’s value if one already exists. The push operation creates a header and value, but will not overwrite an existing header’s value if one already exists. Instead, push will add the value to the existing header.

data type: enumerated string [add, set, push]

yes

header

The header property specifies the header to be created or modified.

Any string

yes

value

The value property specifies the associated value that will be assigned according to the header and op properties.

Any string

yes

Policy object example

{
  "name": "headers",
  "version": "builtin",
  "configuration": {
    "response": [
      {
        "op": "add",
        "header": "Custom-Header",
        "value": "any-value"
      }
    ],
    "request": [
      {
        "op": "set",
        "header": "Authorization",
        "value": "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
      }
    ]
  }
}

For information on how to configure policies, refer to the Creating a policy chain section of the documentation.

6.1.5. Token introspection

Note

Red Hat does not offer support for this policy.

The Token introspection policy performs OAuth 2.0 token introspection each time a request is made. The Token introspection policy operates using the following fields:

  • Client ID
  • Introspection URL
  • Client secret
propertydescriptionvaluesrequired?

introspection_url

The introspection_url property specifies the url at which APIcast will seek the token authority

data type: string, Any valid url

yes

client_id

The client_id property allows you to specify an ID string which APIcast will use to identify itself to the token authority.

data type: string, any valid client ID

yes

client_secret

The client_secret property allows you to specify a secret string that APIcast will use to authenticate with the token authority.

data type: string, any valid client secret

yes

Policy object example

{
  "name": "token_introspection",
  "version": "builtin",
  "configuration": {
    "introspection_url": "https://idp.example.com/token/introspect",
    "client_id": "myclient",
    "client_secret": "mysecret"
  }
}

For information on how to configure policies, refer to the Creating a policy chain section of the documentation.

6.1.6. SOAP

The SOAP policy matches SOAP action URIs provided in the SOAPAction or Content-Type header of an HTTP request with mapping rules specified in the policy.

Configuration properties

propertydescriptionvaluesrequired?

pattern

The pattern property allows you to specify a string that APIcast will seek matches for in the SOAPAction URI.

data type: string

yes

metric_system_name

The metric_system_name property allows you to specify the 3scale backend metric with which your matched pattern will register a hit.

data type: string, must be a valid metric

yes

Policy object example

{
  "name": "soap",
  "version": "builtin",
  "configuration": {
    "mapping_rules": [
      {
        "pattern": "http://example.com/soap#request",
        "metric_system_name": "soap",
        "delta": 1
      }
    ]
  }
}

For information on how to configure policies, refer to the Creating a policy chain section of the documentation.

6.1.7. Upstream policy

The upstream policy allows you to parse the Host request header using regular expressions and replace the upstream URL defined in the Private Base URL with a different URL.

For Example:

A policy with a regex /foo, and URL field newexample.com would replace the URL https://www.example.com/foo/123/ with newexample.com

Policy chain reference:

propertydescriptionvaluesrequired?

regex

The regex property allows you to specify the regular expression that the Upstream policy will use when searching for a match with the request path.

data type: string, Must be a valid regular expression syntax

yes

url

Using the url property, you can specify the replacement URL in the event of a match. Note that the upstream policy does not check whether or not this URL is valid.

data type: string, ensure this is a valid URL

yes

Policy object example

{
  "name": "upstream",
  "version": "builtin",
  "configuration": {
    "rules": [
      {
        "regex": "^/v1/.*",
        "url": "https://api-v1.example.com",

      }
    ]
  }
}

For information on how to configure policies, refer to the Creating a policy chain section of the documentation.

6.1.8. URL rewriting

The URL rewriting policy allows you to modify the path of a request using the OpenResty web platform sub and gsub operations.

Configuration properties

propertydescriptionvaluesrequired?

op

The op property allows you to specify which OpenResty web platform operation to use. The sub operation will replace only the first occurrence of a match with your specified regular expression. The gsub operation will replace all occurrences of a match with your specified regular expression.

data type: enumerated string [sub, gsub]

yes

regex

The regex property allows you to specify the regular expression syntax the URL rewriting policy will use when searching for a match.

data type: string, must be a valid regular expression

yes

replace

The replace property allows you to specify a replacement string that will be used in the event of a match.

data type: string

yes

options

Using the options property you can specify the OpenResty web platform options that the URL rewriting policy will use when searching for a match. See the ngx.re.match section of the OpenResty lua module project documentation for information on available options.

data type: string, must be a valid OpenResty sub argument.

no

break

If break property is enabled, the command rewrote the URL will be the last one applied. Otherwise, the policy will continue to apply the subsequent operations.

data type: boolean

no

Policy object example

{
  "name": "url_rewriting",
  "version": "builtin",
  "configuration": {
    "commands": [
      {
        "op": "gsub",
        "regex": "^/v1/products",
        "break": false,
        "replace": "/api/internal/products",
        "options": "oji"
      }
    ]
  }
}

For information on how to configure policies, refer to the Creating a policy chain section of the documentation.

6.2. Enabling a standard Policy

Perform the following procedure to enable policies in the admin portal UI:

  1. Log in to your AMP
  2. Navigate to the API page and select the desired API
navigate to APIcast integrations page
  1. From the Integration page, select edit APIcast configuration
navigate to APIcast configuration page
  1. Under the POLICIES section, click add policy
policyChainOverview
  1. Select the policy you want to add and fill out the required fields
  2. Click the Update and test in Staging Environment button to save the policy chain

6.3. Creating custom APIcast policies

You can create custom APIcast policies entirely or modify the standard policies.

In order to create custom policies, you must understand the following:

  • policies are written in lua
  • policies must adhere to and be placed in the proper file directory
  • policy behavior is affected by how they are placed in a policy chain

6.4. Adding custom policies to APIcast

If you have created custom policies, you must add them to APIcast. How you do this depends on where APIcast is deployed.

You can add custom policies to the following APIcast self-managed deployments:

  • APIcast built-in gateways as part of a 3scale on-premises deployment on OpenShift
  • APIcast on OpenShift and the Docker containerized environment

You cannot add custom policies to APIcast hosted.

Warning

Never make policy changes directly onto a production gateway. Always test your changes.

6.4.1. Adding custom policies to APIcast built-in

To add custom APIcast policies to an On-Premises deployment, you must build an OpenShift image containing your custom policies and add it to your deployment. Red Hat 3scale provides a sample repository you can use as a framework to create and add custom policies to an on-premises deployment.

This sample repository contains the correct directory structure for a custom policy, as well as a template which creates an image stream and BuildConfigs for building a new APIcast OpenShift image containing any custom policies you create.

Warning

When you build apicast-custom-policies, the build process "pushes" a new image to the amp-apicast:latest tag. When there is an image change on this image stream tag (:latest), both the apicast-staging and the apicast-production tags, by default, are configured to automatically start new deployment. To avoid any disruptions to your production service (or staging, if you prefer) it is recommended to disable automatic deployment ("Automatically start a new deployment when the image changes" checkbox), or configure a different image stream tag for production (e.g. amp-apicast:production).

Follow these steps to add a custom policy to an on-premises deployment:

  1. Fork the https://github.com/3scale/apicast-example-policy [public repository with the policy example] or create a private repository with its content. You need to have the code of your custom policy available in a Git repository for OpenShift to build the image. Note that in order to use a private Git repository, you must set up the secrets in OpenShift.
  2. Clone the repository locally, add the implementation for your policy, and push the changes to your Git repository.
  3. Update the openshift.yml template. Specifically, change the following parameters:

    1. spec.source.git.uri: https://github.com/3scale/apicast-example-policy.git in the policy BuildConfig – change it to your Git repository location.
    2. spec.source.images[0].paths.sourcePath: /opt/app-root/policies/example in the custom policies BuildConfig - change example to the name of the custom policy that you have added under the policies directory in the repository.
    3. Optionally, update the OpenShift object names and image tags. However, you must ensure that the changes are coherent (example: apicast-example-policy BuildConfig builds and pushes the apicast-policy:example image that is then used as a source by the apicast-custom-policies BuildConfig. So, the tag should be the same).
  4. Create the OpenShift objects by running the command:

    oc new-app -f openshift.yml --param AMP_RELEASE=2.2.0
  5. In case the builds do not start automatically, run the following two commands. In case you changed it, replace apicast-example-policy with your own BuildConfig name (e.g. apicast-<name>-policy). Wait for the first command to complete before you execute the second one.

    oc start-build apicast-example-policy
    oc start-build apicast-custom-policies

If the build-in APIcast images have a trigger on them tracking the changes in the amp-apicast:latest image stream, the new deployment for APIcast will start. After apicast-staging has restarted, go to the Integration page on the admin portal, and click the Add Policy button to see your custom policy listed. After selecting and configuring it, click Update & test in Staging Environment to make your custom policy work in the staging APIcast.

6.4.2. Adding custom policies to APIcast on another OpenShift Container Platform

You can add custom policies to APIcast on OpenShift Container Platform (OCP) by fetching APIcast images containing your custom policies from the the Integrated OpenShift Container Registry.

Add custom policies to APIcast on another OpenShift Container Platform

  1. Add policies to APIcast built-in
  2. If you are not deploying your APIcast gateway on your primary OpenShift cluster, establish access to the internal registry on your primary OpenShift cluster.
  3. Download the 3scale 2.2 APIcast OpenShift template.
  4. To modify the template, replace the default image directory with the full image name in your internal registry.

    image: <registry>/<project>/amp-apicast:latest
  5. Deploy APIcast using the OpenShift template, specifying your customized image:

    oc new-app -f customizedApicast.yml

6.5. Creating a policy chain in the AMP

Create a policy chain in the AMP as part of your APIcast gateway configuration. Follow these steps to modify the policy chain in the UI:

  1. Log in to your AMP
  2. Navigate to the API page and select the desired API
navigate to APIcast integrations page
  1. From the Integration page, select edit APIcast configuration
navigate to APIcast configuration page
  1. Under the POLICIES section, use the arrow icons to reorder policies in the policy chain. Always place the APIcast policy last in the policy chain.
policyChainOverview
  1. Click the Update and test in Staging Environment button to save the policy chain

6.6. Creating a policy chain JSON configuration file

If you are using a native deployment of APIcast, you can create a JSON configuration file to control your policy chain outside of the AMP.

A JSON configuration file policy chain contains a JSON array composed of the following information:

  • the services object with an id value that specifies which service the policy chain applies to by number
  • the proxy object, which contains the policy_chain and subsequent objects
  • the policy_chain object, which contains the values that define the policy chain
  • individual policy objects which specify both name and configuration data necessary to identify the policy and configure policy behavior

The following is an example policy chain for a custom policy sample_policy_1 and the API introspection standard policy token_introspection:

{
  "services":[
    {
      "id":1,
      "proxy":{
        "policy_chain":[
          {
            "name":"sample_policy_1", "version": "1.0",
            "configuration":{
              "sample_config_param_1":["value_1"],
              "sample_config_param_2":["value_2"]
            }
          },
          {
            "name": "token_introspection", "version": "builtin",
            "configuration": {
              introspection_url:["https://tokenauthorityexample.com"],
              client_id:["exampleName"],
              client_secret:["secretexamplekey123"]
          },
          {
             "name": "apicast", "version": "builtin",
          }
        ]
      }
    }
  ]
}

All policy chains must include the built-in policy apicast. Where you place APIcast in the policy chain will affect policy behavior.