production.py 11 KB

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