diff --git a/src/palace/manager/service/logging/log.py b/src/palace/manager/service/logging/log.py index f6be104d9..828d12ecd 100644 --- a/src/palace/manager/service/logging/log.py +++ b/src/palace/manager/service/logging/log.py @@ -100,6 +100,16 @@ def ensure_str(s: Any) -> Any: if user_agent := flask_request.headers.get("User-Agent"): data["request"]["user_agent"] = user_agent + forwarded_for_list = [] + if forwarded_for := flask_request.headers.get("X-Forwarded-For"): + forwarded_for_list.extend( + [ip.strip() for ip in forwarded_for.split(",")] + ) + if remote_addr := flask_request.remote_addr: + forwarded_for_list.append(remote_addr) + if forwarded_for_list: + data["request"]["forwarded_for"] = forwarded_for_list + # If we are running in uwsgi context, we include the worker id in the log if uwsgi: data["uwsgi"] = {"worker": uwsgi.worker_id()} diff --git a/tests/manager/service/logging/test_log.py b/tests/manager/service/logging/test_log.py index 6a079755f..f4b433d29 100644 --- a/tests/manager/service/logging/test_log.py +++ b/tests/manager/service/logging/test_log.py @@ -182,10 +182,18 @@ def test_flask_request( assert request["method"] == "GET" assert "host" in request assert "query" not in request - assert "user-agent" not in request + assert "user_agent" not in request + assert "forwarded_for" not in request with flask_app_fixture.test_request_context( - "/test?query=string&foo=bar", method="POST", headers={"User-Agent": "UA"} + "/test?query=string&foo=bar", + method="POST", + headers=[ + ("User-Agent", "UA"), + ("X-Forwarded-For", "xyz, abc"), + ("X-Forwarded-For", "123"), + ], + environ_base={"REMOTE_ADDR": "456"}, ): data = json.loads(formatter.format(record)) assert "request" in data @@ -194,6 +202,7 @@ def test_flask_request( assert request["method"] == "POST" assert request["query"] == "query=string&foo=bar" assert request["user_agent"] == "UA" + assert request["forwarded_for"] == ["xyz", "abc", "123", "456"] # If flask is not installed, the request data is not included in the log. with patch("palace.manager.service.logging.log.flask_request", None):