We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Failed ACH transfers aren't reflected in user balance
When payday initiates an ACH transfer for a user's balance, that user's balance is immediately reduced by the amount of the transfer. The problem come on the rare occasions where the ACH fails. The only notification we get (that I know about) is an email from Balanced about ACH failures. We need to restore funds to the user's account when the transfer did not, in fact, occur.

Failed ACH transfers aren't reflected in user balance
When payday initiates an ACH transfer for a user's balance, that user's balance is immediately reduced by the amount of the transfer. The problem come on the rare occasions where the ACH fails. The only notification we get (that I know about) is an email from Balanced about ACH failures. We need to restore funds to the user's account when the transfer did not, in fact, occur.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `gittip/security/csrf.py`
Content:
```
1 """Cross Site Request Forgery middleware, borrowed from Django.
2 
3 See also:
4 
5     https://github.com/django/django/blob/master/django/middleware/csrf.py
6     https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
7     https://github.com/gittip/www.gittip.com/issues/88
8 
9 """
10 
11 from datetime import timedelta
12 import re
13 import urlparse
14 from aspen import log_dammit
15 
16 
17 #from django.utils.cache import patch_vary_headers
18 cc_delim_re = re.compile(r'\s*,\s*')
19 def patch_vary_headers(response, newheaders):
20     """
21     Adds (or updates) the "Vary" header in the given HttpResponse object.
22     newheaders is a list of header names that should be in "Vary". Existing
23     headers in "Vary" aren't removed.
24     """
25     # Note that we need to keep the original order intact, because cache
26     # implementations may rely on the order of the Vary contents in, say,
27     # computing an MD5 hash.
28     if 'Vary' in response.headers:
29         vary_headers = cc_delim_re.split(response.headers['Vary'])
30     else:
31         vary_headers = []
32     # Use .lower() here so we treat headers as case-insensitive.
33     existing_headers = set([header.lower() for header in vary_headers])
34     additional_headers = [newheader for newheader in newheaders
35                           if newheader.lower() not in existing_headers]
36     response.headers['Vary'] = ', '.join(vary_headers + additional_headers)
37 
38 
39 #from django.utils.http import same_origin
40 def same_origin(url1, url2):
41     """
42     Checks if two URLs are 'same-origin'
43     """
44     p1, p2 = urlparse.urlparse(url1), urlparse.urlparse(url2)
45     return (p1.scheme, p1.hostname, p1.port) == (p2.scheme, p2.hostname, p2.port)
46 
47 
48 from aspen import Response
49 from crypto import constant_time_compare, get_random_string
50 
51 REASON_NO_REFERER = "Referer checking failed - no Referer."
52 REASON_BAD_REFERER = "Referer checking failed - %s does not match %s."
53 REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
54 REASON_BAD_TOKEN = "CSRF token missing or incorrect."
55 
56 TOKEN_LENGTH = 32
57 CSRF_TIMEOUT = timedelta(days=7)
58 
59 
60 def _get_new_csrf_key():
61     return get_random_string(TOKEN_LENGTH)
62 
63 
64 def _sanitize_token(token):
65     # Allow only alphanum, and ensure we return a 'str' for the sake
66     # of the post processing middleware.
67     if len(token) > TOKEN_LENGTH:
68         return _get_new_csrf_key()
69     token = re.sub('[^a-zA-Z0-9]+', '', str(token.decode('ascii', 'ignore')))
70     if token == "":
71         # In case the cookie has been truncated to nothing at some point.
72         return _get_new_csrf_key()
73     return token
74 
75 def _is_secure(request):
76     import gittip
77     return gittip.canonical_scheme == 'https'
78 
79 def _get_host(request):
80     """Returns the HTTP host using the request headers.
81     """
82     return request.headers.get('X-Forwarded-Host', request.headers['Host'])
83 
84 
85 
86 def inbound(request):
87     """Given a Request object, reject it if it's a forgery.
88     """
89     if request.line.uri.startswith('/assets/'): return
90 
91     try:
92         csrf_token = request.headers.cookie.get('csrf_token')
93         csrf_token = '' if csrf_token is None else csrf_token.value
94         csrf_token = _sanitize_token(csrf_token)
95     except KeyError:
96         csrf_token = _get_new_csrf_key()
97 
98     request.context['csrf_token'] = csrf_token
99 
100     # Assume that anything not defined as 'safe' by RC2616 needs protection
101     if request.line.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
102 
103         if _is_secure(request):
104             # Suppose user visits http://example.com/
105             # An active network attacker (man-in-the-middle, MITM) sends a
106             # POST form that targets https://example.com/detonate-bomb/ and
107             # submits it via JavaScript.
108             #
109             # The attacker will need to provide a CSRF cookie and token, but
110             # that's no problem for a MITM and the session-independent
111             # nonce we're using. So the MITM can circumvent the CSRF
112             # protection. This is true for any HTTP connection, but anyone
113             # using HTTPS expects better! For this reason, for
114             # https://example.com/ we need additional protection that treats
115             # http://example.com/ as completely untrusted. Under HTTPS,
116             # Barth et al. found that the Referer header is missing for
117             # same-domain requests in only about 0.2% of cases or less, so
118             # we can use strict Referer checking.
119             referer = request.headers.get('Referer')
120             if referer is None:
121                 raise Response(403, REASON_NO_REFERER)
122 
123             good_referer = 'https://%s/' % _get_host(request)
124             if not same_origin(referer, good_referer):
125                 reason = REASON_BAD_REFERER % (referer, good_referer)
126                 log_dammit(reason)
127                 raise Response(403, reason)
128 
129         if csrf_token is None:
130             raise Response(403, REASON_NO_CSRF_COOKIE)
131 
132         # Check non-cookie token for match.
133         request_csrf_token = ""
134         if request.line.method == "POST":
135             request_csrf_token = request.body.get('csrf_token', '')
136 
137         if request_csrf_token == "":
138             # Fall back to X-CSRF-TOKEN, to make things easier for AJAX,
139             # and possible for PUT/DELETE.
140             request_csrf_token = request.headers.get('X-CSRF-TOKEN', '')
141 
142         if not constant_time_compare(request_csrf_token, csrf_token):
143             raise Response(403, REASON_BAD_TOKEN)
144 
145 
146 def outbound(request, response):
147     """Store the latest CSRF token as a cookie.
148     """
149     csrf_token = request.context.get('csrf_token')
150     if csrf_token:
151         response.set_cookie('csrf_token', csrf_token, expires=CSRF_TIMEOUT, httponly=False)
152 
153         # Content varies with the CSRF cookie, so set the Vary header.
154         patch_vary_headers(response, ('Cookie',))
155
```
--- 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()

