settings.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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 re
  11. import sys
  12. import warnings
  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 sentry_sdk.integrations.django import DjangoIntegration
  20. env = environ.Env(
  21. ALLOWED_HOSTS=(list, ["*"]),
  22. DEFAULT_FILE_STORAGE=(str, None),
  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. GS_BUCKET_NAME=(str, None),
  33. GS_PROJECT_ID=(str, None),
  34. DEBUG=(bool, False),
  35. DEBUG_TOOLBAR=(bool, False),
  36. STATIC_URL=(str, "/"),
  37. STATICFILES_STORAGE=(
  38. str,
  39. "whitenoise.storage.CompressedManifestStaticFilesStorage",
  40. ),
  41. ENABLE_OBSERVABILITY_API=(bool, False),
  42. )
  43. path = environ.Path()
  44. # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
  45. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  46. # Quick-start development settings - unsuitable for production
  47. # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
  48. # SECURITY WARNING: keep the secret key used in production secret!
  49. SECRET_KEY = env.str("SECRET_KEY", "change_me")
  50. # SECURITY WARNING: don't run with debug turned on in production!
  51. DEBUG = env("DEBUG")
  52. # Enable only for running end to end testing. Debug must be True to use.
  53. ENABLE_TEST_API = env.bool("ENABLE_TEST_API", False)
  54. if DEBUG is False:
  55. ENABLE_TEST_API = False
  56. ALLOWED_HOSTS = env("ALLOWED_HOSTS")
  57. # Necessary for kubernetes health checks
  58. POD_IP = env.str("POD_IP", default=None)
  59. if POD_IP:
  60. ALLOWED_HOSTS.append(POD_IP)
  61. ENVIRONMENT = env.str("ENVIRONMENT", None)
  62. GLITCHTIP_VERSION = env.str("GLITCHTIP_VERSION", "0.0.0-unknown")
  63. # Used in email and DSN generation. Set to full domain such as https://glitchtip.example.com
  64. default_url = env.str(
  65. "APP_URL", env.str("GLITCHTIP_DOMAIN", "http://localhost:8000")
  66. ) # DigitalOcean App Platform uses APP_URL
  67. GLITCHTIP_URL = env.url("GLITCHTIP_URL", default_url)
  68. if GLITCHTIP_URL.scheme not in ["http", "https"]:
  69. raise ImproperlyConfigured("GLITCHTIP_DOMAIN must start with http or https")
  70. # 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", True)
  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 django.DisallowedHost errors in Sentry."""
  99. if "log_record" in hint:
  100. if hint["log_record"].name == "django.security.DisallowedHost":
  101. return None
  102. return event
  103. SENTRY_DSN = env.str("SENTRY_DSN", None)
  104. # Optionally allow a different DSN for the frontend
  105. SENTRY_FRONTEND_DSN = env.str("SENTRY_FRONTEND_DSN", SENTRY_DSN)
  106. # Set traces_sample_rate to 1.0 to capture 100%. Recommended to keep this value low.
  107. SENTRY_TRACES_SAMPLE_RATE = env.float("SENTRY_TRACES_SAMPLE_RATE", 0.1)
  108. # Ignore whitenoise served static routes
  109. def traces_sampler(sampling_context):
  110. if (
  111. sampling_context.get("wsgi_environ", {})
  112. .get("PATH_INFO", "")
  113. .startswith(STATIC_URL)
  114. ):
  115. return 0.0
  116. return SENTRY_TRACES_SAMPLE_RATE
  117. if SENTRY_DSN:
  118. release = "glitchtip@" + GLITCHTIP_VERSION if GLITCHTIP_VERSION else None
  119. sentry_sdk.init(
  120. dsn=SENTRY_DSN,
  121. integrations=[DjangoIntegration()],
  122. before_send=before_send,
  123. release=release,
  124. environment=ENVIRONMENT,
  125. auto_session_tracking=False,
  126. traces_sample_rate=SENTRY_TRACES_SAMPLE_RATE,
  127. traces_sampler=traces_sampler,
  128. )
  129. def show_toolbar(request):
  130. return env("DEBUG_TOOLBAR")
  131. DEBUG_TOOLBAR = env("DEBUG_TOOLBAR")
  132. DEBUG_TOOLBAR_CONFIG = {"SHOW_TOOLBAR_CALLBACK": show_toolbar}
  133. DEBUG_TOOLBAR_PANELS = [
  134. "debug_toolbar.panels.versions.VersionsPanel",
  135. "debug_toolbar.panels.timer.TimerPanel",
  136. "debug_toolbar.panels.settings.SettingsPanel",
  137. "debug_toolbar.panels.headers.HeadersPanel",
  138. "debug_toolbar.panels.request.RequestPanel",
  139. "debug_toolbar.panels.sql.SQLPanel",
  140. ]
  141. # Application definition
  142. INSTALLED_APPS = [
  143. "django_rest_mfa.mfa_admin",
  144. "django.contrib.admin",
  145. "django.contrib.auth",
  146. "django.contrib.contenttypes",
  147. "django.contrib.sessions",
  148. "django.contrib.messages",
  149. "django.contrib.staticfiles",
  150. "django.contrib.postgres",
  151. "django_prometheus",
  152. "allauth",
  153. "allauth.account",
  154. "allauth.socialaccount",
  155. "allauth.socialaccount.providers.digitalocean",
  156. "allauth.socialaccount.providers.gitea",
  157. "allauth.socialaccount.providers.github",
  158. "allauth.socialaccount.providers.gitlab",
  159. "allauth.socialaccount.providers.google",
  160. "allauth.socialaccount.providers.microsoft",
  161. "allauth.socialaccount.providers.nextcloud",
  162. "allauth.socialaccount.providers.keycloak",
  163. "allauth.socialaccount.providers.openid_connect",
  164. "anymail",
  165. "corsheaders",
  166. "django_filters",
  167. "django_extensions",
  168. "django_rest_mfa",
  169. ]
  170. if DEBUG_TOOLBAR:
  171. INSTALLED_APPS.append("debug_toolbar")
  172. INSTALLED_APPS += [
  173. "rest_framework",
  174. "drf_yasg",
  175. "dj_rest_auth",
  176. "dj_rest_auth.registration",
  177. "import_export",
  178. "storages",
  179. "glitchtip",
  180. "alerts",
  181. "api_tokens",
  182. "environments",
  183. "files",
  184. "organizations_ext",
  185. "events",
  186. "issues",
  187. "users",
  188. "user_reports",
  189. "glitchtip.importer",
  190. "glitchtip.uptime",
  191. "performance",
  192. "projects",
  193. "teams",
  194. "releases",
  195. "difs",
  196. ]
  197. # Ensure no one uses runsslserver in production
  198. if SECRET_KEY == "change_me" and DEBUG is True:
  199. INSTALLED_APPS += ["sslserver"]
  200. ENABLE_OBSERVABILITY_API = env("ENABLE_OBSERVABILITY_API")
  201. # Workaround https://github.com/korfuri/django-prometheus/issues/34
  202. PROMETHEUS_EXPORT_MIGRATIONS = False
  203. # https://github.com/korfuri/django-prometheus/blob/master/documentation/exports.md#exporting-metrics-in-a-wsgi-application-with-multiple-processes-per-process
  204. if start_port := env.int("METRICS_START_PORT", None):
  205. PROMETHEUS_METRICS_EXPORT_PORT_RANGE = range(
  206. start_port, start_port + env.int("UWSGI_WORKERS", 1)
  207. )
  208. MIDDLEWARE = [
  209. "django.middleware.security.SecurityMiddleware",
  210. "django.contrib.sessions.middleware.SessionMiddleware",
  211. "corsheaders.middleware.CorsMiddleware",
  212. "csp.middleware.CSPMiddleware",
  213. "django.middleware.clickjacking.XFrameOptionsMiddleware",
  214. "whitenoise.middleware.WhiteNoiseMiddleware",
  215. ]
  216. if DEBUG_TOOLBAR:
  217. MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware")
  218. MIDDLEWARE += [
  219. "django.middleware.common.CommonMiddleware",
  220. "django.middleware.csrf.CsrfViewMiddleware",
  221. "django.contrib.auth.middleware.AuthenticationMiddleware",
  222. "django.contrib.messages.middleware.MessageMiddleware",
  223. "django.middleware.clickjacking.XFrameOptionsMiddleware",
  224. "sentry.middleware.proxy.DecompressBodyMiddleware",
  225. "django.middleware.locale.LocaleMiddleware",
  226. ]
  227. if ENABLE_OBSERVABILITY_API:
  228. MIDDLEWARE.insert(0, "django_prometheus.middleware.PrometheusBeforeMiddleware")
  229. MIDDLEWARE.append("django_prometheus.middleware.PrometheusAfterMiddleware")
  230. ROOT_URLCONF = "glitchtip.urls"
  231. TEMPLATES = [
  232. {
  233. "BACKEND": "django.template.backends.django.DjangoTemplates",
  234. "DIRS": [path("dist"), path("templates")],
  235. "APP_DIRS": True,
  236. "OPTIONS": {
  237. "context_processors": [
  238. "django.template.context_processors.debug",
  239. "django.template.context_processors.request",
  240. "django.contrib.auth.context_processors.auth",
  241. "django.contrib.messages.context_processors.messages",
  242. ],
  243. },
  244. },
  245. ]
  246. WSGI_APPLICATION = "glitchtip.wsgi.application"
  247. CORS_ORIGIN_ALLOW_ALL = env.bool("CORS_ORIGIN_ALLOW_ALL", True)
  248. CORS_ORIGIN_WHITELIST = env.tuple("CORS_ORIGIN_WHITELIST", str, default=())
  249. CORS_ALLOW_HEADERS = list(default_headers) + [
  250. "x-sentry-auth",
  251. ]
  252. BILLING_ENABLED = False
  253. if env.str("STRIPE_TEST_PUBLIC_KEY", None) or env.str("STRIPE_LIVE_PUBLIC_KEY", None):
  254. BILLING_ENABLED = True
  255. # Set to chatwoot website token to enable live help widget. Assumes app.chatwoot.com.
  256. CHATWOOT_WEBSITE_TOKEN = env.str("CHATWOOT_WEBSITE_TOKEN", None)
  257. CHATWOOT_IDENTITY_TOKEN = env.str("CHATWOOT_IDENTITY_TOKEN", None)
  258. CSRF_TRUSTED_ORIGINS = env.list("CSRF_TRUSTED_ORIGINS", str, [])
  259. SECURE_BROWSER_XSS_FILTER = True
  260. CSP_DEFAULT_SRC = env.list("CSP_DEFAULT_SRC", str, ["'self'"])
  261. CSP_STYLE_SRC = env.list(
  262. "CSP_STYLE_SRC", str, ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"]
  263. )
  264. CSP_STYLE_SRC_ELEM = env.list(
  265. "CSP_STYLE_SRC_ELEM",
  266. str,
  267. ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
  268. )
  269. CSP_FONT_SRC = env.list(
  270. "CSP_FONT_SRC", str, ["'self'", "https://fonts.gstatic.com", "data:"]
  271. )
  272. # Redoc requires blob
  273. CSP_WORKER_SRC = env.list("CSP_WORKER_SRC", str, ["'self'", "blob:"])
  274. # Enable Chatwoot only when configured
  275. default_connect_src = ["'self'", "https://*.glitchtip.com"]
  276. if CHATWOOT_WEBSITE_TOKEN:
  277. default_connect_src.append("https://app.chatwoot.com")
  278. CSP_CONNECT_SRC = env.list("CSP_CONNECT_SRC", str, default_connect_src)
  279. # Enable stripe by default only when configured
  280. stripe_domain = "https://js.stripe.com"
  281. default_script_src = ["'self'", "https://*.glitchtip.com"]
  282. default_frame_src = ["'self'"]
  283. if BILLING_ENABLED:
  284. default_script_src.append(stripe_domain)
  285. default_frame_src.append(stripe_domain)
  286. CSP_SCRIPT_SRC = env.list("CSP_SCRIPT_SRC", str, default_script_src)
  287. CSP_IMG_SRC = env.list("CSP_IMG_SRC", str, ["'self'"])
  288. CSP_FRAME_SRC = env.list("CSP_FRAME_SRC", str, default_frame_src)
  289. # Consider tracking CSP reports with GlitchTip itself
  290. CSP_REPORT_URI = env.tuple("CSP_REPORT_URI", str, None)
  291. CSP_REPORT_ONLY = env.bool("CSP_REPORT_ONLY", False)
  292. SECURE_HSTS_SECONDS = env.int("SECURE_HSTS_SECONDS", 0)
  293. SECURE_HSTS_PRELOAD = env.bool("SECURE_HSTS_PRELOAD", False)
  294. SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("SECURE_HSTS_INCLUDE_SUBDOMAINS", False)
  295. SESSION_COOKIE_SECURE = env.bool("SESSION_COOKIE_SECURE", False)
  296. SESSION_COOKIE_SAMESITE = env.str("SESSION_COOKIE_SAMESITE", "Lax")
  297. DEFAULT_FROM_EMAIL = env.str("DEFAULT_FROM_EMAIL", "webmaster@localhost")
  298. ANYMAIL_SETTINGS = [
  299. "MAILGUN_API_KEY",
  300. "MAILGUN_SENDER_DOMAIN",
  301. "MAILGUN_API_URL",
  302. "MAILGUN_WEBHOOK_SIGNING_KEY",
  303. "SENDGRID_API_KEY",
  304. "SENDGRID_API_URL",
  305. "POSTMARK_SERVER_TOKEN",
  306. "POSTMARK_API_URL",
  307. "MANDRILL_API_KEY",
  308. "MANDRILL_WEBHOOK_KEY",
  309. "MANDRILL_WEBHOOK_URL",
  310. "MANDRILL_API_URL",
  311. "SENDINBLUE_API_KEY",
  312. "SENDINBLUE_API_URL",
  313. "MAILJET_API_KEY",
  314. "MAILJET_SECRET_KEY",
  315. "MAILJET_API_URL",
  316. "POSTAL_API_KEY",
  317. "POSTAL_API_URL",
  318. "POSTAL_WEBHOOK_KEY",
  319. "SPARKPOST_API_KEY",
  320. "SPARKPOST_API_URL",
  321. "SPARKPOST_TRACK_INITIAL_OPEN_AS_OPENED",
  322. ]
  323. ANYMAIL = {
  324. anymail_var: env.str(anymail_var)
  325. for anymail_var in ANYMAIL_SETTINGS
  326. if anymail_var in os.environ
  327. }
  328. ACCOUNT_EMAIL_SUBJECT_PREFIX = env.str("ACCOUNT_EMAIL_SUBJECT_PREFIX", "")
  329. # Database
  330. # https://docs.djangoproject.com/en/dev/ref/settings/#databases
  331. DATABASES = {
  332. "default": env.db(default="postgres://postgres:postgres@postgres:5432/postgres")
  333. }
  334. # Support setting DATABASES in parts in order to get values from the postgresql helm chart
  335. DATABASE_HOST = env.str("DATABASE_HOST", None)
  336. DATABASE_PASSWORD = env.str("DATABASE_PASSWORD", None)
  337. if DATABASE_HOST and DATABASE_PASSWORD:
  338. DATABASES["default"] = {
  339. "ENGINE": "django.db.backends.postgresql",
  340. "NAME": env.str("DATABASE_NAME", "postgres"),
  341. "USER": env.str("DATABASE_USER", "postgres"),
  342. "PASSWORD": DATABASE_PASSWORD,
  343. "HOST": DATABASE_HOST,
  344. "PORT": env.str("DATABASE_PORT", "5432"),
  345. "CONN_MAX_AGE": env.int("DATABASE_CONN_MAX_AGE", 0),
  346. "CONN_HEALTH_CHECKS": env.bool("DATABASE_CONN_HEALTH_CHECKS", False),
  347. }
  348. DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
  349. # We need to support both url and broken out host to support helm redis chart
  350. REDIS_HOST = env.str("REDIS_HOST", None)
  351. if REDIS_HOST:
  352. REDIS_PORT = env.str("REDIS_PORT", "6379")
  353. REDIS_DATABASE = env.str("REDIS_DATABASE", "0")
  354. REDIS_PASSWORD = env.str("REDIS_PASSWORD", None)
  355. if REDIS_PASSWORD:
  356. REDIS_URL = (
  357. f"redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_DATABASE}"
  358. )
  359. else:
  360. REDIS_URL = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DATABASE}"
  361. else:
  362. REDIS_URL = env.str("REDIS_URL", "redis://redis:6379/0")
  363. REDIS_RETRY = env.bool("REDIS_RETRY", True)
  364. REDIS_MAX_CONNECTIONS = env.int("REDIS_MAX_CONNECTIONS", 100)
  365. CELERY_BROKER_URL = env.str("CELERY_BROKER_URL", REDIS_URL)
  366. CELERY_BROKER_TRANSPORT_OPTIONS = {
  367. "fanout_prefix": True,
  368. "fanout_patterns": True,
  369. "retry_on_timeout": REDIS_RETRY,
  370. "max_connections": REDIS_MAX_CONNECTIONS,
  371. }
  372. CELERY_REDIS_RETRY_ON_TIMEOUT = REDIS_RETRY
  373. CELERY_REDIS_MAX_CONNECTIONS = REDIS_MAX_CONNECTIONS
  374. if CELERY_BROKER_URL.startswith("sentinel"):
  375. CELERY_BROKER_TRANSPORT_OPTIONS["master_name"] = env.str(
  376. "CELERY_BROKER_MASTER_NAME", "mymaster"
  377. )
  378. if socket_timeout := env.int("CELERY_BROKER_SOCKET_TIMEOUT", None):
  379. CELERY_BROKER_TRANSPORT_OPTIONS["socket_timeout"] = socket_timeout
  380. if broker_sentinel_password := env.str("CELERY_BROKER_SENTINEL_KWARGS_PASSWORD", None):
  381. CELERY_BROKER_TRANSPORT_OPTIONS["sentinel_kwargs"] = {
  382. "password": broker_sentinel_password
  383. }
  384. # Time in seconds to debounce some frequently run tasks
  385. TASK_DEBOUNCE_DELAY = env.int("TASK_DEBOUNCE_DELAY", 30)
  386. UPTIME_CHECK_INTERVAL = 10
  387. CELERY_BEAT_SCHEDULE = {
  388. "send-alert-notifications": {
  389. "task": "alerts.tasks.process_event_alerts",
  390. "schedule": 60,
  391. },
  392. "cleanup-old-events": {
  393. "task": "issues.tasks.cleanup_old_events",
  394. "schedule": crontab(hour=5),
  395. },
  396. "reindex-issues-model": {
  397. "task": "issues.tasks.reindex_issues_model",
  398. "schedule": crontab(hour=5, minute=30),
  399. },
  400. "cleanup-old-transaction-events": {
  401. "task": "performance.tasks.cleanup_old_transaction_events",
  402. "schedule": crontab(hour=6),
  403. },
  404. "cleanup-old-monitor-checks": {
  405. "task": "glitchtip.uptime.tasks.cleanup_old_monitor_checks",
  406. "schedule": crontab(hour=6, minute=30),
  407. },
  408. "cleanup-old-files": {
  409. "task": "files.tasks.cleanup_old_files",
  410. "schedule": crontab(hour=7),
  411. },
  412. "uptime-dispatch-checks": {
  413. "task": "glitchtip.uptime.tasks.dispatch_checks",
  414. "schedule": UPTIME_CHECK_INTERVAL,
  415. },
  416. }
  417. if os.environ.get("CACHE_URL"):
  418. CACHES = {
  419. "default": env.cache(),
  420. }
  421. else: # Default to REDIS when unset
  422. CACHES = {
  423. "default": {
  424. "BACKEND": "django_redis.cache.RedisCache",
  425. "LOCATION": REDIS_URL,
  426. "PARSER_CLASS": "redis.connection.HiredisParser",
  427. "OPTIONS": {
  428. "CONNECTION_POOL_KWARGS": {
  429. "retry_on_timeout": REDIS_RETRY,
  430. "max_connections": REDIS_MAX_CONNECTIONS,
  431. }
  432. },
  433. }
  434. }
  435. if cache_sentinel_url := env.str("CACHE_SENTINEL_URL", None):
  436. try:
  437. cache_sentinel_host, cache_sentinel_port = cache_sentinel_url.split(":")
  438. SENTINELS = [(cache_sentinel_host, int(cache_sentinel_port))]
  439. except ValueError as err:
  440. raise ImproperlyConfigured(
  441. "Invalid cache redis sentinel url, format is host:port"
  442. ) from err
  443. DJANGO_REDIS_CONNECTION_FACTORY = "django_redis.pool.SentinelConnectionFactory"
  444. CACHES["default"]["OPTIONS"]["SENTINELS"] = SENTINELS
  445. if cache_sentinel_password := env.str("CACHE_SENTINEL_PASSWORD", None):
  446. CACHES["default"]["OPTIONS"]["SENTINEL_KWARGS"] = {
  447. "password": cache_sentinel_password
  448. }
  449. if os.environ.get("SESSION_ENGINE"):
  450. SESSION_ENGINE = env.str("SESSION_ENGINE")
  451. if os.environ.get("SESSION_CACHE_ALIAS"):
  452. SESSION_CACHE_ALIAS = env.str("SESSION_CACHE_ALIAS")
  453. if os.environ.get("SESSION_COOKIE_AGE"):
  454. SESSION_COOKIE_AGE = env.int("SESSION_COOKIE_AGE")
  455. # Password validation
  456. # https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
  457. AUTH_PASSWORD_VALIDATORS = [
  458. {
  459. "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
  460. },
  461. {
  462. "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
  463. },
  464. {
  465. "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
  466. },
  467. {
  468. "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
  469. },
  470. ]
  471. # Internationalization
  472. # https://docs.djangoproject.com/en/dev/topics/i18n/
  473. LANGUAGE_CODE = "en-us"
  474. TIME_ZONE = "UTC"
  475. USE_I18N = True
  476. USE_TZ = True
  477. if env("DEFAULT_FILE_STORAGE"):
  478. DEFAULT_FILE_STORAGE = env("DEFAULT_FILE_STORAGE")
  479. AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID")
  480. AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY")
  481. AWS_STORAGE_BUCKET_NAME = env("AWS_STORAGE_BUCKET_NAME")
  482. AWS_S3_ENDPOINT_URL = env("AWS_S3_ENDPOINT_URL")
  483. AWS_LOCATION = env("AWS_LOCATION")
  484. AZURE_ACCOUNT_NAME = env("AZURE_ACCOUNT_NAME")
  485. AZURE_ACCOUNT_KEY = env("AZURE_ACCOUNT_KEY")
  486. AZURE_CONTAINER = env("AZURE_CONTAINER")
  487. AZURE_URL_EXPIRATION_SECS = env("AZURE_URL_EXPIRATION_SECS")
  488. GS_BUCKET_NAME = env("GS_BUCKET_NAME")
  489. GS_PROJECT_ID = env("GS_PROJECT_ID")
  490. if AWS_S3_ENDPOINT_URL:
  491. MEDIA_URL = env.str(
  492. "MEDIA_URL", "https://%s/%s/" % (AWS_S3_ENDPOINT_URL, AWS_LOCATION)
  493. )
  494. DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
  495. else:
  496. MEDIA_URL = "media/"
  497. MEDIA_ROOT = env.str("MEDIA_ROOT", "")
  498. STATICFILES_DIRS = [
  499. "assets",
  500. "dist",
  501. ]
  502. STATIC_ROOT = path("static/")
  503. STATICFILES_STORAGE = env("STATICFILES_STORAGE")
  504. EMAIL_BACKEND = env.str(
  505. "EMAIL_BACKEND", default="django.core.mail.backends.smtp.EmailBackend"
  506. )
  507. if os.getenv("EMAIL_HOST_USER"):
  508. EMAIL_HOST_USER = env.str("EMAIL_HOST_USER")
  509. if os.getenv("EMAIL_HOST_PASSWORD"):
  510. EMAIL_HOST_PASSWORD = env.str("EMAIL_HOST_PASSWORD")
  511. if os.getenv("EMAIL_HOST"):
  512. EMAIL_HOST = env.str("EMAIL_HOST")
  513. if os.getenv("EMAIL_PORT"):
  514. EMAIL_PORT = env.str("EMAIL_PORT")
  515. if os.getenv("EMAIL_USE_TLS"):
  516. EMAIL_USE_TLS = env.str("EMAIL_USE_TLS")
  517. if os.getenv("EMAIL_USE_SSL"):
  518. EMAIL_USE_SSL = env.str("EMAIL_USE_SSL")
  519. if os.getenv("EMAIL_TIMEOUT"):
  520. EMAIL_TIMEOUT = env.str("EMAIL_TIMEOUT")
  521. if os.getenv("EMAIL_FILE_PATH"):
  522. EMAIL_FILE_PATH = env.str("EMAIL_FILE_PATH")
  523. if os.getenv(
  524. "EMAIL_URL"
  525. ): # 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.
  526. EMAIL_CONFIG = env.email_url("EMAIL_URL")
  527. vars().update(EMAIL_CONFIG)
  528. AUTH_USER_MODEL = "users.User"
  529. ACCOUNT_AUTHENTICATION_METHOD = "email"
  530. ACCOUNT_EMAIL_REQUIRED = True
  531. ACCOUNT_USERNAME_REQUIRED = False
  532. ACCOUNT_USER_MODEL_USERNAME_FIELD = None
  533. ACCOUNT_ADAPTER = "glitchtip.social.MFAAccountAdapter"
  534. SOCIALACCOUNT_ADAPTER = "glitchtip.social.CustomSocialAccountAdapter"
  535. INVITATION_BACKEND = "organizations_ext.invitation_backend.InvitationBackend"
  536. SOCIALACCOUNT_PROVIDERS = {}
  537. if GITLAB_URL := env.url("SOCIALACCOUNT_PROVIDERS_gitlab_GITLAB_URL", None):
  538. SOCIALACCOUNT_PROVIDERS["gitlab"] = {"GITLAB_URL": GITLAB_URL.geturl()}
  539. if GITEA_URL := env.url("SOCIALACCOUNT_PROVIDERS_gitea_GITEA_URL", None):
  540. SOCIALACCOUNT_PROVIDERS["gitea"] = {"GITEA_URL": GITEA_URL.geturl()}
  541. if NEXTCLOUD_URL := env.url("SOCIALACCOUNT_PROVIDERS_nextcloud_SERVER", None):
  542. SOCIALACCOUNT_PROVIDERS["nextcloud"] = {"SERVER": NEXTCLOUD_URL.geturl()}
  543. if KEYCLOAK_URL := env.url("SOCIALACCOUNT_PROVIDERS_keycloak_KEYCLOAK_URL", None):
  544. alt_url_env = env.url("SOCIALACCOUNT_PROVIDERS_keycloak_KEYCLOAK_URL_ALT", None)
  545. if alt_url_env:
  546. alt_url = alt_url_env.geturl()
  547. else:
  548. alt_url = None
  549. SOCIALACCOUNT_PROVIDERS["keycloak"] = {
  550. "KEYCLOAK_URL": KEYCLOAK_URL.geturl(),
  551. "KEYCLOAK_REALM": env.str(
  552. "SOCIALACCOUNT_PROVIDERS_keycloak_KEYCLOAK_REALM", None
  553. ),
  554. "KEYCLOAK_URL_ALT": alt_url,
  555. }
  556. if MICROSOFT_TENANT := env.str("SOCIALACCOUNT_PROVIDERS_microsoft_TENANT", None):
  557. SOCIALACCOUNT_PROVIDERS["microsoft"] = {"TENANT": MICROSOFT_TENANT}
  558. # Parse oidc settings as nested dict in array. Example:
  559. # SOCIALACCOUNT_PROVIDERS_openid_connect_SERVERS_0_id: "g-oidc"
  560. # SOCIALACCOUNT_PROVIDERS_openid_connect_SERVERS_0_server_url: "https://accounts.google.com"
  561. oidc_prefix = "SOCIALACCOUNT_PROVIDERS_openid_connect_SERVERS_"
  562. oidc_pattern = re.compile(r"{prefix}\w+".format(prefix=oidc_prefix))
  563. oidc_servers = {}
  564. for key, value in {
  565. key.replace(oidc_prefix, ""): val
  566. for key, val in os.environ.items()
  567. if oidc_pattern.match(key)
  568. }.items():
  569. number, setting = key.split("_", 1)
  570. if number in oidc_servers:
  571. oidc_servers[number][setting] = value
  572. else:
  573. oidc_servers[number] = {setting: value}
  574. oidc_servers = [x for x in oidc_servers.values()]
  575. SOCIALACCOUNT_PROVIDERS["openid_connect"] = {"SERVERS": oidc_servers}
  576. # Remove in GlitchTip4.0
  577. if "ENABLE_OPEN_USER_REGISTRATION" in os.environ:
  578. warnings.warn(
  579. "ENABLE_OPEN_USER_REGISTRATION is deprecated. Set ENABLE_ORGANIZATION_CREATION instead.",
  580. DeprecationWarning,
  581. )
  582. ENABLE_USER_REGISTRATION = env.bool("ENABLE_USER_REGISTRATION", True)
  583. ENABLE_ORGANIZATION_CREATION = env.bool(
  584. "ENABLE_OPEN_USER_REGISTRATION", env.bool("ENABLE_ORGANIZATION_CREATION", False)
  585. )
  586. REST_AUTH = {
  587. "TOKEN_MODEL": None,
  588. "TOKEN_CREATOR": "users.utils.noop_token_creator",
  589. "REGISTER_PERMISSION_CLASSES": (
  590. "glitchtip.permissions.UserRegistrationPermission",
  591. ),
  592. "REGISTER_SERIALIZER": "users.serializers.RegisterSerializer",
  593. "USER_DETAILS_SERIALIZER": "users.serializers.UserSerializer",
  594. "TOKEN_SERIALIZER": "users.serializers.NoopTokenSerializer",
  595. "PASSWORD_RESET_SERIALIZER": "users.serializers.PasswordSetResetSerializer",
  596. "OLD_PASSWORD_FIELD_ENABLED": True,
  597. }
  598. AUTHENTICATION_BACKENDS = (
  599. # Needed to login by username in Django admin, regardless of `allauth`
  600. "django.contrib.auth.backends.ModelBackend",
  601. # `allauth` specific authentication methods, such as login by e-mail
  602. "allauth.account.auth_backends.AuthenticationBackend",
  603. )
  604. DEFAULT_RENDERER_CLASSES = ("rest_framework.renderers.JSONRenderer",)
  605. if DEBUG:
  606. DEFAULT_RENDERER_CLASSES = DEFAULT_RENDERER_CLASSES + (
  607. "rest_framework.renderers.BrowsableAPIRenderer",
  608. )
  609. REST_FRAMEWORK = {
  610. "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
  611. "DEFAULT_PAGINATION_CLASS": "glitchtip.pagination.LinkHeaderPagination",
  612. "PAGE_SIZE": 50,
  613. "ORDERING_PARAM": "sort",
  614. "DEFAULT_FILTER_BACKENDS": ("django_filters.rest_framework.DjangoFilterBackend",),
  615. "DEFAULT_RENDERER_CLASSES": DEFAULT_RENDERER_CLASSES,
  616. "DEFAULT_AUTHENTICATION_CLASSES": [
  617. "rest_framework.authentication.SessionAuthentication",
  618. "glitchtip.authentication.BearerTokenAuthentication",
  619. ],
  620. "DEFAULT_THROTTLE_RATES": {"anon": "100/minute"},
  621. }
  622. DRF_YASG_EXCLUDE_VIEWS = [
  623. "users.views.SocialAccountDisconnectView",
  624. ]
  625. SWAGGER_SETTINGS = {
  626. "DEFAULT_AUTO_SCHEMA_CLASS": "glitchtip.yasg.SquadSwaggerAutoSchema",
  627. }
  628. LOGGING_HANDLER_CLASS = env.str("DJANGO_LOGGING_HANDLER_CLASS", "logging.StreamHandler")
  629. LOGGING = {
  630. "version": 1,
  631. "disable_existing_loggers": False,
  632. "handlers": {
  633. "null": {
  634. "class": "logging.NullHandler",
  635. },
  636. "console": {
  637. "class": LOGGING_HANDLER_CLASS,
  638. },
  639. },
  640. "loggers": {
  641. "django.security.DisallowedHost": {
  642. "handlers": ["null"],
  643. "propagate": False,
  644. },
  645. },
  646. "root": {"handlers": ["console"]},
  647. }
  648. if LOGGING_HANDLER_CLASS is not logging.StreamHandler:
  649. from celery.signals import after_setup_logger, after_setup_task_logger
  650. @after_setup_logger.connect
  651. @after_setup_task_logger.connect
  652. def setup_celery_logging(logger, **kwargs):
  653. from django.utils.module_loading import import_string
  654. handler = import_string(LOGGING_HANDLER_CLASS)
  655. for h in logger.handlers:
  656. logger.removeHandler(h)
  657. logger.addHandler(handler())
  658. def organization_request_callback(request):
  659. raise ImproperlyConfigured(
  660. "Organization request callback required by dj-stripe but not used."
  661. )
  662. # Set to track activity with Plausible
  663. PLAUSIBLE_URL = env.str("PLAUSIBLE_URL", default=None)
  664. PLAUSIBLE_DOMAIN = env.str("PLAUSIBLE_DOMAIN", default=None)
  665. # Is running unit test
  666. TESTING = len(sys.argv) > 1 and sys.argv[1] == "test"
  667. # See https://liberapay.com/GlitchTip/donate - suggested self-host donation is $5/month/user.
  668. # Support plans available. Email info@burkesoftware.com for more info.
  669. I_PAID_FOR_GLITCHTIP = env.bool("I_PAID_FOR_GLITCHTIP", False)
  670. # Max events per month for free tier
  671. BILLING_FREE_TIER_EVENTS = env.int("BILLING_FREE_TIER_EVENTS", 1000)
  672. DJSTRIPE_SUBSCRIBER_MODEL = "organizations_ext.Organization"
  673. DJSTRIPE_SUBSCRIBER_MODEL_REQUEST_CALLBACK = organization_request_callback
  674. DJSTRIPE_USE_NATIVE_JSONFIELD = True
  675. DJSTRIPE_FOREIGN_KEY_TO_FIELD = "djstripe_id"
  676. STRIPE_AUTOMATIC_TAX = env.bool("STRIPE_AUTOMATIC_TAX", False)
  677. STRIPE_LIVE_MODE = env.bool("STRIPE_LIVE_MODE", False)
  678. if BILLING_ENABLED:
  679. I_PAID_FOR_GLITCHTIP = True
  680. INSTALLED_APPS.append("djstripe")
  681. INSTALLED_APPS.append("djstripe_ext")
  682. STRIPE_TEST_PUBLIC_KEY = env.str("STRIPE_TEST_PUBLIC_KEY", None)
  683. STRIPE_TEST_SECRET_KEY = env.str("STRIPE_TEST_SECRET_KEY", None)
  684. STRIPE_LIVE_PUBLIC_KEY = env.str("STRIPE_LIVE_PUBLIC_KEY", None)
  685. STRIPE_LIVE_SECRET_KEY = env.str("STRIPE_LIVE_SECRET_KEY", None)
  686. DJSTRIPE_WEBHOOK_SECRET = env.str("DJSTRIPE_WEBHOOK_SECRET", None)
  687. CELERY_BEAT_SCHEDULE["set-organization-throttle"] = {
  688. "task": "organizations_ext.tasks.set_organization_throttle",
  689. "schedule": crontab(hour=7, minute=1),
  690. }
  691. CELERY_BEAT_SCHEDULE["warn-organization-throttle"] = {
  692. "task": "djstripe_ext.tasks.warn_organization_throttle",
  693. "schedule": crontab(minute=30),
  694. }
  695. elif TESTING:
  696. # Must run tests with djstripe enabled
  697. BILLING_ENABLED = True
  698. INSTALLED_APPS.append("djstripe")
  699. INSTALLED_APPS.append("djstripe_ext")
  700. STRIPE_TEST_PUBLIC_KEY = "fake"
  701. STRIPE_TEST_SECRET_KEY = "sk_test_fake" # nosec
  702. DJSTRIPE_WEBHOOK_SECRET = "whsec_fake" # nosec
  703. logging.disable(logging.WARNING)
  704. CELERY_TASK_ALWAYS_EAGER = env.bool("CELERY_TASK_ALWAYS_EAGER", False)
  705. if TESTING:
  706. CELERY_TASK_ALWAYS_EAGER = True
  707. STATICFILES_STORAGE = global_settings.STATICFILES_STORAGE
  708. # https://github.com/evansd/whitenoise/issues/215
  709. warnings.filterwarnings(
  710. "ignore", message="No directory at", module="whitenoise.base"
  711. )
  712. if CELERY_TASK_ALWAYS_EAGER:
  713. CACHES = {
  714. "default": {
  715. "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
  716. }
  717. }
  718. MFA_SERVER_NAME = GLITCHTIP_URL.hostname
  719. FIDO_SERVER_ID = GLITCHTIP_URL.hostname