Skip to content

Commit

Permalink
fix: LSDV-5071: Ensure secret key is securely set persisting a new on…
Browse files Browse the repository at this point in the history
…e if required (#4690)

* feat: retrieve SECRET_KEY from env with fallback

* fix: LSDV-5071: Ensure secret key is securely set persisting a new one if required

* use the ls data dir env if specified with a fallback to the standard directory location

* add more context to warning message

---------

Co-authored-by: Robert Schuh <github@eneticum.de>
  • Loading branch information
bmartel and Robbilie committed Aug 28, 2023
1 parent 20d78ad commit 3d06c51
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 2 deletions.
1 change: 1 addition & 0 deletions deploy/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Django==3.2.20
django-storages==1.12.3
django_annoying==0.10.6
django_debug_toolbar==3.2.1
django-environ==0.10.0
django_filter==2.4.0
django_model_utils==4.1.1
django_rq==2.5.1
Expand Down
4 changes: 2 additions & 2 deletions label_studio/core/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
if not logging.getLogger().hasHandlers():
logging.basicConfig(level=logging.DEBUG, format='%(message)s')

from label_studio.core.utils.io import get_data_dir
from label_studio.core.utils.io import get_data_dir, generate_key_if_missing
from label_studio.core.utils.params import get_bool_env, get_env, get_env_list_int

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -105,7 +105,7 @@
INTERNAL_PORT = '8080'

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$(fefwefwef13;LFK{P!)@#*!)kdsjfWF2l+i5e3t(8a1n'
SECRET_KEY = generate_key_if_missing('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = get_bool_env('DEBUG', True)
Expand Down
19 changes: 19 additions & 0 deletions label_studio/core/utils/io.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import os
import socket
Expand All @@ -16,6 +17,8 @@
from tempfile import mkstemp, mkdtemp

from django.conf import settings
from django.core.management.utils import get_random_secret_key
from label_studio.core.utils.params import env, env_file
from appdirs import user_config_dir, user_data_dir, user_cache_dir

# full path import results in unit test failures
Expand Down Expand Up @@ -208,3 +211,19 @@ def validate_upload_url(url, block_local_urls=True):
if ipaddress.ip_address(ip) in ipaddress.ip_network(subnet):
raise InvalidUploadUrlError

def generate_key_if_missing(key):
value = env.str(key, "")

if value == "":
print(f'Warning: {key} not found in environment variables will generate a random key.')
value = get_random_secret_key()
try:
with open(env_file, 'a') as f:
f.write(f'\n{key}={value}\n')
except Exception as e:
print(f'Warning: failed to write {key} to .env file: {e}, new key will be regenerated on every server restart. If this key is used for signing, it will invalidate all existing sessions or tokens. Please set {key} in your environment variables to avoid this warning.')

os.environ[key] = value

return value

7 changes: 7 additions & 0 deletions label_studio/core/utils/params.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import os
import environ

from rest_framework.exceptions import ValidationError


env = environ.Env()
data_dir = os.environ.get('LABEL_STUDIO_DATA_DIR', os.path.join(os.path.dirname(__file__), '..', '..', '..', 'data'))
env_file = os.path.join(data_dir, '.env')
environ.Env.read_env(env_file)

def cast_bool_from_str(value):
if isinstance(value, str):
if value.lower() in ['true', 'yes', 'on', '1']:
Expand Down

0 comments on commit 3d06c51

Please sign in to comment.