2020-03-25 22:10:19 +01:00
|
|
|
# Script for mitmproxy, used in ../rundev.sh. Not meant to be run directly.
|
|
|
|
|
2022-06-08 17:27:50 +02:00
|
|
|
from mitmproxy import http, ctx, flow
|
2020-03-25 22:10:19 +01:00
|
|
|
|
|
|
|
# More information about CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
|
|
|
|
2020-03-31 13:27:08 +02:00
|
|
|
ALLOWED_ORIGINS = ["http://localhost:8000"]
|
2020-03-25 22:10:19 +01:00
|
|
|
ALLOW_HEADERS = "Authorization, *" # Which headers the browser may send
|
|
|
|
EXPOSE_HEADERS = "Authorization, *" # Which headers the browser may expose to scripts
|
|
|
|
|
2021-02-17 16:54:40 +01:00
|
|
|
DEFAULT_PORTS = {"http": 80, "https": 443}
|
|
|
|
|
2020-03-25 22:10:19 +01:00
|
|
|
|
2020-03-31 13:27:08 +02:00
|
|
|
def allowed_origin(origin):
|
|
|
|
return origin if origin in ALLOWED_ORIGINS else ALLOWED_ORIGINS[0]
|
|
|
|
|
2022-06-08 17:27:50 +02:00
|
|
|
def response(flow: flow.Flow):
|
2020-03-31 13:27:08 +02:00
|
|
|
flow.response.headers["Access-Control-Allow-Origin"] = allowed_origin(flow.request.headers["Origin"])
|
2020-03-25 22:10:19 +01:00
|
|
|
flow.response.headers["Access-Control-Expose-Headers"] = EXPOSE_HEADERS
|
|
|
|
|
2022-06-08 17:27:50 +02:00
|
|
|
def request(flow: flow.Flow):
|
2021-02-17 16:54:40 +01:00
|
|
|
original_origin = flow.request.headers["Origin"]
|
|
|
|
|
|
|
|
# Spoof Origin, necessary for Mattermost to accept creating a websocket
|
|
|
|
if original_origin in ALLOWED_ORIGINS:
|
|
|
|
port_appendix = f":{flow.request.port}" if flow.request.port != DEFAULT_PORTS.get(flow.request.scheme) else ""
|
|
|
|
flow.request.headers["Origin"] = f"{flow.request.scheme}://{flow.request.host}{port_appendix}";
|
|
|
|
|
2020-03-25 22:10:19 +01:00
|
|
|
# Hijack CORS OPTIONS request
|
|
|
|
if flow.request.method == "OPTIONS":
|
2022-06-08 17:27:56 +02:00
|
|
|
flow.response = http.Response.make(200, b"", {
|
2021-02-17 16:54:40 +01:00
|
|
|
"Access-Control-Allow-Origin": allowed_origin(original_origin),
|
2020-03-25 22:10:19 +01:00
|
|
|
"Access-Control-Allow-Methods": "GET,POST",
|
|
|
|
"Access-Control-Allow-Headers": ALLOW_HEADERS,
|
2022-06-18 22:08:52 +02:00
|
|
|
"Access-Control-Max-Age": "86400",
|
|
|
|
"Cache-Control": "public, max-age=86400",
|
|
|
|
"Vary": "origin",
|
2020-03-25 22:10:19 +01:00
|
|
|
})
|