From 3b588d2da51c88573995e94d3221957569d86c2e Mon Sep 17 00:00:00 2001 From: DarkCat09 Date: Fri, 24 Mar 2023 19:00:31 +0400 Subject: [PATCH] Different keys for session and csrf checking middleware, some comments in compose yml and .env --- .env | 5 ++++- app/common.py | 41 +++++++++++++++++++++++++---------------- app/main.py | 4 ++-- docker-compose.yml | 12 ++++++++---- 4 files changed, 39 insertions(+), 23 deletions(-) diff --git a/.env b/.env index cbec572..a6c7090 100644 --- a/.env +++ b/.env @@ -2,7 +2,10 @@ APP_HOST=0.0.0.0 APP_PORT=8000 # Generate a strong secret key -# On Linux: openssl rand -hex 32 +# +# On Linux: tr -dc A-Za-z0-9_- None: +def secret_key_check(name: SecretKey) -> None: """Generates a secret key automatically - if the env var `secret_key` is not set + if an environment variable is not set or contains text `secret`""" - if settings.secret_key == 'secret': + settings_dict = settings.dict() + if settings_dict.get(name) != 'secret': + return - key_file = Path('/tmp/secret_key') + key_file = Path(f'/tmp/{name}') - if key_file.exists(): - with key_file.open('rt') as f: - secret_key = f.read() + if key_file.exists(): + with key_file.open('rt') as f: + key = f.read() - else: - secret_key = secrets.token_hex(32) - with key_file.open('wt') as f: - f.write(secret_key) + else: + key = secrets.token_hex(32) + with key_file.open('wt') as f: + f.write(key) - settings.secret_key = secret_key + settings_dict[name] = key -# Call the function -secret_key_check() +# Calling the function +# for session and CSRF keys +secret_key_check('session_key') +secret_key_check('csrf_key') diff --git a/app/main.py b/app/main.py index 3b83319..cb7a407 100644 --- a/app/main.py +++ b/app/main.py @@ -42,9 +42,9 @@ for p in paths: # Add WTForms CSRF protection middlewares app.add_middleware( SessionMiddleware, - secret_key=common.settings.secret_key, + secret_key=common.settings.session_key, ) app.add_middleware( CSRFProtectMiddleware, - csrf_secret=common.settings.secret_key, + csrf_secret=common.settings.csrf_key, ) diff --git a/docker-compose.yml b/docker-compose.yml index 051d19e..beac7ed 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,20 +2,20 @@ version: "3" services: - ${REPO_NAME_SNAKE}: + app: image: ${REPO_OWNER_LOWER}/${REPO_NAME_SNAKE}:latest container_name: ${REPO_NAME_SNAKE} restart: unless-stopped ports: - "8080:8000" links: - - ${REPO_NAME_SNAKE}_db + - database env_file: .env depends_on: - ${REPO_NAME_SNAKE}_db: + database: condition: service_healthy - ${REPO_NAME_SNAKE}_db: + database: image: mariadb:latest container_name: ${REPO_NAME_SNAKE}_db restart: unless-stopped @@ -29,5 +29,9 @@ services: timeout: 3s retries: 20 +# Comment or remove these lines and +# edit `volumes` in services->database +# if you are going to store +# your DB in a directory volumes: db_data: