settings.py 28 KB

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