zulip/zproject/config.py
Zixuan James Li 059d0e7be8 settings: Make SHARED_SECRET mandatory.
This implements get_mandatory_secret that ensures SHARED_SECRET is
set when we hit zerver.decorator.authenticate_notify. To avoid getting
ZulipSettingsError when setting up the secrets, we set an environment
variable DISABLE_MANDATORY_SECRET_CHECK to skip the check and default
its value to an empty string.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-08-25 12:13:03 -07:00

76 lines
2.0 KiB
Python

import configparser
import os
from typing import Optional, overload
from django.core.exceptions import ImproperlyConfigured
class ZulipSettingsError(ImproperlyConfigured):
pass
DEPLOY_ROOT = os.path.realpath(os.path.dirname(os.path.dirname(__file__)))
config_file = configparser.RawConfigParser()
config_file.read("/etc/zulip/zulip.conf")
# Whether this instance of Zulip is running in a production environment.
PRODUCTION = config_file.has_option("machine", "deploy_type")
DEVELOPMENT = not PRODUCTION
secrets_file = configparser.RawConfigParser()
if PRODUCTION:
secrets_file.read("/etc/zulip/zulip-secrets.conf")
else:
secrets_file.read(os.path.join(DEPLOY_ROOT, "zproject/dev-secrets.conf"))
@overload
def get_secret(key: str, default_value: str, development_only: bool = False) -> str:
...
@overload
def get_secret(
key: str, default_value: Optional[str] = None, development_only: bool = False
) -> Optional[str]:
...
def get_secret(
key: str, default_value: Optional[str] = None, development_only: bool = False
) -> Optional[str]:
if development_only and PRODUCTION:
return default_value
return secrets_file.get("secrets", key, fallback=default_value)
def get_mandatory_secret(key: str) -> str:
secret = get_secret(key)
if secret is None:
if os.environ.get("DISABLE_MANDATORY_SECRET_CHECK") == "True":
return ""
raise ZulipSettingsError(f'Mandatory secret "{key}" is not set')
return secret
@overload
def get_config(section: str, key: str, default_value: str) -> str:
...
@overload
def get_config(section: str, key: str, default_value: Optional[str] = None) -> Optional[str]:
...
def get_config(section: str, key: str, default_value: Optional[str] = None) -> Optional[str]:
return config_file.get(section, key, fallback=default_value)
def get_from_file_if_exists(path: str) -> str:
if os.path.exists(path):
with open(path) as f:
return f.read()
else:
return ""