pax_global_header00006660000000000000000000000064147737152130014524gustar00rootroot0000000000000052 comment=02f68e85d2e51f8a2049cb15ee4d5466d38cf1db djangorestframework-api-key-3.1.0/000077500000000000000000000000001477371521300171405ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/.coveragerc_dj22000066400000000000000000000001011477371521300220720ustar00rootroot00000000000000[report] exclude_lines = pragma: no cover pragma: nodj22 djangorestframework-api-key-3.1.0/.github/000077500000000000000000000000001477371521300205005ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/.github/ISSUE_TEMPLATE/000077500000000000000000000000001477371521300226635ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000012641477371521300253600ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS: [e.g. Linux] - Version: [e.g. 0.2.2] - Python Version: [e.g. 3.7] - Django Version: [e.g. 2.1] - DRF Version: [e.g. 3.8.2] **Additional context** Add any other context about the problem here. djangorestframework-api-key-3.1.0/.github/ISSUE_TEMPLATE/discussion.md000066400000000000000000000002141477371521300253650ustar00rootroot00000000000000--- name: Discussion/Other about: Discuss something that is not a bug report or a feature request. --- It's free form! Just start typing. djangorestframework-api-key-3.1.0/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000010601477371521300264050ustar00rootroot00000000000000--- name: Feature request about: Suggest an idea for this project --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. djangorestframework-api-key-3.1.0/.gitignore000066400000000000000000000023371477371521300211350ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ # databases *.sqlite3 .idea/ .ruff_cache/ djangorestframework-api-key-3.1.0/CHANGELOG.md000066400000000000000000000136421477371521300207570ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## 3.1.0 - 2025-04-04 ### Added - Add official support for Python 3.12 and 3.13, and Django 5.0 up to 5.2, accomodating changes to `USE_TZ`. (Pull #266) ## 3.0.0 - 2023-09-30 ### Changed - Use faster SHA512-based key hasher instead of password hashers. Reduces server load by making API key validation orders of magnitude faster (10x to 30x according to estimations, network latency aside). Hashed key will be transparently upgraded the first time `.is_valid()` is called. (Pull #244, Pull #251) ### Removed - Dropped support for Python 3.7, which has reached EOL. (Pull #247) - Drop redundant `.has_object_permission()` implementation on `BaseHasAPIKey` when using DRF 3.14.0 or above. (Pull #240) ### Added - Add official support for Python 3.11. (Pull #247) ## 2.3.0 - 2023-01-19 ### Removed - Drop support for Python 3.6, which has reached EOL. (Pull #210) ### Fixed - Fix migration 0004 when run against a non default database. (Pull #215) ## 2.2.0 - 2022-03-11 ### Added - Added support for Django config detection for different versions (PR #187) ### Changed - Add official support for Django 3.2 and Python 3.9 and 3.10 (PR #189) - Bumped `hashed_key` field's `max_length` from 100 to 150 to address length issue with `argon2-cffi` (PR #193) ## 2.1.0 - 2021-09-24 ### Added - Add support for custom API `keyword`. (Pull #175) ## 2.0.0 - 2020-04-07 **NOTE**: this release drops compatibility with certain Python and Django versions, but contains no other breaking changes. See [Upgrade to 2.0](https://florimondmanca.github.io/djangorestframework-api-key/upgrade/2.0/) for detailed migration steps. ### Removed - Dropped support for Django 2.0 and Django 2.1. (Pull #126) - Dropped support for Python 3.5. (Pull #84) ### Added - Add support for Django 3.0. (Pull #82) - Add support for Python 3.8. (Pull #81) - Add `BaseAPIKeyManager.get_from_key()` to allow retrieving API keys from views. (Pull #93) - Add type annotations, and partial support for `django-stubs` and `djangorestframework-stubs`. (Pull #88, Pull #122) ## 1.4.1 - 2019-08-24 ### Added - Now ships with type annotations ([PEP 561](https://www.python.org/dev/peps/pep-0561/)). (Pull #73) ## 1.4.0 - 2019-07-16 **NOTE**: this release contains migrations. See [Upgrade to v1.4](https://florimondmanca.github.io/djangorestframework-api-key/upgrade/1.4/) for detailed instructions. ### Added - The `prefix` and `hashed_key` are now stored in dedicated fields on the `APIKey` model. (Pull #62) ## 1.3.0 - 2019-06-28 **NOTE**: this release contains migrations. In your Django project, run them using: ```python python manage.py migrate rest_framework_api_key ``` ### Added - Add abstract API key model (`AbstractAPIKey`) and base manager (`BaseAPIKeyManager`). (Pull #36) - Add base permissions (`BaseHasAPIKey`). (Pull #46) ### Changed - The `id` field of `APIKey` is now non-`editable`. - `APIKeyModelAdmin` does not define `fieldsets` anymore. This allows subclasses to benefit from Django's automatic fieldsets. (Pull #52) ### Fixed - Explicitly use `utf-8` encoding in `setup.py`, which could previously lead to issues when installing on certain systems. (Pull #58) ## 1.2.1 - 2019-06-03 ### Fixed - Fixed a critical bug in `APIKeyModelAdmin` that prevented `rest_framework_api_key` from passing Django system checks. (Pull #39) ## 1.2.0 - 2019-05-29 **NOTE**: this release contains migrations. In your Django project, run them using: ```python python manage.py migrate rest_framework_api_key ``` ### Added - API keys can now have an optional `expiry_date`. (Pull #33) `HasAPIKey` denies access if the API key has expired, i.e. if `expiry_date`, if set, is in the past. - It is now possible to search by `prefix` in the API key admin panel. - The `prefix` is now displayed in the edit view of the API key admin panel. ## 1.1.0 - 2019-05-14 ### Added - Improve documentation on which password hasher is used. - Add tests against the Argon2, BcryptSHA256 and PBKDF2SHA1 hashers. (Pull #32) ### Fixed - Fix support for password hashers that generate hashes that contain dots. (Pull #31) ## 1.0.0 - 2019-04-24 **This release is incompatible with 0.x**. See [Upgrade to 1.0](https://florimondmanca.github.io/djangorestframework-api-key/upgrade/1.4/) for migration steps. ### Removed - Remove `HasAPIKeyOrIsAuthenticated` permission class. You should use bitwise composition now, e.g. `HasAPIKey | IsAuthenticated`. - Drop the `DRF_API_KEY_*` settings. (Pull #19) ### Changed - Switch to a new API key generation and validation scheme. Clients must now authorize using a single API key header (Pull #19). The header is `Authorization` by default. It can be customized using the `API_KEY_CUSTOM_HEADER` setting (Pull #26). Use the `name` field to identify clients. ### Added - Add support for Django 2.2. (Pull #27) - Add programmatic API key creation using `APIKey.objects.create_key()`. (Pull #19) ### Fixed - Improved API key storage using Django's password hashing helpers. (Uses the default Django password hasher.) (Pull #19) ## 0.4.0 - 2019-04-21 ### Removed - Drop support for Python 3.4. Only 3.5, 3.6 and 3.7 are supported now. - Drop support for Django < 2.0. Only 2.0 and 2.1 are supported now. ### Fixed - `HasAPIKey` now implements `.has_object_permissions()`, which allows to compose it with other permission classes and perform object-level permission checks. (Pull #25) ## 0.3.1 - 2018-11-17 _Initial changelog entry._ ### Added - `APIKey` model. - `HasAPIKey` and `HasAPIKeyOrIsAuthenticated` permission classes. - Generate, view and revoke API keys from the Django admin. - Authenticate requests using the `Api-Token` and `Api-Secret-Key` headers. Customizable via the `DRF_API_KEY_TOKEN_HEADER` and `DRF_API_KEY_SECRET_KEY_HEADER` settings. djangorestframework-api-key-3.1.0/CONTRIBUTING.md000066400000000000000000000041741477371521300213770ustar00rootroot00000000000000# Contributing Thanks for your interest in contributing to this project! Here are a few ways in which you can help: - Discovered a bug? Please open a [bug report](https://github.com/florimondmanca/djangorestframework-api-key/issues/new?template=bug_report.md). - Have a feature you'd like to see implemented? Please open a [Feature Request](https://github.com/florimondmanca/djangorestframework-api-key/issues/new?template=feature_request.md). - For any other contribution, please open a [discussion](https://github.com/florimondmanca/djangorestframework-api-key/issues/new?template=discussion.md). **NOTE**: for **non-trivial changes** we _highly_ encourage you to **open an issue** first. This will allow maintainers and contributors to confirm that the problem you are trying to solve is well-posed, in the scope of the project, and/or can't be solved with existing features. ### Installation 1. Fork the repository. 1. Clone it on your machine. 1. Install dependencies: ``` make install ``` ### Tests Run the tests using: ``` make test ``` ### Code style Run code auto-formatting with: ``` make format ``` Run code style checks using: ``` make check ``` ### Generating migrations This package includes migrations. To update them in case of changes without setting up a Django project, run: ``` make migrations ``` ### Documentation Build the documentation using: ``` make docs ``` Serve the docs site locally (with hot-reload) using: ``` make docs-serve ``` ## Notes to maintainers ### Releasing - Create a release PR with the following: - Bump the package version by editing `__version__.py`. - Update the changelog with any relevant PRs merged since the last version: bug fixes, new features, changes, deprecations, removals. - Once the release PR is merged, create a [new release](https://github.com/florimondmanca/djangorestframework-api-key/releases/new), including: - Tag version, like `2.1.0`. - Release title, `Version 2.1.0`. - Description copied from the changelog. - Once created, this release will be automatically uploaded to PyPI via a publish job on Azure Pipelines. - Deploy the docs using: `make docs-deploy` djangorestframework-api-key-3.1.0/LICENSE000066400000000000000000000020601477371521300201430ustar00rootroot00000000000000MIT License Copyright (c) 2018 Florimond Manca Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. djangorestframework-api-key-3.1.0/MANIFEST.in000066400000000000000000000001011477371521300206660ustar00rootroot00000000000000graft src include README.md include CHANGELOG.md include LICENSE djangorestframework-api-key-3.1.0/Makefile000066400000000000000000000014411477371521300206000ustar00rootroot00000000000000.PHONY: docs venv = venv bin = ${venv}/bin/ pysources = src/ test_project/ tests/ build: ${bin}python -m build check: ${bin}ruff check ${pysources} ${bin}black --check --diff ${pysources} ${bin}mypy ${pysources} make migrations-check docs: ${bin}mkdocs build docs-serve: ${bin}mkdocs serve docs-deploy: ${bin}mkdocs gh-deploy install: install-python venv: python3 -m venv ${venv} install-python: venv ${bin}pip install -U pip wheel ${bin}pip install -U build ${bin}pip install -r requirements.txt ./tools/install_django.sh ${bin}pip format: ${bin}ruff check --fix ${pysources} ${bin}black ${pysources} migrations: ${bin}python -m tools.makemigrations migrations-check: ${bin}python -m tools.makemigrations --check publish: ${bin}twine upload dist/* test: ${bin}pytest djangorestframework-api-key-3.1.0/README.md000066400000000000000000000100041477371521300204120ustar00rootroot00000000000000# Django REST Framework API Key API key permissions for the [Django REST Framework](https://www.django-rest-framework.org).
build status coverage package version
python versions django versions drf versions
## Introduction **Django REST Framework API Key is a library for allowing server-side clients to safely use your API.** These clients are typically third-party backends and services (i.e. _machines_) which do not have a user account but still need to interact with your API in a secure way. ### Features - ✌️ **Simple to use**: create, view and revoke API keys via the admin site, or use built-in helpers to create API keys programmatically. - πŸ”’ **As secure as possible**: API keys are treated with the same level of care as user passwords. They are only visible at creation and hashed before storing in the database. - 🎨 **Customizable**: satisfy specific business requirements by building your own customized API key models, permission classes and admin panels. ### Should I use API keys? There are important security aspects you need to consider before switching to an API key access control scheme. We've listed some of these in [Security caveats](docs/security.md#caveats), including serving your API over HTTPS. Besides, see [Why and when to use API keys](https://cloud.google.com/endpoints/docs/openapi/when-why-api-key#top_of_page) for hints on whether API keys can fit your use case. API keys are ideal in the following situations: - Blocking anonymous traffic. - Implementing API key-based [throttling](https://www.django-rest-framework.org/api-guide/throttling/). (Note that Django REST Framework already has may built-in utilities for this use case.) - Identifying usage patterns by logging request information along with the API key. They can also present enough security for authorizing internal services, such as your API server and an internal frontend application. > Please note that this package is NOT meant for authentication. You should NOT use this package to identify individual users, either directly or indirectly. > > If you need server-to-server authentication, you may want to consider OAuth instead. Libraries such as [django-oauth-toolkit](https://django-oauth-toolkit.readthedocs.io/en/latest/index.html) can help. ## Quickstart Install with `pip`: ```bash pip install "djangorestframework-api-key==3.*" ``` _**Note**: It is highly recommended to **pin your dependency** to the latest major version (as depicted above), as breaking changes may and will happen between major releases._ Add the app to your `INSTALLED_APPS`: ```python # settings.py INSTALLED_APPS = [ # ... "rest_framework", "rest_framework_api_key", ] ``` Run the included migrations: ```bash python manage.py migrate ``` To learn how to configure permissions and manage API keys, head to the [Documentation](https://florimondmanca.github.io/djangorestframework-api-key). ## Changelog See [CHANGELOG.md](https://github.com/florimondmanca/djangorestframework-api-key/tree/master/CHANGELOG.md). ## Contributing See [CONTRIBUTING.md](https://github.com/florimondmanca/djangorestframework-api-key/tree/master/CONTRIBUTING.md). ## License MIT djangorestframework-api-key-3.1.0/ci/000077500000000000000000000000001477371521300175335ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/ci/azure-pipelines.yml000066400000000000000000000036231477371521300233760ustar00rootroot00000000000000resources: repositories: - repository: templates type: github endpoint: github name: florimondmanca/azure-pipelines-templates ref: refs/tags/6.3 containers: - container: pg15 image: postgres:15-alpine ports: - 5432:5432 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: default trigger: - master - refs/tags/* pr: - master variables: - name: CI value: "true" - name: PIP_CACHE_DIR value: $(Pipeline.Workspace)/.cache/pip - group: pypi-credentials stages: - stage: test jobs: - template: job--python-check.yml@templates parameters: pythonVersion: "3.13" - template: job--python-docs-build.yml@templates parameters: pythonVersion: "3.13" - template: job--python-test.yml@templates parameters: jobs: py38_dj22: variables: DJANGO_VERSION: "2.2.*" PYTEST_ADDOPTS: "--cov-config=.coveragerc_dj22" py38_dj32: coverage: true variables: DJANGO_VERSION: "3.2.*" py311_dj42: coverage: true variables: DJANGO_VERSION: "4.2.*" PYTEST_ADDOPTS: "--cov=tests" py313_dj52: coverage: true variables: DJANGO_VERSION: "5.2.*" PYTEST_ADDOPTS: "--cov=tests" py313_postgres: services: postgres: pg15 variables: DATABASE_URL: "postgresql://postgres:postgres@localhost:5432/default" - stage: publish condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/') jobs: - template: job--python-publish.yml@templates parameters: token: $(pypiToken) pythonVersion: "3.13" djangorestframework-api-key-3.1.0/docs/000077500000000000000000000000001477371521300200705ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/docs/guide.md000066400000000000000000000401701477371521300215110ustar00rootroot00000000000000# User Guide ## Getting started ### Installation Install with `pip`: ```bash pip install "djangorestframework-api-key==3.*" ``` _**Note**: It is highly recommended to **pin your dependency** to the latest major version (as depicted above), as breaking changes may and will happen between major releases._ ### Project setup Add the app to your `INSTALLED_APPS`: ```py # settings.py INSTALLED_APPS = [ # ... "rest_framework", "rest_framework_api_key", ] ``` Run the included migrations: ```bash python manage.py migrate ``` ### Setting permissions The `HasAPIKey` permission class protects a view behind API key authorization. You can set the permission globally: ```python # settings.py REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": [ "rest_framework_api_key.permissions.HasAPIKey", ] } ``` or on a per-view basis: ```python # views.py from rest_framework.views import APIView from rest_framework_api_key.permissions import HasAPIKey class UserListView(APIView): permission_classes = [HasAPIKey] # ... ``` See also [Setting the permission policy](http://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy) for more information on using permission classes in the Django REST Framework. !!! tip You can use the bitwise operators `|` and `&` to compose `HasAPIKey` with other permission classes and achieve more complex authorization behaviour. For example, to require a valid API key _or_ authentication credentials, use: ```python from rest_framework.permissions import IsAuthenticated from rest_framework_api_key.permissions import HasAPIKey # ... permission_classes = [HasAPIKey | IsAuthenticated] ``` ### Manually validating API keys You can also manually validate an API key with the `APIKey` objects manager using the `is_valid()` method on the manager lke below. This is useful for validating API keys outside of a normal Django view, such as inside a websocket consumer from Django Channels. ```python from rest_framework_api_key.permissions import APIKey # this should be a string containing only the API key - remove any additional text like "Api-Key" if present raw_key = "XXXXXXXX.XXXXXXXXXX" is_valid_key = APIKey.objects.is_valid(raw_key) ``` ### Making authorized requests #### Authorization header By default, clients must pass their API key via the `Authorization` header. It must be formatted as follows: ``` Authorization: Api-Key ``` where `` refers to the full generated API key (see [Creating and managing API keys](#creating-and-managing-api-keys) below). To know under which conditions access is granted, please see [Grant scheme](security.md#grant-scheme). If wanting to also customize the keyword used for parsing the Api-Key, please see [API key Custom Keyword](guide.md#api-key-custom-keyword) #### Custom header You can set the `API_KEY_CUSTOM_HEADER` setting to a non-`None` value to require clients to pass their API key in a custom header instead of the `Authorization` header. This is useful if you plan to use API keys _AND_ an authentication scheme which already uses the `Authorization` header (e.g. token-based authentication). For example, if you set: ```python # settings.py API_KEY_CUSTOM_HEADER = "HTTP_X_API_KEY" ``` then clients must make authorized requests using: ``` X-Api-Key: ``` where `` refers to the full generated API key. Please refer to [HttpRequest.META](https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.HttpRequest.META) for more information on headers in Django. ### Creating and managing API keys #### Admin site When it is installed, `djangorestframework-api-key` adds an "API Key Permissions" section to the Django admin site where you can create, view and revoke API keys. !!! note Upon creating an API key from the admin, the full API key is shown only once in a success message banner. **This is what should be passed in authorization headers.** After creation, only the prefix of the API key is shown in the admin site, mostly for identification purposes. If you lose the full API key, you'll need to regenerate a new one. #### Programmatic usage API keys can be created, viewed, revoked, and validated programmatically by manipulating the `APIKey` model. - You can validate API keys manually, see the "Manually validating API keys" section above. !!! note The examples below use the [Django shell](https://docs.djangoproject.com/en/2.2/ref/django-admin/#django-admin-shell). - You can view and query `APIKey` like any other model. For example, to know the total number of API keys: ```python >>> from rest_framework_api_key.models import APIKey >>> APIKey.objects.count() 42 ``` - If you wish to create an API key programmatically, you'll most likely want a one-time access to its generated key too. To do so, use the `.create_key()` method on the `APIKey` objects manager instead of `.create()`: ```python >>> from rest_framework_api_key.models import APIKey >>> api_key, key = APIKey.objects.create_key(name="my-remote-service") >>> # Proceed with `api_key` and `key`... ``` !!! danger To prevent leaking API keys, you must only give the `key` **to the client that triggered its generation**. In particular, **do not keep any trace of it on the server**. - To retrieve an `APIKey` instance based on its generated key (which is not stored in the database) use the `.get_from_key()` method on the `APIKey` objects manager instead of `.get()`. This is useful if you'd like to access an `APIKey` object from a view protected by a `HasAPIKey` permission. ```python from rest_framework.views import APIView from rest_framework_api_key.models import APIKey from rest_framework_api_key.permissions import HasAPIKey from .models import Project class ProjectListView(APIView): permission_classes = [HasAPIKey] def get(self, request): """Retrieve a project based on the request API key.""" key = request.META["HTTP_AUTHORIZATION"].split()[1] api_key = APIKey.objects.get_from_key(key) project = Project.objects.get(api_key=api_key) ``` ## Customization This package provides various customization APIs that allow you to extend its basic behavior. ### API key models If the built-in `APIKey` model doesn't fit your needs, you can create your own by subclassing `AbstractAPIKey`. This is particularly useful if you need to **store extra information** or **link API keys to other models** using a `ForeignKey` or a `ManyToManyField`. !!! warning Associating API keys to users, directly or indirectly, can present a security risk. See also: [Should I use API keys?](https://florimondmanca.github.io/djangorestframework-api-key/#should-i-use-api-keys). #### Example Here's how you could link API keys to an imaginary `Organization` model: ```python # organizations/models.py from django.db import models from rest_framework_api_key.models import AbstractAPIKey class Organization(models.Model): name = models.CharField(max_length=128) active = models.BooleanField(default=True) class OrganizationAPIKey(AbstractAPIKey): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="api_keys", ) ``` If you need to customize the model's `Meta`, it should inherit from `AbstractAPIKey.Meta`: ```python class OrganizationAPIKey(AbstractAPIKey): # ... class Meta(AbstractAPIKey.Meta): verbose_name = "Organization API key" verbose_name_plural = "Organization API keys" ``` #### Migrations Because `AbstractAPIKey` is an [abstract model](https://docs.djangoproject.com/en/2.2/topics/db/models/#abstract-base-classes), the custom API key model will have its own table in the database. This means that you need to **generate a migration** and then **apply it** to be able to query the new API key model: ```bash python manage.py makemigrations python manage.py migrate ``` !!! important If `AbstractAPIKey` changes (e.g. because of an update to Django REST Framework API Key), you will need to **generate and apply migrations again** to account for these changes. #### Managers The `APIKey` model as well as custom API keys models inherited from `AbstractAPIKey` have a dedicated [manager](https://docs.djangoproject.com/en/2.2/topics/db/managers) which is responsible for implementing `.create_key()` and other important behavior. As a result, if you want to build a custom API key manager, it should inherit from `BaseAPIKeyManager` instead of Django's `Manager`. Besides [customization APIs that come with Django's managers](https://docs.djangoproject.com/en/2.2/topics/db/managers/#custom-managers), `BaseAPIKeyManager` gives you one extra hook: you can override `.get_usable_keys()` to customize which set of API keys clients can use in authorized requests. For example, here's how to restrict usable keys to those of active organizations only: ```python class OrganizationAPIKeyManager(BaseAPIKeyManager): def get_usable_keys(self): return super().get_usable_keys().filter(organization__active=True) ``` !!! check Note the call to the parent implementation using `super()` here. This is because `.get_usable_keys()` has some default behavior, including making sure that revoked API keys cannot be used. !!! tip You don't need to use a custom model to use a custom manager β€” it can be used on the built-in `APIKey` model as well. #### Admin panel If you'd like to view and manage your custom API key model via the [Django admin site](https://docs.djangoproject.com/en/2.2/ref/contrib/admin/), you can create and register a subclass of `APIKeyModelAdmin`: ```python # organizations/admin.py from django.contrib import admin from rest_framework_api_key.admin import APIKeyModelAdmin from .models import OrganizationAPIKey @admin.register(OrganizationAPIKey) class OrganizationAPIKeyModelAdmin(APIKeyModelAdmin): pass ``` You can also customize any of the default attributes defined in `APIKeyModelAdmin`. For example, to display the organization's name in the list view, and allow searching `OrganizationAPIKey` instances by organization name while keeping the original search behavior, you can write: ```python list_display = [*APIKeyModelAdmin.list_display, "organization__name"] search_fields = [*APIKeyModelAdmin.search_fields, "organization__name"] ``` !!! question "How can I display API keys on the detail page of a related model instance?" In theory, this could be done using Django's [`InlineModelAdmin`](https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#inlinemodeladmin-objects). However, due to the limitations of inlines, this cannot be easily achieved while correctly saving and displaying the generated key in the detail page of the related model. As an alternative, you can use the `.list_filter` class attribute to filter API keys by an identifying field on the related model. In the examples above, you could use `organization__name` to filter API keys by organization. ### Permission classes The built-in `HasAPIKey` permission class only checks against the built-in `APIKey` model. This means that if you use a custom API key model, you need to create a **custom permission class** for your application to validate API keys against it. You can do so by subclassing `BaseHasAPIKey` and specifying the `.model` class attribute: ```python # organizations/permissions.py from rest_framework_api_key.permissions import BaseHasAPIKey from .models import OrganizationAPIKey class HasOrganizationAPIKey(BaseHasAPIKey): model = OrganizationAPIKey ``` You can then use `HasOrganizationAPIKey` as described in [Setting permissions](#setting-permissions). !!! tip If you need to customize `.has_permission()` or `.has_object_permission()`, feel free to read the [source code](https://github.com/florimondmanca/djangorestframework-api-key/blob/master/src/rest_framework_api_key/permissions.py). #### API key parsing By default, API key permission classes retrieve the API key from the `Authorization` header or a custom header, as described in [Making authorized requests](#making-authorized-requests). You can customize or override this behavior in several ways. If you are building an API for an application you do not control that requires a specific header keyword, e.g. a client that sends API keys using the `Bearer` keyword as follows: ``` Authorization: Bearer ``` Then you can subclass `KeyParser` with a custom `keyword`, and attach it to a custom permission class, like so: ```python # settings.py from rest_framework_api_key.models import HasAPIKey from rest_framework_api_key.permissions import BaseHasAPIKey, KeyParser class BearerKeyParser(KeyParser): keyword = "Bearer" class HasAPIKey(BaseHasAPIKey): model = APIKey # Or a custom model key_parser = BearerKeyParser() ``` You can also override the default header-based parsing completely. To do so, redefine the `.get_key()` method on your custom permission class. This method accepts the [HttpRequest](https://docs.djangoproject.com/en/2.2/ref/request-response/#httprequest-objects) object as unique argument and should return the API key as an `str` if one was found, or `None` otherwise. For example, here's how you could retrieve the API key from a cookie: ```python class HasAPIKey(BaseHasAPIKey): model = APIKey # Or a custom model def get_key(self, request): return request.COOKIES.get("api_key") ``` If your custom key parsing algorithm is more complex, you may want to define it as a separate component. To do so, build a key parser class, which must implement the `.get()` method with the same signature as `.get_key()`, then set it as the `.key_parser`, as follows: ```python class CookieKeyParser: def get(self, request): cookie_name = getattr(settings, "API_KEY_COOKIE_NAME", "api_key") return request.COOKIES.get(cookie_name) class HasAPIKey(BaseHasAPIKey): model = APIKey # Or a custom model key_parser = CookieKeyParser() ``` ### Key generation !!! warning **This is an advanced topic**. Customizing the key generation algorithm must be done with care to prevent security issues. If you proceed, it is best to customize key generation **with a clean database state**, that is **before running initial migrations**, and more importantly **before any API key is created**. This package ships with a key generation algorithm based on Django's password hashing infrastructure (see also [Security](security.md)). The `.key_generator` attribute on `BaseAPIKeyManager` allows you to customize key generation. For example, you can customize the length of the prefix and secret key using: ```python from rest_framework_api_key.models import BaseAPIKeyManager from rest_framework_api_key.crypto import KeyGenerator class OrganizationAPIKeyManager(BaseAPIKeyManager): key_generator = KeyGenerator(prefix_length=8, secret_key_length=32) # Default values class OrganizationAPIKey(AbstractAPIKey): objects = OrganizationAPIKeyManager() # ... ``` If you want to replace the key generation algorithm entirely, you can create your own `KeyGenerator` class. It must implement the `.generate()` and `.verify()` methods. At this point, it's probably best to read the [source code](https://github.com/florimondmanca/djangorestframework-api-key/blob/master/src/rest_framework_api_key/crypto.py) for the built-in `KeyGenerator`. !!! check If the signature of your `.generate()` method is different from the built-in one, you'll need to override `.assign_key()` in your custom API key manager as well. Likewise, if `.verify()` must accept anything else than the `key` and `hashed_key`, you'll need to override `.is_valid()` on your custom API key model. See [models.py](https://github.com/florimondmanca/djangorestframework-api-key/blob/master/src/rest_framework_api_key/models.py) for the source code of `BaseAPIKeyManager`. ## Typing support This package provides type information starting with version 2.0, making it suitable for usage with type checkers such as `mypy`. For the best experience, you may want to install packages such as [`django-stubs`](https://github.com/typeddjango/django-stubs) and [`djangorestframework-stubs`](https://github.com/typeddjango/djangorestframework-stubs). Note however that a seamless integration with these packages is not guaranteed yet. djangorestframework-api-key-3.1.0/docs/index.md000066400000000000000000000100011477371521300215110ustar00rootroot00000000000000

Django REST Framework API Key

API key permissions for Django REST Framework

python versions django versions drf versions
## Introduction **Django REST Framework API Key is a powerful library for allowing server-side clients to safely use your API.** These clients are typically third-party backends and services (i.e. _machines_) which do not have a user account but still need to interact with your API in a secure way. ### Features - ✌️ **Simple to use**: create, view and revoke API keys via the admin site, or use built-in helpers to create API keys programmatically. - πŸ”’ **As secure as possible**: API keys are treated with the same level of care as user passwords. They are only visible at creation and hashed before storing in the database. - 🎨 **Customizable**: satisfy specific business requirements by building your own customized API key models, permission classes and admin panels. ### Should I use API keys? There are important security aspects you need to consider before switching to an API key access control scheme. We've listed some of these in [Security caveats](security.md#caveats), including serving your API over HTTPS. Besides, see [Why and when to use API keys](https://cloud.google.com/endpoints/docs/openapi/when-why-api-key#top_of_page) for hints on whether API keys can fit your use case. API keys are ideal in the following situations: - Blocking anonymous traffic. - Implementing API key-based [throttling](https://www.django-rest-framework.org/api-guide/throttling/). (Note that Django REST Framework already has many built-in utilities for this use case.) - Identifying usage patterns by logging request information along with the API key. They can also present enough security for authorizing internal services, such as your API server and an internal frontend application. !!! warning Please note that this package is NOT meant for authentication. You should NOT use this package to identify individual users, either directly or indirectly. If you need server-to-server authentication, you may want to consider OAuth instead. Libraries such as [django-oauth-toolkit](https://django-oauth-toolkit.readthedocs.io/en/latest/index.html) can help. ## Quickstart Install with `pip`: ```bash pip install "djangorestframework-api-key==3.*" ``` !!! important It is highly recommended to **pin your dependency** to the latest major version (as depicted above), as breaking changes may and will happen between major releases. Add the app to your `INSTALLED_APPS`: ```python # settings.py INSTALLED_APPS = [ # ... "rest_framework", "rest_framework_api_key", ] ``` Run the included migrations: ```bash python manage.py migrate ``` To learn how to configure permissions and manage API keys, head to the [User Guide](guide.md). djangorestframework-api-key-3.1.0/docs/security.md000066400000000000000000000047361477371521300222730ustar00rootroot00000000000000# Security ## Implementation details ### Key generation scheme An API key is composed of two items: - A prefix `P`, which is a generated string of 8 characters. - A secret key `SK`, which is a generated string of 32 characters. The generated key that clients use to [make authorized requests](#making-authorized-requests) is `GK = P.SK`. It is treated with the same level of care as passwords: - Only a hashed version is stored in the database. The hashing algorithm is sha512. [^1] - The generated key is shown only once to the client upon API key creation. [^1]: Older versions of this module used the same hashers as Django's [`PASSWORD_HASHERS`](https://docs.djangoproject.com/en/2.2/ref/settings/#std:setting-PASSWORD_HASHERS). These hashers come with a large performance penalty and while critical for passwords, they aren't needed for high-entropy, randomly generated keys like the ones created by this module. Keys stored using these slower hashers will be upgraded when used. ### Grant scheme Access is granted if and only if all of the following is true: 1. The configured API key header is present and correctly formatted. [^3] 2. A usable API key with the prefix of the given key exists in the database. [^4] 3. The hash of the given key matches that of the API key. [^3]: To customize this behavior, see [API key parsing](guide.md#api-key-parsing). [^4]: Only unrevoked keys are usable by default, but this can be customized with a [custom manager](guide.md#managers). ## Caveats [API keys β‰  Security](https://nordicapis.com/why-api-keys-are-not-enough/): depending on your situation, you should probably not use API keys only to authorize your clients. Besides, it is NOT recommended to use this package for authentication, i.e. retrieving user information from API keys. Indeed, **using API keys shifts the responsibility of Information Security on your clients**. This induces risks, especially if obtaining an API key gives access to confidential information or write operations. For example, an attacker could impersonate clients if they let their API keys leak. As a best practice, you should apply the _Principle of Least Privilege_: allow only those who require resources to access those specific resources. In other words: **if your client needs to access an endpoint, add API permissions on that endpoint only** instead of the whole API. Besides, it is highly recommended to serve the API over **HTTPS** to ensure the confidentiality of API keys passed in requests. Act responsibly! djangorestframework-api-key-3.1.0/docs/upgrade/000077500000000000000000000000001477371521300215175ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/docs/upgrade/1.0.md000066400000000000000000000022211477371521300223340ustar00rootroot00000000000000# Upgrading to 1.0 ## Introduction **The 1.0 release is incompatible with 0.x**. It introduces a new and more transparent API key generation and validation scheme which allows to pass it in a single header, instead of two previously. This document lists the steps necessary to upgrade from 0.x to 1.0. ## Steps ### 1. Backup existing API keys Unfortunately, it is not possible to provide a migration that would preserve existing API keys. This is because the cryptographic generation and validation methods have changed fundamentally, which means that new keys cannot be inferred from existing ones. As a result, **all existing API keys will be destroyed** during Step 1/ described below. You may want to backup the existing data so that you can regenerate keys notify clients once migration is complete. ### 2. Reset migrations **This step will destroy existing API keys**. It is necessary for the new migrations to run correctly. ```bash python manage.py migrate rest_framework_api_key zero ``` ### 3. Upgrade ```bash pip install "djangorestframework-api-key==1.0.*" ``` ### 4. Run migrations ```bash python manage.py migrate rest_framework_api_key ``` djangorestframework-api-key-3.1.0/docs/upgrade/1.4.md000066400000000000000000000020041477371521300223370ustar00rootroot00000000000000# Upgrading to 1.4 ## Introduction The 1.4 release includes a migration that adds and populates the `prefix` and `hashed_key` fields to API keys. This document lists the steps necessary to upgrade from 1.3.x to 1.4. ## Steps ### 1. Migrate the built-in API key model The `APIKey` model can be migrated using the migration shipped with this package: ```bash python manage.py migrate rest_framework_api_key ``` ### 2. Migrate custom API key models (if applicable) If you have a custom API key model deriving from `AbstractAPIKey`, you need to **manually add the migration** to your application. - Copy the migration script below to your app's `migrations/` directory. Be sure to modify `APP_NAME`, `MODEL_NAME` and `DEPENDENCIES` as seems fit. You can name the migration script `xxxx_prefix_hashed_key.py` (replace `xxxx` with the next available migration ID). ```python --8<-- "src/rest_framework_api_key/migrations/0004_prefix_hashed_key.py" ``` - Apply the migration: ```bash python manage.py migrate ``` djangorestframework-api-key-3.1.0/docs/upgrade/2.0.md000066400000000000000000000015311477371521300223400ustar00rootroot00000000000000# Upgrading to 2.0 ## Introduction This document lists the steps necessary to upgrade from 1.4.x to 2.0. The full list of changes can be found in the [Changelog](https://github.com/florimondmanca/djangorestframework-api-key/blob/master/CHANGELOG.md). ## Steps ### 1. Upgrade your Python to 3.6+ The 2.0 release dropped support for Python 3.5. Before upgrading, make sure you are running on Python 3.6 or above. ### 2. Upgrade your Django to 2.2+ To 2.0 release dropped official support for Django 2.0 and Django 2.1, which have both reached EOL (see [Django: Supported Versions](https://www.djangoproject.com/download/#supported-versions)). Django 2.2 is still supported, and support for Django 3.0 was added. While we there are no internal changes due to this change, you should make sure you are running on Django 2.2 or above before upgrading. djangorestframework-api-key-3.1.0/docs/upgrade/3.0.md000066400000000000000000000042421477371521300223430ustar00rootroot00000000000000# Upgrading to 3.0 ## Introduction This document lists the steps necessary to upgrade from 2.x to 3.0. The full list of changes can be found in the [Changelog](https://github.com/florimondmanca/djangorestframework-api-key/blob/master/CHANGELOG.md). ## Steps ### 1. Upgrade your Python to 3.8+ The 3.0 release drops support for Python 3.7, which has reached EOL in June 2023. Before upgrading, make sure you are running on Python 3.8 or above. ### 2. Review usage of `.has_object_permission()` on DRF 3.14+ with custom API key models An implementation of `.has_object_permission()` on `BaseHasAPIKey` that was redundant with `.has_permission()` has been dropped when using Django REST Framework 3.14.0 and above. If you are using DRF 3.14+ and have custom API key models, you will want to review any implementation of `.has_object_permission()`. Calls to `super().has_object_permission()` will now return `True` (the DRF default) instead of re-validating the API key. This is the desirable thing to do, but you may need some adjustements if you relied on the previous behavior somehow until now. ### 3. Review upgrade of API key hashes following switch to SHA512 This release brings a notable performance improvement by changing the hashing algorithm for API keys. Hashing API keys used to be done using Django's `PASSWORD_HASHERS`. These hashers are slow by design as they're meant to deal with low-entropy strings such as user passwords. As a result, they typically added 200ms or more on every single request. On the contrary, API keys are long, randomly generated strings of ASCII characters. This means they have a high entropy, so we can get away with hashing them with a simpler β€” and faster β€” algorithm. Consequently, version 3.0 now uses SHA512 for hashing API keys. Limited testing has shown API key verification should be at least 10x faster on typical CPUs β€” although greater improvements could be observed. The hashes of existing API keys will be transparently updated the next time `.is_valid()` is called (i.e. the next time the API key is used). There shouldn't be any action required on your side, but you may want to test things in a staging environment out of caution. djangorestframework-api-key-3.1.0/mkdocs.yml000066400000000000000000000020541477371521300211440ustar00rootroot00000000000000site_name: Django REST Framework API Key site_url: https://florimondmanca.github.io/djangorestframework-api-key copyright: Β© 2018-2020 Florimond Manca theme: name: "material" palette: primary: "red" accent: "red" repo_name: florimondmanca/djangorestframework-api-key repo_url: https://github.com/florimondmanca/djangorestframework-api-key nav: - Home: index.md - User Guide: guide.md - Security: security.md - Upgrade Guides: - "3.0": upgrade/3.0.md - "2.0": upgrade/2.0.md - "1.4": upgrade/1.4.md - "1.0": upgrade/1.0.md - Contributing: https://github.com/florimondmanca/djangorestframework-api-key/tree/master/CONTRIBUTING.md - Changelog: https://github.com/florimondmanca/djangorestframework-api-key/tree/master/CHANGELOG.md - License: https://github.com/florimondmanca/djangorestframework-api-key/tree/master/LICENSE markdown_extensions: - admonition - footnotes - pymdownx.superfences - pymdownx.snippets: check_paths: true - codehilite: guess_lang: false - toc: permalink: true djangorestframework-api-key-3.1.0/pyproject.toml000066400000000000000000000030321477371521300220520ustar00rootroot00000000000000[build-system] requires = ["setuptools", "setuptools-scm", "wheel"] build-backend = "setuptools.build_meta" [project] name = "djangorestframework-api-key" description = "API key permissions for the Django REST Framework" requires-python = ">=3.8" license = { text = "MIT" } authors = [ { name = "Florimond Manca", email = "florimond.manca@protonmail.com" }, ] classifiers = [ "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Intended Audience :: Developers", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Environment :: Web Environment", "Topic :: Software Development :: Libraries :: Python Modules", "Framework :: Django", "Framework :: Django :: 2.2", "Framework :: Django :: 3.2", "Framework :: Django :: 4.2", "Framework :: Django :: 5.2", ] dependencies = [ "packaging", ] dynamic = ["version", "readme"] [project.urls] "Homepage" = "https://github.com/florimondmanca/djangorestframework-api-key" "Documentation" = "https://florimondmanca.github.io/djangorestframework-api-key/" [tool.setuptools.dynamic] version = { attr = "rest_framework_api_key.__version__" } readme = { file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown" } [tool.ruff] select = ["E", "F", "I"] line-length = 88 src = ["src", "test_project", "tests"] djangorestframework-api-key-3.1.0/requirements.txt000066400000000000000000000006141477371521300224250ustar00rootroot00000000000000-e . # Django environment. # django[argon2,bcrypt] # See tools/install_django.sh djangorestframework==3.14.* dj-database-url django-dotenv # PostgreSQL testing. psycopg2-binary # Packaging. twine wheel # Tooling. black==23.9.1 django-test-migrations==1.3.0 mkdocs==1.5.2 mkdocs-material==9.3.1 pymdown-extensions==10.3 mypy==1.5.1 pytest==7.4.2 pytest-django==4.5.2 pytest-cov ruff==0.0.289 djangorestframework-api-key-3.1.0/setup.cfg000066400000000000000000000002641477371521300207630ustar00rootroot00000000000000[mypy] disallow_untyped_defs = True ignore_missing_imports = True [tool:pytest] testpaths = tests addopts = -rxXs --cov=src --cov-report=term-missing --cov-fail-under=100 djangorestframework-api-key-3.1.0/setup.py000066400000000000000000000000741477371521300206530ustar00rootroot00000000000000from setuptools import setup setup() # Editable installs. djangorestframework-api-key-3.1.0/src/000077500000000000000000000000001477371521300177275ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/src/rest_framework_api_key/000077500000000000000000000000001477371521300244625ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/src/rest_framework_api_key/__init__.py000066400000000000000000000004371477371521300265770ustar00rootroot00000000000000try: import django except ImportError: # pragma: no cover pass else: if django.VERSION < (3, 2): # pragma: no cover default_app_config = "rest_framework_api_key.apps.RestFrameworkApiKeyConfig" __version__ = "3.1.0" __all__ = ["__version__", "default_app_config"] djangorestframework-api-key-3.1.0/src/rest_framework_api_key/admin.py000066400000000000000000000031371477371521300261300ustar00rootroot00000000000000import typing from django.contrib import admin, messages from django.db import models from django.http.request import HttpRequest from django.utils.translation import gettext_lazy as _ from .models import AbstractAPIKey, APIKey class APIKeyModelAdmin(admin.ModelAdmin): model: typing.Type[AbstractAPIKey] list_display = ( "prefix", "name", "created", "expiry_date", "_has_expired", "revoked", ) list_filter = ("created",) search_fields = ("name", "prefix") def get_readonly_fields( self, request: HttpRequest, obj: models.Model = None ) -> typing.Tuple[str, ...]: obj = typing.cast(AbstractAPIKey, obj) fields: typing.Tuple[str, ...] fields = ("prefix",) if obj is not None and obj.revoked: fields = fields + ("name", "revoked", "expiry_date") return fields def save_model( self, request: HttpRequest, obj: AbstractAPIKey, form: typing.Any = None, change: bool = False, ) -> None: created = not obj.pk if created: key = self.model.objects.assign_key(obj) obj.save() message = _( "The API key for {} is: {}. ".format(obj.name, key) + "Please store it somewhere safe: " + "you will not be able to see it again." ) messages.add_message(request, messages.WARNING, message) else: obj.save() admin.site.register(APIKey, APIKeyModelAdmin) APIKeyAdmin = APIKeyModelAdmin # Compatibility with <1.3 djangorestframework-api-key-3.1.0/src/rest_framework_api_key/apps.py000066400000000000000000000002351477371521300257770ustar00rootroot00000000000000from django.apps import AppConfig class RestFrameworkApiKeyConfig(AppConfig): name = "rest_framework_api_key" verbose_name = "API Key Permissions" djangorestframework-api-key-3.1.0/src/rest_framework_api_key/crypto.py000066400000000000000000000051461477371521300263620ustar00rootroot00000000000000import hashlib import typing from django.contrib.auth.hashers import ( BasePasswordHasher, check_password, make_password, ) from django.utils.crypto import constant_time_compare, get_random_string def concatenate(left: str, right: str) -> str: return "{}.{}".format(left, right) def split(concatenated: str) -> typing.Tuple[str, str]: left, _, right = concatenated.partition(".") return left, right class Sha512ApiKeyHasher(BasePasswordHasher): """ An API key hasher using the sha512 algorithm. This hasher should *NEVER* be used in Django's `PASSWORD_HASHERS` setting. It is insecure for use in hashing passwords, but is safe for hashing high entropy, randomly generated API keys. """ algorithm = "sha512" def salt(self) -> str: """No need for a salt on a high entropy key.""" return "" def encode(self, password: str, salt: str) -> str: if salt != "": raise ValueError("salt is unnecessary for high entropy API tokens.") hash = hashlib.sha512(password.encode()).hexdigest() return "%s$$%s" % (self.algorithm, hash) def verify(self, password: str, encoded: str) -> bool: encoded_2 = self.encode(password, "") return constant_time_compare(encoded, encoded_2) class KeyGenerator: preferred_hasher = Sha512ApiKeyHasher() def __init__(self, prefix_length: int = 8, secret_key_length: int = 32): self.prefix_length = prefix_length self.secret_key_length = secret_key_length def get_prefix(self) -> str: return get_random_string(self.prefix_length) def get_secret_key(self) -> str: return get_random_string(self.secret_key_length) def hash(self, value: str) -> str: return make_password(value, hasher=self.preferred_hasher) def generate(self) -> typing.Tuple[str, str, str]: prefix = self.get_prefix() secret_key = self.get_secret_key() key = concatenate(prefix, secret_key) hashed_key = self.hash(key) return key, prefix, hashed_key def verify(self, key: str, hashed_key: str) -> bool: if self.using_preferred_hasher(hashed_key): # New simpler hasher result = self.preferred_hasher.verify(key, hashed_key) else: # Slower password hashers from Django # If verified, these will be transparently updated to the preferred hasher result = check_password(key, hashed_key) return result def using_preferred_hasher(self, hashed_key: str) -> bool: return hashed_key.startswith(f"{self.preferred_hasher.algorithm}$$") djangorestframework-api-key-3.1.0/src/rest_framework_api_key/migrations/000077500000000000000000000000001477371521300266365ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/src/rest_framework_api_key/migrations/0001_initial.py000066400000000000000000000023051477371521300313010ustar00rootroot00000000000000# Generated by Django 2.1.7 on 2019-04-03 16:11 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] # type: ignore operations = [ migrations.CreateModel( name="APIKey", fields=[ ( "id", models.CharField( max_length=100, primary_key=True, serialize=False, unique=True ), ), ("created", models.DateTimeField(auto_now_add=True, db_index=True)), ("name", models.CharField(default=None, max_length=50)), ( "revoked", models.BooleanField( blank=True, default=False, help_text=( "If the API key is revoked, clients cannot use it anymore." ), ), ), ], options={ "verbose_name": "API key", "verbose_name_plural": "API keys", "ordering": ("-created",), }, ) ] djangorestframework-api-key-3.1.0/src/rest_framework_api_key/migrations/0002_auto_20190529_2243.py000066400000000000000000000024561477371521300322750ustar00rootroot00000000000000# Generated by Django 2.2.1 on 2019-05-29 22:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("rest_framework_api_key", "0001_initial")] operations = [ migrations.AddField( model_name="apikey", name="expiry_date", field=models.DateTimeField( blank=True, help_text="Once API key expires, clients cannot use it anymore.", null=True, verbose_name="Expires", ), ), migrations.AlterField( model_name="apikey", name="name", field=models.CharField( default=None, help_text=( "A free-form name for the API key. Need not be unique. " "50 characters max." ), max_length=50, ), ), migrations.AlterField( model_name="apikey", name="revoked", field=models.BooleanField( blank=True, default=False, help_text=( "If the API key is revoked, clients cannot use it anymore. " "(This cannot be undone.)" ), ), ), ] djangorestframework-api-key-3.1.0/src/rest_framework_api_key/migrations/0003_auto_20190623_1952.py000066400000000000000000000010341477371521300322660ustar00rootroot00000000000000# Generated by Django 2.2.2 on 2019-06-23 19:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("rest_framework_api_key", "0002_auto_20190529_2243")] operations = [ migrations.AlterField( model_name="apikey", name="id", field=models.CharField( editable=False, max_length=100, primary_key=True, serialize=False, unique=True, ), ) ] djangorestframework-api-key-3.1.0/src/rest_framework_api_key/migrations/0004_prefix_hashed_key.py000066400000000000000000000027141477371521300333400ustar00rootroot00000000000000# Generated by Django 2.2.2 on 2019-06-29 10:38 from django.db import migrations, models APP_NAME = "rest_framework_api_key" MODEL_NAME = "apikey" DEPENDENCIES = [(APP_NAME, "0003_auto_20190623_1952")] def populate_prefix_hashed_key(apps, schema_editor) -> None: # type: ignore model = apps.get_model(APP_NAME, MODEL_NAME) for api_key in model.objects.using( schema_editor.connection.alias ).all(): # pragma: nodj22 prefix, _, hashed_key = api_key.id.partition(".") api_key.prefix = prefix api_key.hashed_key = hashed_key api_key.save() class Migration(migrations.Migration): dependencies = DEPENDENCIES operations = [ migrations.AddField( model_name=MODEL_NAME, name="hashed_key", field=models.CharField(max_length=100, null=True), ), migrations.AddField( model_name=MODEL_NAME, name="prefix", field=models.CharField(max_length=8, unique=True, null=True), ), migrations.RunPython(populate_prefix_hashed_key, migrations.RunPython.noop), migrations.AlterField( model_name=MODEL_NAME, name="hashed_key", field=models.CharField(max_length=100, editable=False), ), migrations.AlterField( model_name=MODEL_NAME, name="prefix", field=models.CharField(max_length=8, unique=True, editable=False), ), ] djangorestframework-api-key-3.1.0/src/rest_framework_api_key/migrations/0005_auto_20220110_1102.py000066400000000000000000000013321477371521300322350ustar00rootroot00000000000000# Generated by Django 3.2.11 on 2022-01-10 11:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("rest_framework_api_key", "0004_prefix_hashed_key"), ] operations = [ migrations.AlterField( model_name="apikey", name="hashed_key", field=models.CharField(editable=False, max_length=150), ), migrations.AlterField( model_name="apikey", name="id", field=models.CharField( editable=False, max_length=150, primary_key=True, serialize=False, unique=True, ), ), ] djangorestframework-api-key-3.1.0/src/rest_framework_api_key/migrations/__init__.py000066400000000000000000000000001477371521300307350ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/src/rest_framework_api_key/models.py000066400000000000000000000117061477371521300263240ustar00rootroot00000000000000import typing from django.core.exceptions import ValidationError from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .crypto import KeyGenerator, concatenate, split class BaseAPIKeyManager(models.Manager): key_generator = KeyGenerator() def assign_key(self, obj: "AbstractAPIKey") -> str: try: key, prefix, hashed_key = self.key_generator.generate() except ValueError: # Compatibility with < 1.4 generate = typing.cast( typing.Callable[[], typing.Tuple[str, str]], self.key_generator.generate ) key, hashed_key = generate() pk = hashed_key prefix, hashed_key = split(hashed_key) else: pk = concatenate(prefix, hashed_key) obj.id = pk obj.prefix = prefix obj.hashed_key = hashed_key return key def create_key(self, **kwargs: typing.Any) -> typing.Tuple["AbstractAPIKey", str]: # Prevent from manually setting the primary key. kwargs.pop("id", None) obj = self.model(**kwargs) key = self.assign_key(obj) obj.save() return obj, key def get_usable_keys(self) -> models.QuerySet: return self.filter(revoked=False) def get_from_key(self, key: str) -> "AbstractAPIKey": prefix, _, _ = key.partition(".") queryset = self.get_usable_keys() try: api_key = queryset.get(prefix=prefix) except self.model.DoesNotExist: raise # For the sake of being explicit. if not api_key.is_valid(key): raise self.model.DoesNotExist("Key is not valid.") else: return api_key def is_valid(self, key: str) -> bool: try: api_key = self.get_from_key(key) except self.model.DoesNotExist: return False if api_key.has_expired: return False return True class APIKeyManager(BaseAPIKeyManager): pass class AbstractAPIKey(models.Model): objects = APIKeyManager() id = models.CharField(max_length=150, unique=True, primary_key=True, editable=False) prefix = models.CharField(max_length=8, unique=True, editable=False) hashed_key = models.CharField(max_length=150, editable=False) created = models.DateTimeField(auto_now_add=True, db_index=True) name = models.CharField( max_length=50, blank=False, default=None, help_text=( _( "A free-form name for the API key. " "Need not be unique. " "50 characters max." ) ), ) revoked = models.BooleanField( blank=True, default=False, help_text=( _( "If the API key is revoked, clients cannot use it anymore. " "(This cannot be undone.)" ) ), ) expiry_date = models.DateTimeField( blank=True, null=True, verbose_name=_("Expires"), help_text=_("Once API key expires, clients cannot use it anymore."), ) class Meta: # noqa abstract = True ordering = ("-created",) verbose_name = "API key" verbose_name_plural = "API keys" def __init__(self, *args: typing.Any, **kwargs: typing.Any): super().__init__(*args, **kwargs) # Store the initial value of `revoked` to detect changes. self._initial_revoked = self.revoked def _has_expired(self) -> bool: if self.expiry_date is None: return False return self.expiry_date < timezone.now() _has_expired.short_description = "Has expired" # type: ignore _has_expired.boolean = True # type: ignore has_expired = property(_has_expired) def is_valid(self, key: str) -> bool: key_generator = type(self).objects.key_generator valid = key_generator.verify(key, self.hashed_key) # Transparently update the key to use the preferred hasher # if it is using an outdated hasher. if valid and not key_generator.using_preferred_hasher(self.hashed_key): # Note that since the PK includes the hashed key, # they will be internally inconsistent following this upgrade. # See: https://github.com/florimondmanca/djangorestframework-api-key/issues/128 self.hashed_key = key_generator.hash(key) self.save() return valid def clean(self) -> None: self._validate_revoked() def save(self, *args: typing.Any, **kwargs: typing.Any) -> None: self._validate_revoked() super().save(*args, **kwargs) def _validate_revoked(self) -> None: if self._initial_revoked and not self.revoked: raise ValidationError( _("The API key has been revoked, which cannot be undone.") ) def __str__(self) -> str: return str(self.name) class APIKey(AbstractAPIKey): pass djangorestframework-api-key-3.1.0/src/rest_framework_api_key/permissions.py000066400000000000000000000053421477371521300274130ustar00rootroot00000000000000import typing import packaging.version from django.conf import settings from django.http import HttpRequest from rest_framework import __version__ as __drf_version__ from rest_framework import permissions from .models import AbstractAPIKey, APIKey _drf_version = packaging.version.parse(__drf_version__) _3_14_0 = packaging.version.parse("3.14.0") class KeyParser: keyword = "Api-Key" def get(self, request: HttpRequest) -> typing.Optional[str]: custom_header = getattr(settings, "API_KEY_CUSTOM_HEADER", None) if custom_header is not None: return self.get_from_header(request, custom_header) return self.get_from_authorization(request) def get_from_authorization(self, request: HttpRequest) -> typing.Optional[str]: authorization = request.META.get("HTTP_AUTHORIZATION", "") if not authorization: return None keyword, found, key = authorization.partition(" ") if not found: return None if keyword.lower() != self.keyword.lower(): return None return key def get_from_header(self, request: HttpRequest, name: str) -> typing.Optional[str]: return request.META.get(name) or None class BaseHasAPIKey(permissions.BasePermission): model: typing.Optional[typing.Type[AbstractAPIKey]] = None key_parser = KeyParser() def get_key(self, request: HttpRequest) -> typing.Optional[str]: return self.key_parser.get(request) def has_permission(self, request: HttpRequest, view: typing.Any) -> bool: assert self.model is not None, ( "%s must define `.model` with the API key model to use" % self.__class__.__name__ ) key = self.get_key(request) if not key: return False return self.model.objects.is_valid(key) def has_object_permission( self, request: HttpRequest, view: typing.Any, obj: AbstractAPIKey ) -> bool: if _drf_version < _3_14_0: # pragma: no cover # Before DRF 3.14.0 (released in Sept 2022), bitwise OR would skip # .has_permision() and only call .has_object_permission(), resulting in # API key permissions not being checked unless we implemented # .has_object_permission(). # Since 3.14.0, DRF appropriately checks for both .has_permission() and # .has_object_permission() when checking object permissions of a bitwise OR. # We kept the old redundant behavior to avoid regressions for users who have # not updated their DRF yet. return self.has_permission(request, view) return super().has_object_permission(request, view, obj) class HasAPIKey(BaseHasAPIKey): model = APIKey djangorestframework-api-key-3.1.0/src/rest_framework_api_key/py.typed000066400000000000000000000000001477371521300261470ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/test_project/000077500000000000000000000000001477371521300216455ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/test_project/README.md000066400000000000000000000006041477371521300231240ustar00rootroot00000000000000# project Test project for Django REST Framework API Key. ## Usage - Run migrations (creates an SQLite database): ```bash python test_project/manage.py migrate ``` - Create a superuser to access the admin site: ```bash python test_project/manage.py createsuperuser # Enter user information as instructed ``` - Start the server: ```bash python test_project/manage.py runserver ``` djangorestframework-api-key-3.1.0/test_project/__init__.py000066400000000000000000000000001477371521300237440ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/test_project/heroes/000077500000000000000000000000001477371521300231325ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/test_project/heroes/__init__.py000066400000000000000000000000001477371521300252310ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/test_project/heroes/admin.py000066400000000000000000000004401477371521300245720ustar00rootroot00000000000000from django.contrib import admin from rest_framework_api_key.admin import APIKeyModelAdmin from .models import Hero, HeroAPIKey @admin.register(HeroAPIKey) class HeroAPIKeyModelAdmin(APIKeyModelAdmin): pass @admin.register(Hero) class HeroModelAdmin(admin.ModelAdmin): pass djangorestframework-api-key-3.1.0/test_project/heroes/apps.py000066400000000000000000000002351477371521300244470ustar00rootroot00000000000000from django.apps import AppConfig class HeroesConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "test_project.heroes" djangorestframework-api-key-3.1.0/test_project/heroes/migrations/000077500000000000000000000000001477371521300253065ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/test_project/heroes/migrations/0001_initial.py000066400000000000000000000057221477371521300277570ustar00rootroot00000000000000# Generated by Django 2.2.2 on 2019-06-23 19:53 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): initial = True operations = [ migrations.CreateModel( name="Hero", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(max_length=64)), ("retired", models.BooleanField(default=False)), ], options={"verbose_name_plural": "heroes"}, ), migrations.CreateModel( name="HeroAPIKey", fields=[ ( "id", models.CharField( editable=False, max_length=100, primary_key=True, serialize=False, unique=True, ), ), ("created", models.DateTimeField(auto_now_add=True, db_index=True)), ( "name", models.CharField( default=None, help_text=( "A free-form name for the API key. Need not be unique. " "50 characters max." ), max_length=50, ), ), ( "revoked", models.BooleanField( blank=True, default=False, help_text=( "If the API key is revoked, clients cannot use it anymore. " "(This cannot be undone.)" ), ), ), ( "expiry_date", models.DateTimeField( blank=True, help_text=( "Once API key expires, clients cannot use it anymore." ), null=True, verbose_name="Expires", ), ), ( "hero", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="api_keys", to="heroes.Hero", ), ), ], options={ "verbose_name": "Hero API key", "verbose_name_plural": "Hero API keys", "ordering": ("-created",), "abstract": False, }, ), ] djangorestframework-api-key-3.1.0/test_project/heroes/migrations/0002_prefix_hashed_key.py000066400000000000000000000026151477371521300320060ustar00rootroot00000000000000# Generated by Django 2.2.2 on 2019-06-29 10:38 from django.db import migrations, models APP_NAME = "heroes" MODEL_NAME = "heroapikey" DEPENDENCIES = [(APP_NAME, "0001_initial")] def populate_prefix_hashed_key(apps, schema_editor): # type: ignore model = apps.get_model(APP_NAME, MODEL_NAME) for api_key in model.objects.using(schema_editor.connection.alias).all(): prefix, _, hashed_key = api_key.id.partition(".") api_key.prefix = prefix api_key.hashed_key = hashed_key api_key.save() class Migration(migrations.Migration): dependencies = DEPENDENCIES operations = [ migrations.AddField( model_name=MODEL_NAME, name="hashed_key", field=models.CharField(max_length=100, null=True), ), migrations.AddField( model_name=MODEL_NAME, name="prefix", field=models.CharField(max_length=8, unique=True, null=True), ), migrations.RunPython(populate_prefix_hashed_key, migrations.RunPython.noop), migrations.AlterField( model_name=MODEL_NAME, name="hashed_key", field=models.CharField(max_length=100, editable=False), ), migrations.AlterField( model_name=MODEL_NAME, name="prefix", field=models.CharField(max_length=8, unique=True, editable=False), ), ] djangorestframework-api-key-3.1.0/test_project/heroes/migrations/0003_alter_hero_id.py000066400000000000000000000007241477371521300311250ustar00rootroot00000000000000# Generated by Django 3.2.9 on 2021-12-05 17:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("heroes", "0002_prefix_hashed_key"), ] operations = [ migrations.AlterField( model_name="hero", name="id", field=models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID" ), ), ] djangorestframework-api-key-3.1.0/test_project/heroes/migrations/0004_auto_20220110_1102.py000066400000000000000000000013161477371521300307060ustar00rootroot00000000000000# Generated by Django 3.2.11 on 2022-01-10 11:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("heroes", "0003_alter_hero_id"), ] operations = [ migrations.AlterField( model_name="heroapikey", name="hashed_key", field=models.CharField(editable=False, max_length=150), ), migrations.AlterField( model_name="heroapikey", name="id", field=models.CharField( editable=False, max_length=150, primary_key=True, serialize=False, unique=True, ), ), ] djangorestframework-api-key-3.1.0/test_project/heroes/migrations/__init__.py000066400000000000000000000000001477371521300274050ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/test_project/heroes/models.py000066400000000000000000000014541477371521300247730ustar00rootroot00000000000000from django.db import models from rest_framework_api_key.models import AbstractAPIKey, BaseAPIKeyManager class Hero(models.Model): objects = models.Manager() name = models.CharField(max_length=64) retired = models.BooleanField(default=False) class Meta: verbose_name_plural = "heroes" def __str__(self) -> str: return self.name class HeroAPIKeyManager(BaseAPIKeyManager): def get_usable_keys(self) -> models.QuerySet: return super().get_usable_keys().filter(hero__retired=False) class HeroAPIKey(AbstractAPIKey): objects = HeroAPIKeyManager() hero = models.ForeignKey(Hero, on_delete=models.CASCADE, related_name="api_keys") class Meta(AbstractAPIKey.Meta): verbose_name = "Hero API key" verbose_name_plural = "Hero API keys" djangorestframework-api-key-3.1.0/test_project/heroes/permissions.py000066400000000000000000000002321477371521300260540ustar00rootroot00000000000000from rest_framework_api_key.permissions import BaseHasAPIKey from .models import HeroAPIKey class HasHeroAPIKey(BaseHasAPIKey): model = HeroAPIKey djangorestframework-api-key-3.1.0/test_project/manage.py000077500000000000000000000012771477371521300234610ustar00rootroot00000000000000#!/usr/bin/env python import os import pathlib import sys import dotenv root = pathlib.Path(__file__).parent.parent if __name__ == "__main__": dotenv.read_dotenv(str(root / ".env")) sys.path.append(str(root)) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.project.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) djangorestframework-api-key-3.1.0/test_project/project/000077500000000000000000000000001477371521300233135ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/test_project/project/__init__.py000066400000000000000000000000001477371521300254120ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/test_project/project/settings.py000066400000000000000000000051371477371521300255330ustar00rootroot00000000000000import os import dj_database_url BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = "*(q7fo7duyzqhv$qmiym5#z%w^qqh67a9rqk$jr4n1))nvnql^" DEBUG = True ALLOWED_HOSTS = ["localhost", "127.0.0.1"] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "rest_framework_api_key", "test_project.heroes", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "project.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ] }, } ] WSGI_APPLICATION = "project.wsgi.application" # Database DATABASES = { "default": dj_database_url.config(default="sqlite:///db.sqlite3"), "test": dj_database_url.config( "TEST_DATABASE_URL", default="sqlite://test.sqlite3" ), } # Password validation AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" # noqa: E501 }, {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"}, {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, ] # Password hashers PASSWORD_HASHERS = [ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.Argon2PasswordHasher", "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", "django.contrib.auth.hashers.ScryptPasswordHasher", ] # Internationalization LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) STATIC_URL = "/static/" djangorestframework-api-key-3.1.0/test_project/project/urls.py000066400000000000000000000005141477371521300246520ustar00rootroot00000000000000from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path("admin/", admin.site.urls), path("api/public/", views.PublicAPIView.as_view()), path("api/protected/", views.ProtectedAPIView.as_view()), path("api/protected/object/", views.ProtectedObjectAPIView.as_view()), ] djangorestframework-api-key-3.1.0/test_project/project/views.py000066400000000000000000000013521477371521300250230ustar00rootroot00000000000000from rest_framework.request import Request from rest_framework.response import Response from rest_framework.views import APIView from test_project.heroes.permissions import HasHeroAPIKey class PublicAPIView(APIView): def get(self, request: Request) -> Response: return Response({"message": "Hello, world!"}) class ProtectedAPIView(APIView): permission_classes = [HasHeroAPIKey] def get(self, request: Request) -> Response: return Response({"message": "Hello, world!"}) class ProtectedObjectAPIView(APIView): permission_classes = [HasHeroAPIKey] def get(self, request: Request) -> Response: self.check_object_permissions(request, object()) return Response({"message": "Hello, world!"}) djangorestframework-api-key-3.1.0/test_project/project/wsgi.py000066400000000000000000000002471477371521300246410ustar00rootroot00000000000000import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") application = get_wsgi_application() djangorestframework-api-key-3.1.0/tests/000077500000000000000000000000001477371521300203025ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/tests/__init__.py000066400000000000000000000000001477371521300224010ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/tests/conftest.py000066400000000000000000000034201477371521300225000ustar00rootroot00000000000000from pathlib import Path import dj_database_url import dotenv from django.conf import settings def pytest_configure() -> None: dotenv.read_dotenv(str(Path(__file__).parent.parent / ".env")) settings.configure( **{ "SECRET_KEY": "abcd", "INSTALLED_APPS": [ # Mandatory "django.contrib.contenttypes", # Permissions "django.contrib.auth", # Admin "django.contrib.admin", "django.contrib.messages", "django.contrib.sessions", # Project "rest_framework", "rest_framework_api_key", "test_project.heroes", ], "TEMPLATES": [ # Admin { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "context_processors": [ "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ] }, } ], "MIDDLEWARE": [ # Admin "django.contrib.sessions.middleware.SessionMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", ], "ROOT_URLCONF": "test_project.project.urls", "DATABASES": { "default": dj_database_url.config(default="sqlite://:memory:"), "test": dj_database_url.config(default="sqlite://:memory:"), }, "USE_TZ": True, } ) djangorestframework-api-key-3.1.0/tests/dateutils.py000066400000000000000000000002371477371521300226540ustar00rootroot00000000000000from datetime import datetime, timedelta, timezone NOW = datetime.now(tz=timezone.utc) TOMORROW = NOW + timedelta(days=1) YESTERDAY = NOW - timedelta(days=1) djangorestframework-api-key-3.1.0/tests/test_admin.py000066400000000000000000000053711477371521300230110ustar00rootroot00000000000000import pytest from django.contrib.admin import site from django.contrib.messages import get_messages from django.contrib.messages.middleware import MessageMiddleware from django.contrib.sessions.middleware import SessionMiddleware from django.http.request import HttpRequest from django.http.response import HttpResponse from django.test import RequestFactory from test_project.heroes.admin import HeroAPIKeyModelAdmin from test_project.heroes.models import Hero, HeroAPIKey from rest_framework_api_key.admin import APIKeyModelAdmin from rest_framework_api_key.models import APIKey def build_admin_request(rf: RequestFactory) -> HttpRequest: request = rf.post("/") def get_response(request: HttpRequest) -> HttpResponse: raise NotImplementedError # pragma: no cover # Unused in these tests. # NOTE: all middleware must be instantiated before # any middleware can process the request. sessions = SessionMiddleware(get_response) messages = MessageMiddleware(sessions.get_response) sessions.process_request(request) messages.process_request(request) return request @pytest.mark.django_db def test_admin_readonly_fields(rf: RequestFactory) -> None: request = build_admin_request(rf) admin = APIKeyModelAdmin(APIKey, site) assert admin.get_readonly_fields(request) == ("prefix",) api_key = APIKey(name="test") assert admin.get_readonly_fields(request, obj=api_key) == ("prefix",) api_key = APIKey(name="test", revoked=True) assert admin.get_readonly_fields(request, obj=api_key) == ( "prefix", "name", "revoked", "expiry_date", ) @pytest.mark.django_db def test_admin_create_api_key(rf: RequestFactory) -> None: request = build_admin_request(rf) admin = APIKeyModelAdmin(APIKey, site) api_key = APIKey(name="test") assert not api_key.pk admin.save_model(request, obj=api_key) assert api_key.pk messages = get_messages(request) assert len(messages) == 1 @pytest.mark.django_db def test_admin_create_custom_api_key(rf: RequestFactory) -> None: request = build_admin_request(rf) admin = HeroAPIKeyModelAdmin(HeroAPIKey, site) api_key = HeroAPIKey(name="test", hero=Hero.objects.create()) assert not api_key.pk admin.save_model(request, obj=api_key) assert api_key.pk messages = get_messages(request) assert len(messages) == 1 @pytest.mark.django_db def test_admin_update_api_key(rf: RequestFactory) -> None: request = build_admin_request(rf) admin = APIKeyModelAdmin(APIKey, site) api_key, _ = APIKey.objects.create_key(name="test") api_key.name = "another-test" admin.save_model(request, obj=api_key) refreshed = APIKey.objects.get(pk=api_key.pk) assert refreshed.name == "another-test" djangorestframework-api-key-3.1.0/tests/test_checks.py000066400000000000000000000001631477371521300231530ustar00rootroot00000000000000from django.core.management import call_command def test_system_checks_pass() -> None: call_command("check") djangorestframework-api-key-3.1.0/tests/test_compatibility.py000066400000000000000000000010471477371521300245660ustar00rootroot00000000000000import django import pytest import rest_framework_api_key @pytest.mark.skipif( django.VERSION < (3, 2), reason="app config is automatically defined by django" ) def test_app_config_not_defined() -> None: # pragma: no cover assert hasattr(rest_framework_api_key, "default_app_config") is False @pytest.mark.skipif( django.VERSION >= (3, 2), reason="app config is not automatically defined by django" ) def test_app_config_defined() -> None: # pragma: no cover assert hasattr(rest_framework_api_key, "default_app_config") is True djangorestframework-api-key-3.1.0/tests/test_hashers.py000066400000000000000000000007151477371521300233530ustar00rootroot00000000000000import pytest from rest_framework_api_key.crypto import Sha512ApiKeyHasher def test_sha512hasher_encode() -> None: hasher = Sha512ApiKeyHasher() key = "test" hashed_key = hasher.encode(key, "") assert hasher.verify(key, hashed_key) assert not hasher.verify("not-test", hashed_key) def test_sha512hasher_invalid_salt() -> None: hasher = Sha512ApiKeyHasher() with pytest.raises(ValueError): hasher.encode("test", "salt") djangorestframework-api-key-3.1.0/tests/test_legacy_key_generator.py000066400000000000000000000025011477371521300260730ustar00rootroot00000000000000from typing import Tuple import pytest from django.contrib.auth.hashers import make_password from django.utils.crypto import get_random_string from rest_framework_api_key.crypto import KeyGenerator from rest_framework_api_key.models import APIKey, BaseAPIKeyManager pytestmark = pytest.mark.django_db class LegacyKeyGenerator(KeyGenerator): """ Pre-1.4 key generator. The key generator interface was updated in v1.4 via: https://github.com/florimondmanca/djangorestframework-api-key/pull/62 We must ensure that custom key generators created based on the pre-1.4 interface continue to work in 1.x. """ def generate(self) -> Tuple[str, str]: # type: ignore # NOTE: this method should replicate the behavior before #62, and # have no dependencies on the current `rest_framework_api_key` package. prefix = get_random_string(8) secret_key = get_random_string(32) key = prefix + "." + secret_key key_id = prefix + "." + make_password(key) return key, key_id def test_manager_with_legacy_key_generator() -> None: class Manager(BaseAPIKeyManager): key_generator = LegacyKeyGenerator() manager = Manager() manager.model = APIKey api_key, generated_key = manager.create_key(name="test") assert api_key.is_valid(generated_key) djangorestframework-api-key-3.1.0/tests/test_migrations.py000066400000000000000000000047021477371521300240720ustar00rootroot00000000000000from typing import Any, Tuple import pytest try: from django_test_migrations.migrator import Migrator except ImportError: # pragma: no cover # Most likely Django < 3.2 Migrator = None # type: ignore pytestmark = pytest.mark.skipif( Migrator is None, reason="django-test-migrations is not available", ) @pytest.mark.django_db def test_migrations_0001_initial(migrator: Migrator) -> None: old_state = migrator.apply_initial_migration(("rest_framework_api_key", None)) with pytest.raises(LookupError): old_state.apps.get_model("rest_framework_api_key", "APIKey") new_state = migrator.apply_tested_migration( ("rest_framework_api_key", "0001_initial") ) APIKey = new_state.apps.get_model("rest_framework_api_key", "APIKey") assert APIKey.objects.count() == 0 @pytest.mark.django_db def test_migrations_0004_prefix_hashed_key(migrator: Migrator) -> None: from django.contrib.auth.hashers import make_password from django.utils.crypto import get_random_string def _generate() -> Tuple[str, str]: # Replicate bejavior before PR #62 (i.e. before v1.4). prefix = get_random_string(8) secret_key = get_random_string(32) key = prefix + "." + secret_key key_id = prefix + "." + make_password(key) return key, key_id def _assign_key(obj: Any) -> None: # Replicate bejavior before PR #62 (i.e. before v1.4). _, hashed_key = _generate() pk = hashed_key prefix, _, hashed_key = hashed_key.partition(".") obj.id = pk obj.prefix = prefix obj.hashed_key = hashed_key old_state = migrator.apply_initial_migration( ("rest_framework_api_key", "0003_auto_20190623_1952") ) APIKey = old_state.apps.get_model("rest_framework_api_key", "APIKey") # Create a key as it if were created before PR #62 (i.e. before v1.4). api_key = APIKey.objects.create(name="test") _assign_key(api_key) api_key.save() prefix, _, hashed_key = api_key.id.partition(".") # Apply migration added by PR #62. new_state = migrator.apply_tested_migration( ("rest_framework_api_key", "0004_prefix_hashed_key") ) APIKey = new_state.apps.get_model("rest_framework_api_key", "APIKey") # Ensure new `prefix`` and `hashed_key` fields were successfully populated. api_key = APIKey.objects.get(id=api_key.id) assert api_key.prefix == prefix assert api_key.hashed_key == hashed_key djangorestframework-api-key-3.1.0/tests/test_model.py000066400000000000000000000075001477371521300230150ustar00rootroot00000000000000import datetime as dt import string import pytest from django.contrib.auth.hashers import make_password from django.core.exceptions import ValidationError from django.db.utils import IntegrityError from test_project.heroes.models import Hero, HeroAPIKey from rest_framework_api_key.models import APIKey from .dateutils import NOW, TOMORROW, YESTERDAY pytestmark = pytest.mark.django_db def test_key_generation() -> None: api_key, generated_key = APIKey.objects.create_key(name="test") prefix = api_key.prefix hashed_key = api_key.hashed_key assert prefix and hashed_key charset = set(string.ascii_letters + string.digits + ".") assert all(c in charset for c in generated_key) # The generated key must be valid… assert api_key.is_valid(generated_key) is True # But not the hashed key. assert api_key.is_valid(hashed_key) is False def test_name_is_required() -> None: with pytest.raises(IntegrityError): APIKey.objects.create() def test_cannot_unrevoke() -> None: api_key, _ = APIKey.objects.create_key(name="test", revoked=True) # Try to unrevoke the API key programmatically. api_key.revoked = False with pytest.raises(ValidationError): api_key.save() with pytest.raises(ValidationError): api_key.clean() @pytest.mark.parametrize( "expiry_date, has_expired", [(None, False), (NOW, True), (TOMORROW, False), (YESTERDAY, True)], ) def test_has_expired(expiry_date: dt.datetime, has_expired: bool) -> None: api_key, _ = APIKey.objects.create_key(name="test", expiry_date=expiry_date) assert api_key.has_expired is has_expired def test_custom_api_key_model() -> None: hero = Hero.objects.create() hero_api_key, generated_key = HeroAPIKey.objects.create_key(name="test", hero=hero) assert hero_api_key.is_valid(generated_key) assert hero_api_key.hero.id == hero.id assert hero.api_keys.first() == hero_api_key @pytest.mark.django_db def test_api_key_hash_upgrade() -> None: """Tests the hashing algo upgrade from Django's PW hashers to sha512.""" key_generator = APIKey.objects.key_generator api_key, generated_key = APIKey.objects.create_key(name="test") assert api_key.is_valid(generated_key) assert key_generator.using_preferred_hasher(api_key.hashed_key) # Use Django's built-in hashers, the old way of storing a key api_key.hashed_key = make_password(generated_key) api_key.save() # Simple sanity check to ensure the hash is still being checked # and that we aren't using the preferred hasher (using Django's slower hashers) assert not api_key.is_valid(key_generator.hash("invalid-key")) assert not key_generator.using_preferred_hasher(api_key.hashed_key) # After calling `is_valid`, the key has been upgraded to use the preferred hasher assert api_key.is_valid(generated_key) assert key_generator.using_preferred_hasher(api_key.hashed_key) @pytest.mark.django_db def test_api_key_manager_get_from_key() -> None: api_key, generated_key = APIKey.objects.create_key(name="test") retrieved_key = APIKey.objects.get_from_key(generated_key) assert retrieved_key == api_key @pytest.mark.django_db def test_api_key_manager_get_from_key_missing_key() -> None: with pytest.raises(APIKey.DoesNotExist): APIKey.objects.get_from_key("foobar") @pytest.mark.django_db def test_api_key_manager_get_from_key_invalid_key() -> None: api_key, generated_key = APIKey.objects.create_key(name="test") prefix, _, _ = generated_key.partition(".") invalid_key = f"{prefix}.foobar" with pytest.raises(APIKey.DoesNotExist): APIKey.objects.get_from_key(invalid_key) def test_api_key_str() -> None: _, generated_key = APIKey.objects.create_key(name="test") retrieved_key = APIKey.objects.get_from_key(generated_key) assert str(retrieved_key) == "test" djangorestframework-api-key-3.1.0/tests/test_permissions.py000066400000000000000000000112351477371521300242700ustar00rootroot00000000000000import datetime as dt from typing import Callable import pytest from django.test import RequestFactory, override_settings from rest_framework.decorators import api_view, permission_classes from rest_framework.request import Request from rest_framework.response import Response from rest_framework_api_key.models import APIKey from rest_framework_api_key.permissions import BaseHasAPIKey, HasAPIKey, KeyParser pytestmark = pytest.mark.django_db @api_view() @permission_classes([HasAPIKey]) def view(request: Request) -> Response: return Response() def test_if_valid_api_key_then_permission_granted(rf: RequestFactory) -> None: _, key = APIKey.objects.create_key(name="test") authorization = f"Api-Key {key}" request = rf.get("/test/", HTTP_AUTHORIZATION=authorization) response = view(request) assert response.status_code == 200 def test_if_valid_api_key_custom_header_then_permission_granted( rf: RequestFactory, ) -> None: with override_settings(API_KEY_CUSTOM_HEADER="HTTP_X_API_KEY"): _, key = APIKey.objects.create_key(name="test") request = rf.get("/test/", HTTP_X_API_KEY=key) response = view(request) assert response.status_code == 200 def test_if_no_api_key_then_permission_denied(rf: RequestFactory) -> None: request = rf.get("/test/") response = view(request) assert response.status_code == 403 def _scramble_prefix(key: str) -> str: prefix, _, secret_key = key.partition(".") truncated_prefix = prefix[:-1] return truncated_prefix + "." + secret_key @pytest.mark.parametrize( "modifier", [ lambda _: "", lambda _: "abcd", lambda _: "foo.bar", lambda key: " " + key, lambda key: key.upper(), lambda key: key.lower(), lambda key: _scramble_prefix(key), ], ) def test_if_invalid_api_key_then_permission_denied( rf: RequestFactory, modifier: Callable[[str], str], ) -> None: _, key = APIKey.objects.create_key(name="test") authorization = f"Api-Key {modifier(key)}" request = rf.get("/test/", HTTP_AUTHORIZATION=authorization) response = view(request) assert response.status_code == 403 @pytest.mark.parametrize( "authorization_fmt", [ pytest.param("X-Key {key}", id="wrong-scheme"), pytest.param("Api-Key:{key}", id="not-space-separated"), ], ) def test_if_malformed_authorization_then_permission_denied( rf: RequestFactory, authorization_fmt: str ) -> None: _, key = APIKey.objects.create_key(name="test") authorization = authorization_fmt.format(key=key) request = rf.get("/test/", HTTP_AUTHORIZATION=authorization) response = view(request) assert response.status_code == 403 def test_if_invalid_api_key_custom_header_then_permission_denied( rf: RequestFactory, ) -> None: with override_settings(API_KEY_CUSTOM_HEADER="HTTP_X_API_KEY"): request = rf.get("/test/", HTTP_X_API_KEY="doesnotexist") response = view(request) assert response.status_code == 403 def test_if_revoked_then_permission_denied(rf: RequestFactory) -> None: _, key = APIKey.objects.create_key(name="test", revoked=True) authorization = f"Api-Key {key}" request = rf.get("/test/", HTTP_AUTHORIZATION=authorization) response = view(request) assert response.status_code == 403 NOW = dt.datetime.now() TOMORROW = NOW + dt.timedelta(days=1) TWO_DAYS_AGO = NOW - dt.timedelta(days=2) @pytest.mark.parametrize("expiry_date, ok", [(TOMORROW, True), (TWO_DAYS_AGO, False)]) def test_expiry_date(rf: RequestFactory, expiry_date: dt.datetime, ok: bool) -> None: _, key = APIKey.objects.create_key(name="test", expiry_date=expiry_date) authorization = f"Api-Key {key}" request = rf.get("/test/", HTTP_AUTHORIZATION=authorization) response = view(request) status_code = 200 if ok else 403 assert response.status_code == status_code def test_keyparser_keyword_override(rf: RequestFactory) -> None: class BearerKeyParser(KeyParser): keyword = "Bearer" class BearerHasAPIKey(BaseHasAPIKey): model = APIKey key_parser = BearerKeyParser() @api_view() @permission_classes([BearerHasAPIKey]) def bearer_view(request: Request) -> Response: return Response() _, key = APIKey.objects.create_key(name="test") authorization = f"Bearer {key}" request = rf.get("/test/", HTTP_AUTHORIZATION=authorization) response = bearer_view(request) assert response.status_code == 200 def test_keyparser_lookup_exact_keyword(rf: RequestFactory) -> None: wrong_key = "My-Special-Api-Key 12345" request = rf.get("/test/", HTTP_AUTHORIZATION=wrong_key) assert KeyParser().get(request) is None djangorestframework-api-key-3.1.0/tests/test_permissions_combination.py000066400000000000000000000026501477371521300266530ustar00rootroot00000000000000import pytest from django.contrib.auth import get_user_model from django.test import RequestFactory from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.request import Request from rest_framework.response import Response from rest_framework.test import force_authenticate from rest_framework_api_key.models import APIKey from rest_framework_api_key.permissions import HasAPIKey pytestmark = pytest.mark.django_db @api_view() @permission_classes([HasAPIKey | IsAuthenticated]) def view(request: Request) -> Response: return Response() def test_if_authenticated_and_no_api_key_then_permission_granted( rf: RequestFactory, ) -> None: user = get_user_model().objects.create_user(username="foo", password="bar") request = rf.get("/test/") force_authenticate(request, user) response = view(request) assert response.status_code == 200, response.data def test_if_authenticated_and_revoked_api_key_then_permission_granted( rf: RequestFactory, ) -> None: user = get_user_model().objects.create_user(username="foo", password="bar") _, key = APIKey.objects.create_key(name="test", revoked=True) authorization = f"Api-Key {key}" request = rf.get("/test/", HTTP_AUTHORIZATION=authorization) force_authenticate(request, user) response = view(request) assert response.status_code == 200, response.data djangorestframework-api-key-3.1.0/tests/test_permissions_custom.py000066400000000000000000000027131477371521300256630ustar00rootroot00000000000000import pytest from django.test import RequestFactory from rest_framework.decorators import api_view, permission_classes from rest_framework.request import Request from rest_framework.response import Response from test_project.heroes.models import Hero, HeroAPIKey from test_project.heroes.permissions import HasHeroAPIKey from rest_framework_api_key.models import APIKey pytestmark = pytest.mark.django_db @api_view() @permission_classes([HasHeroAPIKey]) def view(request: Request) -> Response: return Response() def test_non_hero_api_key_denied(rf: RequestFactory) -> None: _, key = APIKey.objects.create_key(name="test") authorization = f"Api-Key {key}" request = rf.get("/test/", HTTP_AUTHORIZATION=authorization) response = view(request) assert response.status_code == 403 def test_hero_api_key_granted(rf: RequestFactory) -> None: hero = Hero.objects.create() _, key = HeroAPIKey.objects.create_key(name="test", hero=hero) authorization = f"Api-Key {key}" request = rf.get("/test/", HTTP_AUTHORIZATION=authorization) response = view(request) assert response.status_code == 200 def test_retired_hero_denied(rf: RequestFactory) -> None: hero = Hero.objects.create(retired=True) _, key = HeroAPIKey.objects.create_key(name="test", hero=hero) authorization = f"Api-Key {key}" request = rf.get("/test/", HTTP_AUTHORIZATION=authorization) response = view(request) assert response.status_code == 403 djangorestframework-api-key-3.1.0/tests/test_test_project.py000066400000000000000000000013501477371521300244170ustar00rootroot00000000000000import pytest from rest_framework.test import APIClient from test_project.heroes.models import Hero from test_project.heroes.permissions import HeroAPIKey @pytest.mark.django_db def test_test_project_routes() -> None: batman = Hero.objects.create(name="Batman") _, key = HeroAPIKey.objects.create_key(name="test", hero=batman) headers = {"HTTP_AUTHORIZATION": f"Api-Key {key}"} client = APIClient() response = client.get("/api/public/", format="json") assert response.status_code == 200 response = client.get("/api/protected/", format="json", **headers) assert response.status_code == 200 response = client.get("/api/protected/object/", format="json", **headers) assert response.status_code == 200 djangorestframework-api-key-3.1.0/tools/000077500000000000000000000000001477371521300203005ustar00rootroot00000000000000djangorestframework-api-key-3.1.0/tools/install_django.sh000077500000000000000000000001541477371521300236270ustar00rootroot00000000000000#!/bin/sh -ex PIP="$1" DJANGO_VERSION=${DJANGO_VERSION:-5.2} exec ${PIP} install django==$DJANGO_VERSION djangorestframework-api-key-3.1.0/tools/makemigrations.py000077500000000000000000000011441477371521300236670ustar00rootroot00000000000000"""A stand-alone equivalent of `python manage.py makemigrations`.""" import pathlib import sys import django from django.conf import settings from django.core.management import call_command root = pathlib.Path(__file__).parent.parent sys.path.append(str(root)) if __name__ == "__main__": APP = "rest_framework_api_key" settings.configure(INSTALLED_APPS=[APP, "test_project.heroes"]) django.setup() # For available options, see: # https://docs.djangoproject.com/en/3.0/ref/django-admin/#makemigrations options = sys.argv[1:] call_command("makemigrations", *options, APP, "heroes")