aws-cdk-secure-api


Nameaws-cdk-secure-api JSON
Version 0.5.0 PyPI version JSON
download
home_pagehttps://github.com/rnag/aws-cdk-secure-api
SummaryA CDK (v2) Construct Library for Secure REST APIs
upload_time2023-06-23 19:20:29
maintainer
docs_urlNone
authorRitvik Nag
requires_python
licenseMIT
keywords aws-cdk secure rest-api api-gateway api key cdk
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            ==================
aws-cdk-secure-api
==================


.. image:: https://img.shields.io/pypi/v/aws-cdk-secure-api.svg
        :target: https://pypi.org/project/aws-cdk-secure-api

.. image:: https://img.shields.io/pypi/pyversions/aws-cdk-secure-api.svg
        :target: https://pypi.org/project/aws-cdk-secure-api

.. image:: https://github.com/rnag/aws-cdk-secure-api/actions/workflows/dev.yml/badge.svg
        :target: https://github.com/rnag/aws-cdk-secure-api/actions/workflows/dev.yml

.. image:: https://readthedocs.org/projects/aws-cdk-secure-api/badge/?version=latest
        :target: https://aws-cdk-secure-api.readthedocs.io/en/latest/?version=latest
        :alt: Documentation Status


.. image:: https://pyup.io/repos/github/rnag/aws-cdk-secure-api/shield.svg
     :target: https://pyup.io/repos/github/rnag/aws-cdk-secure-api/
     :alt: Updates


An unofficial `AWS CDK v2`_ Construct Library for Secure REST APIs.

* Documentation: https://aws-cdk-secure-api.readthedocs.io.

.. _`AWS CDK v2`: https://aws.amazon.com/about-aws/whats-new/2021/12/aws-cloud-development-kit-cdk-generally-available/

Install
-------

.. code-block:: console

    pip install aws-cdk-secure-api

Constructs
----------

* ``SecureRestApi`` - A construct to create a (public) REST API secured behind an API key, which needs to be
  specified in the ``x-api-key`` header for all requests.

* ``IAMSecureRestApi`` - A construct to create a (public) REST API secured behind `AWS IAM authentication`_, which
  requires IAM credentials `to be signed`_ and included in all requests.

.. _to be signed: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-access-control-iam.html

Features
--------

* A CDK Construct which sets up a `RestApi`_ secured behind (one of):

  * API key

    * An API key is `auto-generated`_ and stored in SSM Parameter Store (which is
      a free service) as needed.

    * Local cache for the API key, so that API calls are not needed in future
      CDK deployments.

  * `AWS IAM authentication`_

    * An IAM User (and Policy/Role) is created with minimal permissions to call / invoke the API.

    * The IAM User Credentials (Access Keys) are stored in AWS Secrets Manager.

* Helper methods for all constructs, such as ``add_resource_and_lambda_methods``, to make it easier to
  integrate a method for an AWS Lambda function for example.

.. _`RestApi`: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.RestApi.html
.. _`auto-generated`: https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetRandomPassword.html

Usage
-----

The ``SecureRestApi`` construct represents a Secure REST API in Amazon API Gateway.

    Use ``add_resource``, ``add_lambda_methods``, and ``add_methods`` to
    configure the API model, as shown below.

**Using a root resource**:

.. code:: python3

    from aws_cdk.aws_apigateway import StageOptions
    from aws_cdk.aws_lambda import Function, Runtime

    from aws_cdk_secure_api import Http, SecureRestApi

    # noinspection PyTypeChecker
    py_runtime: Runtime = Runtime.PYTHON_3_10

    get_handler = Function(self, 'lambda1', runtime=py_runtime, ...)
    put_handler = Function(self, 'lambda2', runtime=py_runtime, ...)

    api = SecureRestApi(
        self, 'api',
        rest_api_name='My Secure Service',
        # optional: specify a deployment stage
        deploy_options=StageOptions(stage_name='dev')
    )

    api.add_lambda_methods(get_handler, 'GET')  # GET /
    api.add_lambda_methods(put_handler, Http.PUT, Http.POST)  # PUT /, POST /

