prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  CSRF token PR fails in prod due to referer checks
  The cookies seem to be working properly, but referer checks are failing?
  
  ```
  Jan 31 18:46:57 coma gunicorn[23653]: Forbidden (Referer checking failed - https://www.ocf.berkeley.edu/account/register/ does not match any trusted origins.): /account/register/
  ```
  
  Explained in the docs:
  https://docs.djangoproject.com/en/dev/ref/csrf/#how-it-works
  
  Maybe the referer header is not what we think it is due to the proxying?
  
  I reverted my change in 89a8931ff0fe9e511905780a42be24a63b1d5c9a
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `ocfweb/settings.py`
  Content:
  ```
  1 import configparser
  2 import os
  3 from getpass import getuser
  4 
  5 from django.template.base import TemplateSyntaxError
  6 
  7 
  8 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  9 
  10 SECRET_KEY = 'not_a_secret'
  11 DEBUG = True
  12 
  13 ALLOWED_HOSTS = [
  14     'www.ocf.berkeley.edu',
  15     'dev.ocf.berkeley.edu',
  16     'dev-www.ocf.berkeley.edu',
  17     'ocfweb.ocf.berkeley.edu',
  18 ]
  19 
  20 INSTALLED_APPS = (
  21     'bootstrapform',
  22     'django.contrib.humanize',
  23     'django.contrib.messages',
  24     'django.contrib.sessions',
  25     'django.contrib.staticfiles',
  26     'mathfilters',
  27     'ocfweb',
  28     'ocfweb.about',
  29     'ocfweb.account',
  30     'ocfweb.docs',
  31     'ocfweb.login',
  32     'ocfweb.main',
  33     'ocfweb.middleware',
  34     'ocfweb.stats',
  35     'ocfweb.test',
  36 )
  37 
  38 MIDDLEWARE_CLASSES = (
  39     'django.contrib.sessions.middleware.SessionMiddleware',
  40     'django.middleware.common.CommonMiddleware',
  41     'django.middleware.csrf.CsrfViewMiddleware',
  42     'django.contrib.messages.middleware.MessageMiddleware',
  43     'django.middleware.clickjacking.XFrameOptionsMiddleware',
  44     'ocfweb.middleware.errors.OcflibErrorMiddleware',
  45 )
  46 
  47 SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
  48 ROOT_URLCONF = 'ocfweb.urls'
  49 
  50 
  51 class InvalidReferenceInTemplate(str):
  52     """Raise exceptions on invalid references in templates.
  53 
  54     By default Django just replaces references to undefined variables with
  55     empty strings. This is a horrible idea, so we instead hack it to raise an
  56     exception.
  57     """
  58 
  59     def __mod__(self, ref):
  60         raise TemplateSyntaxError('Invalid reference in template: {}'.format(ref))
  61 
  62 
  63 TEMPLATES = [{
  64     'BACKEND': 'django.template.backends.django.DjangoTemplates',
  65     'DIRS': [],
  66     'APP_DIRS': True,
  67     'OPTIONS': {
  68         'context_processors': [
  69             'django.template.context_processors.request',
  70             'django.contrib.messages.context_processors.messages',
  71             'ocfweb.context_processors.ocf_template_processor',
  72         ],
  73         'string_if_invalid': InvalidReferenceInTemplate('%s'),
  74     },
  75 }]
  76 
  77 WSGI_APPLICATION = 'ocfweb.wsgi.application'
  78 
  79 DATABASES = {}
  80 
  81 # store sessions in the cache
  82 SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
  83 
  84 # XXX: DO NOT CHANGE
  85 # Ensure cookies can't be read by JavaScript.
  86 SESSION_COOKIE_HTTPONLY = True
  87 SESSION_COOKIE_SECURE = False
  88 SESSION_COOKIE_PATH = '/'
  89 SESSION_COOKIE_NAME = 'OCFWEB_SESSIONID'
  90 
  91 CACHES = {  # sessions are stored here
  92     'default': {
  93         # on dev, we use a file-backed cache so that you don't get logged out
  94         # every time you update code and the server restarts.
  95         'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
  96         'LOCATION': os.path.expanduser('~/.ocfweb-cache'),
  97     },
  98     'TIMEOUT': 60 * 60 * 12,  # 12 hours
  99     'OPTIONS': {
  100         'MAX_ENTRIES': 1000,
  101     },
  102 }
  103 
  104 LANGUAGE_CODE = 'en-us'
  105 TIME_ZONE = 'America/Los_Angeles'
  106 USE_I18N = False
  107 USE_L10N = False
  108 USE_TZ = True
  109 
  110 STATIC_URL = '/static/'
  111 os.environ.setdefault('OCFWEB_STATIC_ROOT', '')
  112 STATIC_ROOT = os.environ['OCFWEB_STATIC_ROOT']
  113 
  114 X_FRAME_OPTIONS = 'DENY'
  115 
  116 # log exceptions to stderr
  117 LOGGING = {
  118     'version': 1,
  119     'disable_existing_loggers': False,
  120     'handlers': {
  121         'console': {
  122             'class': 'logging.StreamHandler',
  123         },
  124     },
  125     'loggers': {
  126         'django': {
  127             'handlers': ['console'],
  128             'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
  129         },
  130     },
  131 }
  132 
  133 CELERY_BROKER = 'redis://create'
  134 CELERY_BACKEND = 'redis://create'
  135 
  136 if getuser() == 'ocfweb':
  137     # not running in development, override options from config file
  138     conf = configparser.ConfigParser()
  139     conf.read('/etc/ocfweb/ocfweb.conf')
  140 
  141     SECRET_KEY = conf.get('django', 'secret')
  142     DEBUG = conf.getboolean('django', 'debug')
  143 
  144     STATIC_URL = conf.get('django', 'static_url')
  145     STATIC_ROOT = conf.get('django', 'static_root')
  146 
  147     CELERY_BROKER = conf.get('celery', 'broker')
  148     CELERY_BACKEND = conf.get('celery', 'backend')
  149 
  150     # on prod, we use Redis as a cache
  151     CACHES['default'] = {
  152         'BACKEND': 'django_redis.cache.RedisCache',
  153         'LOCATION': 'redis://localhost:6379/0',
  154         'OPTIONS': {
  155             'CLIENT_CLASS': 'django_redis.client.DefaultClient',
  156         }
  157     }
  158 
  159     SESSION_COOKIE_SECURE = True
  160     SESSION_COOKIE_DOMAIN = 'www.ocf.berkeley.edu'
  161 else:
  162     # running in development
  163 
  164     # try to read celery values used by approve
  165     # (only works on supernova by staff members)
  166     try:
  167         conf = configparser.ConfigParser()
  168         conf.read('/etc/ocf-create/ocf-create.conf')
  169         CELERY_BROKER = conf.get('celery', 'broker')
  170         CELERY_BACKEND = conf.get('celery', 'backend')
  171     except configparser.NoSectionError:
  172         pass
  173
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/ocfweb/settings.py b/ocfweb/settings.py
  --- a/ocfweb/settings.py
  +++ b/ocfweb/settings.py
  @@ -82,7 +82,13 @@
   SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
   
   # XXX: DO NOT CHANGE
  -# Ensure cookies can't be read by JavaScript.
  +# Ensure cookies can't be read by JavaScript or users.
  +# Our proxy filters cookies starting with "OCFWEB_" when going to user sites,
  +# so it's important our cookies match this pattern.
  +CSRF_COOKIE_HTTPONLY = True
  +CSRF_COOKIE_SECURE = False
  +CSRF_COOKIE_PATH = '/'
  +CSRF_COOKIE_NAME = 'OCFWEB_CSRF_TOKEN'
   SESSION_COOKIE_HTTPONLY = True
   SESSION_COOKIE_SECURE = False
   SESSION_COOKIE_PATH = '/'
  @@ -156,6 +162,9 @@
           }
       }
   
  +    CSRF_COOKIE_SECURE = True
  +    CSRF_COOKIE_DOMAIN = 'www.ocf.berkeley.edu'
  +    CSRF_TRUSTED_ORIGINS = ['www.ocf.berkeley.edu']
       SESSION_COOKIE_SECURE = True
       SESSION_COOKIE_DOMAIN = 'www.ocf.berkeley.edu'
   else:
  
verification_info: {"golden_diff": "diff --git a/ocfweb/settings.py b/ocfweb/settings.py\n--- a/ocfweb/settings.py\n+++ b/ocfweb/settings.py\n@@ -82,7 +82,13 @@\n SESSION_ENGINE = 'django.contrib.sessions.backends.cache'\n \n # XXX: DO NOT CHANGE\n-# Ensure cookies can't be read by JavaScript.\n+# Ensure cookies can't be read by JavaScript or users.\n+# Our proxy filters cookies starting with \"OCFWEB_\" when going to user sites,\n+# so it's important our cookies match this pattern.\n+CSRF_COOKIE_HTTPONLY = True\n+CSRF_COOKIE_SECURE = False\n+CSRF_COOKIE_PATH = '/'\n+CSRF_COOKIE_NAME = 'OCFWEB_CSRF_TOKEN'\n SESSION_COOKIE_HTTPONLY = True\n SESSION_COOKIE_SECURE = False\n SESSION_COOKIE_PATH = '/'\n@@ -156,6 +162,9 @@\n         }\n     }\n \n+    CSRF_COOKIE_SECURE = True\n+    CSRF_COOKIE_DOMAIN = 'www.ocf.berkeley.edu'\n+    CSRF_TRUSTED_ORIGINS = ['www.ocf.berkeley.edu']\n     SESSION_COOKIE_SECURE = True\n     SESSION_COOKIE_DOMAIN = 'www.ocf.berkeley.edu'\n else:\n", "issue": "CSRF token PR fails in prod due to referer checks\nThe cookies seem to be working properly, but referer checks are failing?\n\n```\nJan 31 18:46:57 coma gunicorn[23653]: Forbidden (Referer checking failed - https://www.ocf.berkeley.edu/account/register/ does not match any trusted origins.): /account/register/\n```\n\nExplained in the docs:\nhttps://docs.djangoproject.com/en/dev/ref/csrf/#how-it-works\n\nMaybe the referer header is not what we think it is due to the proxying?\n\nI reverted my change in 89a8931ff0fe9e511905780a42be24a63b1d5c9a\n\n", "before_files": [{"content": "import configparser\nimport os\nfrom getpass import getuser\n\nfrom django.template.base import TemplateSyntaxError\n\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nSECRET_KEY = 'not_a_secret'\nDEBUG = True\n\nALLOWED_HOSTS = [\n    'www.ocf.berkeley.edu',\n    'dev.ocf.berkeley.edu',\n    'dev-www.ocf.berkeley.edu',\n    'ocfweb.ocf.berkeley.edu',\n]\n\nINSTALLED_APPS = (\n    'bootstrapform',\n    'django.contrib.humanize',\n    'django.contrib.messages',\n    'django.contrib.sessions',\n    'django.contrib.staticfiles',\n    'mathfilters',\n    'ocfweb',\n    'ocfweb.about',\n    'ocfweb.account',\n    'ocfweb.docs',\n    'ocfweb.login',\n    'ocfweb.main',\n    'ocfweb.middleware',\n    'ocfweb.stats',\n    'ocfweb.test',\n)\n\nMIDDLEWARE_CLASSES = (\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.middleware.csrf.CsrfViewMiddleware',\n    'django.contrib.messages.middleware.MessageMiddleware',\n    'django.middleware.clickjacking.XFrameOptionsMiddleware',\n    'ocfweb.middleware.errors.OcflibErrorMiddleware',\n)\n\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\nROOT_URLCONF = 'ocfweb.urls'\n\n\nclass InvalidReferenceInTemplate(str):\n    \"\"\"Raise exceptions on invalid references in templates.\n\n    By default Django just replaces references to undefined variables with\n    empty strings. This is a horrible idea, so we instead hack it to raise an\n    exception.\n    \"\"\"\n\n    def __mod__(self, ref):\n        raise TemplateSyntaxError('Invalid reference in template: {}'.format(ref))\n\n\nTEMPLATES = [{\n    'BACKEND': 'django.template.backends.django.DjangoTemplates',\n    'DIRS': [],\n    'APP_DIRS': True,\n    'OPTIONS': {\n        'context_processors': [\n            'django.template.context_processors.request',\n            'django.contrib.messages.context_processors.messages',\n            'ocfweb.context_processors.ocf_template_processor',\n        ],\n        'string_if_invalid': InvalidReferenceInTemplate('%s'),\n    },\n}]\n\nWSGI_APPLICATION = 'ocfweb.wsgi.application'\n\nDATABASES = {}\n\n# store sessions in the cache\nSESSION_ENGINE = 'django.contrib.sessions.backends.cache'\n\n# XXX: DO NOT CHANGE\n# Ensure cookies can't be read by JavaScript.\nSESSION_COOKIE_HTTPONLY = True\nSESSION_COOKIE_SECURE = False\nSESSION_COOKIE_PATH = '/'\nSESSION_COOKIE_NAME = 'OCFWEB_SESSIONID'\n\nCACHES = {  # sessions are stored here\n    'default': {\n        # on dev, we use a file-backed cache so that you don't get logged out\n        # every time you update code and the server restarts.\n        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',\n        'LOCATION': os.path.expanduser('~/.ocfweb-cache'),\n    },\n    'TIMEOUT': 60 * 60 * 12,  # 12 hours\n    'OPTIONS': {\n        'MAX_ENTRIES': 1000,\n    },\n}\n\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'America/Los_Angeles'\nUSE_I18N = False\nUSE_L10N = False\nUSE_TZ = True\n\nSTATIC_URL = '/static/'\nos.environ.setdefault('OCFWEB_STATIC_ROOT', '')\nSTATIC_ROOT = os.environ['OCFWEB_STATIC_ROOT']\n\nX_FRAME_OPTIONS = 'DENY'\n\n# log exceptions to stderr\nLOGGING = {\n    'version': 1,\n    'disable_existing_loggers': False,\n    'handlers': {\n        'console': {\n            'class': 'logging.StreamHandler',\n        },\n    },\n    'loggers': {\n        'django': {\n            'handlers': ['console'],\n            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),\n        },\n    },\n}\n\nCELERY_BROKER = 'redis://create'\nCELERY_BACKEND = 'redis://create'\n\nif getuser() == 'ocfweb':\n    # not running in development, override options from config file\n    conf = configparser.ConfigParser()\n    conf.read('/etc/ocfweb/ocfweb.conf')\n\n    SECRET_KEY = conf.get('django', 'secret')\n    DEBUG = conf.getboolean('django', 'debug')\n\n    STATIC_URL = conf.get('django', 'static_url')\n    STATIC_ROOT = conf.get('django', 'static_root')\n\n    CELERY_BROKER = conf.get('celery', 'broker')\n    CELERY_BACKEND = conf.get('celery', 'backend')\n\n    # on prod, we use Redis as a cache\n    CACHES['default'] = {\n        'BACKEND': 'django_redis.cache.RedisCache',\n        'LOCATION': 'redis://localhost:6379/0',\n        'OPTIONS': {\n            'CLIENT_CLASS': 'django_redis.client.DefaultClient',\n        }\n    }\n\n    SESSION_COOKIE_SECURE = True\n    SESSION_COOKIE_DOMAIN = 'www.ocf.berkeley.edu'\nelse:\n    # running in development\n\n    # try to read celery values used by approve\n    # (only works on supernova by staff members)\n    try:\n        conf = configparser.ConfigParser()\n        conf.read('/etc/ocf-create/ocf-create.conf')\n        CELERY_BROKER = conf.get('celery', 'broker')\n        CELERY_BACKEND = conf.get('celery', 'backend')\n    except configparser.NoSectionError:\n        pass\n", "path": "ocfweb/settings.py"}], "after_files": [{"content": "import configparser\nimport os\nfrom getpass import getuser\n\nfrom django.template.base import TemplateSyntaxError\n\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nSECRET_KEY = 'not_a_secret'\nDEBUG = True\n\nALLOWED_HOSTS = [\n    'www.ocf.berkeley.edu',\n    'dev.ocf.berkeley.edu',\n    'dev-www.ocf.berkeley.edu',\n    'ocfweb.ocf.berkeley.edu',\n]\n\nINSTALLED_APPS = (\n    'bootstrapform',\n    'django.contrib.humanize',\n    'django.contrib.messages',\n    'django.contrib.sessions',\n    'django.contrib.staticfiles',\n    'mathfilters',\n    'ocfweb',\n    'ocfweb.about',\n    'ocfweb.account',\n    'ocfweb.docs',\n    'ocfweb.login',\n    'ocfweb.main',\n    'ocfweb.middleware',\n    'ocfweb.stats',\n    'ocfweb.test',\n)\n\nMIDDLEWARE_CLASSES = (\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.middleware.csrf.CsrfViewMiddleware',\n    'django.contrib.messages.middleware.MessageMiddleware',\n    'django.middleware.clickjacking.XFrameOptionsMiddleware',\n    'ocfweb.middleware.errors.OcflibErrorMiddleware',\n)\n\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\nROOT_URLCONF = 'ocfweb.urls'\n\n\nclass InvalidReferenceInTemplate(str):\n    \"\"\"Raise exceptions on invalid references in templates.\n\n    By default Django just replaces references to undefined variables with\n    empty strings. This is a horrible idea, so we instead hack it to raise an\n    exception.\n    \"\"\"\n\n    def __mod__(self, ref):\n        raise TemplateSyntaxError('Invalid reference in template: {}'.format(ref))\n\n\nTEMPLATES = [{\n    'BACKEND': 'django.template.backends.django.DjangoTemplates',\n    'DIRS': [],\n    'APP_DIRS': True,\n    'OPTIONS': {\n        'context_processors': [\n            'django.template.context_processors.request',\n            'django.contrib.messages.context_processors.messages',\n            'ocfweb.context_processors.ocf_template_processor',\n        ],\n        'string_if_invalid': InvalidReferenceInTemplate('%s'),\n    },\n}]\n\nWSGI_APPLICATION = 'ocfweb.wsgi.application'\n\nDATABASES = {}\n\n# store sessions in the cache\nSESSION_ENGINE = 'django.contrib.sessions.backends.cache'\n\n# XXX: DO NOT CHANGE\n# Ensure cookies can't be read by JavaScript or users.\n# Our proxy filters cookies starting with \"OCFWEB_\" when going to user sites,\n# so it's important our cookies match this pattern.\nCSRF_COOKIE_HTTPONLY = True\nCSRF_COOKIE_SECURE = False\nCSRF_COOKIE_PATH = '/'\nCSRF_COOKIE_NAME = 'OCFWEB_CSRF_TOKEN'\nSESSION_COOKIE_HTTPONLY = True\nSESSION_COOKIE_SECURE = False\nSESSION_COOKIE_PATH = '/'\nSESSION_COOKIE_NAME = 'OCFWEB_SESSIONID'\n\nCACHES = {  # sessions are stored here\n    'default': {\n        # on dev, we use a file-backed cache so that you don't get logged out\n        # every time you update code and the server restarts.\n        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',\n        'LOCATION': os.path.expanduser('~/.ocfweb-cache'),\n    },\n    'TIMEOUT': 60 * 60 * 12,  # 12 hours\n    'OPTIONS': {\n        'MAX_ENTRIES': 1000,\n    },\n}\n\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'America/Los_Angeles'\nUSE_I18N = False\nUSE_L10N = False\nUSE_TZ = True\n\nSTATIC_URL = '/static/'\nos.environ.setdefault('OCFWEB_STATIC_ROOT', '')\nSTATIC_ROOT = os.environ['OCFWEB_STATIC_ROOT']\n\nX_FRAME_OPTIONS = 'DENY'\n\n# log exceptions to stderr\nLOGGING = {\n    'version': 1,\n    'disable_existing_loggers': False,\n    'handlers': {\n        'console': {\n            'class': 'logging.StreamHandler',\n        },\n    },\n    'loggers': {\n        'django': {\n            'handlers': ['console'],\n            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),\n        },\n    },\n}\n\nCELERY_BROKER = 'redis://create'\nCELERY_BACKEND = 'redis://create'\n\nif getuser() == 'ocfweb':\n    # not running in development, override options from config file\n    conf = configparser.ConfigParser()\n    conf.read('/etc/ocfweb/ocfweb.conf')\n\n    SECRET_KEY = conf.get('django', 'secret')\n    DEBUG = conf.getboolean('django', 'debug')\n\n    STATIC_URL = conf.get('django', 'static_url')\n    STATIC_ROOT = conf.get('django', 'static_root')\n\n    CELERY_BROKER = conf.get('celery', 'broker')\n    CELERY_BACKEND = conf.get('celery', 'backend')\n\n    # on prod, we use Redis as a cache\n    CACHES['default'] = {\n        'BACKEND': 'django_redis.cache.RedisCache',\n        'LOCATION': 'redis://localhost:6379/0',\n        'OPTIONS': {\n            'CLIENT_CLASS': 'django_redis.client.DefaultClient',\n        }\n    }\n\n    CSRF_COOKIE_SECURE = True\n    CSRF_COOKIE_DOMAIN = 'www.ocf.berkeley.edu'\n    CSRF_TRUSTED_ORIGINS = ['www.ocf.berkeley.edu']\n    SESSION_COOKIE_SECURE = True\n    SESSION_COOKIE_DOMAIN = 'www.ocf.berkeley.edu'\nelse:\n    # running in development\n\n    # try to read celery values used by approve\n    # (only works on supernova by staff members)\n    try:\n        conf = configparser.ConfigParser()\n        conf.read('/etc/ocf-create/ocf-create.conf')\n        CELERY_BROKER = conf.get('celery', 'broker')\n        CELERY_BACKEND = conf.get('celery', 'backend')\n    except configparser.NoSectionError:\n        pass\n", "path": "ocfweb/settings.py"}]}