| 1 |
Handling Secrets |
| 2 |
================ |
| 3 |
|
| 4 |
Overview |
| 5 |
-------- |
| 6 |
|
| 7 |
Two data structures are available to assist in handling secrets in web services: |
| 8 |
:class:`SecretString <datastructures.SecretString>` and :class:`SecretBytes <datastructures.SecretBytes>`. These are |
| 9 |
containers for holding sensitive data within your application. |
| 10 |
|
| 11 |
Secret Parameters |
| 12 |
----------------- |
| 13 |
|
| 14 |
The following example demonstrates how to use :class:`~datastructures.SecretString` to accept a secret value as a parameter in a GET request: |
| 15 |
|
| 16 |
.. literalinclude:: /examples/datastructures/secrets/secret_header.py |
| 17 |
:language: python |
| 18 |
:caption: Example of using ``SecretString`` for a Header Parameter |
| 19 |
|
| 20 |
.. note:: |
| 21 |
|
| 22 |
When storing and comparing secrets, use secure practices to prevent unauthorized access. For example, use |
| 23 |
environment variables, secret management services, or encrypted databases to store secrets securely. When comparing |
| 24 |
secrets, use :func:`secrets.compare_digest` or similar to mitigate the risk of timing attacks. |
| 25 |
|
| 26 |
.. note:: |
| 27 |
|
| 28 |
The :func:`headers <connection.ASGIConnection.headers>` attribute of the :class:`~connection.ASGIConnection` |
| 29 |
object stores the headers exactly as they are parsed from the ASGI message. Care should be taken to ensure that |
| 30 |
these headers are not logged or otherwise exposed in a way that could compromise the security of the application. |
| 31 |
|
| 32 |
Secret Body |
| 33 |
----------- |
| 34 |
|
| 35 |
This example demonstrates use of a data structure with a :class:`~datastructures.SecretString` field to accept a secret |
| 36 |
within the HTTP body of a request: |
| 37 |
|
| 38 |
.. literalinclude:: /examples/datastructures/secrets/secret_body.py |
| 39 |
:language: python |
| 40 |
:caption: Example of using ``SecretString`` for a Request Body |
| 41 |
|
| 42 |
Security Considerations |
| 43 |
----------------------- |
| 44 |
|
| 45 |
While :class:`SecretString` and :class:`SecretBytes` can help in securely transferring secret data through the framework, |
| 46 |
it's vital to adopt secure practices for storing and comparing secrets within your application. Here are a few |
| 47 |
guidelines: |
| 48 |
|
| 49 |
- Store secrets securely, using environment variables, secret management services, or encrypted databases. |
| 50 |
- Always use constant time comparison functions such as :func:`secrets.compare_digest` for comparing secret values to |
| 51 |
mitigate the risk of timing attacks. |
| 52 |
- Implement access controls and logging to monitor and restrict who can access sensitive information. |