70 lines
2.0 KiB
Python
70 lines
2.0 KiB
Python
import logging
|
|
import os
|
|
|
|
import requests
|
|
from flask import Flask, Response, request
|
|
|
|
app = Flask(__name__)
|
|
|
|
logging.basicConfig(
|
|
level=os.environ.get("LOG_LEVEL", "INFO"),
|
|
format="%(asctime)s %(levelname)s %(message)s",
|
|
)
|
|
logger = logging.getLogger("mtls-bridge")
|
|
|
|
# Config via env
|
|
TARGET_URL = os.environ.get("TARGET_URL")
|
|
CLIENT_CERT = os.environ.get("CLIENT_CERT", "/certs/client.crt")
|
|
CLIENT_KEY = os.environ.get("CLIENT_KEY", "/certs/client.key")
|
|
CA_CERT = os.environ.get("CA_CERT", "/certs/ca.crt")
|
|
TIMEOUT = int(os.environ.get("TIMEOUT", "5"))
|
|
|
|
|
|
@app.route("/health", methods=["GET"])
|
|
def health():
|
|
return "OK", 200
|
|
|
|
|
|
@app.route("/", defaults={"path": ""}, methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
|
|
@app.route("/<path:path>", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
|
|
def proxy(path):
|
|
logger.info("request method=%s path=/%s", request.method, path)
|
|
|
|
if not TARGET_URL:
|
|
return Response("TARGET_URL is not set", status=500)
|
|
|
|
try:
|
|
url = f"{TARGET_URL.rstrip('/')}/{path}".rstrip("/")
|
|
headers = {k: v for k, v in request.headers if k.lower() != "host"}
|
|
headers["X-Forwarded-By"] = "mtls-bridge"
|
|
|
|
resp = requests.request(
|
|
method=request.method,
|
|
url=url,
|
|
headers=headers,
|
|
data=request.get_data(),
|
|
cookies=request.cookies,
|
|
cert=(CLIENT_CERT, CLIENT_KEY),
|
|
verify=CA_CERT,
|
|
timeout=TIMEOUT,
|
|
)
|
|
|
|
logger.info("upstream status=%s url=%s", resp.status_code, url)
|
|
|
|
excluded_headers = ["content-encoding", "content-length", "transfer-encoding", "connection"]
|
|
response_headers = [
|
|
(k, v)
|
|
for k, v in resp.raw.headers.items()
|
|
if k.lower() not in excluded_headers
|
|
]
|
|
|
|
return Response(resp.content, resp.status_code, response_headers)
|
|
|
|
except Exception as e:
|
|
logger.exception("proxy request failed")
|
|
return Response(str(e), status=500)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
app.run(host="0.0.0.0", port=8080)
|