fastapi-sqlmodel-security


Namefastapi-sqlmodel-security JSON
Version 0.2.0 PyPI version JSON
download
home_pagehttps://github.com/cwang/fastapi_sqlmodel_security
SummaryAPI key-based security for FastAPI using SQLModel
upload_time2023-10-05 21:34:09
maintainer
docs_urlNone
authorChen Wang
requires_python>=3.10,<4
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # FastAPI Simple Security via SQLModel

[![codecov](https://codecov.io/github/cwang/fastapi_sqlmodel_security/branch/main/graph/badge.svg?token=LHTBNHFVKK)](https://codecov.io/github/cwang/fastapi_sqlmodel_security)
[![Python Tests](https://github.com/cwang/fastapi_sqlmodel_security/actions/workflows/pr_python_tests.yml/badge.svg)](https://github.com/cwang/fastapi_sqlmodel_security/actions/workflows/pr_python_tests.yml)
[![Linting](https://github.com/cwang/fastapi_sqlmodel_security/actions/workflows/push_linting.yml/badge.svg)](https://github.com/cwang/fastapi_sqlmodel_security/actions/workflows/push_linting.yml)

[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![pre-commit enabled][pre-commit badge]][pre-commit project]
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white)](https://conventionalcommits.org)

[pre-commit badge]: <https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white>
[pre-commit project]: <https://pre-commit.com/>

(This is forked from [FastAPI Simple Security](https://github.com/mrtolkien/fastapi_simple_security/) with an SQLModel adaption. Credits to the original author!)

API key based security package for FastAPI, focused on simplicity of use:

- Full functionality out of the box, no configuration required
- API key security with local `sqlite` backend, working with both header and query parameters
- Default 15 days deprecation for generated API keys
- Key creation, revocation, renewing, and usage logs handled through administrator endpoints
- No dependencies, only requiring `FastAPI` and the python standard library

This module cannot be used for any kind of distributed deployment. It's goal is to help have some basic security features
for simple one-server API deployments, mostly during development.

## Installation

`pip install fastapi_sqlmodel_security`

### Usage

### Creating an application

The key is to configure an instance of [data store](./fastapi_sqlmodel_security/data_store.py), which can usually be done with `SqlModelDataStore` as shown below.

```python
from fastapi_sqlmodel_security import create_auth_router, ApiKeySecurity, DataStore, SqlModelDataStore
from fastapi import Depends, FastAPI

app = FastAPI()

data_store = SqlModelDataStore(conn_url="sqlite3:///keys.db")

app.include_router(create_auth_router(data_store), prefix="/auth", tags=["_auth"])

@app.get("/secure", dependencies=[Depends(ApiKeySecurity(data_store))])
async def secure_endpoint():
    return {"message": "This is a secure endpoint"}
```

Both the auth router and your own routes would need dependencies to be configured with the aforementioned data store.

Resulting app is:

![app](./images/auth_endpoints.png)

More can be found in the [demo app](./app/main.py). 

### API key creation through docs

Start your API and check the logs for the automatically generated secret key if you did not provide one through
environment variables.

![secret](./images/secret.png)

Go to `/docs` on your API and inform this secret key in the `Authorize/Secret header` box.
All the administrator endpoints only support header security to make sure the secret key is not inadvertently
shared when sharing an URL.

![secret_header](./images/secret_header.png)

Then, you can use `/auth/new` to generate a new API key.

![api key](./images/new_api_key.png)

And finally, you can use this API key to access the secure endpoint.

![secure endpoint](./images/secure_endpoint.png)

### API key creation in python

You can of course automate API key acquisition through python with `requests` and directly querying the endpoints.

If you do so, you can hide the endpoints from your API documentation with the environment variable
`FASTAPI_SQLMODEL_SECURITY_HIDE_DOCS`.

## Configuration

Environment variables:

- `FASTAPI_SQLMODEL_SECURITY_SECRET`: Secret administrator key

  - Generated automatically on server startup if not provided
  - Allows generation of new API keys, revoking of existing ones, and API key usage view
  - It being compromised compromises the security of the API

- `FASTAPI_SQLMODEL_SECURITY_HIDE_DOCS`: Whether or not to hide the API key related endpoints from the documentation

- `FASTAPI_SQLMODEL_SECURITY_AUTOMATIC_EXPIRATION`: Duration, in days, until an API key is deemed expired
  - 15 days by default

## Contributing

### Setting up python environment

```shell script
poetry install
poetry shell
```

### Setting up pre-commit hooks

```shell script
pre-commit install
```

### Running tests

```shell script
pytest
```

### Running the dev environment

The attached docker image runs a test app on `localhost:8080` with secret key `TEST_SECRET`. Run it with:

```shell script
docker-compose build && docker-compose up
```

## Needed contributions

- More options with sensible defaults
- Logging per API key?
- More back-end options for API key storage?

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/cwang/fastapi_sqlmodel_security",
    "name": "fastapi-sqlmodel-security",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.10,<4",
    "maintainer_email": "",
    "keywords": "",
    "author": "Chen Wang",
    "author_email": "dev@chenwang.org",
    "download_url": "https://files.pythonhosted.org/packages/72/3f/76d9ffacd700f0e715cc79952d60888256e032056c6f0f6f5a362607971d/fastapi_sqlmodel_security-0.2.0.tar.gz",
    "platform": null,
    "description": "# FastAPI Simple Security via SQLModel\n\n[![codecov](https://codecov.io/github/cwang/fastapi_sqlmodel_security/branch/main/graph/badge.svg?token=LHTBNHFVKK)](https://codecov.io/github/cwang/fastapi_sqlmodel_security)\n[![Python Tests](https://github.com/cwang/fastapi_sqlmodel_security/actions/workflows/pr_python_tests.yml/badge.svg)](https://github.com/cwang/fastapi_sqlmodel_security/actions/workflows/pr_python_tests.yml)\n[![Linting](https://github.com/cwang/fastapi_sqlmodel_security/actions/workflows/push_linting.yml/badge.svg)](https://github.com/cwang/fastapi_sqlmodel_security/actions/workflows/push_linting.yml)\n\n[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![pre-commit enabled][pre-commit badge]][pre-commit project]\n[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white)](https://conventionalcommits.org)\n\n[pre-commit badge]: <https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white>\n[pre-commit project]: <https://pre-commit.com/>\n\n(This is forked from [FastAPI Simple Security](https://github.com/mrtolkien/fastapi_simple_security/) with an SQLModel adaption. Credits to the original author!)\n\nAPI key based security package for FastAPI, focused on simplicity of use:\n\n- Full functionality out of the box, no configuration required\n- API key security with local `sqlite` backend, working with both header and query parameters\n- Default 15 days deprecation for generated API keys\n- Key creation, revocation, renewing, and usage logs handled through administrator endpoints\n- No dependencies, only requiring `FastAPI` and the python standard library\n\nThis module cannot be used for any kind of distributed deployment. It's goal is to help have some basic security features\nfor simple one-server API deployments, mostly during development.\n\n## Installation\n\n`pip install fastapi_sqlmodel_security`\n\n### Usage\n\n### Creating an application\n\nThe key is to configure an instance of [data store](./fastapi_sqlmodel_security/data_store.py), which can usually be done with `SqlModelDataStore` as shown below.\n\n```python\nfrom fastapi_sqlmodel_security import create_auth_router, ApiKeySecurity, DataStore, SqlModelDataStore\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\ndata_store = SqlModelDataStore(conn_url=\"sqlite3:///keys.db\")\n\napp.include_router(create_auth_router(data_store), prefix=\"/auth\", tags=[\"_auth\"])\n\n@app.get(\"/secure\", dependencies=[Depends(ApiKeySecurity(data_store))])\nasync def secure_endpoint():\n    return {\"message\": \"This is a secure endpoint\"}\n```\n\nBoth the auth router and your own routes would need dependencies to be configured with the aforementioned data store.\n\nResulting app is:\n\n![app](./images/auth_endpoints.png)\n\nMore can be found in the [demo app](./app/main.py). \n\n### API key creation through docs\n\nStart your API and check the logs for the automatically generated secret key if you did not provide one through\nenvironment variables.\n\n![secret](./images/secret.png)\n\nGo to `/docs` on your API and inform this secret key in the `Authorize/Secret header` box.\nAll the administrator endpoints only support header security to make sure the secret key is not inadvertently\nshared when sharing an URL.\n\n![secret_header](./images/secret_header.png)\n\nThen, you can use `/auth/new` to generate a new API key.\n\n![api key](./images/new_api_key.png)\n\nAnd finally, you can use this API key to access the secure endpoint.\n\n![secure endpoint](./images/secure_endpoint.png)\n\n### API key creation in python\n\nYou can of course automate API key acquisition through python with `requests` and directly querying the endpoints.\n\nIf you do so, you can hide the endpoints from your API documentation with the environment variable\n`FASTAPI_SQLMODEL_SECURITY_HIDE_DOCS`.\n\n## Configuration\n\nEnvironment variables:\n\n- `FASTAPI_SQLMODEL_SECURITY_SECRET`: Secret administrator key\n\n  - Generated automatically on server startup if not provided\n  - Allows generation of new API keys, revoking of existing ones, and API key usage view\n  - It being compromised compromises the security of the API\n\n- `FASTAPI_SQLMODEL_SECURITY_HIDE_DOCS`: Whether or not to hide the API key related endpoints from the documentation\n\n- `FASTAPI_SQLMODEL_SECURITY_AUTOMATIC_EXPIRATION`: Duration, in days, until an API key is deemed expired\n  - 15 days by default\n\n## Contributing\n\n### Setting up python environment\n\n```shell script\npoetry install\npoetry shell\n```\n\n### Setting up pre-commit hooks\n\n```shell script\npre-commit install\n```\n\n### Running tests\n\n```shell script\npytest\n```\n\n### Running the dev environment\n\nThe attached docker image runs a test app on `localhost:8080` with secret key `TEST_SECRET`. Run it with:\n\n```shell script\ndocker-compose build && docker-compose up\n```\n\n## Needed contributions\n\n- More options with sensible defaults\n- Logging per API key?\n- More back-end options for API key storage?\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "API key-based security for FastAPI using SQLModel",
    "version": "0.2.0",
    "project_urls": {
        "Homepage": "https://github.com/cwang/fastapi_sqlmodel_security",
        "Repository": "https://github.com/cwang/fastapi_sqlmodel_security"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1233cabd411a6366cc5c0ef49848c1f850908dcfd775d0e96fec0ee4740bef4a",
                "md5": "84ef06a02b65f8ef466d89eba1c538d0",
                "sha256": "716174d61b7ed882650a83e4f46a3f838deec46f28d1076e070bc22a25e87efd"
            },
            "downloads": -1,
            "filename": "fastapi_sqlmodel_security-0.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "84ef06a02b65f8ef466d89eba1c538d0",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10,<4",
            "size": 8997,
            "upload_time": "2023-10-05T21:34:08",
            "upload_time_iso_8601": "2023-10-05T21:34:08.167151Z",
            "url": "https://files.pythonhosted.org/packages/12/33/cabd411a6366cc5c0ef49848c1f850908dcfd775d0e96fec0ee4740bef4a/fastapi_sqlmodel_security-0.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "723f76d9ffacd700f0e715cc79952d60888256e032056c6f0f6f5a362607971d",
                "md5": "5941380b8bc2ec192d127f23006d996f",
                "sha256": "f692388a7a4471cf5a165b65bc8d62d049b18d070d4f8b5ce58a42aa79e26e6f"
            },
            "downloads": -1,
            "filename": "fastapi_sqlmodel_security-0.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "5941380b8bc2ec192d127f23006d996f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10,<4",
            "size": 6787,
            "upload_time": "2023-10-05T21:34:09",
            "upload_time_iso_8601": "2023-10-05T21:34:09.644205Z",
            "url": "https://files.pythonhosted.org/packages/72/3f/76d9ffacd700f0e715cc79952d60888256e032056c6f0f6f5a362607971d/fastapi_sqlmodel_security-0.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-05 21:34:09",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "cwang",
    "github_project": "fastapi_sqlmodel_security",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "fastapi-sqlmodel-security"
}
        
Elapsed time: 0.12877s