Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ Functions that generate an HTTP service, such as `run_app`, accept a number of k
* `framework=py2http.config.BOTTLE` The HTTP framework to use.
* `input_mapper=py2http.default_configs.default_input_mapper` A function to map an HTTP request to a dict of input arguments.
* `output_mapper=py2http.default_configs.default_output_mapper` A function to map the output of a function to an HTTP response.
* `error_handler=py2http.default_configs.default_error_handler` A function to map an exception to an HTTP response.
* `error_handler=py2http.default_configs.default_error_handler` A function to map an exception to an HTTP response. An unexpected error (500) answers "Internal server error (error id …)" and logs the exception under that id; set `PY2HTTP_EXPOSE_ERRORS=1` to send the exception text instead (development only).
* `header_inputs={}` A dict of object properties in JSON schema format describing keys that should be excluded from request body definitions. These inputs are expected to be extracted from the request headers in the input mapper.
* `host='localhost'` The hostname the server can be reached at, to include in the OpenAPI specification.
* `port=3030` The TCP port to listen on.
Expand Down
5 changes: 5 additions & 0 deletions py2http/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,8 @@
#: Environment variable naming the challenge for a 401 a dispatched function raised
#: (``AuthorizationError``); the deployment's auth decides it. Default: Bearer.
WWW_AUTHENTICATE_ENV_VAR = "PY2HTTP_WWW_AUTHENTICATE"
#: Set (to anything non-empty) to send an unexpected error's text to the client in a
#: 500 body. Off by default: exception text can carry paths, connection strings or data.
EXPOSE_ERRORS_ENV_VAR = "PY2HTTP_EXPOSE_ERRORS"
#: Legacy switch that forces the generic 500 message (now the default); still honoured.
OPAQUE_ERRORS_ENV_VAR = "OPAQUE_ERRORS"
40 changes: 34 additions & 6 deletions py2http/default_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import json
import logging
import os
import uuid
from functools import wraps

from i2.errors import (
Expand All @@ -33,7 +34,9 @@
from py2http.config import AIOHTTP, BOTTLE, FLASK
from py2http.constants import (
BEARER_CHALLENGE,
EXPOSE_ERRORS_ENV_VAR,
JSON_CONTENT_TYPE,
OPAQUE_ERRORS_ENV_VAR,
WWW_AUTHENTICATE_ENV_VAR,
)

Expand Down Expand Up @@ -203,10 +206,35 @@ def error_status(error: Exception) -> int:
return 500



def server_error_message(error: Exception) -> str:
"""The text a client gets for an unexpected (500) error.

By default it is a generic message carrying an error id, and the exception is
logged server-side under that id, so the text of the exception (which can hold
file paths, connection strings or data) never reaches the client. Set
``PY2HTTP_EXPOSE_ERRORS`` to send ``str(error)`` instead (development);
``OPAQUE_ERRORS`` still forces the generic message.

>>> import os
>>> os.environ.pop("PY2HTTP_EXPOSE_ERRORS", None) and None
>>> server_error_message(KeyError("secret path")).startswith("Internal server error")
True
"""
if os.getenv(EXPOSE_ERRORS_ENV_VAR) and not os.getenv(OPAQUE_ERRORS_ENV_VAR):
return str(error)
error_id = uuid.uuid4().hex[:12]
logger.error(
"Internal server error %s: %s", error_id, error, exc_info=error
)
return f"Internal server error (error id {error_id})"

def aiohttp_error_handler(error: Exception):
status = error_status(error)
if status == 500:
_raise_http_client_error(web.HTTPInternalServerError, "Internal server error")
_raise_http_client_error(
web.HTTPInternalServerError, server_error_message(error)
)
reason = type(error).__name__ if status == 400 else None
_raise_http_client_error(
_AIOHTTP_ERRORS[status],
Expand All @@ -222,14 +250,14 @@ def bottle_error_handler(error: Exception):
response.status = f"400 {type(error).__name__}" if status == 400 else status
for header, value in _status_headers(status).items():
response.set_header(header, value)
if status == 500 and os.getenv("OPAQUE_ERRORS", None):
message = "Internal server error"
if status == 500:
message = server_error_message(error)
return {"error": message}


def flask_error_handler(error: Exception):
"""The ``(body, status, headers)`` a Flask view returns for an error, mapped like
the bottle handler (``OPAQUE_ERRORS`` hides the text of a 500)."""
the bottle handler (a 500 carries :func:`server_error_message`, not the exception text)."""
message = str(error)
status = error_status(error)
code = getattr(
Expand All @@ -242,8 +270,8 @@ def flask_error_handler(error: Exception):
and hasattr(error, "get_response")
):
status, message = code, getattr(error, "description", None) or message
if status == 500 and os.getenv("OPAQUE_ERRORS", None):
message = "Internal server error"
if status == 500:
message = server_error_message(error)
status_line = f"400 {type(error).__name__}" if status == 400 else status
headers = _status_headers(status)
if hasattr(error, "get_response") and status == code: # e.g. the ``Allow`` of a 405
Expand Down
30 changes: 25 additions & 5 deletions py2http/tests/test_error_statuses.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,28 @@ def test_bottle_400_reason_names_the_error():
assert got == "400 InputError"


def test_opaque_errors_hides_500_text(monkeypatch, capsys):
def test_500_text_hidden_by_default(monkeypatch, capsys, caplog):
monkeypatch.delenv("PY2HTTP_EXPOSE_ERRORS", raising=False)
_, body = call_wsgi(_app_raising(KeyError("internal detail")), "/fail", {})
assert "internal detail" not in body["error"]
assert body["error"].startswith("Internal server error (error id ")
error_id = body["error"].rsplit(" ", 1)[-1].rstrip(")")
# the operator can find the exception under the id the client was given
assert any(error_id in r.getMessage() and "internal detail" in r.getMessage() for r in caplog.records)


def test_expose_errors_sends_500_text(monkeypatch, capsys):
monkeypatch.setenv("PY2HTTP_EXPOSE_ERRORS", "1")
monkeypatch.delenv("OPAQUE_ERRORS", raising=False)
_, body = call_wsgi(_app_raising(KeyError("internal detail")), "/fail", {})
assert "internal detail" in body["error"]


def test_opaque_errors_wins_over_expose(monkeypatch, capsys):
monkeypatch.setenv("PY2HTTP_EXPOSE_ERRORS", "1")
monkeypatch.setenv("OPAQUE_ERRORS", "1")
_, body = call_wsgi(_app_raising(KeyError("internal detail")), "/fail", {})
assert body == {"error": "Internal server error"}
assert "internal detail" not in body["error"]


@pytest.mark.parametrize("error, status", CASES)
Expand Down Expand Up @@ -88,8 +106,8 @@ def fail():
assert response.headers["WWW-Authenticate"] == "Bearer"
else:
assert "WWW-Authenticate" not in response.headers
if status == 500:
assert "internal detail" in response.get_json()["error"]
if status == 500: # hidden by default (i2mint/py2http#35)
assert "internal detail" not in response.get_json()["error"]


def test_flask_opaque_errors_hides_500_text(monkeypatch):
Expand All @@ -101,7 +119,9 @@ def test_flask_opaque_errors_hides_500_text(monkeypatch):
app.add_url_rule(
"/f", "f", lambda: flask_error_handler(KeyError("internal detail"))
)
assert app.test_client().get("/f").get_json() == {"error": "Internal server error"}
assert app.test_client().get("/f").get_json()["error"].startswith(
"Internal server error"
)


@pytest.mark.parametrize("error, status", CASES)
Expand Down
Loading