production.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. # ruff: noqa: F405
  2. import os
  3. import random
  4. import string
  5. from .base import * # noqa: F403
  6. DEBUG = False
  7. # DJANGO_SECRET_KEY *should* be specified in the environment. If it's not, generate an ephemeral key.
  8. if "DJANGO_SECRET_KEY" in os.environ:
  9. SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
  10. else:
  11. # Use if/else rather than a default value to avoid calculating this if we don't need it
  12. print( # noqa: T201
  13. "WARNING: DJANGO_SECRET_KEY not found in os.environ. Generating ephemeral SECRET_KEY."
  14. )
  15. SECRET_KEY = "".join(
  16. [random.SystemRandom().choice(string.printable) for i in range(50)]
  17. )
  18. # Make sure Django can detect a secure connection properly on Heroku:
  19. SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
  20. # Accept all hostnames, since we don't know in advance which hostname will be used for any given Heroku instance.
  21. # IMPORTANT: Set this to a real hostname when using this in production!
  22. # See https://docs.djangoproject.com/en/stable/ref/settings/#allowed-hosts
  23. ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS", "*").split(",")
  24. EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
  25. # This is used by Wagtail's email notifications for constructing absolute
  26. # URLs. Please set to the domain that users will access the admin site.
  27. if "PRIMARY_HOST" in os.environ:
  28. WAGTAILADMIN_BASE_URL = "https://{}".format(os.environ["PRIMARY_HOST"])
  29. # AWS creds may be used for S3 and/or Elasticsearch
  30. AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID", "")
  31. AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY", "")
  32. AWS_REGION = os.getenv("AWS_REGION", "")
  33. # Server-side cache settings. Do not confuse with front-end cache.
  34. # https://docs.djangoproject.com/en/stable/topics/cache/
  35. # If the server has a Redis instance exposed via a URL string in the REDIS_URL
  36. # environment variable, prefer that. Otherwise use the database backend. We
  37. # usually use Redis in production and database backend on staging and dev. In
  38. # order to use database cache backend you need to run
  39. # "./manage.py createcachetable" to create a table for the cache.
  40. #
  41. # Do not use the same Redis instance for other things like Celery!
  42. # Prefer the TLS connection URL over non
  43. REDIS_URL = os.environ.get("REDIS_TLS_URL", os.environ.get("REDIS_URL"))
  44. if REDIS_URL:
  45. connection_pool_kwargs = {}
  46. if REDIS_URL.startswith("rediss"):
  47. # Heroku Redis uses self-signed certificates for secure redis connections
  48. # When using TLS, we need to disable certificate validation checks.
  49. connection_pool_kwargs["ssl_cert_reqs"] = None
  50. redis_options = {
  51. "IGNORE_EXCEPTIONS": True,
  52. "SOCKET_CONNECT_TIMEOUT": 2, # seconds
  53. "SOCKET_TIMEOUT": 2, # seconds
  54. "CONNECTION_POOL_KWARGS": connection_pool_kwargs,
  55. }
  56. CACHES = {
  57. "default": {
  58. "BACKEND": "django_redis.cache.RedisCache",
  59. "LOCATION": REDIS_URL + "/0",
  60. "OPTIONS": redis_options,
  61. },
  62. "renditions": {
  63. "BACKEND": "django_redis.cache.RedisCache",
  64. "LOCATION": REDIS_URL + "/1",
  65. "OPTIONS": redis_options,
  66. },
  67. }
  68. DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS = True
  69. else:
  70. CACHES = {
  71. "default": {
  72. "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
  73. "LOCATION": "bakerydemo",
  74. }
  75. }
  76. # Configure Elasticsearch, if present in os.environ
  77. ELASTICSEARCH_ENDPOINT = os.getenv("ELASTICSEARCH_ENDPOINT", "")
  78. if ELASTICSEARCH_ENDPOINT:
  79. from elasticsearch import RequestsHttpConnection
  80. WAGTAILSEARCH_BACKENDS = {
  81. "default": {
  82. "BACKEND": "wagtail.search.backends.elasticsearch5",
  83. "HOSTS": [
  84. {
  85. "host": ELASTICSEARCH_ENDPOINT,
  86. "port": int(os.getenv("ELASTICSEARCH_PORT", "9200")),
  87. "use_ssl": os.getenv("ELASTICSEARCH_USE_SSL", "off") == "on",
  88. "verify_certs": os.getenv("ELASTICSEARCH_VERIFY_CERTS", "off")
  89. == "on",
  90. }
  91. ],
  92. "OPTIONS": {
  93. "connection_class": RequestsHttpConnection,
  94. },
  95. }
  96. }
  97. if AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY:
  98. from aws_requests_auth.aws_auth import AWSRequestsAuth
  99. WAGTAILSEARCH_BACKENDS["default"]["HOSTS"][0]["http_auth"] = AWSRequestsAuth(
  100. aws_access_key=AWS_ACCESS_KEY_ID,
  101. aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
  102. aws_token=os.getenv("AWS_SESSION_TOKEN", ""),
  103. aws_host=ELASTICSEARCH_ENDPOINT,
  104. aws_region=AWS_REGION,
  105. aws_service="es",
  106. )
  107. elif AWS_REGION:
  108. # No API keys in the environ, so attempt to discover them with Boto instead, per:
  109. # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html#configuring-credentials
  110. # This may be useful if your credentials are obtained via EC2 instance meta data.
  111. from aws_requests_auth.boto_utils import BotoAWSRequestsAuth
  112. WAGTAILSEARCH_BACKENDS["default"]["HOSTS"][0][
  113. "http_auth"
  114. ] = BotoAWSRequestsAuth(
  115. aws_host=ELASTICSEARCH_ENDPOINT,
  116. aws_region=AWS_REGION,
  117. aws_service="es",
  118. )
  119. # Simplified static file serving.
  120. # https://warehouse.python.org/project/whitenoise/
  121. MIDDLEWARE.append("whitenoise.middleware.WhiteNoiseMiddleware")
  122. STORAGES["staticfiles"][
  123. "BACKEND"
  124. ] = "whitenoise.storage.CompressedManifestStaticFilesStorage"
  125. if "AWS_STORAGE_BUCKET_NAME" in os.environ:
  126. AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME")
  127. AWS_QUERYSTRING_AUTH = False
  128. INSTALLED_APPS.append("storages")
  129. STORAGES["default"]["BACKEND"] = "storages.backends.s3boto3.S3Boto3Storage"
  130. AWS_S3_FILE_OVERWRITE = False
  131. AWS_DEFAULT_ACL = "private"
  132. if "AWS_S3_CUSTOM_DOMAIN" in os.environ:
  133. AWS_S3_CUSTOM_DOMAIN = os.environ["AWS_S3_CUSTOM_DOMAIN"]
  134. if "AWS_S3_REGION_NAME" in os.environ:
  135. AWS_S3_REGION_NAME = os.environ["AWS_S3_REGION_NAME"]
  136. if "GS_BUCKET_NAME" in os.environ:
  137. GS_BUCKET_NAME = os.getenv("GS_BUCKET_NAME")
  138. GS_PROJECT_ID = os.getenv("GS_PROJECT_ID")
  139. GS_DEFAULT_ACL = "publicRead"
  140. GS_AUTO_CREATE_BUCKET = True
  141. INSTALLED_APPS.append("storages")
  142. STORAGES["default"]["BACKEND"] = "storages.backends.gcloud.GoogleCloudStorage"
  143. LOGGING = {
  144. "version": 1,
  145. "disable_existing_loggers": False,
  146. "handlers": {
  147. "console": {
  148. "class": "logging.StreamHandler",
  149. },
  150. },
  151. "loggers": {
  152. "django": {
  153. "handlers": ["console"],
  154. "level": os.getenv("DJANGO_LOG_LEVEL", "INFO"),
  155. },
  156. },
  157. }
  158. # Front-end cache
  159. # This configuration is used to allow purging pages from cache when they are
  160. # published.
  161. # These settings are usually used only on the production sites.
  162. # This is a configuration of the CDN/front-end cache that is used to cache the
  163. # production websites.
  164. # https://docs.wagtail.org/en/stable/reference/contrib/frontendcache.html
  165. # The backend can be configured to use an account-wide API key, or an API token with
  166. # restricted access.
  167. if (
  168. "FRONTEND_CACHE_CLOUDFLARE_TOKEN" in os.environ
  169. or "FRONTEND_CACHE_CLOUDFLARE_BEARER_TOKEN" in os.environ
  170. ):
  171. INSTALLED_APPS.append("wagtail.contrib.frontend_cache")
  172. WAGTAILFRONTENDCACHE = {
  173. "default": {
  174. "BACKEND": "wagtail.contrib.frontend_cache.backends.CloudflareBackend",
  175. "ZONEID": os.environ["FRONTEND_CACHE_CLOUDFLARE_ZONEID"],
  176. }
  177. }
  178. if "FRONTEND_CACHE_CLOUDFLARE_TOKEN" in os.environ:
  179. # To use an account-wide API key, set the following:
  180. # * $FRONTEND_CACHE_CLOUDFLARE_TOKEN
  181. # * $FRONTEND_CACHE_CLOUDFLARE_EMAIL
  182. # * $FRONTEND_CACHE_CLOUDFLARE_ZONEID
  183. # These can be obtained from a sysadmin.
  184. WAGTAILFRONTENDCACHE["default"].update(
  185. {
  186. "EMAIL": os.environ["FRONTEND_CACHE_CLOUDFLARE_EMAIL"],
  187. "TOKEN": os.environ["FRONTEND_CACHE_CLOUDFLARE_TOKEN"],
  188. }
  189. )
  190. else:
  191. # To use an API token with restricted access, set the following:
  192. # * $FRONTEND_CACHE_CLOUDFLARE_BEARER_TOKEN
  193. # * $FRONTEND_CACHE_CLOUDFLARE_ZONEID
  194. WAGTAILFRONTENDCACHE["default"].update(
  195. {"BEARER_TOKEN": os.environ["FRONTEND_CACHE_CLOUDFLARE_BEARER_TOKEN"]}
  196. )
  197. # Basic authentication settings
  198. # These are settings to configure the third-party library:
  199. # https://gitlab.com/tmkn/django-basic-auth-ip-whitelist
  200. if os.environ.get("BASIC_AUTH_ENABLED", "false").lower().strip() == "true":
  201. # Insert basic auth as a first middleware to be checked first, before
  202. # anything else.
  203. MIDDLEWARE.insert(0, "baipw.middleware.BasicAuthIPWhitelistMiddleware")
  204. # This is the credentials users will have to use to access the site.
  205. BASIC_AUTH_LOGIN = os.environ.get("BASIC_AUTH_LOGIN", "wagtail")
  206. BASIC_AUTH_PASSWORD = os.environ.get("BASIC_AUTH_PASSWORD", "wagtail")
  207. # Wagtail requires Authorization header to be present for the previews
  208. BASIC_AUTH_DISABLE_CONSUMING_AUTHORIZATION_HEADER = True
  209. # This is the list of hosts that website can be accessed without basic auth
  210. # check.
  211. if "BASIC_AUTH_WHITELISTED_HTTP_HOSTS" in os.environ:
  212. BASIC_AUTH_WHITELISTED_HTTP_HOSTS = os.environ[
  213. "BASIC_AUTH_WHITELISTED_HTTP_HOSTS"
  214. ].split(",")
  215. BASIC_AUTH_RESPONSE_TEMPLATE = "base/basic_auth.html"
  216. # Force HTTPS redirect (enabled by default!)
  217. # https://docs.djangoproject.com/en/stable/ref/settings/#secure-ssl-redirect
  218. SECURE_SSL_REDIRECT = True
  219. # This will allow the cache to swallow the fact that the website is behind TLS
  220. # and inform the Django using "X-Forwarded-Proto" HTTP header.
  221. # https://docs.djangoproject.com/en/stable/ref/settings/#secure-proxy-ssl-header
  222. SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
  223. # This is a setting activating the HSTS header. This will enforce the visitors to use
  224. # HTTPS for an amount of time specified in the header. Since we are expecting our apps
  225. # to run via TLS by default, this header is activated by default.
  226. # The header can be deactivated by setting this setting to 0, as it is done in the
  227. # dev and testing settings.
  228. # https://docs.djangoproject.com/en/stable/ref/settings/#secure-hsts-seconds
  229. DEFAULT_HSTS_SECONDS = 30 * 24 * 60 * 60 # 30 days
  230. SECURE_HSTS_SECONDS = int(
  231. os.environ.get("SECURE_HSTS_SECONDS", DEFAULT_HSTS_SECONDS)
  232. ) # noqa
  233. # Do not use the `includeSubDomains` directive for HSTS. This needs to be prevented
  234. # because the apps are running on client domains (or our own for staging), that are
  235. # being used for other applications as well. We should therefore not impose any
  236. # restrictions on these unrelated applications.
  237. # https://docs.djangoproject.com/en/stable/ref/settings/#secure-hsts-include-subdomains
  238. SECURE_HSTS_INCLUDE_SUBDOMAINS = False
  239. # https://docs.djangoproject.com/en/stable/ref/settings/#secure-browser-xss-filter
  240. SECURE_BROWSER_XSS_FILTER = True
  241. # https://docs.djangoproject.com/en/stable/ref/settings/#secure-content-type-nosniff
  242. SECURE_CONTENT_TYPE_NOSNIFF = True
  243. # Referrer-policy header settings.
  244. # https://django-referrer-policy.readthedocs.io/en/1.0/
  245. REFERRER_POLICY = os.environ.get( # noqa
  246. "SECURE_REFERRER_POLICY", "no-referrer-when-downgrade"
  247. ).strip()
  248. # Allow the redirect importer to work in load-balanced / cloud environments.
  249. # https://docs.wagtail.org/en/stable/reference/settings.html#redirects
  250. WAGTAIL_REDIRECTS_FILE_STORAGE = "cache"