Skip to content
Merged
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
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,28 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## Unreleased

### Fixed

- **A success response whose body is not JSON now raises `GlpiProtocolError`
instead of a bare `json.JSONDecodeError`.** A server or a proxy answering
200 with an HTML page or a garbled body used to surface a `ValueError`
that read like bad input. Every decode of a success body, on the v2
transport, the v1 session and the OAuth token manager, now goes through
one helper that raises the new `GlpiResponseBodyError` (a subclass of
`GlpiProtocolError`) with `status_code`, `url`, `content_type`,
`body_length` and a bounded `body_excerpt`, and chains the decode error as
`__cause__`. The body is kept out of the message. It is not retried: a
2xx means the request was processed. Empty answers on routes that accept
them (204, `DELETE`, v1 calls without a payload) are unchanged; an empty
200 on a route that must return JSON raises the same error. The lenient
helpers `response_json_or_empty` and `response_json_mapping` keep an
empty or whitespace-only body as empty but now raise the same error for a non-empty body that
is not JSON; the new error is a `ValueError` subclass like the one it
replaces, so existing `except ValueError` handlers still catch it.

### Added

- **`GlpiResponseBodyError`**, exported from the package root.
A new client setting turns the automatic retries off. Behaviour is unchanged
unless it is set.

Expand Down
4 changes: 4 additions & 0 deletions docs/api_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ guide for the full picture, including which methods raise which type.
:members:
:show-inheritance:

.. autoexception:: GlpiResponseBodyError
:members:
:show-inheritance:

.. autoexception:: GlpiContentError
:members:
:show-inheritance:
Expand Down
30 changes: 30 additions & 0 deletions docs/user_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1816,6 +1816,7 @@ The hierarchy lets you narrow as far as you need:
│ reaches you)
├── GlpiValidationError the client rejected your argument
├── GlpiProtocolError GLPI answered 2xx with an unusable body
│ └── GlpiResponseBodyError the 2xx body is not JSON
└── GlpiContentError a rich-text body could not be converted
between HTML and Markdown

Expand All @@ -1833,6 +1834,35 @@ usually want:
print(exc.url) # the absolute URL that was requested
print(exc.response_text) # the response body

A success status does not guarantee a usable body. When a server, or a
proxy in front of it, answers 2xx with an HTML page, a garbled body or
nothing at all on a route that must return a payload, the client raises
:class:`~glpi_python_client.GlpiResponseBodyError`, a
:class:`~glpi_python_client.GlpiProtocolError`, instead of a bare
``json.JSONDecodeError``. The request was sent and answered, so the failure
is the response, not your arguments:

.. code-block:: python

from glpi_python_client import GlpiResponseBodyError

try:
ticket = client.get_ticket(1)
except GlpiResponseBodyError as exc:
print(exc.status_code) # 200
print(exc.url) # the absolute URL that was requested
print(exc.content_type) # for example "text/html"
print(exc.body_length) # body size in bytes
print(exc.body_excerpt) # first 200 bytes (UTF-8, replacement), for diagnostics

The decode error is chained as ``__cause__``. The message names the status,
URL, content type and length but never the body, which may carry data. The
error is **not** retried: a 2xx means the request was processed, and
sending a write again could apply it twice. Routes that deliberately accept
an empty answer (a 204, a ``DELETE``, a v1 call with no payload) still
return normally; an empty 200 on a route that must return a payload raises
the same error with ``body_length == 0``.

.. note::

:class:`~glpi_python_client.GlpiStatusError`,
Expand Down
2 changes: 2 additions & 0 deletions glpi_python_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
GlpiError,
GlpiNotFoundError,
GlpiProtocolError,
GlpiResponseBodyError,
GlpiServerError,
GlpiStatusError,
GlpiTimeoutError,
Expand Down Expand Up @@ -202,6 +203,7 @@
"GlpiNotFoundError",
"GlpiPriority",
"GlpiProtocolError",
"GlpiResponseBodyError",
"GlpiServerError",
"GlpiSolutionStatus",
"GlpiStatusError",
Expand Down
6 changes: 4 additions & 2 deletions glpi_python_client/_async/auth/_v1_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
)
from glpi_python_client._async.clients.commons._config import build_http_session
from glpi_python_client._async.clients.commons._http import (
decode_json_body,
ensure_response_status,
finalize_request_response,
response_json_or_empty,
Expand Down Expand Up @@ -180,7 +181,8 @@ async def _init_session(self) -> None:
failure_message="GLPI v1 initSession failed",
)

token = response.json().get("session_token")
body = decode_json_body(response)
token = body.get("session_token") if isinstance(body, dict) else None
if not token:
raise GlpiProtocolError("GLPI v1 initSession returned no session_token")

