diff --git a/CHANGELOG.md b/CHANGELOG.md index 10b8bc3..0130add 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ All notable changes to python-libei are recorded here. The format follows ## [Unreleased] +## [0.8.1] - 2026-11-11 + ### Added - **A socketpair round-trip covering the event accessors no test reached.** @@ -66,6 +68,40 @@ All notable changes to python-libei are recorded here. The format follows `Region.convert_point()` is out of reach, and every remaining marker was swept against 1.0.0's real headers: 17 `ei_` and 18 `eis_` markers, none of them contradicted. +- **A malformed `Response` reply to a portal request now raises the typed + `PortalProtocolError` instead of a timeout or a crash.** Every + Request-returning portal call waits on a `Response` specified as + `(u response, a{sv} results)`, and `_request` unpacked it on faith: a + wrong-arity payload raised inside the GLib signal callback -- where PyGI + prints the traceback to stderr and swallows it, so the step silently + degraded to a full-timeout `PortalTimeoutError` -- while a non-dict + `results` slipped through to callers, whose `.get()` crashed with a raw + `AttributeError` past `except PortalError`. The shape is now checked in + the callback and any mismatch ends the wait with `PortalProtocolError` + (the same hardening the session signals received in 0.8.0), so what + `_request` returns is structurally guaranteed: an `int` code and a + `dict` of results. `GetZones`' and `SetPointerBarriers`' result *values* + are converted under the same kind of guard as the Activated signal's + (`zone_set` and each zone's four coordinates as the spec's integers, + `failed_barriers` as a list of them) -- and a `d` where the spec gives + an integer is now rejected rather than silently truncated by `int()`, so + a `0.9` coordinate or a `1.9` refused-barrier id cannot read back as a + different, valid-looking value. And a `Response` landing in the same + main-context iteration as + the request's deadline now resolves to whichever outcome was recorded + first, rather than the delivered reply being dropped for a timeout -- + the same simultaneous-dispatch fix `_wait_for_signal` already had. +- **Every event pulled from the dispatch queue leaked one C reference.** + `ei_get_event()` and `eis_get_event()` transfer ownership of the + returned event to the caller, but `ei.Context.events()` and + `eis.Eis.events()` wrapped it with `wrap()`, which is for *borrowed* + pointers and takes its own extra ref -- so the transferred reference was + never released, leaking one `ei_event`/`eis_event` for every event the + iterator yielded. They now `adopt()` the transferred reference, which + takes no extra ref and lets the wrapper's finalizer balance the one the + C API handed over. + +## [0.8.0] - 2026-10-20 ### Added diff --git a/README.md b/README.md index 80d75ee..39e60d3 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ and why, is in ## Status -Beta (`0.8.0`), published on [PyPI](https://pypi.org/project/python-libei/) +Beta (`0.8.1`), published on [PyPI](https://pypi.org/project/python-libei/) since `0.1.0`, and **the API is not frozen** — expect renames before 1.0. The injection path is exercised end to end against the real libraries by the diff --git a/docs/developers/verification.md b/docs/developers/verification.md index 29f5fee..e3af5a4 100644 --- a/docs/developers/verification.md +++ b/docs/developers/verification.md @@ -1,6 +1,6 @@ # What has actually been verified -The package is beta (`0.8.0`) and the API is not frozen — expect renames +The package is beta (`0.8.1`) and the API is not frozen — expect renames before 1.0. This page is what that qualifier covers, concretely: which paths have been driven against real libraries, which have only ever been driven against fakes, and which libei versions the whole thing has met. diff --git a/docs/recipes.md b/docs/recipes.md index ac6452f..3231484 100644 --- a/docs/recipes.md +++ b/docs/recipes.md @@ -112,7 +112,8 @@ Regions carry more than bounds. `region.mapping_id` groups the ones that map to the same thing, `device.region_at(x, y)` finds which region a point falls in, and `region.convert_point(x, y)` turns a desktop-wide point into one relative to that region — returning `None` when it falls outside, which also -answers "is it in here?" in a single call. All three need libei 1.1. +answers "is it in here?" in a single call. `mapping_id` and `region_at()` +need libei 1.1; `convert_point()` works on the libei 1.0.0 floor. ## Picking the right device when several resume diff --git a/pyproject.toml b/pyproject.toml index fdf6b1d..3bbcfc4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "python-libei" -version = "0.8.0" +version = "0.8.1" description = "Inject, receive and capture input on Wayland from Python: ctypes bindings for libei, libeis and liboeffis, plus the RemoteDesktop and InputCapture portals" readme = "README.md" license = "MIT" diff --git a/src/libei/__init__.py b/src/libei/__init__.py index 340b03a..6edd5f1 100644 --- a/src/libei/__init__.py +++ b/src/libei/__init__.py @@ -31,6 +31,6 @@ Beta: the API is not frozen. """ -__version__ = "0.8.0" +__version__ = "0.8.1" __all__ = ["__version__"] diff --git a/src/libei/ei.py b/src/libei/ei.py index d225a50..8a3a923 100644 --- a/src/libei/ei.py +++ b/src/libei/ei.py @@ -372,8 +372,7 @@ def convert_point(self, x: float, y: float) -> tuple[float, float] | None: Returns the point with the region's offset subtracted, or ``None`` if it falls outside the region -- which is also how you test - membership without a second :meth:`contains` call. Requires - libei 1.1. + membership without a second :meth:`contains` call. """ # x/y are in-out parameters: libei overwrites them only when the # point is inside, so the return value has to gate reading them. @@ -1127,7 +1126,10 @@ def events(self) -> Iterator[Event]: pointer = _capi.libei.get_event(self) if not pointer: break - event = Event.wrap(pointer) + # adopt(), not wrap(): ei_get_event() transfers ownership of + # the returned reference to the caller, and the unref in + # release() below is the one that balances it. + event = Event.adopt(pointer) assert event is not None # try/finally, not a bare call after yield: breaking out of a # `for event in ctx.events:` loop (or an exception propagating diff --git a/src/libei/eis.py b/src/libei/eis.py index 4a03631..4144c29 100644 --- a/src/libei/eis.py +++ b/src/libei/eis.py @@ -1161,7 +1161,10 @@ def events(self) -> Iterator[Event]: pointer = _capi.libeis.get_event(self) if not pointer: break - event = Event.wrap(pointer) + # adopt(), not wrap(): eis_get_event() transfers ownership of + # the returned reference to the caller, and the unref in + # release() below is the one that balances it. + event = Event.adopt(pointer) assert event is not None # See ei.Context.events: try/finally so release() still runs # if the caller breaks out of the loop (GeneratorExit at the @@ -1179,9 +1182,11 @@ def now(self) -> int: def set_flag(self, flag: Flag) -> None: """Change this context's protocol behavior. Requires libei 1.6. - Must be called before the backend is set up, so in practice - before :meth:`create_for_fd` / :meth:`create_for_socket` -- which - also means this is only reachable on a context built by hand. + Must be called before the backend is set up, so the supported + way to use it is the ``flags`` parameter of + :meth:`create_for_fd` / :meth:`create_for_socket`, which apply + each flag at exactly that point; calling it directly only works + on a context built by hand, before its backend is set up. Takes one flag, never a bitmask; call it again for another. """ result = _capi.libeis.set_flag(self, flag) diff --git a/src/libei/portal.py b/src/libei/portal.py index 37842a3..01e2174 100644 --- a/src/libei/portal.py +++ b/src/libei/portal.py @@ -207,6 +207,14 @@ class PortalProtocolError(PortalError): default message names the expected shape), a phrase for a value fault (naming the field). ``payload`` is whatever best shows the fault -- the whole signal tuple for a shape fault, the options dict for a value one. + + :func:`_request` raises it the same way for a ``Request``'s + ``Response`` reply that does not match its own ``(u response, a{sv} + results)`` shape, and :meth:`InputCaptureSession.zones` for a result + value that is not the type the spec gives it -- always with a + ``detail`` phrase, since the default shape message above is specific + to the session signals. ``step`` is then the method name, matching the + sibling errors raised from the same call. """ def __init__(self, step: str, payload: object, detail: str | None = None) -> None: @@ -457,6 +465,18 @@ def _request( for 60 seconds means the answer arrives inside 60 seconds, not inside however many 60-second waits the sequence happens to be built from. + A ``Response`` whose payload does not match the spec's ``(u response, + a{sv} results)`` shape raises :class:`PortalProtocolError` rather than + being unpacked on faith -- the same hardening `_wait_for_signal` + applies to the signals it waits on, and for the same two reasons: a + wrong-arity payload used to raise inside the GLib callback, where PyGI + swallows it, degrading the step to a full-timeout + :class:`PortalTimeoutError`; a non-dict ``results`` instead slipped + through to the caller, whose ``.get()`` crashed with a raw + ``AttributeError`` past ``except PortalError``. The guarantee callers + rely on is therefore structural: what this returns is always an + ``int`` code and a ``dict`` of results. + ``trailing_args``, appended after ``options`` in the call's parameter tuple, exists for ``InputCapture.SetPointerBarriers`` -- the one Request-returning method in either portal whose ``options`` is not its @@ -474,12 +494,28 @@ def _request( loop = GLib.MainLoop() result: dict[str, Any] = {} + malformed: dict[str, Any] = {} subscriptions: list[Any] = [] # Set inside the timeout callback rather than inferred from an empty # `result` afterwards: a Response carrying no results is legitimate # (SelectDevices answers with an empty dict), so "did the loop end # because it timed out" has to be recorded, not deduced. timed_out = False + # Distinct from `timed_out`: whether `on_timeout` ran at all, either + # path -- the flag the cleanup below keys "already removed?" on. See + # the matching pair in `_wait_for_signal`. + timeout_fired = False + + def _settled() -> bool: + """Whether some terminal outcome has already been recorded. + + Same role as in `_wait_for_signal`: GLib dispatches every source + ready in one main-context iteration regardless of an earlier + ``loop.quit()``, so a Response and the deadline can both fire in + the same poll -- the first recorded outcome wins, and a delivered + reply is never dropped for a timeout (or vice versa). + """ + return bool(result) or bool(malformed) or timed_out def on_response( _conn: Any, @@ -491,14 +527,42 @@ def on_response( *_a: Any, ) -> None: """Record the first reply and quit the loop; later replies are ignored.""" - if result: # both subscriptions may fire; the first reply wins + if _settled(): # both subscriptions may fire; the first reply wins return - result["code"], result["results"] = params.unpack() + args = params.unpack() + # Checked here, raised only after the loop: this runs inside a + # GLib callback, where PyGI prints an exception to stderr and + # swallows it -- a bare raise on a malformed Response would leave + # the loop running until the full timeout, misreported as + # PortalTimeoutError; a non-dict `results` let through instead + # crashed the caller's `.get()` with a raw AttributeError past + # `except PortalError`. Same hardening `_wait_for_signal` applies + # to the signals it waits on. + if ( + not isinstance(args, tuple) + or len(args) != 2 + or isinstance(args[0], bool) + or not isinstance(args[0], int) + or not isinstance(args[1], dict) + ): + malformed["args"] = args + loop.quit() + return + result["code"], result["results"] = args loop.quit() def on_timeout() -> bool: """Stop the loop and record that it timed out rather than finished.""" - nonlocal timed_out + nonlocal timed_out, timeout_fired + # Set first, before the early return: GLib removes the source the + # moment this returns False (which both paths do), so the finally + # block keys "already removed" on this, not on `timed_out` -- see + # the same dance in `_wait_for_signal`. + timeout_fired = True + if _settled(): + # A Response delivered in the same poll as the deadline has + # already recorded its outcome; do not overwrite it. + return False timed_out = True loop.quit() return False # one-shot; GLib removes the source when this is False @@ -542,12 +606,14 @@ def subscribe(path: str) -> None: handle = _returned_handle(reply) if handle is not None and handle != expected_path: subscribe(handle) - # `if not result` because a synchronous answer (a fast + # `if not _settled()` because a synchronous answer (a fast # non-interactive Response, or a test double) can arrive during the # call above, before run() is reached -- and quit() on a loop that # is not running yet does not stop the later run(), so running it - # then would block with the reply already delivered. - if not result: + # then would block with the reply already delivered. A malformed + # synchronous reply counts: it too has already quit a loop that + # was not running yet. + if not _settled(): timeout_source = GLib.timeout_add(_msec_until(deadline), on_timeout) try: loop.run() @@ -559,12 +625,27 @@ def subscribe(path: str) -> None: # fixed for _wait_for_signal below. Only remove it when the # *Response* woke the loop instead; leaving a live source in # that case holds a reference to this closure and fires it - # into a dead loop on some later request. - if not timed_out: + # into a dead loop on some later request. Keyed on + # `timeout_fired` (did on_timeout run), not `timed_out` (did + # the wait time out): a Response landing in the same poll as + # the deadline runs on_timeout down its `_settled` early + # return, which removes the source yet leaves `timed_out` + # False. + if not timeout_fired: GLib.source_remove(timeout_source) finally: for subscription in subscriptions: connection.signal_unsubscribe(subscription) + # Mirrors `_signal_outcome`: only one of these is ever set (every + # callback checks `_settled()` first), so the order here only decides + # between genuinely simultaneous dispatches. + if malformed: + raise PortalProtocolError( + method, + malformed["args"], + "the Request's Response signal is specified as " + "(uint response, results dict)", + ) if timed_out: raise PortalTimeoutError(method, timeout) return result["code"], result["results"] @@ -1100,6 +1181,23 @@ def _classify_signal_payload( return "take" +def _spec_int(value: Any) -> int: + """``int(value)`` for a spec ``u``/``i``, refusing a silent truncation. + + A portal integer field arrives as a Python ``int``. A malformed portal + that put a ``d`` (double) there would still reach ``int()``, and + ``int(0.9) == 0`` / ``int(1.9) == 1`` truncates it *silently* -- a zone + coordinate or a refused barrier id quietly becomes a different, + valid-looking value rather than an error. Reject any ``float`` + (``inf``/``nan`` included) with the ``ValueError`` the surrounding + guards already turn into a :class:`PortalProtocolError`, so an off-spec + fractional value is refused on the same footing as a non-numeric one. + """ + if isinstance(value, float): + raise ValueError("a fractional value where the spec gives an integer") + return int(value) + + def _deactivation_id(options: dict[str, Any], signal: str) -> int: """The ``activation_id`` from Deactivated's options, as the spec's ``u``. @@ -1107,13 +1205,12 @@ def _deactivation_id(options: dict[str, Any], signal: str) -> int: dict -- but not the types of the values in it. ``activation_id`` is a ``u``, and a non-conforming portal that put something else there would crash the caller with ``ValueError``/``TypeError``/``OverflowError`` - (the last from ``int(float('inf'))``) past the shape check. Converting - it here turns that into the same typed :class:`PortalProtocolError` the - shape check raises, so a caller that guards against malformed signals - catches one error, not two. + past the shape check. Converting it here turns that into the same typed + :class:`PortalProtocolError` the shape check raises, so a caller that + guards against malformed signals catches one error, not two. """ try: - return int(options.get("activation_id", 0)) + return _spec_int(options.get("activation_id", 0)) except (ValueError, TypeError, OverflowError) as exc: raise PortalProtocolError( signal, options, "activation_id is not an integer" @@ -1134,7 +1231,7 @@ def _activation_from_options(options: dict[str, Any], signal: str) -> Activation fourth hand-rolled check nobody remembers to write. """ try: - activation_id = int(options.get("activation_id", 0)) + activation_id = _spec_int(options.get("activation_id", 0)) cursor = options.get("cursor_position") if cursor is None: cursor_position = None @@ -1142,7 +1239,7 @@ def _activation_from_options(options: dict[str, Any], signal: str) -> Activation cx, cy = cursor # (dd): exactly two, or this unpacking raises cursor_position = (float(cx), float(cy)) barrier = options.get("barrier_id") - barrier_id = None if barrier is None else int(barrier) + barrier_id = None if barrier is None else _spec_int(barrier) except (ValueError, TypeError, OverflowError) as exc: raise PortalProtocolError( signal, options, "an option value is not the type the spec gives it" @@ -1608,9 +1705,26 @@ def zones( ) if code != 0: raise PortalDeniedError("GetZones") - zone_set = results.get("zone_set", 0) - zones = [tuple(z) for z in results.get("zones", [])] - return int(zone_set), zones + # `results` is a dict by `_request`'s own guarantee; the *values* + # are still the portal's to malform. The spec types them -- + # `zone_set` is a `u`, `zones` an `a(uuii)` -- so convert them + # under one guard, the same way `_activation_from_options` covers + # the Activated signal's values: a non-conforming value becomes + # the typed PortalProtocolError rather than a raw + # TypeError/ValueError past `except PortalError` in the caller. + try: + zone_set = _spec_int(results.get("zone_set", 0)) + zones = [ + (_spec_int(w), _spec_int(h), _spec_int(x), _spec_int(y)) + for w, h, x, y in results.get("zones", []) + ] + except (ValueError, TypeError, OverflowError) as exc: + raise PortalProtocolError( + "GetZones", + results, + "a result value is not the type the spec gives it", + ) from exc + return zone_set, zones def set_pointer_barriers( self, @@ -1659,7 +1773,19 @@ def set_pointer_barriers( ) if code != 0: raise PortalDeniedError("SetPointerBarriers") - failed = list(results.get("failed_barriers", [])) + # `results` is a dict by `_request`'s own guarantee; the *value* at + # `failed_barriers` (an `au` per the spec) is not. A non-iterable + # there would crash the caller with a raw TypeError past + # `except PortalError` -- the same value-level hole `zones()` guards + # -- so a malformed one becomes the typed PortalProtocolError. + try: + failed = [_spec_int(b) for b in results.get("failed_barriers", [])] + except (ValueError, TypeError, OverflowError) as exc: + raise PortalProtocolError( + "SetPointerBarriers", + results, + "a result value is not the type the spec gives it", + ) from exc # A partially-refused set is the quiet failure here: the call # succeeds, some barriers stand, and an edge the caller believes is # armed simply never triggers. Callers see only the returned list, diff --git a/tests/test_inputcapture.py b/tests/test_inputcapture.py index 0475a55..2aad124 100644 --- a/tests/test_inputcapture.py +++ b/tests/test_inputcapture.py @@ -205,13 +205,14 @@ def signal_subscribe( payload = self._pending_deactivated self._pending_deactivated = None self._emit_session_signal(callback, "Deactivated", payload) - elif signal == "Closed" and self._pending_closed: + elif ( + signal == "Closed" and self._pending_closed and path == self.session_handle + ): # Closed fires on the session object's own path, not the # portal's -- the opposite of Activated/Deactivated above -- so # it is only delivered to a subscription made there. - if path == self.session_handle: - self._pending_closed = False - callback(None, None, path, None, "Closed", FakeReply(({},))) + self._pending_closed = False + callback(None, None, path, None, "Closed", FakeReply(({},))) return self._next_subscription_id def _emit_session_signal( @@ -464,6 +465,72 @@ def test_a_declined_get_zones_raises_portal_denied_error() -> None: assert excinfo.value.step == "GetZones" +def test_a_non_dict_get_zones_results_raises_a_typed_error() -> None: + # _request's shape check, seen from a consumer: zones() used to call + # .get() on whatever the Response carried, so a non-dict `results` + # crashed it with a raw AttributeError past `except PortalError`. The + # check lives in _request, which is why `step` names the method. + responses: dict[str, Any] = {"GetZones": (0, ["not", "a", "dict"])} + connection = FakeInputCaptureConnection(responses=responses) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError) as excinfo: + session.zones() + assert excinfo.value.step == "GetZones" + assert excinfo.value.payload == (0, ["not", "a", "dict"]) + + +def test_a_non_integer_zone_set_raises_a_typed_error() -> None: + # Shape-valid results (a dict), but zone_set is not the `u` the spec + # promises -- this passes _request's shape check and used to crash the + # caller with ValueError on int(). Now the same typed error as a shape + # violation, with a value-level detail, exactly like a malformed + # activation_id (test_a_non_integer_activation_id_raises_a_typed_error). + connection = FakeInputCaptureConnection( + responses={"GetZones": (0, {"zone_set": "seven", "zones": []})} + ) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError) as excinfo: + session.zones() + assert excinfo.value.step == "GetZones" + assert excinfo.value.detail is not None + assert "shape" not in str(excinfo.value) + + +def test_a_malformed_zone_entry_raises_a_typed_error() -> None: + # A zone that is not the spec's (uuii) quadruple used to be handed + # back verbatim -- `tuple(z)` kept whatever arity arrived, quietly + # violating the annotated (int, int, int, int) -- while a `zones` + # value that is not a list of sequences at all escaped as a raw + # TypeError. Both are now the same typed error. + connection = FakeInputCaptureConnection( + responses={"GetZones": (0, {"zone_set": 1, "zones": [(1920, 1080)]})} + ) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError) as excinfo: + session.zones() + assert excinfo.value.step == "GetZones" + assert excinfo.value.detail is not None + + +def test_a_fractional_zone_value_is_rejected_not_truncated() -> None: + # The quiet case int() would hide: a `d` where the spec gives an `i`. + # int(0.9) == 0 silently, so a zone whose x started at 0.9 would read + # back as a different, valid-looking rectangle. _spec_int refuses it on + # the same footing as a non-numeric value rather than truncating. + connection = FakeInputCaptureConnection( + responses={"GetZones": (0, {"zone_set": 1, "zones": [(1920, 1080, 0.9, 0)]})} + ) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError) as excinfo: + session.zones() + assert excinfo.value.step == "GetZones" + assert excinfo.value.detail is not None + + def test_set_pointer_barriers_sends_barrier_id_and_position() -> None: connection = FakeInputCaptureConnection() with install_fake_gi(connection): @@ -490,6 +557,39 @@ def test_set_pointer_barriers_reports_the_failed_ones() -> None: assert failed == [2] +def test_a_malformed_failed_barriers_value_raises_a_typed_error() -> None: + # `failed_barriers` is an `au`; a non-iterable (or non-integer element) + # there used to crash the caller with a raw TypeError/ValueError past + # `except PortalError`, the same value-level hole zones() closed. Now a + # typed PortalProtocolError. + connection = FakeInputCaptureConnection( + responses={"SetPointerBarriers": (0, {"failed_barriers": 7})} + ) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError) as excinfo: + session.set_pointer_barriers([(1, 0, 0, 1919, 0)], zone_set=7) + assert excinfo.value.step == "SetPointerBarriers" + assert excinfo.value.detail is not None + + +def test_a_fractional_failed_barrier_is_rejected_not_truncated() -> None: + # int(1.9) == 1 would hand the caller a *different* armed barrier's id + # as the refused one -- a silent mis-identification rather than an + # error. _spec_int rejects the off-spec `d` instead of truncating it. + connection = FakeInputCaptureConnection( + responses={"SetPointerBarriers": (0, {"failed_barriers": [1.9]})} + ) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError) as excinfo: + session.set_pointer_barriers( + [(1, 0, 0, 1919, 0), (2, 1920, 0, 1920, 1079)], zone_set=7 + ) + assert excinfo.value.step == "SetPointerBarriers" + assert excinfo.value.detail is not None + + def test_partially_refused_barriers_are_logged( caplog: pytest.LogCaptureFixture, ) -> None: @@ -686,10 +786,24 @@ def test_a_non_integer_barrier_id_raises_a_typed_error() -> None: session.wait_for_activation(timeout=1.0) +def test_a_fractional_barrier_id_is_rejected_not_truncated() -> None: + # The Activated signal's `u` barrier_id, same hazard as the zones and + # failed-barriers values: int(2.9) == 2 would silently name a different + # armed barrier as the one that triggered. _spec_int refuses the float. + connection = FakeInputCaptureConnection( + pending_activated={"activation_id": 1, "barrier_id": 2.9} + ) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError): + session.wait_for_activation(timeout=1.0) + + def test_an_infinite_activation_id_raises_a_typed_error() -> None: - # int(float('inf')) raises OverflowError, which the old (ValueError, - # TypeError) guard missed -- it would have escaped a caller's - # `except PortalError`. + # A non-finite float is still a float, so _spec_int rejects it before + # int() is reached -- int(float('inf')) would raise OverflowError, which + # the original (ValueError, TypeError) guard missed and a caller's + # `except PortalError` would not have caught. connection = FakeInputCaptureConnection( pending_activated={"activation_id": float("inf")} ) diff --git a/tests/test_portal.py b/tests/test_portal.py index 90183b0..aeaad6b 100644 --- a/tests/test_portal.py +++ b/tests/test_portal.py @@ -618,6 +618,179 @@ def call_sync( source_remove.assert_not_called() +class RawResponseConnection(FakeConnection): + """Fires every Request's Response with a verbatim payload tuple. + + FakeConnection always answers in the spec's ``(u response, a{sv} + results)`` shape; this is how a test hands `_request()` a Response a + spec-conforming portal cannot send -- the same job + ``pending_activated_raw`` does for the session signals in + test_inputcapture.py's FakeInputCaptureConnection. + """ + + def __init__(self, raw: tuple[Any, ...], **kwargs: Any) -> None: + super().__init__(**kwargs) + self._raw = raw + + def call_sync( + self, + bus_name: Any, + object_path: Any, + interface: Any, + method: str, + parameters: FakeVariant | None, + reply_type: Any, + flags: Any, + timeout: Any, + cancellable: Any, + ) -> FakeReply: + self.calls.append((method, None if parameters is None else parameters.value)) + self.call_targets.append((method, bus_name, object_path, timeout)) + if parameters is None: + return FakeReply(()) + if method == "Get": + return FakeReply((self.version,)) + *_leading, options = parameters.value + token = options["handle_token"].value + path = ( + f"/org/freedesktop/portal/desktop/request/{self._escaped_sender()}/{token}" + ) + # The subscribe-before-call pattern guarantees this is registered. + callback = self._subscriptions[path] + callback(None, None, path, None, "Response", FakeReply(self._raw)) + return FakeReply((path,)) + + +def test_a_wrong_arity_response_raises_a_typed_error() -> None: + # Before the shape check, unpacking this raised ValueError *inside* the + # GLib signal callback -- where PyGI prints the traceback to stderr and + # swallows it, so no reply was ever recorded and the step silently + # degraded to a full-timeout PortalTimeoutError. Same hardening the + # session signals got in _wait_for_signal (see test_inputcapture.py's + # test_a_malformed_activated_payload_raises_a_typed_error). + connection = RawResponseConnection((0,)) + with install_fake_gi(connection): + with pytest.raises(portal.PortalProtocolError) as excinfo: + portal.RemoteDesktopSession.negotiate(connection=connection, timeout=0.01) + # `.step` is the method name, matching the PortalTimeoutError and + # PortalDeniedError raised for the same call. + assert excinfo.value.step == "CreateSession" + assert excinfo.value.payload == (0,) + # The default shape message names the *signal* payload shape, which + # would misdescribe a Response -- _request always passes its own. + assert excinfo.value.detail is not None + + +def test_a_non_integer_response_code_raises_a_typed_error() -> None: + # Arity-valid, but the response code is not the spec's `u`. Letting it + # through would misreport the step: `code != 0` on a string is simply + # True, which reads as PortalDeniedError -- "the user declined" -- for + # what is actually a non-conforming portal. + connection = RawResponseConnection(("denied", {})) + with install_fake_gi(connection): + with pytest.raises(portal.PortalProtocolError) as excinfo: + portal.RemoteDesktopSession.negotiate(connection=connection, timeout=0.01) + assert excinfo.value.step == "CreateSession" + assert excinfo.value.payload == ("denied", {}) + + +def test_a_non_dict_response_results_raises_a_typed_error() -> None: + # The other failure mode of unpacking on faith: a two-element payload + # whose `results` is not a dict sailed through _request and crashed the + # *caller's* results.get() with a raw AttributeError -- past `except + # PortalError`. FakeConnection fires whatever `responses` holds, so no + # raw-payload subclass is needed for this one. + responses: dict[str, Any] = {"CreateSession": (0, "not-a-dict")} + connection = FakeConnection(responses=responses) + with install_fake_gi(connection): + with pytest.raises(portal.PortalProtocolError) as excinfo: + portal.RemoteDesktopSession.negotiate(connection=connection, timeout=0.01) + assert excinfo.value.step == "CreateSession" + assert excinfo.value.payload == (0, "not-a-dict") + + +def test_a_response_and_the_deadline_in_one_poll_return_the_reply() -> None: + # GLib dispatches every source ready in one main-context iteration + # regardless of an earlier loop.quit(), so a Response can land in the + # same poll as the request's deadline. on_response records the reply + # and quits; on_timeout still runs, must see the wait already settled + # rather than overwrite a delivered reply with PortalTimeoutError, and + # must not have the finally block remove the source its own False + # return already deregistered. The same race _wait_for_signal already + # handles -- see test_inputcapture.py's + # test_a_signal_and_the_deadline_in_one_poll_do_not_double_remove_the_source. + class FirstRequestSilentConnection(FakeConnection): + """Leaves the first Request unanswered, for the test to deliver.""" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.race_path: str | None = None + self.race_reply: tuple[int, dict[str, Any]] | None = None + + def call_sync( + self, + bus_name: Any, + object_path: Any, + interface: Any, + method: str, + parameters: FakeVariant | None, + reply_type: Any, + flags: Any, + timeout: Any, + cancellable: Any, + ) -> FakeReply: + if self.race_path is not None or parameters is None or method == "Get": + return super().call_sync( + bus_name, + object_path, + interface, + method, + parameters, + reply_type, + flags, + timeout, + cancellable, + ) + self.calls.append((method, parameters.value)) + self.call_targets.append((method, bus_name, object_path, timeout)) + *_leading, options = parameters.value + token = options["handle_token"].value + sender = self._escaped_sender() + self.race_path = f"/org/freedesktop/portal/desktop/request/{sender}/{token}" + self.race_reply = self.responses.get(method, (0, {})) + return FakeReply((self.race_path,)) + + connection = FirstRequestSilentConnection() + + def deliver_response() -> None: + assert connection.race_path is not None + assert connection.race_reply is not None + code, results = connection.race_reply + connection._subscriptions[connection.race_path]( + None, + None, + connection.race_path, + None, + "Response", + FakeReply((code, results)), + ) + + with install_fake_gi(connection): + glib = sys.modules["gi.repository.GLib"] + FakeMainLoop.inject_before_timeout = deliver_response + with mock.patch.object(glib, "source_remove") as source_remove: + session = portal.RemoteDesktopSession.negotiate( + connection=connection, timeout=5.0 + ) + # The delivered reply wins -- negotiation ran every step to completion + # instead of raising PortalTimeoutError at CreateSession -- and the + # source the firing on_timeout already removed is not removed again. + assert session is not None + methods = [c[0] for c in connection.calls] + assert methods == ["Get", "CreateSession", "SelectDevices", "Start", "ConnectToEIS"] + source_remove.assert_not_called() + + def test_close_closes_an_unclaimed_eis_fd() -> None: # The fd arrives dup'd and owned. If nobody ever reads `eis_fd` (so it # was never handed to a Sender, which would close it itself), nothing