-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: LEAP-38: Rework secret key generation to use data volume more re…
…liably (#4716) fix: LEAP-38: rework secret key generation to use data volume more reliably (#4713) * fix: LEAP-38: rework secret key generation to use data volume more reliably * remove key name param * Update label_studio/core/utils/secret_key.py --------- Co-authored-by: Jo Booth <[email protected]>
- Loading branch information
Showing
4 changed files
with
33 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import logging | ||
import os | ||
import environ | ||
from django.core.management.utils import get_random_secret_key | ||
|
||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
def generate_secret_key_if_missing(data_dir: str) -> str: | ||
env_key = 'SECRET_KEY' | ||
env = environ.Env() | ||
env_filepath = os.path.join(data_dir, '.env') | ||
environ.Env.read_env(env_filepath) | ||
|
||
if existing_secret := env.str(env_key, ""): | ||
return existing_secret | ||
|
||
logger.warning(f'Warning: {env_key} not found in environment variables. Will generate a random key.') | ||
new_secret = get_random_secret_key() | ||
try: | ||
with open(env_filepath, 'a') as f: | ||
f.write(f'\n{env_key}={new_secret}\n') # nosec | ||
except Exception as e: | ||
logger.warning(f'Warning: failed to write {env_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[env_key] = new_secret | ||
return new_secret |