settings.py 28 KB

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