From 9c787a008660d3f251bcd5c3ab0885ea8055f802 Mon Sep 17 00:00:00 2001 From: baraline Date: Sun, 22 Nov 2026 22:57:56 +0100 Subject: [PATCH 1/2] Serialise GLPI v1 session renewals so concurrent requests open and kill the session once A client shared by concurrent tasks or threads renewed the v1 session once per request that found the token stale, on the first lazy initSession, and after a 401 or 403 rejection. Each renewal killed the token and opened a session: the second killSession answered 401, and the first new session was overwritten and never killed, leaking one server-side session per renewal. Every acquisition now takes a lock (the library's auth Lock type) and re-checks under it whether the work is still needed: token still missing, still stale, or still the very token the failed request used. Waiters reuse the token the first renewal obtained. Only _ensure_session, _renew_rejected_session and close take the lock, and none calls another, so the non-re-entrant sync lock cannot deadlock. The retry decorators are unchanged. Tests are hand-written on both sides (task bursts on the async tree, thread bursts on the sync tree) and fail without the lock. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 ++ glpi_python_client/_async/auth/_v1_session.py | 67 ++++++-- .../auth/tests/test_v1_session_concurrency.py | 148 +++++++++++++++++ glpi_python_client/_sync/auth/_v1_session.py | 67 ++++++-- .../auth/tests/test_v1_session_concurrency.py | 154 ++++++++++++++++++ unasync_build.py | 6 +- 6 files changed, 419 insertions(+), 37 deletions(-) create mode 100644 glpi_python_client/_async/auth/tests/test_v1_session_concurrency.py create mode 100644 glpi_python_client/_sync/auth/tests/test_v1_session_concurrency.py diff --git a/CHANGELOG.md b/CHANGELOG.md index a654cc2..118abe1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## Unreleased + +### Fixed + +- **Concurrent renewals of the legacy v1 session.** A client shared by + concurrent tasks or threads renewed the v1 session once per request that + found the token stale (every 15 minutes by default), on the first lazy + `initSession`, and after a 401/403 rejection: each renewal killed the + token and opened a session, so a second `killSession` answered 401 and + one server-side session leaked per renewal. Every acquisition now takes a + lock and re-checks under it whether the work is still needed, so waiters + reuse the token the first renewal obtained and the session is killed and + opened once. Retry behaviour is unchanged. + ## 0.6.10 — 2026-11-16 A minor addition: the GLPI v2 `/Dropdowns/ITILCategory` routes, so a caller diff --git a/glpi_python_client/_async/auth/_v1_session.py b/glpi_python_client/_async/auth/_v1_session.py index 0c2304d..ba57094 100644 --- a/glpi_python_client/_async/auth/_v1_session.py +++ b/glpi_python_client/_async/auth/_v1_session.py @@ -43,6 +43,7 @@ import httpx from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed +from glpi_python_client._async._concurrency import Lock from glpi_python_client._async.clients.commons._config import build_http_session from glpi_python_client._async.clients.commons._http import ( ensure_response_status, @@ -111,6 +112,11 @@ def __init__( self._session_token: str | None = None self._session_started_at: datetime | None = None + # Serialises every acquisition or replacement of the session token. + # It is not re-entrant: only ``_ensure_session``, + # ``_renew_rejected_session`` and ``close`` take it, and none of them + # calls another of them (or ``_headers``) while holding it. + self._session_lock = Lock() async def _dispatch(self, method: str, url: str, **kwargs: Any) -> httpx.Response: """Send one raw v1 HTTP call, translating transport faults. @@ -178,13 +184,32 @@ async def _ensure_session(self) -> None: The helper is called by every authenticated request before any header construction so callers never have to manage the lifecycle directly. + Concurrent callers are serialised and the need is re-tested under the + lock, so a caller that waited reuses the token the first one obtained. """ - if self._session_token is None: - await self._init_session() + if self._session_token is not None and not self._is_session_stale(): return - if self._is_session_stale(): - logger.info("GLPI v1 session reached refresh interval; renewing session.") + async with self._session_lock: + if self._session_token is None: + await self._init_session() + elif self._is_session_stale(): + logger.info( + "GLPI v1 session reached refresh interval; renewing session." + ) + await self._renew_session() + + async def _renew_rejected_session(self, rejected_token: str | None) -> None: + """Renew the session after the server rejected ``rejected_token``. + + Under the lock the current token is compared with the rejected one: + when another request already replaced it, the new token is reused + and nothing is killed or opened. + """ + + async with self._session_lock: + if self._session_token != rejected_token: + return await self._renew_session() def _is_session_stale(self) -> bool: @@ -218,6 +243,8 @@ def _session_headers(self) -> dict[str, str]: async def _renew_session(self) -> None: """Drop the current GLPI v1 session token and acquire a new one. + The caller must hold ``_session_lock``; the helper never takes it. + The previous token is best-effort killed so the GLPI server can release the associated session state immediately. ``_init_session`` will set the new token on success or raise, leaving the existing state @@ -267,7 +294,8 @@ async def _authenticated_request( the caller to validate with :func:`ensure_response_status`. """ - request_headers = {**await self._headers(), **(headers or {})} + session_headers = await self._headers() + request_headers = {**session_headers, **(headers or {})} # Dispatch through ``request(method, ...)`` rather than looking up a # per-verb attribute: it is the one call shape both transports share, # and it keeps the verb a value instead of an attribute name. @@ -278,7 +306,7 @@ async def _authenticated_request( "GLPI v1 session token was rejected; refreshing session and " "retrying request once." ) - await self._renew_session() + await self._renew_rejected_session(session_headers["Session-Token"]) request_headers = {**await self._headers(), **(headers or {})} response = await self._dispatch( verb, url, headers=request_headers, **kwargs @@ -299,19 +327,22 @@ async def close(self) -> None: """ try: - if self._session_token is not None: - await self._dispatch( - "GET", - f"{self._base_url}/killSession", - headers=self._session_headers(), - timeout=10, - ) - logger.info("GLPI v1 session killed.") - except Exception: - logger.warning("Failed to kill GLPI v1 session.", exc_info=True) + async with self._session_lock: + try: + if self._session_token is not None: + await self._dispatch( + "GET", + f"{self._base_url}/killSession", + headers=self._session_headers(), + timeout=10, + ) + logger.info("GLPI v1 session killed.") + except Exception: + logger.warning("Failed to kill GLPI v1 session.", exc_info=True) + finally: + self._session_token = None + self._session_started_at = None finally: - self._session_token = None - self._session_started_at = None await self._http.aclose() @_RETRY_ON_NETWORK_ERRORS diff --git a/glpi_python_client/_async/auth/tests/test_v1_session_concurrency.py b/glpi_python_client/_async/auth/tests/test_v1_session_concurrency.py new file mode 100644 index 0000000..97a681b --- /dev/null +++ b/glpi_python_client/_async/auth/tests/test_v1_session_concurrency.py @@ -0,0 +1,148 @@ +"""Concurrency tests for :class:`GLPIV1Session` on the async surface. + +Hand-written on both sides of the codegen (see ``HAND_WRITTEN`` in +``unasync_build.py``): the claim is that tasks sharing one session renew it +once, which needs real suspension points inside the fake transport. The sync +twin of this module drives the same scenarios from threads. +""" + +from __future__ import annotations + +import asyncio +from datetime import UTC, datetime, timedelta +from typing import Any, cast + +import httpx + +from glpi_python_client._async.auth._v1_session import GLPIV1Session +from glpi_python_client.testing.utils import FakeResponse + +_TASKS = 8 + + +class _ServerSimulation: + """Fake v1 server that tracks which session tokens are alive. + + ``killSession`` answers 401 for a token that is already dead, and any + other call answers 401 for a dead or unknown token, like the real API. + """ + + def __init__(self) -> None: + self.alive: set[str] = set() + self.inits = 0 + self.kills = 0 + self.failed_kills = 0 + self.tokens_used: list[str] = [] + + async def request( + self, method: str, url: str, headers: dict[str, str], **kwargs: Any + ) -> FakeResponse: + await asyncio.sleep(0.01) # a real suspension point on every call + if url.endswith("/initSession"): + self.inits += 1 + token = f"tk{self.inits}" + self.alive.add(token) + return FakeResponse(status_code=200, payload={"session_token": token}) + token = headers["Session-Token"] + if url.endswith("/killSession"): + self.kills += 1 + if token not in self.alive: + self.failed_kills += 1 + return FakeResponse(status_code=401, payload={}) + self.alive.discard(token) + return FakeResponse(status_code=200, payload={}) + self.tokens_used.append(token) + if token not in self.alive: + return FakeResponse(status_code=401, payload={"err": "invalid"}) + return FakeResponse(status_code=200, payload={"ok": True}) + + async def aclose(self) -> None: + return None + + +def _make(server: _ServerSimulation) -> GLPIV1Session: + session = GLPIV1Session( + base_url="https://glpi.example.test/apirest.php", + user_token="user-token", + app_token="app-token", + ) + session._http = cast(httpx.AsyncClient, server) # type: ignore[assignment] + return session + + +def _adopt( + session: GLPIV1Session, server: _ServerSimulation, *, age: timedelta +) -> None: + """Give ``session`` a live token acquired ``age`` ago.""" + + server.inits += 1 + token = f"tk{server.inits}" + server.alive.add(token) + session._session_token = token + session._session_started_at = datetime.now(tz=UTC) - age + + +async def _burst(session: GLPIV1Session) -> list[object]: + return list( + await asyncio.wait_for( + asyncio.gather( + *(session.request_json("GET", "Ticket") for _ in range(_TASKS)) + ), + timeout=10, + ) + ) + + +async def test_concurrent_requests_on_a_stale_session_renew_it_once() -> None: + server = _ServerSimulation() + session = _make(server) + _adopt(session, server, age=timedelta(hours=1)) + + results = await _burst(session) + + assert results == [{"ok": True}] * _TASKS + assert server.kills == 1 + assert server.failed_kills == 0 + assert server.inits == 2 # the adopted session and its single replacement + assert server.tokens_used == ["tk2"] * _TASKS + assert server.alive == {"tk2"} # nothing leaked on the server + + +async def test_concurrent_first_use_opens_one_session() -> None: + server = _ServerSimulation() + session = _make(server) + + results = await _burst(session) + + assert results == [{"ok": True}] * _TASKS + assert server.inits == 1 + assert server.kills == 0 + assert server.tokens_used == ["tk1"] * _TASKS + + +async def test_concurrent_rejections_of_one_token_renew_it_once() -> None: + server = _ServerSimulation() + session = _make(server) + _adopt(session, server, age=timedelta(seconds=1)) + server.alive.clear() # the server dropped the session behind the client's back + + results = await _burst(session) + + assert results == [{"ok": True}] * _TASKS + assert server.inits == 2 + assert server.kills == 1 # one best-effort kill of the dead token + assert server.alive == {"tk2"} + assert server.tokens_used.count("tk2") == _TASKS + + +async def test_close_after_a_renewal_kills_only_the_current_session() -> None: + server = _ServerSimulation() + session = _make(server) + _adopt(session, server, age=timedelta(hours=1)) + await _burst(session) + + await session.close() + + assert server.alive == set() + assert server.kills == 2 + assert session._session_token is None diff --git a/glpi_python_client/_sync/auth/_v1_session.py b/glpi_python_client/_sync/auth/_v1_session.py index 222afcd..5ebb7a1 100644 --- a/glpi_python_client/_sync/auth/_v1_session.py +++ b/glpi_python_client/_sync/auth/_v1_session.py @@ -43,6 +43,7 @@ import httpx from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed +from glpi_python_client._sync._concurrency import Lock from glpi_python_client._sync.clients.commons._config import build_http_session from glpi_python_client._sync.clients.commons._http import ( ensure_response_status, @@ -111,6 +112,11 @@ def __init__( self._session_token: str | None = None self._session_started_at: datetime | None = None + # Serialises every acquisition or replacement of the session token. + # It is not re-entrant: only ``_ensure_session``, + # ``_renew_rejected_session`` and ``close`` take it, and none of them + # calls another of them (or ``_headers``) while holding it. + self._session_lock = Lock() def _dispatch(self, method: str, url: str, **kwargs: Any) -> httpx.Response: """Send one raw v1 HTTP call, translating transport faults. @@ -178,13 +184,32 @@ def _ensure_session(self) -> None: The helper is called by every authenticated request before any header construction so callers never have to manage the lifecycle directly. + Concurrent callers are serialised and the need is re-tested under the + lock, so a caller that waited reuses the token the first one obtained. """ - if self._session_token is None: - self._init_session() + if self._session_token is not None and not self._is_session_stale(): return - if self._is_session_stale(): - logger.info("GLPI v1 session reached refresh interval; renewing session.") + with self._session_lock: + if self._session_token is None: + self._init_session() + elif self._is_session_stale(): + logger.info( + "GLPI v1 session reached refresh interval; renewing session." + ) + self._renew_session() + + def _renew_rejected_session(self, rejected_token: str | None) -> None: + """Renew the session after the server rejected ``rejected_token``. + + Under the lock the current token is compared with the rejected one: + when another request already replaced it, the new token is reused + and nothing is killed or opened. + """ + + with self._session_lock: + if self._session_token != rejected_token: + return self._renew_session() def _is_session_stale(self) -> bool: @@ -218,6 +243,8 @@ def _session_headers(self) -> dict[str, str]: def _renew_session(self) -> None: """Drop the current GLPI v1 session token and acquire a new one. + The caller must hold ``_session_lock``; the helper never takes it. + The previous token is best-effort killed so the GLPI server can release the associated session state immediately. ``_init_session`` will set the new token on success or raise, leaving the existing state @@ -267,7 +294,8 @@ def _authenticated_request( the caller to validate with :func:`ensure_response_status`. """ - request_headers = {**self._headers(), **(headers or {})} + session_headers = self._headers() + request_headers = {**session_headers, **(headers or {})} # Dispatch through ``request(method, ...)`` rather than looking up a # per-verb attribute: it is the one call shape both transports share, # and it keeps the verb a value instead of an attribute name. @@ -278,7 +306,7 @@ def _authenticated_request( "GLPI v1 session token was rejected; refreshing session and " "retrying request once." ) - self._renew_session() + self._renew_rejected_session(session_headers["Session-Token"]) request_headers = {**self._headers(), **(headers or {})} response = self._dispatch( verb, url, headers=request_headers, **kwargs @@ -299,19 +327,22 @@ def close(self) -> None: """ try: - if self._session_token is not None: - self._dispatch( - "GET", - f"{self._base_url}/killSession", - headers=self._session_headers(), - timeout=10, - ) - logger.info("GLPI v1 session killed.") - except Exception: - logger.warning("Failed to kill GLPI v1 session.", exc_info=True) + with self._session_lock: + try: + if self._session_token is not None: + self._dispatch( + "GET", + f"{self._base_url}/killSession", + headers=self._session_headers(), + timeout=10, + ) + logger.info("GLPI v1 session killed.") + except Exception: + logger.warning("Failed to kill GLPI v1 session.", exc_info=True) + finally: + self._session_token = None + self._session_started_at = None finally: - self._session_token = None - self._session_started_at = None self._http.close() @_RETRY_ON_NETWORK_ERRORS diff --git a/glpi_python_client/_sync/auth/tests/test_v1_session_concurrency.py b/glpi_python_client/_sync/auth/tests/test_v1_session_concurrency.py new file mode 100644 index 0000000..fe2c74e --- /dev/null +++ b/glpi_python_client/_sync/auth/tests/test_v1_session_concurrency.py @@ -0,0 +1,154 @@ +"""Concurrency tests for :class:`GLPIV1Session` on the sync surface. + +Hand-written on both sides of the codegen (see ``HAND_WRITTEN`` in +``unasync_build.py``): the async twin of this module drives the same +scenarios from tasks, this one from threads sharing one session. +""" + +from __future__ import annotations + +import threading +import time +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from datetime import UTC, datetime, timedelta +from typing import Any, cast + +import httpx + +from glpi_python_client._sync.auth._v1_session import GLPIV1Session +from glpi_python_client.testing.utils import FakeResponse + +_THREADS = 8 + + +class _ServerSimulation: + """Fake v1 server that tracks which session tokens are alive. + + ``killSession`` answers 401 for a token that is already dead, and any + other call answers 401 for a dead or unknown token, like the real API. + A mutex keeps the bookkeeping exact under threads. + """ + + def __init__(self) -> None: + self._mutex = threading.Lock() + self.alive: set[str] = set() + self.inits = 0 + self.kills = 0 + self.failed_kills = 0 + self.tokens_used: list[str] = [] + + def request( + self, method: str, url: str, headers: dict[str, str], **kwargs: Any + ) -> FakeResponse: + time.sleep(0.02) # keeps every call in flight long enough to overlap + with self._mutex: + if url.endswith("/initSession"): + self.inits += 1 + token = f"tk{self.inits}" + self.alive.add(token) + return FakeResponse(status_code=200, payload={"session_token": token}) + token = headers["Session-Token"] + if url.endswith("/killSession"): + self.kills += 1 + if token not in self.alive: + self.failed_kills += 1 + return FakeResponse(status_code=401, payload={}) + self.alive.discard(token) + return FakeResponse(status_code=200, payload={}) + self.tokens_used.append(token) + if token not in self.alive: + return FakeResponse(status_code=401, payload={"err": "invalid"}) + return FakeResponse(status_code=200, payload={"ok": True}) + + def close(self) -> None: + return None + + +def _make(server: _ServerSimulation) -> GLPIV1Session: + session = GLPIV1Session( + base_url="https://glpi.example.test/apirest.php", + user_token="user-token", + app_token="app-token", + ) + session._http = cast(httpx.Client, server) # type: ignore[assignment] + return session + + +def _adopt(session: GLPIV1Session, server: _ServerSimulation, *, age: timedelta) -> None: + """Give ``session`` a live token acquired ``age`` ago.""" + + server.inits += 1 + token = f"tk{server.inits}" + server.alive.add(token) + session._session_token = token + session._session_started_at = datetime.now(tz=UTC) - age + + +def _burst(session: GLPIV1Session) -> list[object]: + """Run ``_THREADS`` requests that all start at the same moment.""" + + barrier = threading.Barrier(_THREADS) + + def _one() -> object: + barrier.wait(timeout=10) + return session.request_json("GET", "Ticket") + + with ThreadPoolExecutor(max_workers=_THREADS) as pool: + futures = [pool.submit(cast(Callable[[], object], _one)) for _ in range(_THREADS)] + return [future.result(timeout=30) for future in futures] + + +def test_concurrent_requests_on_a_stale_session_renew_it_once() -> None: + server = _ServerSimulation() + session = _make(server) + _adopt(session, server, age=timedelta(hours=1)) + + results = _burst(session) + + assert results == [{"ok": True}] * _THREADS + assert server.kills == 1 + assert server.failed_kills == 0 + assert server.inits == 2 # the adopted session and its single replacement + assert server.tokens_used == ["tk2"] * _THREADS + assert server.alive == {"tk2"} # nothing leaked on the server + + +def test_concurrent_first_use_opens_one_session() -> None: + server = _ServerSimulation() + session = _make(server) + + results = _burst(session) + + assert results == [{"ok": True}] * _THREADS + assert server.inits == 1 + assert server.kills == 0 + assert server.tokens_used == ["tk1"] * _THREADS + + +def test_concurrent_rejections_of_one_token_renew_it_once() -> None: + server = _ServerSimulation() + session = _make(server) + _adopt(session, server, age=timedelta(seconds=1)) + server.alive.clear() # the server dropped the session behind the client's back + + results = _burst(session) + + assert results == [{"ok": True}] * _THREADS + assert server.inits == 2 + assert server.kills == 1 # one best-effort kill of the dead token + assert server.alive == {"tk2"} + assert server.tokens_used.count("tk2") == _THREADS + + +def test_close_after_a_renewal_kills_only_the_current_session() -> None: + server = _ServerSimulation() + session = _make(server) + _adopt(session, server, age=timedelta(hours=1)) + _burst(session) + + session.close() + + assert server.alive == set() + assert server.kills == 2 + assert session._session_token is None diff --git a/unasync_build.py b/unasync_build.py index 6d9c9f7..b2497d0 100644 --- a/unasync_build.py +++ b/unasync_build.py @@ -67,7 +67,11 @@ #: on its absence, so ``--check`` would stay green while a whole module #: silently had no twin. Colocated tests make that collision plausible -- #: generic names like ``test_concurrency.py`` now recur per package. -HAND_WRITTEN = {"_concurrency.py", "tests/test_concurrency.py"} +HAND_WRITTEN = { + "_concurrency.py", + "tests/test_concurrency.py", + "auth/tests/test_v1_session_concurrency.py", +} #: Token substitutions beyond unasync's defaults. #: From 9b053579ee0449e85a95c53b5caed88a1179bbde Mon Sep 17 00:00:00 2001 From: baraline Date: Sun, 22 Nov 2026 23:01:14 +0100 Subject: [PATCH 2/2] State in the v1 session module docstring that renewal is serialised Co-Authored-By: Claude Opus 5.5 --- glpi_python_client/_async/auth/_v1_session.py | 3 +++ glpi_python_client/_sync/auth/_v1_session.py | 3 +++ 2 files changed, 6 insertions(+) diff --git a/glpi_python_client/_async/auth/_v1_session.py b/glpi_python_client/_async/auth/_v1_session.py index ba57094..99f8ef8 100644 --- a/glpi_python_client/_async/auth/_v1_session.py +++ b/glpi_python_client/_async/auth/_v1_session.py @@ -13,6 +13,9 @@ kill) and exposes the typed ``upload_document`` helper plus the generic ``request_json`` JSON-only HTTP helper that newer mixins build on. +Session renewal is serialised by a lock and the need is re-checked under it, +so concurrent requests share one new session instead of each renewing. + Retry policy ------------ Every public dispatch helper (``_init_session``, ``request_json``, diff --git a/glpi_python_client/_sync/auth/_v1_session.py b/glpi_python_client/_sync/auth/_v1_session.py index 5ebb7a1..1f0d3a5 100644 --- a/glpi_python_client/_sync/auth/_v1_session.py +++ b/glpi_python_client/_sync/auth/_v1_session.py @@ -13,6 +13,9 @@ kill) and exposes the typed ``upload_document`` helper plus the generic ``request_json`` JSON-only HTTP helper that newer mixins build on. +Session renewal is serialised by a lock and the need is re-checked under it, +so concurrent requests share one new session instead of each renewing. + Retry policy ------------ Every public dispatch helper (``_init_session``, ``request_json``,