settings.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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.FileAwareEnv(
  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.openid_connect",
  163. "anymail",
  164. "corsheaders",
  165. "django_filters",
  166. "django_extensions",
  167. "django_rest_mfa",
  168. ]
  169. if DEBUG_TOOLBAR:
  170. INSTALLED_APPS.append("debug_toolbar")
  171. INSTALLED_APPS += [
  172. "adrf",
  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. "allauth.account.middleware.AccountMiddleware",
  227. ]
  228. if ENABLE_OBSERVABILITY_API:
  229. MIDDLEWARE.insert(0, "django_prometheus.middleware.PrometheusBeforeMiddleware")
  230. MIDDLEWARE.append("django_prometheus.middleware.PrometheusAfterMiddleware")
  231. ROOT_URLCONF = "glitchtip.urls"
  232. TEMPLATES = [
  233. {
  234. "BACKEND": "django.template.backends.django.DjangoTemplates",
  235. "DIRS": [path("dist"), path("templates")],
  236. "APP_DIRS": True,
  237. "OPTIONS": {
  238. "context_processors": [
  239. "django.template.context_processors.debug",
  240. "django.template.context_processors.request",
  241. "django.contrib.auth.context_processors.auth",
  242. "django.contrib.messages.context_processors.messages",
  243. ],
  244. },
  245. },
  246. ]
  247. WSGI_APPLICATION = "glitchtip.wsgi.application"
  248. CORS_ORIGIN_ALLOW_ALL = env.bool("CORS_ORIGIN_ALLOW_ALL", True)
  249. CORS_ORIGIN_WHITELIST = env.tuple("CORS_ORIGIN_WHITELIST", str, default=())
  250. CORS_ALLOW_HEADERS = list(default_headers) + [
  251. "x-sentry-auth",
  252. ]
  253. BILLING_ENABLED = False
  254. if env.str("STRIPE_TEST_PUBLIC_KEY", None) or env.str("STRIPE_LIVE_PUBLIC_KEY", None):
  255. BILLING_ENABLED = True
  256. # Set to chatwoot website token to enable live help widget. Assumes app.chatwoot.com.
  257. CHATWOOT_WEBSITE_TOKEN = env.str("CHATWOOT_WEBSITE_TOKEN", None)
  258. CHATWOOT_IDENTITY_TOKEN = env.str("CHATWOOT_IDENTITY_TOKEN", None)
  259. CSRF_TRUSTED_ORIGINS = env.list("CSRF_TRUSTED_ORIGINS", str, [])
  260. SECURE_BROWSER_XSS_FILTER = True
  261. CSP_DEFAULT_SRC = env.list("CSP_DEFAULT_SRC", str, ["'self'"])
  262. CSP_STYLE_SRC = env.list(
  263. "CSP_STYLE_SRC", str, ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"]
  264. )
  265. CSP_STYLE_SRC_ELEM = env.list(
  266. "CSP_STYLE_SRC_ELEM",
  267. str,
  268. ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
  269. )
  270. CSP_FONT_SRC = env.list(
  271. "CSP_FONT_SRC", str, ["'self'", "https://fonts.gstatic.com", "data:"]
  272. )
  273. # Redoc requires blob
  274. CSP_WORKER_SRC = env.list("CSP_WORKER_SRC", str, ["'self'", "blob:"])
  275. # Enable Chatwoot only when configured
  276. default_connect_src = ["'self'", "https://*.glitchtip.com"]
  277. if CHATWOOT_WEBSITE_TOKEN:
  278. default_connect_src.append("https://app.chatwoot.com")
  279. CSP_CONNECT_SRC = env.list("CSP_CONNECT_SRC", str, default_connect_src)
  280. # Enable stripe by default only when configured
  281. stripe_domain = "https://js.stripe.com"
  282. default_script_src = ["'self'", "https://*.glitchtip.com"]
  283. default_frame_src = ["'self'"]
  284. if BILLING_ENABLED:
  285. default_script_src.append(stripe_domain)
  286. default_frame_src.append(stripe_domain)
  287. CSP_SCRIPT_SRC = env.list("CSP_SCRIPT_SRC", str, default_script_src)
  288. CSP_IMG_SRC = env.list("CSP_IMG_SRC", str, ["'self'"])
  289. CSP_FRAME_SRC = env.list("CSP_FRAME_SRC", str, default_frame_src)
  290. # Consider tracking CSP reports with GlitchTip itself
  291. CSP_REPORT_URI = env.tuple("CSP_REPORT_URI", str, None)
  292. CSP_REPORT_ONLY = env.bool("CSP_REPORT_ONLY", False)
  293. SECURE_HSTS_SECONDS = env.int("SECURE_HSTS_SECONDS", 0)
  294. SECURE_HSTS_PRELOAD = env.bool("SECURE_HSTS_PRELOAD", False)
  295. SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("SECURE_HSTS_INCLUDE_SUBDOMAINS", False)
  296. SESSION_COOKIE_SECURE = env.bool("SESSION_COOKIE_SECURE", False)
  297. SESSION_COOKIE_SAMESITE = env.str("SESSION_COOKIE_SAMESITE", "Lax")
  298. DEFAULT_FROM_EMAIL = env.str("DEFAULT_FROM_EMAIL", "webmaster@localhost")
  299. ANYMAIL_SETTINGS = [
  300. "MAILGUN_API_KEY",
  301. "MAILGUN_SENDER_DOMAIN",
  302. "MAILGUN_API_URL",
  303. "MAILGUN_WEBHOOK_SIGNING_KEY",
  304. "SENDGRID_API_KEY",
  305. "SENDGRID_API_URL",
  306. "POSTMARK_SERVER_TOKEN",
  307. "POSTMARK_API_URL",
  308. "MANDRILL_API_KEY",
  309. "MANDRILL_WEBHOOK_KEY",
  310. "MANDRILL_WEBHOOK_URL",
  311. "MANDRILL_API_URL",
  312. "SENDINBLUE_API_KEY",
  313. "SENDINBLUE_API_URL",
  314. "MAILJET_API_KEY",
  315. "MAILJET_SECRET_KEY",
  316. "MAILJET_API_URL",
  317. "POSTAL_API_KEY",
  318. "POSTAL_API_URL",
  319. "POSTAL_WEBHOOK_KEY",
  320. "SPARKPOST_API_KEY",
  321. "SPARKPOST_API_URL",
  322. "SPARKPOST_TRACK_INITIAL_OPEN_AS_OPENED",
  323. ]
  324. ANYMAIL = {
  325. anymail_var: env.str(anymail_var)
  326. for anymail_var in ANYMAIL_SETTINGS
  327. if anymail_var in os.environ
  328. }
  329. ACCOUNT_EMAIL_SUBJECT_PREFIX = env.str("ACCOUNT_EMAIL_SUBJECT_PREFIX", "")
  330. # Database
  331. # https://docs.djangoproject.com/en/dev/ref/settings/#databases
  332. DATABASES = {
  333. "default": env.db(default="postgres://postgres:postgres@postgres:5432/postgres")
  334. }
  335. # Support setting DATABASES in parts in order to get values from the postgresql helm chart
  336. DATABASE_HOST = env.str("DATABASE_HOST", None)
  337. DATABASE_PASSWORD = env.str("DATABASE_PASSWORD", None)
  338. if DATABASE_HOST and DATABASE_PASSWORD:
  339. DATABASES["default"] = {
  340. "ENGINE": "django.db.backends.postgresql",
  341. "NAME": env.str("DATABASE_NAME", "postgres"),
  342. "USER": env.str("DATABASE_USER", "postgres"),
  343. "PASSWORD": DATABASE_PASSWORD,
  344. "HOST": DATABASE_HOST,
  345. "PORT": env.str("DATABASE_PORT", "5432"),
  346. "CONN_MAX_AGE": env.int("DATABASE_CONN_MAX_AGE", 0),
  347. "CONN_HEALTH_CHECKS": env.bool("DATABASE_CONN_HEALTH_CHECKS", False),
  348. }
  349. DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
  350. # We need to support both url and broken out host to support helm redis chart
  351. REDIS_HOST = env.str("REDIS_HOST", None)
  352. if REDIS_HOST:
  353. REDIS_PORT = env.str("REDIS_PORT", "6379")
  354. REDIS_DATABASE = env.str("REDIS_DATABASE", "0")
  355. REDIS_PASSWORD = env.str("REDIS_PASSWORD", None)
  356. if REDIS_PASSWORD:
  357. REDIS_URL = (
  358. f"redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_DATABASE}"
  359. )
  360. else:
  361. REDIS_URL = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DATABASE}"
  362. else:
  363. REDIS_URL = env.str("REDIS_URL", "redis://redis:6379/0")
  364. REDIS_RETRY = env.bool("REDIS_RETRY", True)
  365. REDIS_MAX_CONNECTIONS = env.int("REDIS_MAX_CONNECTIONS", 100)
  366. CELERY_BROKER_URL = env.str("CELERY_BROKER_URL", REDIS_URL)
  367. CELERY_BROKER_TRANSPORT_OPTIONS = {
  368. "fanout_prefix": True,
  369. "fanout_patterns": True,
  370. "retry_on_timeout": REDIS_RETRY,
  371. "max_connections": REDIS_MAX_CONNECTIONS,
  372. }
  373. CELERY_REDIS_RETRY_ON_TIMEOUT = REDIS_RETRY
  374. CELERY_REDIS_MAX_CONNECTIONS = REDIS_MAX_CONNECTIONS
  375. if CELERY_BROKER_URL.startswith("sentinel"):
  376. CELERY_BROKER_TRANSPORT_OPTIONS["master_name"] = env.str(
  377. "CELERY_BROKER_MASTER_NAME", "mymaster"
  378. )
  379. if socket_timeout := env.int("CELERY_BROKER_SOCKET_TIMEOUT", None):
  380. CELERY_BROKER_TRANSPORT_OPTIONS["socket_timeout"] = socket_timeout
  381. if broker_sentinel_password := env.str("CELERY_BROKER_SENTINEL_KWARGS_PASSWORD", None):
  382. CELERY_BROKER_TRANSPORT_OPTIONS["sentinel_kwargs"] = {
  383. "password": broker_sentinel_password
  384. }
  385. # Time in seconds to debounce some frequently run tasks
  386. TASK_DEBOUNCE_DELAY = env.int("TASK_DEBOUNCE_DELAY", 30)
  387. UPTIME_CHECK_INTERVAL = 10
  388. CELERY_BEAT_SCHEDULE = {
  389. "send-alert-notifications": {
  390. "task": "alerts.tasks.process_event_alerts",
  391. "schedule": 60,
  392. },
  393. "cleanup-old-events": {
  394. "task": "issues.tasks.cleanup_old_events",
  395. "schedule": crontab(hour=5, minute=0),
  396. },
  397. "reindex-issues-model": {
  398. "task": "issues.tasks.reindex_issues_model",
  399. "schedule": crontab(hour=5, minute=30),
  400. },
  401. "cleanup-old-transaction-events": {
  402. "task": "performance.tasks.cleanup_old_transaction_events",
  403. "schedule": crontab(hour=6, minute=0),
  404. },
  405. "cleanup-old-monitor-checks": {
  406. "task": "glitchtip.uptime.tasks.cleanup_old_monitor_checks",
  407. "schedule": crontab(hour=6, minute=30),
  408. },
  409. "cleanup-old-files": {
  410. "task": "files.tasks.cleanup_old_files",
  411. "schedule": crontab(hour=7, minute=0),
  412. },
  413. "uptime-dispatch-checks": {
  414. "task": "glitchtip.uptime.tasks.dispatch_checks",
  415. "schedule": UPTIME_CHECK_INTERVAL,
  416. },
  417. }
  418. if os.environ.get("CACHE_URL"):
  419. CACHES = {
  420. "default": env.cache(),
  421. }
  422. else: # Default to REDIS when unset
  423. CACHES = {
  424. "default": {
  425. "BACKEND": "django_redis.cache.RedisCache",
  426. "LOCATION": REDIS_URL,
  427. "PARSER_CLASS": "redis.connection.HiredisParser",
  428. "OPTIONS": {
  429. "CONNECTION_POOL_KWARGS": {
  430. "retry_on_timeout": REDIS_RETRY,
  431. "max_connections": REDIS_MAX_CONNECTIONS,
  432. }
  433. },
  434. }
  435. }
  436. if cache_sentinel_url := env.str("CACHE_SENTINEL_URL", None):
  437. try:
  438. cache_sentinel_host, cache_sentinel_port = cache_sentinel_url.split(":")
  439. SENTINELS = [(cache_sentinel_host, int(cache_sentinel_port))]
  440. except ValueError as err:
  441. raise ImproperlyConfigured(
  442. "Invalid cache redis sentinel url, format is host:port"
  443. ) from err
  444. DJANGO_REDIS_CONNECTION_FACTORY = "django_redis.pool.SentinelConnectionFactory"
  445. CACHES["default"]["OPTIONS"]["SENTINELS"] = SENTINELS
  446. if cache_sentinel_password := env.str("CACHE_SENTINEL_PASSWORD", None):
  447. CACHES["default"]["OPTIONS"]["SENTINEL_KWARGS"] = {
  448. "password": cache_sentinel_password
  449. }
  450. if os.environ.get("SESSION_ENGINE"):
  451. SESSION_ENGINE = env.str("SESSION_ENGINE")
  452. if os.environ.get("SESSION_CACHE_ALIAS"):
  453. SESSION_CACHE_ALIAS = env.str("SESSION_CACHE_ALIAS")
  454. if os.environ.get("SESSION_COOKIE_AGE"):
  455. SESSION_COOKIE_AGE = env.int("SESSION_COOKIE_AGE")
  456. # Password validation
  457. # https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
  458. AUTH_PASSWORD_VALIDATORS = [
  459. {
  460. "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
  461. },
  462. {
  463. "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
  464. },
  465. {
  466. "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
  467. },
  468. {
  469. "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
  470. },
  471. ]
  472. # Internationalization
  473. # https://docs.djangoproject.com/en/dev/topics/i18n/
  474. LANGUAGE_CODE = "en-us"
  475. TIME_ZONE = "UTC"
  476. USE_I18N = True
  477. USE_TZ = True
  478. if env("DEFAULT_FILE_STORAGE"):
  479. DEFAULT_FILE_STORAGE = env("DEFAULT_FILE_STORAGE")
  480. AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID")
  481. AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY")
  482. AWS_STORAGE_BUCKET_NAME = env("AWS_STORAGE_BUCKET_NAME")
  483. AWS_S3_ENDPOINT_URL = env("AWS_S3_ENDPOINT_URL")
  484. AWS_LOCATION = env("AWS_LOCATION")
  485. AZURE_ACCOUNT_NAME = env("AZURE_ACCOUNT_NAME")
  486. AZURE_ACCOUNT_KEY = env("AZURE_ACCOUNT_KEY")
  487. AZURE_CONTAINER = env("AZURE_CONTAINER")
  488. AZURE_URL_EXPIRATION_SECS = env("AZURE_URL_EXPIRATION_SECS")
  489. GS_BUCKET_NAME = env("GS_BUCKET_NAME")
  490. GS_PROJECT_ID = env("GS_PROJECT_ID")
  491. if AWS_S3_ENDPOINT_URL:
  492. MEDIA_URL = env.str(
  493. "MEDIA_URL", "https://%s/%s/" % (AWS_S3_ENDPOINT_URL, AWS_LOCATION)
  494. )
  495. DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
  496. else:
  497. MEDIA_URL = "media/"
  498. MEDIA_ROOT = env.str("MEDIA_ROOT", "")
  499. STATICFILES_DIRS = [
  500. "assets",
  501. "dist",
  502. ]
  503. STATIC_ROOT = path("static/")
  504. STATICFILES_STORAGE = env("STATICFILES_STORAGE")
  505. EMAIL_BACKEND = env.str(
  506. "EMAIL_BACKEND", default="django.core.mail.backends.smtp.EmailBackend"
  507. )
  508. if os.getenv("EMAIL_HOST_USER"):
  509. EMAIL_HOST_USER = env.str("EMAIL_HOST_USER")
  510. if os.getenv("EMAIL_HOST_PASSWORD"):
  511. EMAIL_HOST_PASSWORD = env.str("EMAIL_HOST_PASSWORD")
  512. if os.getenv("EMAIL_HOST"):
  513. EMAIL_HOST = env.str("EMAIL_HOST")
  514. if os.getenv("EMAIL_PORT"):
  515. EMAIL_PORT = env.str("EMAIL_PORT")
  516. if os.getenv("EMAIL_USE_TLS"):
  517. EMAIL_USE_TLS = env.str("EMAIL_USE_TLS")
  518. if os.getenv("EMAIL_USE_SSL"):
  519. EMAIL_USE_SSL = env.str("EMAIL_USE_SSL")
  520. if os.getenv("EMAIL_TIMEOUT"):
  521. EMAIL_TIMEOUT = env.str("EMAIL_TIMEOUT")
  522. if os.getenv("EMAIL_FILE_PATH"):
  523. EMAIL_FILE_PATH = env.str("EMAIL_FILE_PATH")
  524. if os.getenv(
  525. "EMAIL_URL"
  526. ): # 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.
  527. EMAIL_CONFIG = env.email_url("EMAIL_URL")
  528. vars().update(EMAIL_CONFIG)
  529. AUTH_USER_MODEL = "users.User"
  530. ACCOUNT_AUTHENTICATION_METHOD = "email"
  531. ACCOUNT_EMAIL_REQUIRED = True
  532. ACCOUNT_USERNAME_REQUIRED = False
  533. ACCOUNT_USER_MODEL_USERNAME_FIELD = None
  534. ACCOUNT_ADAPTER = "glitchtip.social.MFAAccountAdapter"
  535. SOCIALACCOUNT_ADAPTER = "glitchtip.social.CustomSocialAccountAdapter"
  536. INVITATION_BACKEND = "organizations_ext.invitation_backend.InvitationBackend"
  537. SOCIALACCOUNT_PROVIDERS = {}
  538. if GITLAB_URL := env.url("SOCIALACCOUNT_PROVIDERS_gitlab_GITLAB_URL", None):
  539. SOCIALACCOUNT_PROVIDERS["gitlab"] = {"GITLAB_URL": GITLAB_URL.geturl()}
  540. if GITEA_URL := env.url("SOCIALACCOUNT_PROVIDERS_gitea_GITEA_URL", None):
  541. SOCIALACCOUNT_PROVIDERS["gitea"] = {"GITEA_URL": GITEA_URL.geturl()}
  542. if NEXTCLOUD_URL := env.url("SOCIALACCOUNT_PROVIDERS_nextcloud_SERVER", None):
  543. SOCIALACCOUNT_PROVIDERS["nextcloud"] = {"SERVER": NEXTCLOUD_URL.geturl()}
  544. # Removed keycloak, use oidc https://django-allauth.readthedocs.io/en/latest/socialaccount/providers/keycloak.html
  545. if MICROSOFT_TENANT := env.str("SOCIALACCOUNT_PROVIDERS_microsoft_TENANT", None):
  546. SOCIALACCOUNT_PROVIDERS["microsoft"] = {"TENANT": MICROSOFT_TENANT}
  547. # Parse oidc settings as nested dict in array. Example:
  548. # SOCIALACCOUNT_PROVIDERS_openid_connect_SERVERS_0_id: "g-oidc"
  549. # SOCIALACCOUNT_PROVIDERS_openid_connect_SERVERS_0_server_url: "https://accounts.google.com"
  550. oidc_prefix = "SOCIALACCOUNT_PROVIDERS_openid_connect_SERVERS_"
  551. oidc_pattern = re.compile(r"{prefix}\w+".format(prefix=oidc_prefix))
  552. oidc_servers = {}
  553. for key, value in {
  554. key.replace(oidc_prefix, ""): val
  555. for key, val in os.environ.items()
  556. if oidc_pattern.match(key)
  557. }.items():
  558. number, setting = key.split("_", 1)
  559. if number in oidc_servers:
  560. oidc_servers[number][setting] = value
  561. else:
  562. oidc_servers[number] = {setting: value}
  563. oidc_servers = [x for x in oidc_servers.values()]
  564. SOCIALACCOUNT_PROVIDERS["openid_connect"] = {"SERVERS": oidc_servers}
  565. # Remove in GlitchTip4.0
  566. if "ENABLE_OPEN_USER_REGISTRATION" in os.environ:
  567. warnings.warn(
  568. "ENABLE_OPEN_USER_REGISTRATION is deprecated. Set ENABLE_ORGANIZATION_CREATION instead.",
  569. DeprecationWarning,
  570. )
  571. ENABLE_USER_REGISTRATION = env.bool("ENABLE_USER_REGISTRATION", True)
  572. ENABLE_ORGANIZATION_CREATION = env.bool(
  573. "ENABLE_OPEN_USER_REGISTRATION", env.bool("ENABLE_ORGANIZATION_CREATION", False)
  574. )
  575. REST_AUTH = {
  576. "TOKEN_MODEL": None,
  577. "TOKEN_CREATOR": "users.utils.noop_token_creator",
  578. "REGISTER_PERMISSION_CLASSES": (
  579. "glitchtip.permissions.UserRegistrationPermission",
  580. ),
  581. "REGISTER_SERIALIZER": "users.serializers.RegisterSerializer",
  582. "USER_DETAILS_SERIALIZER": "users.serializers.UserSerializer",
  583. "TOKEN_SERIALIZER": "users.serializers.NoopTokenSerializer",
  584. "PASSWORD_RESET_SERIALIZER": "users.serializers.PasswordSetResetSerializer",
  585. "OLD_PASSWORD_FIELD_ENABLED": True,
  586. }
  587. AUTHENTICATION_BACKENDS = (
  588. # Needed to login by username in Django admin, regardless of `allauth`
  589. "django.contrib.auth.backends.ModelBackend",
  590. # `allauth` specific authentication methods, such as login by e-mail
  591. "allauth.account.auth_backends.AuthenticationBackend",
  592. )
  593. DEFAULT_RENDERER_CLASSES = ("rest_framework.renderers.JSONRenderer",)
  594. if DEBUG:
  595. DEFAULT_RENDERER_CLASSES = DEFAULT_RENDERER_CLASSES + (
  596. "rest_framework.renderers.BrowsableAPIRenderer",
  597. )
  598. REST_FRAMEWORK = {
  599. "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
  600. "DEFAULT_PAGINATION_CLASS": "glitchtip.pagination.LinkHeaderPagination",
  601. "PAGE_SIZE": 50,
  602. "ORDERING_PARAM": "sort",
  603. "DEFAULT_FILTER_BACKENDS": ("django_filters.rest_framework.DjangoFilterBackend",),
  604. "DEFAULT_RENDERER_CLASSES": DEFAULT_RENDERER_CLASSES,
  605. "DEFAULT_AUTHENTICATION_CLASSES": [
  606. "rest_framework.authentication.SessionAuthentication",
  607. "glitchtip.authentication.BearerTokenAuthentication",
  608. ],
  609. "DEFAULT_THROTTLE_RATES": {"anon": "100/minute"},
  610. }
  611. DRF_YASG_EXCLUDE_VIEWS = [
  612. "users.views.SocialAccountDisconnectView",
  613. ]
  614. SWAGGER_SETTINGS = {
  615. "DEFAULT_AUTO_SCHEMA_CLASS": "glitchtip.yasg.SquadSwaggerAutoSchema",
  616. }
  617. LOGGING_HANDLER_CLASS = env.str("DJANGO_LOGGING_HANDLER_CLASS", "logging.StreamHandler")
  618. LOGGING = {
  619. "version": 1,
  620. "disable_existing_loggers": False,
  621. "handlers": {
  622. "null": {
  623. "class": "logging.NullHandler",
  624. },
  625. "console": {
  626. "class": LOGGING_HANDLER_CLASS,
  627. },
  628. },
  629. "loggers": {
  630. "django.security.DisallowedHost": {
  631. "handlers": ["null"],
  632. "propagate": False,
  633. },
  634. },
  635. "root": {"handlers": ["console"]},
  636. }
  637. if LOGGING_HANDLER_CLASS is not logging.StreamHandler:
  638. from celery.signals import after_setup_logger, after_setup_task_logger
  639. @after_setup_logger.connect
  640. @after_setup_task_logger.connect
  641. def setup_celery_logging(logger, **kwargs):
  642. from django.utils.module_loading import import_string
  643. handler = import_string(LOGGING_HANDLER_CLASS)
  644. for h in logger.handlers:
  645. logger.removeHandler(h)
  646. logger.addHandler(handler())
  647. def organization_request_callback(request):
  648. raise ImproperlyConfigured(
  649. "Organization request callback required by dj-stripe but not used."
  650. )
  651. # Set to track activity with Plausible
  652. PLAUSIBLE_URL = env.str("PLAUSIBLE_URL", default=None)
  653. PLAUSIBLE_DOMAIN = env.str("PLAUSIBLE_DOMAIN", default=None)
  654. # Is running unit test
  655. TESTING = len(sys.argv) > 1 and sys.argv[1] == "test"
  656. # See https://liberapay.com/GlitchTip/donate - suggested self-host donation is $5/month/user.
  657. # Support plans available. Email info@burkesoftware.com for more info.
  658. I_PAID_FOR_GLITCHTIP = env.bool("I_PAID_FOR_GLITCHTIP", False)
  659. # Max events per month for free tier
  660. BILLING_FREE_TIER_EVENTS = env.int("BILLING_FREE_TIER_EVENTS", 1000)
  661. DJSTRIPE_SUBSCRIBER_MODEL = "organizations_ext.Organization"
  662. DJSTRIPE_SUBSCRIBER_MODEL_REQUEST_CALLBACK = organization_request_callback
  663. DJSTRIPE_USE_NATIVE_JSONFIELD = True
  664. DJSTRIPE_FOREIGN_KEY_TO_FIELD = "djstripe_id"
  665. STRIPE_AUTOMATIC_TAX = env.bool("STRIPE_AUTOMATIC_TAX", False)
  666. STRIPE_LIVE_MODE = env.bool("STRIPE_LIVE_MODE", False)
  667. if BILLING_ENABLED:
  668. I_PAID_FOR_GLITCHTIP = True
  669. INSTALLED_APPS.append("djstripe")
  670. INSTALLED_APPS.append("djstripe_ext")
  671. STRIPE_TEST_PUBLIC_KEY = env.str("STRIPE_TEST_PUBLIC_KEY", None)
  672. STRIPE_TEST_SECRET_KEY = env.str("STRIPE_TEST_SECRET_KEY", None)
  673. STRIPE_LIVE_PUBLIC_KEY = env.str("STRIPE_LIVE_PUBLIC_KEY", None)
  674. STRIPE_LIVE_SECRET_KEY = env.str("STRIPE_LIVE_SECRET_KEY", None)
  675. DJSTRIPE_WEBHOOK_SECRET = env.str("DJSTRIPE_WEBHOOK_SECRET", None)
  676. CELERY_BEAT_SCHEDULE["set-organization-throttle"] = {
  677. "task": "organizations_ext.tasks.set_organization_throttle",
  678. "schedule": crontab(hour=7, minute=1),
  679. }
  680. CELERY_BEAT_SCHEDULE["warn-organization-throttle"] = {
  681. "task": "djstripe_ext.tasks.warn_organization_throttle",
  682. "schedule": crontab(minute=30),
  683. }
  684. elif TESTING:
  685. # Must run tests with djstripe enabled
  686. BILLING_ENABLED = True
  687. INSTALLED_APPS.append("djstripe")
  688. INSTALLED_APPS.append("djstripe_ext")
  689. STRIPE_TEST_PUBLIC_KEY = "fake"
  690. STRIPE_TEST_SECRET_KEY = "sk_test_fake" # nosec
  691. DJSTRIPE_WEBHOOK_SECRET = "whsec_fake" # nosec
  692. logging.disable(logging.WARNING)
  693. CELERY_TASK_ALWAYS_EAGER = env.bool("CELERY_TASK_ALWAYS_EAGER", False)
  694. if TESTING:
  695. CELERY_TASK_ALWAYS_EAGER = True
  696. STATICFILES_STORAGE = global_settings.STATICFILES_STORAGE
  697. # https://github.com/evansd/whitenoise/issues/215
  698. warnings.filterwarnings(
  699. "ignore", message="No directory at", module="whitenoise.base"
  700. )
  701. if CELERY_TASK_ALWAYS_EAGER:
  702. CACHES = {
  703. "default": {
  704. "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
  705. }
  706. }
  707. MFA_SERVER_NAME = GLITCHTIP_URL.hostname
  708. FIDO_SERVER_ID = GLITCHTIP_URL.hostname