Expand Down Expand Up @@ -481,7 +483,7 @@ async def upload_document(
success_statuses=(200, 201),
failure_message="GLPI v1 document upload failed",
)
payload = response.json()
payload = decode_json_body(response)
if not isinstance(payload, dict):
raise GlpiProtocolError(
"GLPI v1 document upload returned unexpected payload: "
Expand Down
22 changes: 19 additions & 3 deletions glpi_python_client/_async/auth/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import logging
from datetime import UTC, datetime, timedelta
from typing import cast

import httpx

Expand All @@ -18,7 +19,10 @@
validate_retry_settings,
)
from glpi_python_client._async.clients.commons._config import build_http_session
from glpi_python_client._async.clients.commons._http import transport_error_from
from glpi_python_client._async.clients.commons._http import (
decode_json_body,
transport_error_from,
)
from glpi_python_client._errors import (
GlpiServerError,
GlpiTransportError,
Expand Down Expand Up @@ -233,6 +237,18 @@ def _build_token_request_data(self) -> dict[str, str]:

return data

def _decode_token_body(self, response: httpx.Response) -> dict[str, object]:
"""Decode a successful token response, raising a library error if not JSON.

Raises
------
GlpiResponseBodyError
When the 2xx body is not JSON. Not retried: the endpoint answered.
"""

payload = decode_json_body(response, url=self._token_url)
return cast(dict[str, object], payload)

def _store_token_data(
self, token_data: dict[str, object], label: str = "acquired"
) -> None:
Expand Down Expand Up @@ -323,7 +339,7 @@ async def _acquire_token(self) -> None:
data = self._build_token_request_data()
response = await self._post_token_request(data)
if 200 <= response.status_code < 300:
self._store_token_data(response.json())
self._store_token_data(self._decode_token_body(response))
return
try:
error_detail = response.json()
Expand Down Expand Up @@ -388,7 +404,7 @@ async def _refresh_access_token(self) -> None:
data["client_secret"] = self._client_secret
response = await self._post_token_request(data)
if 200 <= response.status_code < 300:
self._store_token_data(response.json(), label="refreshed")
self._store_token_data(self._decode_token_body(response), label="refreshed")
return
logger.warning("Token refresh failed, acquiring new token...")
await self._acquire_token()
Expand Down
54 changes: 54 additions & 0 deletions glpi_python_client/_async/auth/tests/test_auth.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import json
from datetime import UTC, datetime, timedelta
from typing import cast

Expand All @@ -8,6 +9,7 @@

from glpi_python_client import (
GlpiAuthError,
GlpiResponseBodyError,
GlpiServerError,
GlpiTransportError,
GlpiValidationError,
Expand Down Expand Up @@ -410,3 +412,55 @@ async def post(
await manager.ensure_token()

assert len(session.calls) == 3


@pytest.mark.parametrize("refresh", [False, True])
@pytest.mark.parametrize(
("content", "content_type"),
[
(b"<html><body>Gateway page</body></html>", "text/html"),
(b"\xff\xfe\x00garbled", "application/json"),
],
)
async def test_token_success_body_that_is_not_json_raises_protocol_error_once(
refresh: bool, content: bytes, content_type: str
) -> None:
"""A non-JSON 200 from the token endpoint is a protocol error, not retried.

On the refresh path it is not swallowed into a silent re-acquire either:
the endpoint answered, and the answer is what failed.
"""

url = "https://glpi.example.test/api.php/token"
session = _FakeSession(
response=cast(
FakeResponse,
httpx.Response(
200,
content=content,
headers={"content-type": content_type},
request=httpx.Request("POST", url),
),
)
)
manager = GLPITokenManager(
token_url=url,
client_id="client-id",
client_secret="client-secret",
session=cast(httpx.AsyncClient, session),
)
if refresh:
manager.access_token = "old"
manager.refresh_token = "refresh"
with pytest.raises(GlpiResponseBodyError) as excinfo:
if refresh:
await manager._refresh_access_token()
else:
await manager.ensure_token()

error = excinfo.value
assert isinstance(error.__cause__, (json.JSONDecodeError, UnicodeDecodeError))
assert (error.status_code, error.content_type) == (200, content_type)
assert error.body_length == len(content)
assert error.url == url
assert len(session.calls) == 1
52 changes: 52 additions & 0 deletions glpi_python_client/_async/auth/tests/test_v1_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from glpi_python_client import (
GlpiProtocolError,
GlpiResponseBodyError,
GlpiServerError,
GlpiTransportError,
GlpiValidationError,
Expand Down Expand Up @@ -545,3 +546,54 @@ async def test_session_token_invalid_marker_triggers_renew() -> None:

result = await session.upload_document("a.txt", b"x", "text/plain")
assert result == {"id": 2}


def _non_json(content: bytes, content_type: str) -> httpx.Response:
return httpx.Response(
200,
content=content,
headers={"content-type": content_type},
request=httpx.Request("GET", "https://glpi.example.test/apirest.php/x"),
)


_NON_JSON_BODIES = [
(b"<html><body>Gateway page</body></html>", "text/html"),
(b"\xff\xfe\x00garbled", "application/json"),
]


@pytest.mark.parametrize(("content", "content_type"), _NON_JSON_BODIES)
@pytest.mark.parametrize("step", ["init", "upload", "json"])
async def test_v1_success_body_that_is_not_json_raises_protocol_error_once(
step: str, content: bytes, content_type: str
) -> None:
"""A non-JSON 200 raises ``GlpiResponseBodyError`` and is not retried."""

bad = cast(FakeResponse, _non_json(content, content_type))
good_init = FakeResponse(status_code=200, payload={"session_token": "tk"})
responses: dict[str, list[FakeResponse]] = {
"init": [good_init],
"upload": [],
"json": [],
"kill": [FakeResponse(status_code=200, payload={})],
}
responses["init" if step == "init" else step] = [bad]
http = _FakeV1Http(responses=responses)
session = _make(http)

with pytest.raises(GlpiResponseBodyError) as excinfo:
if step == "init":
await session._init_session()
elif step == "upload":
await session.upload_document("a.txt", b"x", "text/plain")
else:
await session.request_json("GET", "Ticket/1")

error = excinfo.value
assert isinstance(error, GlpiProtocolError)
assert isinstance(error.__cause__, (jsonlib.JSONDecodeError, UnicodeDecodeError))
assert (error.status_code, error.content_type) == (200, content_type)
assert error.body_length == len(content)
target = {"init": "/initSession", "upload": "/Document", "json": "/Ticket/1"}[step]
assert len([c for c in http.calls if c["url"].endswith(target)]) == 1
Loading
Loading