settings.py 27 KB

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