feathermost/etc/mitm_cors.py

39 lines
1.5 KiB
Python
Raw Normal View History

# 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
# 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]
2022-06-08 17:27:50 +02:00
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
2022-06-08 17:27:50 +02:00
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":
2022-06-08 17:27:56 +02:00
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,
2022-06-18 22:08:52 +02:00
"Access-Control-Max-Age": "86400",
"Cache-Control": "public, max-age=86400",
"Vary": "origin",
})