```

diff --git a/gittip/security/csrf.py b/gittip/security/csrf.py
--- a/gittip/security/csrf.py
+++ b/gittip/security/csrf.py
@@ -87,15 +87,14 @@
     """Given a Request object, reject it if it's a forgery.
     """
     if request.line.uri.startswith('/assets/'): return
+    if request.line.uri.startswith('/callbacks/'): return
 
     try:
-        csrf_token = request.headers.cookie.get('csrf_token')
-        csrf_token = '' if csrf_token is None else csrf_token.value
-        csrf_token = _sanitize_token(csrf_token)
+        csrf_token = _sanitize_token(request.headers.cookie['csrf_token'].value)
     except KeyError:
-        csrf_token = _get_new_csrf_key()
+        csrf_token = None
 
-    request.context['csrf_token'] = csrf_token
+    request.context['csrf_token'] = csrf_token or _get_new_csrf_key()
 
     # Assume that anything not defined as 'safe' by RC2616 needs protection
     if request.line.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):

{"golden_diff": "diff --git a/gittip/security/csrf.py b/gittip/security/csrf.py\n--- a/gittip/security/csrf.py\n+++ b/gittip/security/csrf.py\n@@ -87,15 +87,14 @@\n     \"\"\"Given a Request object, reject it if it's a forgery.\n     \"\"\"\n     if request.line.uri.startswith('/assets/'): return\n+    if request.line.uri.startswith('/callbacks/'): return\n \n     try:\n-        csrf_token = request.headers.cookie.get('csrf_token')\n-        csrf_token = '' if csrf_token is None else csrf_token.value\n-        csrf_token = _sanitize_token(csrf_token)\n+        csrf_token = _sanitize_token(request.headers.cookie['csrf_token'].value)\n     except KeyError:\n-        csrf_token = _get_new_csrf_key()\n+        csrf_token = None\n \n-    request.context['csrf_token'] = csrf_token\n+    request.context['csrf_token'] = csrf_token or _get_new_csrf_key()\n \n     # Assume that anything not defined as 'safe' by RC2616 needs protection\n     if request.line.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):\n", "issue": "Failed ACH transfers aren't reflected in user balance\nWhen payday initiates an ACH transfer for a user's balance, that user's balance is immediately reduced by the amount of the transfer. The problem come on the rare occasions where the ACH fails. The only notification we get (that I know about) is an email from Balanced about ACH failures. We need to restore funds to the user's account when the transfer did not, in fact, occur.\n\nFailed ACH transfers aren't reflected in user balance\nWhen payday initiates an ACH transfer for a user's balance, that user's balance is immediately reduced by the amount of the transfer. The problem come on the rare occasions where the ACH fails. The only notification we get (that I know about) is an email from Balanced about ACH failures. We need to restore funds to the user's account when the transfer did not, in fact, occur.\n\n", "before_files": [{"content": "\"\"\"Cross Site Request Forgery middleware, borrowed from Django.\n\nSee also:\n\n    https://github.com/django/django/blob/master/django/middleware/csrf.py\n    https://docs.djangoproject.com/en/dev/ref/contrib/csrf/\n    https://github.com/gittip/www.gittip.com/issues/88\n\n\"\"\"\n\nfrom datetime import timedelta\nimport re\nimport urlparse\nfrom aspen import log_dammit\n\n\n#from django.utils.cache import patch_vary_headers\ncc_delim_re = re.compile(r'\\s*,\\s*')\ndef patch_vary_headers(response, newheaders):\n    \"\"\"\n    Adds (or updates) the \"Vary\" header in the given HttpResponse object.\n    newheaders is a list of header names that should be in \"Vary\". Existing\n    headers in \"Vary\" aren't removed.\n    \"\"\"\n    # Note that we need to keep the original order intact, because cache\n    # implementations may rely on the order of the Vary contents in, say,\n    # computing an MD5 hash.\n    if 'Vary' in response.headers:\n        vary_headers = cc_delim_re.split(response.headers['Vary'])\n    else:\n        vary_headers = []\n    # Use .lower() here so we treat headers as case-insensitive.\n    existing_headers = set([header.lower() for header in vary_headers])\n    additional_headers = [newheader for newheader in newheaders\n                          if newheader.lower() not in existing_headers]\n    response.headers['Vary'] = ', '.join(vary_headers + additional_headers)\n\n\n#from django.utils.http import same_origin\ndef same_origin(url1, url2):\n    \"\"\"\n    Checks if two URLs are 'same-origin'\n    \"\"\"\n    p1, p2 = urlparse.urlparse(url1), urlparse.urlparse(url2)\n    return (p1.scheme, p1.hostname, p1.port) == (p2.scheme, p2.hostname, p2.port)\n\n\nfrom aspen import Response\nfrom crypto import constant_time_compare, get_random_string\n\nREASON_NO_REFERER = \"Referer checking failed - no Referer.\"\nREASON_BAD_REFERER = \"Referer checking failed - %s does not match %s.\"\nREASON_NO_CSRF_COOKIE = \"CSRF cookie not set.\"\nREASON_BAD_TOKEN = \"CSRF token missing or incorrect.\"\n\nTOKEN_LENGTH = 32\nCSRF_TIMEOUT = timedelta(days=7)\n\n\ndef _get_new_csrf_key():\n    return get_random_string(TOKEN_LENGTH)\n\n\ndef _sanitize_token(token):\n    # Allow only alphanum, and ensure we return a 'str' for the sake\n    # of the post processing middleware.\n    if len(token) > TOKEN_LENGTH:\n        return _get_new_csrf_key()\n    token = re.sub('[^a-zA-Z0-9]+', '', str(token.decode('ascii', 'ignore')))\n    if token == \"\":\n        # In case the cookie has been truncated to nothing at some point.\n        return _get_new_csrf_key()\n    return token\n\ndef _is_secure(request):\n    import gittip\n    return gittip.canonical_scheme == 'https'\n\ndef _get_host(request):\n    \"\"\"Returns the HTTP host using the request headers.\n    \"\"\"\n    return request.headers.get('X-Forwarded-Host', request.headers['Host'])\n\n\n\ndef inbound(request):\n    \"\"\"Given a Request object, reject it if it's a forgery.\n    \"\"\"\n    if request.line.uri.startswith('/assets/'): return\n\n    try:\n        csrf_token = request.headers.cookie.get('csrf_token')\n        csrf_token = '' if csrf_token is None else csrf_token.value\n        csrf_token = _sanitize_token(csrf_token)\n    except KeyError:\n        csrf_token = _get_new_csrf_key()\n\n    request.context['csrf_token'] = csrf_token\n\n    # Assume that anything not defined as 'safe' by RC2616 needs protection\n    if request.line.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):\n\n        if _is_secure(request):\n            # Suppose user visits http://example.com/\n            # An active network attacker (man-in-the-middle, MITM) sends a\n            # POST form that targets https://example.com/detonate-bomb/ and\n            # submits it via JavaScript.\n            #\n            # The attacker will need to provide a CSRF cookie and token, but\n            # that's no problem for a MITM and the session-independent\n            # nonce we're using. So the MITM can circumvent the CSRF\n            # protection. This is true for any HTTP connection, but anyone\n            # using HTTPS expects better! For this reason, for\n            # https://example.com/ we need additional protection that treats\n            # http://example.com/ as completely untrusted. Under HTTPS,\n            # Barth et al. found that the Referer header is missing for\n            # same-domain requests in only about 0.2% of cases or less, so\n            # we can use strict Referer checking.\n            referer = request.headers.get('Referer')\n            if referer is None:\n                raise Response(403, REASON_NO_REFERER)\n\n            good_referer = 'https://%s/' % _get_host(request)\n            if not same_origin(referer, good_referer):\n                reason = REASON_BAD_REFERER % (referer, good_referer)\n                log_dammit(reason)\n                raise Response(403, reason)\n\n        if csrf_token is None:\n            raise Response(403, REASON_NO_CSRF_COOKIE)\n\n        # Check non-cookie token for match.\n        request_csrf_token = \"\"\n        if request.line.method == \"POST\":\n            request_csrf_token = request.body.get('csrf_token', '')\n\n        if request_csrf_token == \"\":\n            # Fall back to X-CSRF-TOKEN, to make things easier for AJAX,\n            # and possible for PUT/DELETE.\n            request_csrf_token = request.headers.get('X-CSRF-TOKEN', '')\n\n        if not constant_time_compare(request_csrf_token, csrf_token):\n            raise Response(403, REASON_BAD_TOKEN)\n\n\ndef outbound(request, response):\n    \"\"\"Store the latest CSRF token as a cookie.\n    \"\"\"\n    csrf_token = request.context.get('csrf_token')\n    if csrf_token:\n        response.set_cookie('csrf_token', csrf_token, expires=CSRF_TIMEOUT, httponly=False)\n\n        # Content varies with the CSRF cookie, so set the Vary header.\n        patch_vary_headers(response, ('Cookie',))\n", "path": "gittip/security/csrf.py"}], "after_files": [{"content": "\"\"\"Cross Site Request Forgery middleware, borrowed from Django.\n\nSee also:\n\n    https://github.com/django/django/blob/master/django/middleware/csrf.py\n    https://docs.djangoproject.com/en/dev/ref/contrib/csrf/\n    https://github.com/gittip/www.gittip.com/issues/88\n\n\"\"\"\n\nfrom datetime import timedelta\nimport re\nimport urlparse\nfrom aspen import log_dammit\n\n\n#from django.utils.cache import patch_vary_headers\ncc_delim_re = re.compile(r'\\s*,\\s*')\ndef patch_vary_headers(response, newheaders):\n    \"\"\"\n    Adds (or updates) the \"Vary\" header in the given HttpResponse object.\n    newheaders is a list of header names that should be in \"Vary\". Existing\n    headers in \"Vary\" aren't removed.\n    \"\"\"\n    # Note that we need to keep the original order intact, because cache\n    # implementations may rely on the order of the Vary contents in, say,\n    # computing an MD5 hash.\n    if 'Vary' in response.headers:\n        vary_headers = cc_delim_re.split(response.headers['Vary'])\n    else:\n        vary_headers = []\n    # Use .lower() here so we treat headers as case-insensitive.\n    existing_headers = set([header.lower() for header in vary_headers])\n    additional_headers = [newheader for newheader in newheaders\n                          if newheader.lower() not in existing_headers]\n    response.headers['Vary'] = ', '.join(vary_headers + additional_headers)\n\n\n#from django.utils.http import same_origin\ndef same_origin(url1, url2):\n    \"\"\"\n    Checks if two URLs are 'same-origin'\n    \"\"\"\n    p1, p2 = urlparse.urlparse(url1), urlparse.urlparse(url2)\n    return (p1.scheme, p1.hostname, p1.port) == (p2.scheme, p2.hostname, p2.port)\n\n\nfrom aspen import Response\nfrom crypto import constant_time_compare, get_random_string\n\nREASON_NO_REFERER = \"Referer checking failed - no Referer.\"\nREASON_BAD_REFERER = \"Referer checking failed - %s does not match %s.\"\nREASON_NO_CSRF_COOKIE = \"CSRF cookie not set.\"\nREASON_BAD_TOKEN = \"CSRF token missing or incorrect.\"\n\nTOKEN_LENGTH = 32\nCSRF_TIMEOUT = timedelta(days=7)\n\n\ndef _get_new_csrf_key():\n    return get_random_string(TOKEN_LENGTH)\n\n\ndef _sanitize_token(token):\n    # Allow only alphanum, and ensure we return a 'str' for the sake\n    # of the post processing middleware.\n    if len(token) > TOKEN_LENGTH:\n        return _get_new_csrf_key()\n    token = re.sub('[^a-zA-Z0-9]+', '', str(token.decode('ascii', 'ignore')))\n    if token == \"\":\n        # In case the cookie has been truncated to nothing at some point.\n        return _get_new_csrf_key()\n    return token\n\ndef _is_secure(request):\n    import gittip\n    return gittip.canonical_scheme == 'https'\n\ndef _get_host(request):\n    \"\"\"Returns the HTTP host using the request headers.\n    \"\"\"\n    return request.headers.get('X-Forwarded-Host', request.headers['Host'])\n\n\n\ndef inbound(request):\n    \"\"\"Given a Request object, reject it if it's a forgery.\n    \"\"\"\n    if request.line.uri.startswith('/assets/'): return\n    if request.line.uri.startswith('/callbacks/'): return\n\n    try:\n        csrf_token = _sanitize_token(request.headers.cookie['csrf_token'].value)\n    except KeyError:\n        csrf_token = None\n\n    request.context['csrf_token'] = csrf_token or _get_new_csrf_key()\n\n    # Assume that anything not defined as 'safe' by RC2616 needs protection\n    if request.line.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):\n\n        if _is_secure(request):\n            # Suppose user visits http://example.com/\n            # An active network attacker (man-in-the-middle, MITM) sends a\n            # POST form that targets https://example.com/detonate-bomb/ and\n            # submits it via JavaScript.\n            #\n            # The attacker will need to provide a CSRF cookie and token, but\n            # that's no problem for a MITM and the session-independent\n            # nonce we're using. So the MITM can circumvent the CSRF\n            # protection. This is true for any HTTP connection, but anyone\n            # using HTTPS expects better! For this reason, for\n            # https://example.com/ we need additional protection that treats\n            # http://example.com/ as completely untrusted. Under HTTPS,\n            # Barth et al. found that the Referer header is missing for\n            # same-domain requests in only about 0.2% of cases or less, so\n            # we can use strict Referer checking.\n            referer = request.headers.get('Referer')\n            if referer is None:\n                raise Response(403, REASON_NO_REFERER)\n\n            good_referer = 'https://%s/' % _get_host(request)\n            if not same_origin(referer, good_referer):\n                reason = REASON_BAD_REFERER % (referer, good_referer)\n                log_dammit(reason)\n                raise Response(403, reason)\n\n        if csrf_token is None:\n            raise Response(403, REASON_NO_CSRF_COOKIE)\n\n        # Check non-cookie token for match.\n        request_csrf_token = \"\"\n        if request.line.method == \"POST\":\n            request_csrf_token = request.body.get('csrf_token', '')\n\n        if request_csrf_token == \"\":\n            # Fall back to X-CSRF-TOKEN, to make things easier for AJAX,\n            # and possible for PUT/DELETE.\n            request_csrf_token = request.headers.get('X-CSRF-TOKEN', '')\n\n        if not constant_time_compare(request_csrf_token, csrf_token):\n            raise Response(403, REASON_BAD_TOKEN)\n\n\ndef outbound(request, response):\n    \"\"\"Store the latest CSRF token as a cookie.\n    \"\"\"\n    csrf_token = request.context.get('csrf_token')\n    if csrf_token:\n        response.set_cookie('csrf_token', csrf_token, expires=CSRF_TIMEOUT, httponly=False)\n\n        # Content varies with the CSRF cookie, so set the Vary header.\n        patch_vary_headers(response, ('Cookie',))\n", "path": "gittip/security/csrf.py"}]}