aurweb.asgi: add security headers middleware

This commit introduces a middleware function which adds
the following security headers to each response:

- Content-Security-Policy
    - This includes a new `nonce`, which is tied to a user
      via authentication middleware. Both an anonymous user
      and an authenticated user recieve their own random nonces.
- X-Content-Type-Options
- Referrer-Policy
- X-Frame-Options

They are then tested for existence in test/test_routes.py.

Note: The overcomplicated-looking asyncio behavior in the
middleware function is used to avoid a warning about the old
coroutine awaits being deprecated. See
https://docs.python.org/3/library/asyncio-task.html#asyncio.wait
for more detail.

Signed-off-by: Kevin Morris <kevr@0cost.org>
This commit is contained in:
Kevin Morris 2021-06-12 03:54:41 -07:00
parent 13456fea1e
commit 865c414504
6 changed files with 106 additions and 3 deletions

View file

@ -1,6 +1,8 @@
import base64
import math
import random
import re
import secrets
import string
from collections import OrderedDict
@ -20,6 +22,15 @@ def make_random_string(length):
string.digits, k=length))
def make_nonce(length: int = 8):
""" Generate a single random nonce. Here, token_hex generates a hex
string of 2 hex characters per byte, where the length give is
nbytes. This means that to get our proper string length, we need to
cut it in half and truncate off any remaining (in the case that
length was uneven). """
return secrets.token_hex(math.ceil(length / 2))[:length]
def valid_username(username):
min_len = aurweb.config.getint("options", "username_min_len")
max_len = aurweb.config.getint("options", "username_max_len")