**Using a custom-named resource**:

    Replace above usage of ``add_lambda_methods`` with
    ``add_resource_and_lambda_methods``, as shown below.

.. code:: python3

    # GET /path1
    api.add_resource_and_lambda_methods(get_handler, '/path1', 'GET')
    # PUT /path2, POST /path2
    api.add_resource_and_lambda_methods(put_handler, '/path2', Http.PUT, Http.POST)

The ``IAMSecureRestApi`` construct represents a Secure REST API in Amazon API Gateway,
which requires IAM Authorization.

**Using a custom-named resource**:

.. code:: python3

    from aws_cdk.aws_apigateway import StageOptions
    from aws_cdk.aws_lambda import Function, Runtime

    from aws_cdk_secure_api import Http, IAMConfig, IAMSecureRestApi

    # noinspection PyTypeChecker
    py_runtime: Runtime = Runtime.PYTHON_3_10

    get_handler = Function(self, 'lambda1', runtime=py_runtime, ...)
    put_handler = Function(self, 'lambda2', runtime=py_runtime, ...)

    api = IAMSecureRestApi(
        self, 'api',
        rest_api_name='My IAM Secure Service',
        # optional: specify the name of secret to store IAM User Credentials
        config=IAMConfig(secret_name='my-stack/iam-user-access-keys'),
        # optional: specify a deployment stage
        deploy_options=StageOptions(stage_name='dev')
    )

    # GET /path1
    api.add_resource_and_lambda_methods(get_handler, '/path1', 'GET')
    # PUT /path2, POST /path2
    api.add_resource_and_lambda_methods(put_handler, '/path2', Http.PUT, Http.POST)

To use an IAM Role instead of attaching a Policy directly to User:

.. code:: python3

    IAMConfig(use_role=True)

AWS Profile
-----------

Note that if you normally pass the ``--profile`` to the ``cdk`` tool, for example such as::

    cdk deploy --profile my-aws-profile

The CDK construct won't be able to detect the AWS profile in this particular case.
A few workarounds can be used for this:

1. The environment variable ``AWS_PROFILE`` can be set before calling the ``cdk`` tool.
2. The ``profile`` attribute can be passed in to the ``config`` parameter for ``SecureRestApi``.
3. The ``profile`` context variable can be passed in to the ``cdk`` tool,
   as shown below::

       cdk deploy --profile my-profile -c profile=my-profile

API Keys
--------

Here is the process that the CDK construct uses for generating
or using an API key for a REST API.

1. First, it tries to read the API key from local cache, which is located in your
   home directory, under ``~/.cdk/cache/apigw_api_keys.json``.
2. If an API key is found, then it proceeds to use the cached key value, and *does not*
   perform the following steps.
3. An API call is made to read the key from AWS SSM Parameter Store. The param
   name is ``/{STACK NAME}/api-key``, where ``{STACK NAME}`` is the name of the CDK stack.
4. If the parameter does not exist, an random API key value is auto-generated, and a new
   SSM Parameter is created in the same AWS account and region that the CDK stack is deployed to.
5. The API key value is then cached on the local drive, under the ``~/.cdk/cache`` folder.

Stack Outputs
-------------

The following *stack outputs* will additionally be added to the CDK stack:

* ``APIEndpoint`` - The base endpoint of the Secure REST API.

  * *Note:* this output will not show up if ``override_endpoint_name`` is disabled
    in the ``config`` parameter.

* ``APIKey`` - The API key for the endpoint, which needs to be specified
  as a value in an HTTP request's ``x-api-key`` header.

* ``APIIAMUserCredentials`` - The URL link (to input in a browser) for the Secret
  stored in AWS Secrets Manager containing the AWS IAM Credentials for invoking the REST API.

* ``APIIAMRoleARN`` - The ARN of the IAM Role, used in an `AssumeRole`_ API call with the IAM User credentials.

