settings.py 27 KB

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