settings.py 26 KB

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