.. _`AssumeRole`: https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html

Credits
-------

This package was created with Cookiecutter_ and the `rnag/cookiecutter-pypackage`_ project template.

.. _AWS IAM authentication: https://repost.aws/knowledge-center/iam-authentication-api-gateway
.. _Cookiecutter: https://github.com/cookiecutter/cookiecutter
.. _`rnag/cookiecutter-pypackage`: https://github.com/rnag/cookiecutter-pypackage


=======
History
=======

0.5.0 (2023-06-23)
------------------

**Features and Improvements**

* Add option ``use_role`` in ``IAMConfig``, which when enabled will set up
  an IAM Role (with permissions to invoke the API) to be assumed by the IAM User,
  instead of directly attaching an IAM Policy to said User.

0.4.0 (2023-06-22)
------------------

**Features and Improvements**

* Add IAM Authentication via the new ``IAMSecureRestApi`` construct.

0.3.0 (2023-05-17)
------------------

**Features and Improvements**

* Add a helper method ``add_resource_and_lambda_methods``, to set up a new
  API resource, a lambda integration, and setup HTTP method(s) on the
  new resource at the same time.
* Update other helper methods -- such as ``add_lambda_methods`` -- to accept
  an optional ``resource`` parameter, which defaults to the "root" API
  resource (``/``) by default.
* Add ``test`` parameter (boolean) to ``SecureRestApi`` -- if enabled,
  then a live API call to AWS SSM (Parameter Store)
  won't be performed on an initial run, and instead a dummy API key value
  is used.

0.2.0 (2023-05-17)
------------------

**Bugfixes**

* Make code compatible with *Python 3.11*.

**Features and Improvements**

* Add *3.11* to the list of supported Python versions.

0.1.1 (2022-06-24)
------------------

**Bugfixes**

* Remove ``typing.Literal`` usage, so code is compatible with Python 3.7
* Add an import ``from __future__ import annotations`` to modules where it was missing.

**Features and Improvements**

* Update to use the string value of the ``name`` attribute for a ``Http`` Enum member,
  instead of the ``value`` attribute.

0.1.0 (2022-06-24)
------------------

