Skip to content

Commit 68d4425

Browse files
authored
Copy CORS headers when substituting responses (re-do) (#185)
... otherwise the client won't be able to read the modified response.
1 parent 28e6eea commit 68d4425

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

tests/mitmproxy_addons/callback.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import aiohttp
44
import json
55

6+
import mitmproxy
67
from mitmproxy import ctx, flowfilter
78
from mitmproxy.http import Response
89
from controller import MITM_DOMAIN_NAME
@@ -98,7 +99,7 @@ async def response(self, flow):
9899
}
99100
await self.send_callback(flow, self.config["callback_response_url"], callback_body)
100101

101-
async def send_callback(self, flow, url: str, body: dict):
102+
async def send_callback(self, flow: mitmproxy.http.HTTPFlow, url: str, body: dict):
102103
try:
103104
# use asyncio so we don't block other unrelated requests from being processed
104105
async with aiohttp.request(
@@ -122,12 +123,19 @@ async def send_callback(self, flow, url: str, body: dict):
122123
respond_status_code = test_response_body.get("respond_status_code", body.get("response_code"))
123124
respond_body = test_response_body.get("respond_body", body.get("response_body"))
124125
print(f'{datetime.now().strftime("%H:%M:%S.%f")} callback for {flow.request.url} returning custom response: HTTP {respond_status_code} {json.dumps(respond_body)}')
126+
127+
response_headers = {
128+
"MITM-Proxy": "yes", # so we don't reprocess this
129+
"Content-Type": "application/json",
130+
}
131+
132+
# If we're handling a response callback, copy the CORS headers from the original response
133+
if flow.response is not None:
134+
response_headers.update({k: v for k, v in flow.response.headers.items() if k.startswith("Access-Control")})
135+
125136
flow.response = Response.make(
126-
respond_status_code, json.dumps(respond_body),
127-
headers={
128-
"MITM-Proxy": "yes", # so we don't reprocess this
129-
"Content-Type": "application/json",
130-
})
137+
respond_status_code, json.dumps(respond_body), headers=response_headers,
138+
)
131139
except Exception as error:
132140
print(f"ERR: callback for {flow.request.url} returned {error}")
133141
print(f"ERR: callback, provided request body was {body}")

0 commit comments

Comments
 (0)