feathermost/etc/mitm_cors.py

36 lines
1.4 KiB
Python

# Script for mitmproxy, used in ../rundev.sh. Not meant to be run directly.
from mitmproxy import http, ctx, flow
# More information about CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
ALLOWED_ORIGINS = ["http://localhost:8000"]
ALLOW_HEADERS = "Authorization, *" # Which headers the browser may send
EXPOSE_HEADERS = "Authorization, *" # Which headers the browser may expose to scripts
DEFAULT_PORTS = {"http": 80, "https": 443}
def allowed_origin(origin):
return origin if origin in ALLOWED_ORIGINS else ALLOWED_ORIGINS[0]
def response(flow: flow.Flow):
flow.response.headers["Access-Control-Allow-Origin"] = allowed_origin(flow.request.headers["Origin"])
flow.response.headers["Access-Control-Expose-Headers"] = EXPOSE_HEADERS
def request(flow: flow.Flow):
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}";
# Hijack CORS OPTIONS request
if flow.request.method == "OPTIONS":
flow.response = http.Response.make(200, b"", {
"Access-Control-Allow-Origin": allowed_origin(original_origin),
"Access-Control-Allow-Methods": "GET,POST",
"Access-Control-Allow-Headers": ALLOW_HEADERS,
"Access-Control-Max-Age": "10"
})