[Yandex Cloud documentation](../../index.md) > [Yandex API Gateway](../index.md) > [Tutorials](index.md) > Integration with Yandex and Yandex Cloud services > API Gateway protection with Smart Web Security

# Protecting API Gateway by integrating with Smart Web Security

# API Gateway protection with Smart Web Security


Yandex API Gateway supports integration with [Yandex Smart Web Security](../../smartwebsecurity/concepts/index.md). This allows you to set up DDoS and bot protection for an API gateway at the [OSI model](https://en.wikipedia.org/wiki/OSI_model) application layer (L7).

With Smart Web Security profiles, you can configure protection using various conditions. For example, you can set a [request limit](../../smartwebsecurity/concepts/arl.md) with parameter-based request grouping or configure user IP-based request blocking. To do this:

1. [Get your cloud ready](#before-you-begin).
1. [Create an API gateway](#create-api-gateway).
1. [Create an ARL profile and Smart Web Security profile](#create-arl-and-sws-profiles).
1. [Test the new resources](#check-rules).

If you no longer need the resources you created, [delete them](#clear-out).

## Get your cloud ready {#before-you-begin}

Sign up for Yandex Cloud and create a [billing account](../../billing/concepts/billing-account.md):
1. Navigate to the [management console](https://console.yandex.cloud) and log in to Yandex Cloud or create a new account.
1. On the **[Yandex Cloud Billing](https://center.yandex.cloud/billing/accounts)** page, make sure you have a billing account linked and it has the `ACTIVE` or `TRIAL_ACTIVE` [status](../../billing/concepts/billing-account-statuses.md). If you do not have a billing account, [create one](../../billing/quickstart/index.md) and [link](../../billing/operations/pin-cloud.md) a cloud to it.

If you have an active billing account, you can create or select a [folder](../../resource-manager/concepts/resources-hierarchy.md#folder) for your infrastructure on the [cloud page](https://console.yandex.cloud/cloud).

[Learn more about clouds and folders here](../../resource-manager/concepts/resources-hierarchy.md).

## Create an API gateway {#create-api-gateway}

{% list tabs group=instructions %}

- Management console {#console}

  [Create an API gateway](../operations/api-gw-create.md) named `my-gateway`. When creating it, add the following specification to the **Specification** field:

  ```yaml
  openapi: "3.0.0"

  info:
    version: 1.0.0
    title: Protected application
    license:
      name: MIT
  paths:
    /:
      get:
        x-yc-apigateway-integration:
          type: dummy
          content:
            '*': "This application is protected by SWS!"
          httpCode: 200
  ```

  Leave the other parameters unchanged.

- Terraform {#tf}

  1. If you do not have Terraform yet, [install it](../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
  
  1. [Get the authentication credentials](../../tutorials/infrastructure-management/terraform-quickstart.md#get-credentials). You can add them to environment variables or specify them later in the provider configuration file.
  1. [Configure and initialize a provider](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). There is no need to create a provider configuration file manually, you can [download it](https://github.com/yandex-cloud-examples/yc-terraform-provider-settings/blob/main/provider.tf).

  1. Place the configuration file in a separate working directory and [specify the parameter values](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). If you did not add the authentication credentials to environment variables, specify them in the configuration file.

  1. Download the [api-gw-sws-integration.tf](https://github.com/yandex-cloud-examples/yc-serverless-gateway-protection-with-sws/blob/main/api-gw-sws-integration.tf) configuration file to the same working directory.

      This file describes:

      * ARL profile that sets a request limit and request grouping by `token`.
      * Smart Web Security profile that uses the ARL profile as well as enables IP-based blocking.
      * API gateway configured to work with the Smart Web Security profile.
  
  1. In the local variables section of the `api-gw-sws-integration.tf` file, specify the following:
  
      * `api-gw-name`: API gateway name.
      * `create-api-gw = 1`

  1. Validate your Terraform configuration files using this command:

      ```bash
      terraform validate
      ```

      Terraform will display any configuration errors detected in your files.

  1. Create the required infrastructure:

      1. Run this command to view the planned changes:
      
         ```bash
         terraform plan
         ```
      
         If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
      
      1. If everything looks correct, apply the changes:
         1. Run this command:
      
            ```bash
            terraform apply
            ```
      
         1. Confirm updating the resources.
         1. Wait for the operation to complete.

      All the required resources will be created in the specified folder. You can check resource availability and their settings in the [management console](https://console.yandex.cloud).

{% endlist %}

## Create an ARL profile and Smart Web Security profile {#create-arl-and-sws-profiles}

{% list tabs group=instructions %}

- Management console {#console}

  1. [Create an ARL profile](../../smartwebsecurity/operations/arl-profile-create.md) named `arl-profile`.

  1. [Add to it a rule](../../smartwebsecurity/operations/arl-rule-add.md) with a request limit and request grouping by `token`. Specify the following parameters:

      * **Name**: `query-limit-rule`.
      * **Priority**: `999900`.
      * **Request grouping**: **By property**.
      * **Property**: `Query params`.
      * **Group by**: `token`.
      * **Request limit per group**: `1` per `1 minute`.

  1. [Create a security profile](../../smartwebsecurity/operations/profile-create.md) named `sws-profile` using a preset template. When creating it, select the previously created `arl-profile` in the **ARL profile** field.

  1. [Connect the API gateway named `my-gateway`](../../smartwebsecurity/operations/host-connect.md#gateway) to the security profile.

  1. To set up user IP-based blocking, [add the rule](../../smartwebsecurity/operations/rule-add.md) with the following parameters to the Smart Web Security profile:

      * **Name**: `ip-block-rule`.
      * **Priority**: `999700`.
      * **Rule type**: **Basic**.
      * **Action**: **Allow**.
      * **Conditions for traffic**:

          * **Traffic**: **On condition**.
          * **Conditions**: `IP`.
          * **Conditions for IP**: `Matches or falls within the range`.
          * **IP matches or falls within the range**: Specify your IP address.

- Terraform {#tf}

  1. In the local variables section of the `api-gw-sws-integration.tf` file, specify the following:

      * `arl_name`: ARL profile name.
      * `folder_id`: [ID of the folder](../../resource-manager/operations/folder/get-id.md) to host the new ARL profile.
      * `sws_name`: Smart Web Security profile name.
      * `allowed_ips`: List of IP addresses allowed to access the API gateway.

  1. In the `securityProfileId` parameter of the API gateway specification, specify the security profile ID.
  
  1. Validate your Terraform configuration files using this command:

      ```bash
      terraform validate
      ```

      Terraform will display any configuration errors detected in your files.

  1. Create the required infrastructure:

      1. Run this command to view the planned changes:
      
         ```bash
         terraform plan
         ```
      
         If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
      
      1. If everything looks correct, apply the changes:
         1. Run this command:
      
            ```bash
            terraform apply
            ```
      
         1. Confirm updating the resources.
         1. Wait for the operation to complete.

      All the required resources will be created in the specified folder. You can check resource availability and their settings in the [management console](https://console.yandex.cloud).

{% endlist %}

## Test the new resources {#check-rules}

Test the Smart Web Security settings:

* [Request limit](#check-requests-limiter)
* [Request grouping](#check-query-groupping)
* [IP-based request blocking](#check-ip-block)

### Checking the request limit {#check-requests-limiter}

1. Send a GET request to the API gateway:

    ```bash
    curl <API_gateway_service_domain>
    ```

    Result:

    ```bash
    This application is protected by SWS!
    ```

1. Repeat the request straight away. In response, you will get a web page with error code 429. This means the request limit kicked in and blocked your request.

1. Wait for a minute and repeat the request. The response must be the same as the first time:

    ```bash
    This application is protected by SWS!
    ```

### Checking the request grouping {#check-query-groupping}

1. Send a GET request to the API gateway, specifying `token=token`:

    ```bash
    curl <API_gateway_service_domain>?token=token
    ```

    Result:

    ```bash
    This application is protected by SWS!
    ```

1. Repeat the request straight away. In response, you will get a web page with error code 429. This means the request limit kicked in and blocked your request.

1. Repeat the request within the same minute but change the `token` value:

    ```bash
    curl <API_gateway_service_domain>?token=token2
    ```

    Result:

    ```bash
    This application is protected by SWS!
    ```

    This means your request got into a new group that has not yet reached the request limit. That is why the request was successfully completed.

### Checking the IP-based blocking {#check-ip-block}

1. Send a GET request to the API gateway from an IP address you specified in the Smart Web Security profile:

    ```bash
    curl <API_gateway_service_domain>
    ```

    Result:

    ```bash
    This application is protected by SWS!
    ```

1. Send a request from a different IP address, e.g., from a cloud VM:

    ```bash
    curl --verbose <API_gateway_service_domain>
    ```

    In response, you will get a web page with CAPTCHA. This means Smart Web Security has blocked the request from an IP address not listed as an allowed one.

# Delete the resources you created {#clear-out}

Some resources are not free of charge. To avoid paying for them, delete the resources you no longer need depending on how you created them:

{% list tabs group=instructions %}

- Management console {#console}

  1. [Delete the API gateway](../operations/api-gw-delete.md).
  1. [Delete the Smart Web Security profile](../../smartwebsecurity/operations/profile-delete.md).
  1. [Delete the ARL profile](../../smartwebsecurity/operations/arl-profile-delete.md).

- Terraform {#tf}

  1. In the terminal window, go to the directory containing the infrastructure plan.
  
      {% note warning %}
  
      Make sure the directory has no Terraform manifests with the resources you want to keep. Terraform deletes all resources that were created using the manifests in the current directory.
  
      {% endnote %}
  
  1. Delete resources:
  
      1. Run this command:
  
          ```bash
          terraform destroy
          ```
  
      1. Confirm deleting the resources and wait for the operation to complete.
  
      All the resources described in the Terraform manifests will be deleted.

{% endlist %}