settings.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. """
  2. Django settings for GlitchTip project.
  3. For more information on this file, see
  4. https://docs.djangoproject.com/en/dev/topics/settings/
  5. For the full list of settings and their values, see
  6. https://docs.djangoproject.com/en/dev/ref/settings/
  7. """
  8. import logging
  9. import os
  10. import sys
  11. import warnings
  12. from datetime import timedelta
  13. import environ
  14. import sentry_sdk
  15. from celery.schedules import crontab
  16. from corsheaders.defaults import default_headers
  17. from django.conf import global_settings
  18. from django.core.exceptions import ImproperlyConfigured
  19. from django.http import UnreadablePostError
  20. from sentry_sdk.integrations.django import DjangoIntegration
  21. env = environ.FileAwareEnv(
  22. ALLOWED_HOSTS=(list, ["*"]),
  23. DEFAULT_FILE_STORAGE=(str, global_settings.STORAGES["default"]["BACKEND"]),
  24. AWS_ACCESS_KEY_ID=(str, None),
  25. AWS_SECRET_ACCESS_KEY=(str, None),
  26. AWS_STORAGE_BUCKET_NAME=(str, None),
  27. AWS_S3_ENDPOINT_URL=(str, None),
  28. AWS_LOCATION=(str, ""),
  29. AZURE_ACCOUNT_NAME=(str, None),
  30. AZURE_ACCOUNT_KEY=(str, None),
  31. AZURE_CONTAINER=(str, None),
  32. AZURE_URL_EXPIRATION_SECS=(int, None),
  33. IS_LOAD_TEST=(bool, False),
  34. GS_BUCKET_NAME=(str, None),
  35. GS_PROJECT_ID=(str, None),
  36. DEBUG=(bool, False),
  37. DEBUG_TOOLBAR=(bool, False),
  38. STATIC_URL=(str, "/"),
  39. ENABLE_OBSERVABILITY_API=(bool, False),
  40. )
  41. path = environ.Path()
  42. # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
  43. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  44. # Quick-start development settings - unsuitable for production
  45. # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
  46. # SECURITY WARNING: keep the secret key used in production secret!
  47. SECRET_KEY = env.str("SECRET_KEY", "change_me")
  48. # SECURITY WARNING: don't run with debug turned on in production!
  49. DEBUG = env("DEBUG")
  50. # Enable only for running end to end testing. Debug must be True to use.
  51. ENABLE_TEST_API = env.bool("ENABLE_TEST_API", False)
  52. if DEBUG is False:
  53. ENABLE_TEST_API = False
  54. if DEBUG and ENABLE_TEST_API:
  55. ACCOUNT_RATE_LIMITS = False # Disable for e2e tests
  56. ALLOWED_HOSTS = env("ALLOWED_HOSTS")
  57. # Necessary for kubernetes health checks
  58. POD_IP = env.str("POD_IP", default=None)
  59. if POD_IP:
  60. ALLOWED_HOSTS.append(POD_IP)
  61. ENVIRONMENT = env.str("ENVIRONMENT", None)
  62. GLITCHTIP_VERSION = env.str("GLITCHTIP_VERSION", "0.0.0-unknown")
  63. # Used in email and DSN generation. Set to full domain such as https://glitchtip.example.com
  64. default_url = env.str(
  65. "APP_URL", env.str("GLITCHTIP_DOMAIN", "http://localhost:8000")
  66. ) # DigitalOcean App Platform uses APP_URL
  67. GLITCHTIP_URL = env.url("GLITCHTIP_URL", default_url)
  68. if GLITCHTIP_URL.scheme not in ["http", "https"]:
  69. raise ImproperlyConfigured("GLITCHTIP_DOMAIN must start with http or https")
  70. # Is running unit test
  71. TESTING = len(sys.argv) > 1 and sys.argv[1] == "test"
  72. DATA_UPLOAD_MAX_MEMORY_SIZE = 4294967295 # TMP REMOVE THIS
  73. DATA_UPLOAD_MAX_NUMBER_FIELDS = env.int(
  74. "DATA_UPLOAD_MAX_NUMBER_FIELDS",
  75. default=global_settings.DATA_UPLOAD_MAX_NUMBER_FIELDS,
  76. )
  77. # Limits size (in bytes) of uncompressed event payloads. Mitigates DOS risk.
  78. GLITCHTIP_MAX_UNZIPPED_PAYLOAD_SIZE = env.int(
  79. "GLITCHTIP_MAX_UNZIPPED_PAYLOAD_SIZE", global_settings.DATA_UPLOAD_MAX_MEMORY_SIZE
  80. )
  81. # Events and associated data older than this will be deleted from the database
  82. GLITCHTIP_MAX_EVENT_LIFE_DAYS = env.int("GLITCHTIP_MAX_EVENT_LIFE_DAYS", default=90)
  83. GLITCHTIP_MAX_UPTIME_CHECK_LIFE_DAYS = env.int(
  84. "GLITCHTIP_MAX_UPTIME_CHECK_LIFE_DAYS", default=GLITCHTIP_MAX_EVENT_LIFE_DAYS
  85. )
  86. GLITCHTIP_MAX_TRANSACTION_EVENT_LIFE_DAYS = env.int(
  87. "GLITCHTIP_MAX_TRANSACTION_EVENT_LIFE_DAYS", default=GLITCHTIP_MAX_EVENT_LIFE_DAYS
  88. )
  89. GLITCHTIP_MAX_FILE_LIFE_DAYS = env.int(
  90. "GLITCHTIP_MAX_EVENT_LIFE_DAYS", default=GLITCHTIP_MAX_EVENT_LIFE_DAYS
  91. )
  92. # Check if a throttle is needed 1 out of every 5000 event requests
  93. GLITCHTIP_THROTTLE_CHECK_INTERVAL = env.int("GLITCHTIP_THROTTLE_CHECK_INTERVAL", 5000)
  94. # Freezes acceptance of new events, for use during db maintenance
  95. MAINTENANCE_EVENT_FREEZE = env.bool("MAINTENANCE_EVENT_FREEZE", False)
  96. # For development purposes only, prints out inbound event store json
  97. EVENT_STORE_DEBUG = env.bool("EVENT_STORE_DEBUG", False)
  98. # Static files (CSS, JavaScript, Images)
  99. # https://docs.djangoproject.com/en/dev/howto/static-files/
  100. STATIC_URL = "/static/"
  101. # GlitchTip can track GlitchTip's own errors.
  102. # If enabling this, use a different server to avoid infinite loops.
  103. def before_send(event, hint):
  104. """Don't log useless, inactionable errors in Sentry."""
  105. if "log_record" in hint:
  106. if hint["log_record"].name == "django.security.DisallowedHost":
  107. return None
  108. if "exc_info" in hint:
  109. _, exc_value, _ = hint["exc_info"]
  110. if isinstance(exc_value, UnreadablePostError):
  111. return None
  112. return event
  113. SENTRY_DSN = env.str("SENTRY_DSN", None)
  114. # Optionally allow a different DSN for the frontend
  115. SENTRY_FRONTEND_DSN = env.str("SENTRY_FRONTEND_DSN", SENTRY_DSN)
  116. # Set sample_rate to 1.0 to capture 100%.
  117. SENTRY_SAMPLE_RATE = env.float("SENTRY_SAMPLE_RATE", 1.0)
  118. # Set traces_sample_rate to 1.0 to capture 100%. Recommended to keep this value low.
  119. SENTRY_TRACES_SAMPLE_RATE = env.float("SENTRY_TRACES_SAMPLE_RATE", 0.01)
  120. # Ignore whitenoise served static routes
  121. def traces_sampler(sampling_context):
  122. if (
  123. sampling_context.get("wsgi_environ", {})
  124. .get("PATH_INFO", "")
  125. .startswith(STATIC_URL)
  126. ):
  127. return 0.0
  128. return SENTRY_TRACES_SAMPLE_RATE
  129. if SENTRY_DSN:
  130. release = "glitchtip@" + GLITCHTIP_VERSION if GLITCHTIP_VERSION else None
  131. sentry_sdk.init(
  132. dsn=SENTRY_DSN,
  133. integrations=[DjangoIntegration()],
  134. before_send=before_send,
  135. release=release,
  136. environment=ENVIRONMENT,
  137. auto_session_tracking=False,
  138. send_client_reports=False,
  139. sample_rate=SENTRY_SAMPLE_RATE,
  140. traces_sample_rate=SENTRY_TRACES_SAMPLE_RATE,
  141. traces_sampler=traces_sampler,
  142. )
  143. def show_toolbar(request):
  144. return env("DEBUG_TOOLBAR")
  145. DEBUG_TOOLBAR = env("DEBUG_TOOLBAR")
  146. DEBUG_TOOLBAR_CONFIG = {"SHOW_TOOLBAR_CALLBACK": show_toolbar}
  147. DEBUG_TOOLBAR_PANELS = [
  148. "debug_toolbar.panels.versions.VersionsPanel",
  149. "debug_toolbar.panels.timer.TimerPanel",
  150. "debug_toolbar.panels.settings.SettingsPanel",
  151. "debug_toolbar.panels.headers.HeadersPanel",
  152. "debug_toolbar.panels.request.RequestPanel",
  153. "debug_toolbar.panels.sql.SQLPanel",
  154. # "debug_toolbar.panels.history.HistoryPanel",
  155. # "debug_toolbar.panels.profiling.ProfilingPanel",
  156. ]
  157. # Application definition
  158. # Conditionally load to workaround unnecessary memory usage in celery/beat
  159. WEB_INSTALLED_APPS = [
  160. "django.contrib.admin",
  161. "django.contrib.messages",
  162. "django.contrib.staticfiles",
  163. "ninja",
  164. ]
  165. INSTALLED_APPS = [
  166. "django.contrib.auth",
  167. "django.contrib.contenttypes",
  168. "django.contrib.humanize",
  169. "psqlextra",
  170. "django_prometheus",
  171. "allauth",
  172. "allauth.account",
  173. "allauth.headless",
  174. "allauth.mfa",
  175. "allauth.socialaccount",
  176. "allauth.socialaccount.providers.digitalocean",
  177. "allauth.socialaccount.providers.gitea",
  178. "allauth.socialaccount.providers.github",
  179. "allauth.socialaccount.providers.gitlab",
  180. "allauth.socialaccount.providers.google",
  181. "allauth.socialaccount.providers.microsoft",
  182. "allauth.socialaccount.providers.nextcloud",
  183. "allauth.socialaccount.providers.openid_connect",
  184. "allauth.socialaccount.providers.okta",
  185. "anymail",
  186. "django_rest_mfa",
  187. "corsheaders",
  188. "django_extensions",
  189. ]
  190. if DEBUG_TOOLBAR:
  191. INSTALLED_APPS.append("debug_toolbar")
  192. INSTALLED_APPS += [
  193. "storages",
  194. "glitchtip",
  195. "apps.alerts",
  196. "apps.environments",
  197. "apps.organizations_ext",
  198. "events",
  199. "issues",
  200. "apps.users",
  201. "apps.importer",
  202. "apps.uptime",
  203. "apps.performance",
  204. "apps.projects",
  205. "apps.teams",
  206. "apps.releases",
  207. "apps.sourcecode",
  208. "apps.difs",
  209. "apps.api_tokens",
  210. "apps.files",
  211. "apps.issue_events",
  212. "apps.event_ingest",
  213. "import_export", # Contains import management command, keep under apps.importer
  214. ]
  215. IS_CELERY = env.bool("IS_CELERY", False)
  216. if not IS_CELERY:
  217. INSTALLED_APPS = WEB_INSTALLED_APPS + INSTALLED_APPS
  218. # Ensure no one uses runsslserver in production
  219. if SECRET_KEY == "change_me" and DEBUG is True:
  220. INSTALLED_APPS += ["sslserver"]
  221. ENABLE_OBSERVABILITY_API = env("ENABLE_OBSERVABILITY_API")
  222. # Workaround https://github.com/korfuri/django-prometheus/issues/34
  223. PROMETHEUS_EXPORT_MIGRATIONS = False
  224. # https://github.com/korfuri/django-prometheus/blob/master/documentation/exports.md#exporting-metrics-in-a-wsgi-application-with-multiple-processes-per-process
  225. if start_port := env.int("METRICS_START_PORT", None):
  226. PROMETHEUS_METRICS_EXPORT_PORT_RANGE = range(
  227. start_port, start_port + env.int("UWSGI_WORKERS", 1)
  228. )
  229. MIDDLEWARE = [
  230. "django.middleware.security.SecurityMiddleware",
  231. "django.contrib.sessions.middleware.SessionMiddleware",
  232. "corsheaders.middleware.CorsMiddleware",
  233. "csp.middleware.CSPMiddleware",
  234. "django.middleware.clickjacking.XFrameOptionsMiddleware",
  235. "whitenoise.middleware.WhiteNoiseMiddleware",
  236. ]
  237. if DEBUG_TOOLBAR:
  238. MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware")
  239. MIDDLEWARE += [
  240. "django.middleware.common.CommonMiddleware",
  241. "django.middleware.csrf.CsrfViewMiddleware",
  242. "django.contrib.auth.middleware.AuthenticationMiddleware",
  243. "django.contrib.messages.middleware.MessageMiddleware",
  244. "django.middleware.clickjacking.XFrameOptionsMiddleware",
  245. "sentry.middleware.proxy.DecompressBodyMiddleware",
  246. "django.middleware.locale.LocaleMiddleware",
  247. "allauth.account.middleware.AccountMiddleware",
  248. ]
  249. if ENABLE_OBSERVABILITY_API:
  250. MIDDLEWARE.insert(0, "django_prometheus.middleware.PrometheusBeforeMiddleware")
  251. MIDDLEWARE.append("django_prometheus.middleware.PrometheusAfterMiddleware")
  252. ROOT_URLCONF = "glitchtip.urls"
  253. TEMPLATES = [
  254. {
  255. "BACKEND": "django.template.backends.django.DjangoTemplates",
  256. "DIRS": [path("dist"), path("templates")],
  257. "APP_DIRS": True,
  258. "OPTIONS": {
  259. "context_processors": [
  260. "django.template.context_processors.debug",
  261. "django.template.context_processors.request",
  262. "django.contrib.auth.context_processors.auth",
  263. "django.contrib.messages.context_processors.messages",
  264. ],
  265. },
  266. },
  267. ]
  268. WSGI_APPLICATION = "glitchtip.wsgi.application"
  269. CORS_ORIGIN_ALLOW_ALL = env.bool("CORS_ORIGIN_ALLOW_ALL", True)
  270. CORS_ORIGIN_WHITELIST = env.tuple("CORS_ORIGIN_WHITELIST", str, default=())
  271. CORS_ALLOW_HEADERS = list(default_headers) + [
  272. "x-sentry-auth",
  273. "baggage",
  274. "sentry-trace",
  275. ]
  276. BILLING_ENABLED = False
  277. if env.str("STRIPE_TEST_PUBLIC_KEY", None) or env.str("STRIPE_LIVE_PUBLIC_KEY", None):
  278. BILLING_ENABLED = True
  279. # Set to chatwoot website token to enable live help widget. Assumes app.chatwoot.com.
  280. CHATWOOT_WEBSITE_TOKEN = env.str("CHATWOOT_WEBSITE_TOKEN", None)
  281. CHATWOOT_IDENTITY_TOKEN = env.str("CHATWOOT_IDENTITY_TOKEN", None)
  282. CSRF_TRUSTED_ORIGINS = env.list("CSRF_TRUSTED_ORIGINS", str, [])
  283. SECURE_BROWSER_XSS_FILTER = True
  284. CSP_DEFAULT_SRC = env.list("CSP_DEFAULT_SRC", str, ["'self'"])
  285. if "CSP_STYLE_SRC" in os.environ:
  286. CSP_STYLE_SRC = env.list("CSP_STYLE_SRC", str)
  287. if "CSP_STYLE_SRC_ELEM" in os.environ:
  288. CSP_STYLE_SRC_ELEM = env.list("CSP_STYLE_SRC_ELEM", str)
  289. CSP_FONT_SRC = env.list("CSP_FONT_SRC", str, ["'self'", "data:"])
  290. if "CSP_WORKER_SRC" in os.environ:
  291. CSP_WORKER_SRC = env.list("CSP_WORKER_SRC", str)
  292. # Enable Chatwoot only when configured
  293. default_connect_src = ["'self'", "https://*.glitchtip.com"]
  294. if CHATWOOT_WEBSITE_TOKEN:
  295. default_connect_src.append("https://app.chatwoot.com")
  296. CSP_CONNECT_SRC = env.list("CSP_CONNECT_SRC", str, default_connect_src)
  297. # Enable stripe by default only when configured
  298. stripe_domain = "https://js.stripe.com"
  299. default_script_src = [
  300. "'self'",
  301. "https://*.glitchtip.com",
  302. "'sha256-iRcDQ27XiXX4k+jbJ8nGeQFBnBOjmII7FdMlixb6QE4='", # Theme picker inline JS
  303. ]
  304. default_frame_src = ["'self'"]
  305. if BILLING_ENABLED:
  306. default_script_src.append(stripe_domain)
  307. default_frame_src.append(stripe_domain)
  308. CSP_SCRIPT_SRC = env.list("CSP_SCRIPT_SRC", str, default_script_src)
  309. CSP_IMG_SRC = env.list("CSP_IMG_SRC", str, ["'self'"])
  310. CSP_FRAME_SRC = env.list("CSP_FRAME_SRC", str, default_frame_src)
  311. # Consider tracking CSP reports with GlitchTip itself
  312. CSP_REPORT_URI = env.tuple("CSP_REPORT_URI", str, None)
  313. CSP_REPORT_ONLY = env.bool("CSP_REPORT_ONLY", False)
  314. SECURE_HSTS_SECONDS = env.int("SECURE_HSTS_SECONDS", 0)
  315. SECURE_HSTS_PRELOAD = env.bool("SECURE_HSTS_PRELOAD", False)
  316. SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("SECURE_HSTS_INCLUDE_SUBDOMAINS", False)
  317. SESSION_COOKIE_SECURE = env.bool("SESSION_COOKIE_SECURE", False)
  318. SESSION_COOKIE_SAMESITE = env.str("SESSION_COOKIE_SAMESITE", "Lax")
  319. DEFAULT_FROM_EMAIL = env.str("DEFAULT_FROM_EMAIL", "webmaster@localhost")
  320. ANYMAIL_SETTINGS = [
  321. "MAILGUN_API_KEY",
  322. "MAILGUN_SENDER_DOMAIN",
  323. "MAILGUN_API_URL",
  324. "MAILGUN_WEBHOOK_SIGNING_KEY",
  325. "SENDGRID_API_KEY",
  326. "SENDGRID_API_URL",
  327. "POSTMARK_SERVER_TOKEN",
  328. "POSTMARK_API_URL",
  329. "MANDRILL_API_KEY",
  330. "MANDRILL_WEBHOOK_KEY",
  331. "MANDRILL_WEBHOOK_URL",
  332. "MANDRILL_API_URL",
  333. "SENDINBLUE_API_KEY",
  334. "SENDINBLUE_API_URL",
  335. "MAILJET_API_KEY",
  336. "MAILJET_SECRET_KEY",
  337. "MAILJET_API_URL",
  338. "POSTAL_API_KEY",
  339. "POSTAL_API_URL",
  340. "POSTAL_WEBHOOK_KEY",
  341. "SPARKPOST_API_KEY",
  342. "SPARKPOST_API_URL",
  343. "SPARKPOST_TRACK_INITIAL_OPEN_AS_OPENED",
  344. ]
  345. ANYMAIL = {
  346. anymail_var: env.str(anymail_var)
  347. for anymail_var in ANYMAIL_SETTINGS
  348. if anymail_var in os.environ
  349. }
  350. ACCOUNT_EMAIL_SUBJECT_PREFIX = env.str("ACCOUNT_EMAIL_SUBJECT_PREFIX", "")
  351. # Database
  352. # https://docs.djangoproject.com/en/dev/ref/settings/#databases
  353. DATABASES = {
  354. "default": env.db(default="postgres://postgres:postgres@postgres:5432/postgres")
  355. }
  356. # Support setting DATABASES in parts in order to get values from the postgresql helm chart
  357. DATABASE_HOST = env.str("DATABASE_HOST", None)
  358. DATABASE_PASSWORD = env.str("DATABASE_PASSWORD", None)
  359. if DATABASE_HOST and DATABASE_PASSWORD:
  360. DATABASES["default"] = {
  361. "NAME": env.str("DATABASE_NAME", "postgres"),
  362. "USER": env.str("DATABASE_USER", "postgres"),
  363. "PASSWORD": DATABASE_PASSWORD,
  364. "HOST": DATABASE_HOST,
  365. "PORT": env.str("DATABASE_PORT", "5432"),
  366. "CONN_MAX_AGE": env.int("DATABASE_CONN_MAX_AGE", 0),
  367. "CONN_HEALTH_CHECKS": env.bool("DATABASE_CONN_HEALTH_CHECKS", False),
  368. }
  369. DATABASES["default"]["ENGINE"] = "psqlextra.backend"
  370. if not DATABASES["default"].get("OPTIONS"):
  371. DATABASES["default"]["OPTIONS"] = {}
  372. # Enable pool by default, if there is no conn_max_age
  373. if DATABASES["default"].get("CONN_MAX_AGE", 0) == 0:
  374. if env.bool("DATABASE_POOL", True):
  375. pool_options = {}
  376. min_size = env.int("DATABASE_POOL_MIN_SIZE", 2)
  377. max_size = env.int("DATABASE_POOL_MAX_SIZE", 6)
  378. if min_size:
  379. pool_options["min_size"] = min_size
  380. if max_size:
  381. pool_options["max_size"] = max_size
  382. if pool_options:
  383. DATABASES["default"]["OPTIONS"]["pool"] = pool_options
  384. else:
  385. DATABASES["default"]["OPTIONS"]["pool"] = True
  386. PSQLEXTRA_PARTITIONING_MANAGER = "glitchtip.partitioning.manager"
  387. DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
  388. # We need to support both url and broken out host to support helm redis chart
  389. REDIS_HOST = env.str("REDIS_HOST", None)
  390. if REDIS_HOST:
  391. REDIS_PORT = env.str("REDIS_PORT", "6379")
  392. REDIS_DATABASE = env.str("REDIS_DATABASE", "0")
  393. REDIS_PASSWORD = env.str("REDIS_PASSWORD", None)
  394. if REDIS_PASSWORD:
  395. REDIS_URL = (
  396. f"redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_DATABASE}"
  397. )
  398. else:
  399. REDIS_URL = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DATABASE}"
  400. else:
  401. REDIS_URL = env.str("REDIS_URL", "redis://redis:6379/0")
  402. REDIS_RETRY = env.bool("REDIS_RETRY", True)
  403. REDIS_MAX_CONNECTIONS = env.int("REDIS_MAX_CONNECTIONS", 100)
  404. CELERY_BROKER_URL = env.str("CELERY_BROKER_URL", REDIS_URL)
  405. CELERY_BROKER_TRANSPORT_OPTIONS = {
  406. "fanout_prefix": True,
  407. "fanout_patterns": True,
  408. "retry_on_timeout": REDIS_RETRY,
  409. "max_connections": REDIS_MAX_CONNECTIONS,
  410. }
  411. CELERY_REDIS_RETRY_ON_TIMEOUT = REDIS_RETRY
  412. CELERY_REDIS_MAX_CONNECTIONS = REDIS_MAX_CONNECTIONS
  413. if CELERY_BROKER_URL.startswith("sentinel"):
  414. CELERY_BROKER_TRANSPORT_OPTIONS["master_name"] = env.str(
  415. "CELERY_BROKER_MASTER_NAME", "mymaster"
  416. )
  417. IS_LOAD_TEST = env("IS_LOAD_TEST")
  418. # GlitchTip doesn't require a celery result backend
  419. if IS_LOAD_TEST:
  420. CELERY_RESULT_BACKEND = REDIS_URL
  421. if socket_timeout := env.int("CELERY_BROKER_SOCKET_TIMEOUT", None):
  422. CELERY_BROKER_TRANSPORT_OPTIONS["socket_timeout"] = socket_timeout
  423. if broker_sentinel_password := env.str("CELERY_BROKER_SENTINEL_KWARGS_PASSWORD", None):
  424. CELERY_BROKER_TRANSPORT_OPTIONS["sentinel_kwargs"] = {
  425. "password": broker_sentinel_password
  426. }
  427. # Time in seconds to debounce some frequently run tasks
  428. TASK_DEBOUNCE_DELAY = env.int("TASK_DEBOUNCE_DELAY", 30)
  429. UPTIME_CHECK_INTERVAL = 10
  430. ALERT_NOTIFICATION_INTERVAL = env.int("ALERT_NOTIFICATION_INTERVAL", 60)
  431. CELERY_BEAT_SCHEDULE = {
  432. "send-alert-notifications": {
  433. "task": "apps.alerts.tasks.process_event_alerts",
  434. "schedule": ALERT_NOTIFICATION_INTERVAL,
  435. },
  436. "perform-maintenance": {
  437. "task": "glitchtip.tasks.perform_maintenance",
  438. "schedule": crontab(hour=5, minute=0),
  439. },
  440. "uptime-dispatch-checks": {
  441. "task": "apps.uptime.tasks.dispatch_checks",
  442. "schedule": UPTIME_CHECK_INTERVAL,
  443. },
  444. }
  445. # Maximum number of issues send in a single alert payload
  446. MAX_ISSUES_PER_ALERT = env.int("MAX_ISSUES_PER_ALERT", 3)
  447. if os.environ.get("CACHE_URL"):
  448. CACHES = {
  449. "default": env.cache(),
  450. }
  451. else: # Default to REDIS when unset
  452. CACHES = {
  453. "default": {
  454. "BACKEND": "django_redis.cache.RedisCache",
  455. "LOCATION": REDIS_URL,
  456. "PARSER_CLASS": "redis.connection.HiredisParser",
  457. "OPTIONS": {
  458. "CONNECTION_POOL_KWARGS": {
  459. "retry_on_timeout": REDIS_RETRY,
  460. "max_connections": REDIS_MAX_CONNECTIONS,
  461. }
  462. },
  463. }
  464. }
  465. if cache_sentinel_url := env.str("CACHE_SENTINEL_URL", None):
  466. try:
  467. cache_sentinel_host, cache_sentinel_port = cache_sentinel_url.split(":")
  468. SENTINELS = [(cache_sentinel_host, int(cache_sentinel_port))]
  469. except ValueError as err:
  470. raise ImproperlyConfigured(
  471. "Invalid cache redis sentinel url, format is host:port"
  472. ) from err
  473. DJANGO_REDIS_CONNECTION_FACTORY = "django_redis.pool.SentinelConnectionFactory"
  474. CACHES["default"]["OPTIONS"]["SENTINELS"] = SENTINELS
  475. if cache_sentinel_password := env.str("CACHE_SENTINEL_PASSWORD", None):
  476. CACHES["default"]["OPTIONS"]["SENTINEL_KWARGS"] = {
  477. "password": cache_sentinel_password
  478. }
  479. SESSION_ENGINE = "django.contrib.sessions.backends.cache"
  480. SESSION_COOKIE_AGE = env.int("SESSION_COOKIE_AGE", global_settings.SESSION_COOKIE_AGE)
  481. # Password validation
  482. # https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
  483. AUTH_PASSWORD_VALIDATORS = [
  484. {
  485. "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
  486. },
  487. {
  488. "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
  489. },
  490. {
  491. "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
  492. },
  493. {
  494. "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
  495. },
  496. ]
  497. # Internationalization
  498. # https://docs.djangoproject.com/en/dev/topics/i18n/
  499. LANGUAGE_CODE = "en-us"
  500. TIME_ZONE = "UTC"
  501. USE_I18N = True
  502. USE_TZ = True
  503. STORAGES = {
  504. "default": {
  505. "BACKEND": env("DEFAULT_FILE_STORAGE"),
  506. },
  507. "staticfiles": {
  508. "BACKEND": env.str(
  509. "STATICFILES_STORAGE",
  510. "whitenoise.storage.CompressedManifestStaticFilesStorage",
  511. )
  512. },
  513. }
  514. AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID")
  515. AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY")
  516. AWS_STORAGE_BUCKET_NAME = env("AWS_STORAGE_BUCKET_NAME")
  517. AWS_S3_ENDPOINT_URL = env("AWS_S3_ENDPOINT_URL")
  518. AWS_LOCATION = env("AWS_LOCATION")
  519. AZURE_ACCOUNT_NAME = env("AZURE_ACCOUNT_NAME")
  520. AZURE_ACCOUNT_KEY = env("AZURE_ACCOUNT_KEY")
  521. AZURE_CONTAINER = env("AZURE_CONTAINER")
  522. AZURE_URL_EXPIRATION_SECS = env("AZURE_URL_EXPIRATION_SECS")
  523. GS_BUCKET_NAME = env("GS_BUCKET_NAME")
  524. GS_PROJECT_ID = env("GS_PROJECT_ID")
  525. if AWS_S3_ENDPOINT_URL:
  526. MEDIA_URL = env.str(
  527. "MEDIA_URL", "https://%s/%s/" % (AWS_S3_ENDPOINT_URL, AWS_LOCATION)
  528. )
  529. STORAGES["default"] = {"BACKEND": "storages.backends.s3boto3.S3Boto3Storage"}
  530. else:
  531. MEDIA_URL = "media/"
  532. MEDIA_ROOT = env.str("MEDIA_ROOT", "")
  533. STATICFILES_DIRS = [
  534. "assets",
  535. "dist",
  536. ]
  537. STATIC_ROOT = path("static/")
  538. EMAIL_BACKEND = env.str(
  539. "EMAIL_BACKEND", default="django.core.mail.backends.smtp.EmailBackend"
  540. )
  541. if os.getenv("EMAIL_HOST_USER"):
  542. EMAIL_HOST_USER = env.str("EMAIL_HOST_USER")
  543. if os.getenv("EMAIL_HOST_PASSWORD"):
  544. EMAIL_HOST_PASSWORD = env.str("EMAIL_HOST_PASSWORD")
  545. if os.getenv("EMAIL_HOST"):
  546. EMAIL_HOST = env.str("EMAIL_HOST")
  547. if os.getenv("EMAIL_PORT"):
  548. EMAIL_PORT = env.str("EMAIL_PORT")
  549. if os.getenv("EMAIL_USE_TLS"):
  550. EMAIL_USE_TLS = env.bool("EMAIL_USE_TLS")
  551. if os.getenv("EMAIL_USE_SSL"):
  552. EMAIL_USE_SSL = env.bool("EMAIL_USE_SSL")
  553. if os.getenv("EMAIL_TIMEOUT"):
  554. EMAIL_TIMEOUT = env.int("EMAIL_TIMEOUT")
  555. if os.getenv("EMAIL_FILE_PATH"):
  556. EMAIL_FILE_PATH = env.str("EMAIL_FILE_PATH")
  557. if os.getenv(
  558. "EMAIL_URL"
  559. ): # Careful, this will override most EMAIL_*** settings. Set them all individually, or use EMAIL_URL to set them all at once, but don't do both.
  560. EMAIL_CONFIG = env.email_url("EMAIL_URL")
  561. vars().update(EMAIL_CONFIG)
  562. AUTH_USER_MODEL = "users.User"
  563. ACCOUNT_ADAPTER = "glitchtip.adapters.CustomDefaultAccountAdapter"
  564. ACCOUNT_AUTHENTICATION_METHOD = "email"
  565. ACCOUNT_EMAIL_REQUIRED = True
  566. ACCOUNT_USERNAME_REQUIRED = False
  567. ACCOUNT_USER_MODEL_USERNAME_FIELD = None
  568. ACCOUNT_REAUTHENTICATION_TIMEOUT = SESSION_COOKIE_AGE # Disabled for now
  569. LOGIN_REDIRECT_URL = "/"
  570. LOGIN_URL = "/login"
  571. # This config will later default to True and then be removed
  572. USE_NEW_SOCIAL_CALLBACKS = env.bool("USE_NEW_SOCIAL_CALLBACKS", False)
  573. HEADLESS_ONLY = True
  574. HEADLESS_FRONTEND_URLS = {
  575. "account_signup": "/login",
  576. "account_reset_password": "/reset-password",
  577. "account_confirm_email": "/profile/confirm-email/{key}/",
  578. "account_reset_password_from_key": "/reset-password/set-new-password/{key}",
  579. "socialaccount_login_error": "/login?socialLoginError=true",
  580. }
  581. MFA_TOTP_ISSUER = GLITCHTIP_URL.hostname
  582. MFA_TOTP_TOLERANCE = 1
  583. MFA_SUPPORTED_TYPES = ["totp", "webauthn", "recovery_codes"]
  584. MFA_PASSKEY_LOGIN_ENABLED = True
  585. MFA_WEBAUTHN_ALLOW_INSECURE_ORIGIN = DEBUG
  586. SOCIALACCOUNT_ADAPTER = "glitchtip.adapters.CustomSocialAccountAdapter"
  587. INVITATION_BACKEND = "apps.organizations_ext.invitation_backend.InvitationBackend"
  588. SOCIALACCOUNT_PROVIDERS = {}
  589. if GITLAB_URL := env.url("SOCIALACCOUNT_PROVIDERS_gitlab_GITLAB_URL", None):
  590. SOCIALACCOUNT_PROVIDERS["gitlab"] = {"GITLAB_URL": GITLAB_URL.geturl()}
  591. if GITEA_URL := env.url("SOCIALACCOUNT_PROVIDERS_gitea_GITEA_URL", None):
  592. SOCIALACCOUNT_PROVIDERS["gitea"] = {"GITEA_URL": GITEA_URL.geturl()}
  593. if NEXTCLOUD_URL := env.url("SOCIALACCOUNT_PROVIDERS_nextcloud_SERVER", None):
  594. SOCIALACCOUNT_PROVIDERS["nextcloud"] = {"SERVER": NEXTCLOUD_URL.geturl()}
  595. if MICROSOFT_TENANT := env.str("SOCIALACCOUNT_PROVIDERS_microsoft_TENANT", None):
  596. SOCIALACCOUNT_PROVIDERS["microsoft"] = {"TENANT": MICROSOFT_TENANT}
  597. ENABLE_USER_REGISTRATION = env.bool("ENABLE_USER_REGISTRATION", True)
  598. ENABLE_ORGANIZATION_CREATION = env.bool(
  599. "ENABLE_OPEN_USER_REGISTRATION", env.bool("ENABLE_ORGANIZATION_CREATION", False)
  600. )
  601. AUTHENTICATION_BACKENDS = (
  602. # Needed to login by username in Django admin, regardless of `allauth`
  603. "django.contrib.auth.backends.ModelBackend",
  604. # `allauth` specific authentication methods, such as login by e-mail
  605. "allauth.account.auth_backends.AuthenticationBackend",
  606. )
  607. NINJA_PAGINATION_CLASS = "glitchtip.api.pagination.AsyncLinkHeaderPagination"
  608. NINJA_PAGINATION_PER_PAGE = 50
  609. LOGGING_HANDLER_CLASS = env.str("DJANGO_LOGGING_HANDLER_CLASS", "logging.StreamHandler")
  610. LOGGING = {
  611. "version": 1,
  612. "disable_existing_loggers": False,
  613. "handlers": {
  614. "null": {
  615. "class": "logging.NullHandler",
  616. },
  617. "console": {
  618. "class": LOGGING_HANDLER_CLASS,
  619. },
  620. },
  621. "loggers": {
  622. "django.security.DisallowedHost": {
  623. "handlers": ["null"],
  624. "propagate": False,
  625. },
  626. },
  627. "root": {"handlers": ["console"]},
  628. }
  629. if LOGGING_HANDLER_CLASS is not logging.StreamHandler:
  630. from celery.signals import after_setup_logger, after_setup_task_logger
  631. @after_setup_logger.connect
  632. @after_setup_task_logger.connect
  633. def setup_celery_logging(logger, **kwargs):
  634. from django.utils.module_loading import import_string
  635. handler = import_string(LOGGING_HANDLER_CLASS)
  636. for h in logger.handlers:
  637. logger.removeHandler(h)
  638. logger.addHandler(handler())
  639. def organization_request_callback(request):
  640. raise ImproperlyConfigured(
  641. "Organization request callback required by dj-stripe but not used."
  642. )
  643. # Set to track activity with Plausible
  644. PLAUSIBLE_URL = env.str("PLAUSIBLE_URL", default=None)
  645. PLAUSIBLE_DOMAIN = env.str("PLAUSIBLE_DOMAIN", default=None)
  646. # See https://liberapay.com/GlitchTip/donate - suggested self-host donation is $5/month/user.
  647. # Support plans available. Email info@burkesoftware.com for more info.
  648. I_PAID_FOR_GLITCHTIP = env.bool("I_PAID_FOR_GLITCHTIP", False)
  649. DJSTRIPE_SUBSCRIBER_MODEL = "organizations_ext.Organization"
  650. DJSTRIPE_SUBSCRIBER_MODEL_REQUEST_CALLBACK = organization_request_callback
  651. DJSTRIPE_USE_NATIVE_JSONFIELD = True
  652. DJSTRIPE_FOREIGN_KEY_TO_FIELD = "djstripe_id"
  653. MARKETING_URL = "https://glitchtip.com"
  654. STRIPE_AUTOMATIC_TAX = env.bool("STRIPE_AUTOMATIC_TAX", False)
  655. STRIPE_LIVE_MODE = env.bool("STRIPE_LIVE_MODE", False)
  656. if BILLING_ENABLED:
  657. I_PAID_FOR_GLITCHTIP = True
  658. INSTALLED_APPS.append("djstripe")
  659. INSTALLED_APPS.append("apps.djstripe_ext")
  660. STRIPE_TEST_PUBLIC_KEY = env.str("STRIPE_TEST_PUBLIC_KEY", None)
  661. STRIPE_TEST_SECRET_KEY = env.str("STRIPE_TEST_SECRET_KEY", None)
  662. STRIPE_LIVE_PUBLIC_KEY = env.str("STRIPE_LIVE_PUBLIC_KEY", None)
  663. STRIPE_LIVE_SECRET_KEY = env.str("STRIPE_LIVE_SECRET_KEY", None)
  664. DJSTRIPE_WEBHOOK_SECRET = env.str("DJSTRIPE_WEBHOOK_SECRET", None)
  665. CELERY_BEAT_SCHEDULE["check-all-organizations-throttle"] = {
  666. "task": "apps.organizations_ext.tasks.check_all_organizations_throttle",
  667. "schedule": timedelta(hours=4),
  668. }
  669. elif TESTING:
  670. # Must run tests with djstripe enabled
  671. BILLING_ENABLED = True
  672. INSTALLED_APPS.append("djstripe")
  673. INSTALLED_APPS.append("apps.djstripe_ext")
  674. STRIPE_TEST_PUBLIC_KEY = "fake"
  675. STRIPE_TEST_SECRET_KEY = "sk_test_fake" # nosec
  676. DJSTRIPE_WEBHOOK_SECRET = "whsec_fake" # nosec
  677. logging.disable(logging.WARNING)
  678. CELERY_TASK_ALWAYS_EAGER = env.bool("CELERY_TASK_ALWAYS_EAGER", False)
  679. if TESTING:
  680. TEST_RUNNER = "glitchtip.test_runner.TimedTestRunner"
  681. # Optimization
  682. PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
  683. DATABASES["default"]["CONN_MAX_AGE"] = None
  684. DATABASES["default"]["OPTIONS"]["pool"] = False
  685. CELERY_TASK_ALWAYS_EAGER = True
  686. SESSION_ENGINE = "django.contrib.sessions.backends.cache"
  687. STORAGES = global_settings.STORAGES
  688. # https://github.com/evansd/whitenoise/issues/215
  689. warnings.filterwarnings(
  690. "ignore", message="No directory at", module="whitenoise.base"
  691. )
  692. if CELERY_TASK_ALWAYS_EAGER:
  693. CACHES = {
  694. "default": {
  695. "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
  696. }
  697. }
  698. CACHE_IS_REDIS = CACHES["default"]["BACKEND"] == "django_redis.cache.RedisCache"
  699. warnings.filterwarnings(
  700. "ignore", message="No directory at", module="django.core.handlers.base"
  701. )