* First release on PyPI.



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/rnag/aws-cdk-secure-api",
    "name": "aws-cdk-secure-api",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "aws-cdk,secure,rest-api,api-gateway,api key,cdk",
    "author": "Ritvik Nag",
    "author_email": "rv.kvetch@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/7f/99/deef5e4c31000811788c8ff5ea355cbf38edac01f59a6b692573c74b0242/aws-cdk-secure-api-0.5.0.tar.gz",
    "platform": null,
    "description": "==================\naws-cdk-secure-api\n==================\n\n\n.. image:: https://img.shields.io/pypi/v/aws-cdk-secure-api.svg\n        :target: https://pypi.org/project/aws-cdk-secure-api\n\n.. image:: https://img.shields.io/pypi/pyversions/aws-cdk-secure-api.svg\n        :target: https://pypi.org/project/aws-cdk-secure-api\n\n.. image:: https://github.com/rnag/aws-cdk-secure-api/actions/workflows/dev.yml/badge.svg\n        :target: https://github.com/rnag/aws-cdk-secure-api/actions/workflows/dev.yml\n\n.. image:: https://readthedocs.org/projects/aws-cdk-secure-api/badge/?version=latest\n        :target: https://aws-cdk-secure-api.readthedocs.io/en/latest/?version=latest\n        :alt: Documentation Status\n\n\n.. image:: https://pyup.io/repos/github/rnag/aws-cdk-secure-api/shield.svg\n     :target: https://pyup.io/repos/github/rnag/aws-cdk-secure-api/\n     :alt: Updates\n\n\nAn unofficial `AWS CDK v2`_ Construct Library for Secure REST APIs.\n\n* Documentation: https://aws-cdk-secure-api.readthedocs.io.\n\n.. _`AWS CDK v2`: https://aws.amazon.com/about-aws/whats-new/2021/12/aws-cloud-development-kit-cdk-generally-available/\n\nInstall\n-------\n\n.. code-block:: console\n\n    pip install aws-cdk-secure-api\n\nConstructs\n----------\n\n* ``SecureRestApi`` - A construct to create a (public) REST API secured behind an API key, which needs to be\n  specified in the ``x-api-key`` header for all requests.\n\n* ``IAMSecureRestApi`` - A construct to create a (public) REST API secured behind `AWS IAM authentication`_, which\n  requires IAM credentials `to be signed`_ and included in all requests.\n\n.. _to be signed: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-access-control-iam.html\n\nFeatures\n--------\n\n* A CDK Construct which sets up a `RestApi`_ secured behind (one of):\n\n  * API key\n\n    * An API key is `auto-generated`_ and stored in SSM Parameter Store (which is\n      a free service) as needed.\n\n    * Local cache for the API key, so that API calls are not needed in future\n      CDK deployments.\n\n  * `AWS IAM authentication`_\n\n    * An IAM User (and Policy/Role) is created with minimal permissions to call / invoke the API.\n\n    * The IAM User Credentials (Access Keys) are stored in AWS Secrets Manager.\n\n* Helper methods for all constructs, such as ``add_resource_and_lambda_methods``, to make it easier to\n  integrate a method for an AWS Lambda function for example.\n\n.. _`RestApi`: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.RestApi.html\n.. _`auto-generated`: https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetRandomPassword.html\n\nUsage\n-----\n\nThe ``SecureRestApi`` construct represents a Secure REST API in Amazon API Gateway.\n\n    Use ``add_resource``, ``add_lambda_methods``, and ``add_methods`` to\n    configure the API model, as shown below.\n\n**Using a root resource**:\n\n.. code:: python3\n\n    from aws_cdk.aws_apigateway import StageOptions\n    from aws_cdk.aws_lambda import Function, Runtime\n\n    from aws_cdk_secure_api import Http, SecureRestApi\n\n    # noinspection PyTypeChecker\n    py_runtime: Runtime = Runtime.PYTHON_3_10\n\n    get_handler = Function(self, 'lambda1', runtime=py_runtime, ...)\n    put_handler = Function(self, 'lambda2', runtime=py_runtime, ...)\n\n    api = SecureRestApi(\n        self, 'api',\n        rest_api_name='My Secure Service',\n        # optional: specify a deployment stage\n        deploy_options=StageOptions(stage_name='dev')\n    )\n\n    api.add_lambda_methods(get_handler, 'GET')  # GET /\n    api.add_lambda_methods(put_handler, Http.PUT, Http.POST)  # PUT /, POST /\n\n**Using a custom-named resource**:\n\n    Replace above usage of ``add_lambda_methods`` with\n    ``add_resource_and_lambda_methods``, as shown below.\n\n.. code:: python3\n\n    # GET /path1\n    api.add_resource_and_lambda_methods(get_handler, '/path1', 'GET')\n    # PUT /path2, POST /path2\n    api.add_resource_and_lambda_methods(put_handler, '/path2', Http.PUT, Http.POST)\n\nThe ``IAMSecureRestApi`` construct represents a Secure REST API in Amazon API Gateway,\nwhich requires IAM Authorization.\n\n**Using a custom-named resource**:\n\n.. code:: python3\n\n    from aws_cdk.aws_apigateway import StageOptions\n    from aws_cdk.aws_lambda import Function, Runtime\n\n    from aws_cdk_secure_api import Http, IAMConfig, IAMSecureRestApi\n\n    # noinspection PyTypeChecker\n    py_runtime: Runtime = Runtime.PYTHON_3_10\n\n    get_handler = Function(self, 'lambda1', runtime=py_runtime, ...)\n    put_handler = Function(self, 'lambda2', runtime=py_runtime, ...)\n\n    api = IAMSecureRestApi(\n        self, 'api',\n        rest_api_name='My IAM Secure Service',\n        # optional: specify the name of secret to store IAM User Credentials\n        config=IAMConfig(secret_name='my-stack/iam-user-access-keys'),\n        # optional: specify a deployment stage\n        deploy_options=StageOptions(stage_name='dev')\n    )\n\n    # GET /path1\n    api.add_resource_and_lambda_methods(get_handler, '/path1', 'GET')\n    # PUT /path2, POST /path2\n    api.add_resource_and_lambda_methods(put_handler, '/path2', Http.PUT, Http.POST)\n\nTo use an IAM Role instead of attaching a Policy directly to User:\n\n.. code:: python3\n\n    IAMConfig(use_role=True)\n\nAWS Profile\n-----------\n\nNote that if you normally pass the ``--profile`` to the ``cdk`` tool, for example such as::\n\n    cdk deploy --profile my-aws-profile\n\nThe CDK construct won't be able to detect the AWS profile in this particular case.\nA few workarounds can be used for this:\n\n1. The environment variable ``AWS_PROFILE`` can be set before calling the ``cdk`` tool.\n2. The ``profile`` attribute can be passed in to the ``config`` parameter for ``SecureRestApi``.\n3. The ``profile`` context variable can be passed in to the ``cdk`` tool,\n   as shown below::\n\n       cdk deploy --profile my-profile -c profile=my-profile\n\nAPI Keys\n--------\n\nHere is the process that the CDK construct uses for generating\nor using an API key for a REST API.\n\n1. First, it tries to read the API key from local cache, which is located in your\n   home directory, under ``~/.cdk/cache/apigw_api_keys.json``.\n2. If an API key is found, then it proceeds to use the cached key value, and *does not*\n   perform the following steps.\n3. An API call is made to read the key from AWS SSM Parameter Store. The param\n   name is ``/{STACK NAME}/api-key``, where ``{STACK NAME}`` is the name of the CDK stack.\n4. If the parameter does not exist, an random API key value is auto-generated, and a new\n   SSM Parameter is created in the same AWS account and region that the CDK stack is deployed to.\n5. The API key value is then cached on the local drive, under the ``~/.cdk/cache`` folder.\n\nStack Outputs\n-------------\n\nThe following *stack outputs* will additionally be added to the CDK stack:\n\n* ``APIEndpoint`` - The base endpoint of the Secure REST API.\n\n  * *Note:* this output will not show up if ``override_endpoint_name`` is disabled\n    in the ``config`` parameter.\n\n* ``APIKey`` - The API key for the endpoint, which needs to be specified\n  as a value in an HTTP request's ``x-api-key`` header.\n\n* ``APIIAMUserCredentials`` - The URL link (to input in a browser) for the Secret\n  stored in AWS Secrets Manager containing the AWS IAM Credentials for invoking the REST API.\n\n* ``APIIAMRoleARN`` - The ARN of the IAM Role, used in an `AssumeRole`_ API call with the IAM User credentials.\n\n.. _`AssumeRole`: https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html\n\nCredits\n-------\n\nThis package was created with Cookiecutter_ and the `rnag/cookiecutter-pypackage`_ project template.\n\n.. _AWS IAM authentication: https://repost.aws/knowledge-center/iam-authentication-api-gateway\n.. _Cookiecutter: https://github.com/cookiecutter/cookiecutter\n.. _`rnag/cookiecutter-pypackage`: https://github.com/rnag/cookiecutter-pypackage\n\n\n=======\nHistory\n=======\n\n0.5.0 (2023-06-23)\n------------------\n\n**Features and Improvements**\n\n* Add option ``use_role`` in ``IAMConfig``, which when enabled will set up\n  an IAM Role (with permissions to invoke the API) to be assumed by the IAM User,\n  instead of directly attaching an IAM Policy to said User.\n\n0.4.0 (2023-06-22)\n------------------\n\n**Features and Improvements**\n\n* Add IAM Authentication via the new ``IAMSecureRestApi`` construct.\n\n0.3.0 (2023-05-17)\n------------------\n\n**Features and Improvements**\n\n* Add a helper method ``add_resource_and_lambda_methods``, to set up a new\n  API resource, a lambda integration, and setup HTTP method(s) on the\n  new resource at the same time.\n* Update other helper methods -- such as ``add_lambda_methods`` -- to accept\n  an optional ``resource`` parameter, which defaults to the \"root\" API\n  resource (``/``) by default.\n* Add ``test`` parameter (boolean) to ``SecureRestApi`` -- if enabled,\n  then a live API call to AWS SSM (Parameter Store)\n  won't be performed on an initial run, and instead a dummy API key value\n  is used.\n\n0.2.0 (2023-05-17)\n------------------\n\n**Bugfixes**\n\n* Make code compatible with *Python 3.11*.\n\n**Features and Improvements**\n\n* Add *3.11* to the list of supported Python versions.\n\n0.1.1 (2022-06-24)\n------------------\n\n**Bugfixes**\n\n* Remove ``typing.Literal`` usage, so code is compatible with Python 3.7\n* Add an import ``from __future__ import annotations`` to modules where it was missing.\n\n**Features and Improvements**\n\n* Update to use the string value of the ``name`` attribute for a ``Http`` Enum member,\n  instead of the ``value`` attribute.\n\n0.1.0 (2022-06-24)\n------------------\n\n* First release on PyPI.\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A CDK (v2) Construct Library for Secure REST APIs",
    "version": "0.5.0",
    "project_urls": {
        "Documentation": "https://aws-cdk-secure-api.readthedocs.io",
        "Homepage": "https://github.com/rnag/aws-cdk-secure-api",
        "Source": "https://github.com/rnag/aws-cdk-secure-api"
    },
    "split_keywords": [
        "aws-cdk",
        "secure",
        "rest-api",
        "api-gateway",
        "api key",
        "cdk"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "711a0d90ca9a5248fd86b7eaa4a7f1402ddc865b0c2b65f504dc237904b17c78",
                "md5": "12cccc9f10c9776e0ef4957270804c07",
                "sha256": "6c8d7f6f6c2344efbfd9302761def56d0a015c18afe519c56f918095ab2d95bd"
            },
            "downloads": -1,
            "filename": "aws_cdk_secure_api-0.5.0-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "12cccc9f10c9776e0ef4957270804c07",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 16405,
            "upload_time": "2023-06-23T19:20:27",
            "upload_time_iso_8601": "2023-06-23T19:20:27.795420Z",
            "url": "https://files.pythonhosted.org/packages/71/1a/0d90ca9a5248fd86b7eaa4a7f1402ddc865b0c2b65f504dc237904b17c78/aws_cdk_secure_api-0.5.0-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7f99deef5e4c31000811788c8ff5ea355cbf38edac01f59a6b692573c74b0242",
                "md5": "6cb6998799f48ccf6d6d7f7c3a3c9b9f",
                "sha256": "892ec02e63e2a3419e55d026560358e859c969d5d7bf684f9f38d9b14d5fdd56"
            },
            "downloads": -1,
            "filename": "aws-cdk-secure-api-0.5.0.tar.gz",
            "has_sig": false,
            "md5_digest": "6cb6998799f48ccf6d6d7f7c3a3c9b9f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 23627,
            "upload_time": "2023-06-23T19:20:29",
            "upload_time_iso_8601": "2023-06-23T19:20:29.363608Z",
            "url": "https://files.pythonhosted.org/packages/7f/99/deef5e4c31000811788c8ff5ea355cbf38edac01f59a6b692573c74b0242/aws-cdk-secure-api-0.5.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-06-23 19:20:29",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "rnag",
    "github_project": "aws-cdk-secure-api",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "requirements": [],
    "tox": true,
    "lcname": "aws-cdk-secure-api"
}
        
Elapsed time: 0.08541s