diff --git a/CHANGELOG.md b/CHANGELOG.md index b95752e..2df850a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,36 @@ All notable changes to python-libei are recorded here. The format follows ## [Unreleased] +### Added + +- **A malformed portal signal payload now raises the new typed + `PortalProtocolError` instead of hanging or crashing the caller.** Every + signal `wait_for_activation()` and `wait_for_deactivation()` wait on is + specified as `(o session_handle, a{sv} options)`, and that shape used to + be unpacked on faith, failing differently depending on how it was wrong: + an empty tuple raised `IndexError` inside the GLib signal callback — where + PyGI prints the traceback to stderr and swallows it, so the loop kept + running and the wait hung (unboundedly, with `timeout=None`), the worst + case because it was invisible; a wrong-length tuple or a non-dict options + value instead slipped through to the caller and crashed it with + `ValueError`/`AttributeError`. The shape is now checked in one place and + any mismatch ends the wait with `PortalProtocolError`, naming the signal + and the payload that arrived. The value level is covered too: every field + the spec types — `activation_id` (`u`), `cursor_position` (`(dd)`, now + checked for exactly two numeric components rather than any iterable), + `barrier_id` (`u`) — is converted under one guard, so a non-conforming + value in any of them raises the same typed error (including the + `OverflowError` an infinite `activation_id` would otherwise throw past an + `except PortalError`) rather than crashing the caller later doing + arithmetic on a string. One `except PortalProtocolError` therefore covers + every way a non-conforming portal can malform one of these signals. The + error carries `.step` (the signal name, the attribute every sibling + portal error uses), `.payload`, and `.detail` (`None` for a shape fault, + a phrase naming the field for a value fault). Signals and the wait's + deadline or a session close that become ready in the same GLib + main-context iteration now resolve to whichever outcome was recorded + first, rather than a delivered activation being dropped for a timeout. + ## [0.7.0] - 2026-10-16 ### Added diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 22c0e65..62b50e6 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -87,15 +87,18 @@ import each from the module that raises it. | `libei.portal` | `PortalVersionError` | The RemoteDesktop portal is too old to offer `ConnectToEIS` | | `libei.portal` | `PortalTimeoutError` | A step was accepted and never answered. Carries `.step` and `.timeout` | | `libei.portal` | `PortalDeniedError` | `CreateSession`, `SelectDevices` or `Start` came back non-zero — an explicit decline, or any other code the spec does not distinguish from one. Carries `.step` and `.message` | +| `libei.portal` | `PortalSessionClosedError` | The session was ended from the compositor's side while a wait was outstanding — a restart, the portal dying, capture revoked from a settings panel. Carries `.step` | +| `libei.portal` | `PortalProtocolError` | A portal signal's payload does not match the spec — either the `(session_handle, options)` shape or a value inside it (`activation_id`, `cursor_position`, `barrier_id`). Carries `.step`, `.payload`, and `.detail` (`None` for a shape fault, a phrase naming the field for a value fault) | | `libei.ei`, `libei.eis`, `libei.oeffis` | `LibraryNotFoundError` | The native library is missing or too old to export the function being called. A `RuntimeError`, and raised at the first *call* — see below | Which of those to catch depends on the families, because they do not nest under a single base: -- **`except PortalError`** covers `PortalVersionError`, `PortalTimeoutError` - and `PortalDeniedError`. `PortalTimeoutError` is the one to think about before - treating it as a failure: the call is still outstanding, and by far the most - common cause is a consent dialog a user has not answered yet. +- **`except PortalError`** covers `PortalVersionError`, `PortalTimeoutError`, + `PortalDeniedError`, `PortalSessionClosedError` and `PortalProtocolError`. + `PortalTimeoutError` is the one to think about before treating it as a + failure: the call is still outstanding, and by far the most common cause is a + consent dialog a user has not answered yet. - **`except DisconnectedError`** covers `SessionClosedError` too. That one is not an error in libei's view — the session ended normally — which is why it has its own class rather than reusing its base. diff --git a/src/libei/portal.py b/src/libei/portal.py index cce9235..6b2ac58 100644 --- a/src/libei/portal.py +++ b/src/libei/portal.py @@ -90,6 +90,8 @@ "PortalVersionError", "PortalDeniedError", "PortalTimeoutError", + "PortalSessionClosedError", + "PortalProtocolError", "RemoteDesktopSession", "Activation", "InputCaptureSession", @@ -185,6 +187,45 @@ def __init__(self, step: str, message: str | None = None) -> None: self.message = message +class PortalProtocolError(PortalError): + """A portal signal arrived with a payload that does not match the spec. + + Every signal :func:`_wait_for_signal` waits on is specified as + ``(o session_handle, a{sv} options)``, and two kinds of mismatch used + to fail in two different, equally unhelpful ways. The *shape* being + wrong -- an empty tuple, a non-string handle, a wrong-length tuple, a + non-dict options -- either raised ``IndexError`` *inside* the GLib + signal callback, where PyGI prints the traceback to stderr and + swallows it so the wait hung invisibly (unboundedly, with + ``timeout=None``), or slipped through to the caller and crashed it with + ``ValueError``/``AttributeError``. A *value* inside a correctly-shaped + options being wrong -- an ``activation_id`` that is not an integer, a + ``cursor_position`` that is not two numbers -- crashed the caller later + still, doing arithmetic on it. Both now end the wait with this error. + + ``detail`` distinguishes the two: ``None`` for a shape fault (the + 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. + """ + + def __init__(self, step: str, payload: object, detail: str | None = None) -> None: + """Name the signal, what arrived, and -- for a value fault -- which.""" + reason = detail or ( + "the portal spec gives it the shape (session_handle, options dict)" + ) + super().__init__( + f"{step} arrived with a malformed payload: {reason}, got {payload!r}" + ) + # `step` mirrors the attribute every sibling portal error raised + # from the same `_wait_for_signal` call site carries + # (PortalTimeoutError, PortalSessionClosedError), so a caller that + # catches PortalError and reads `.step` works across all of them. + self.step = step + self.payload = payload + self.detail = detail + + class PortalSessionClosedError(PortalError): """The portal session ended while something was still waiting on it. @@ -1021,6 +1062,88 @@ def _create_input_capture_session_v1( return session_handle +def _classify_signal_payload( + args: tuple[Any, ...], session_handle: str, signal: str +) -> str: + """How `_wait_for_signal` should treat one unpacked signal payload. + + ``"take"`` -- it is this session's, correctly shaped, record it. + ``"drop"`` -- another session's; keep waiting (logged, since a dropped + signal is otherwise indistinguishable from one that never fired). + ``"malformed"`` -- not the ``(o session_handle, a{sv} options)`` shape + the spec gives every signal here; the session filter runs *between* the + two shape checks on purpose, so a malformed payload for another session + is still dropped rather than raised in this waiter. + """ + if not args or not isinstance(args[0], str): + return "malformed" + if args[0] != session_handle: + logger.debug( + "ignoring %s for session %s while waiting for %s", + signal, + args[0], + session_handle, + ) + return "drop" + if len(args) != 2 or not isinstance(args[1], dict): + return "malformed" + return "take" + + +def _deactivation_id(options: dict[str, Any], signal: str) -> int: + """The ``activation_id`` from Deactivated's options, as the spec's ``u``. + + ``_wait_for_signal`` checks the payload's *shape* -- that options is a + 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. + """ + try: + return int(options.get("activation_id", 0)) + except (ValueError, TypeError, OverflowError) as exc: + raise PortalProtocolError( + signal, options, "activation_id is not an integer" + ) from exc + + +def _activation_from_options(options: dict[str, Any], signal: str) -> Activation: + """Build an :class:`Activation` from Activated's options, spec-typed. + + The companion to the shape check in ``_wait_for_signal`` for the value + level: every field the portal spec types is converted here under one + guard, so a non-conforming value in any of them -- an ``activation_id`` + that is not a ``u``, a ``cursor_position`` that is not two ``d``s, a + ``barrier_id`` that is not a ``u`` -- becomes the same typed + :class:`PortalProtocolError` rather than a crash in the caller later, + doing arithmetic on a string. One guard rather than three means the + next field added to the signal is validated by construction, not by a + fourth hand-rolled check nobody remembers to write. + """ + try: + activation_id = int(options.get("activation_id", 0)) + cursor = options.get("cursor_position") + if cursor is None: + cursor_position = None + else: + 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) + except (ValueError, TypeError, OverflowError) as exc: + raise PortalProtocolError( + signal, options, "an option value is not the type the spec gives it" + ) from exc + return Activation( + activation_id=activation_id, + cursor_position=cursor_position, + barrier_id=barrier_id, + ) + + def _wait_for_signal( connection: Any, Gio: Any, @@ -1056,12 +1179,31 @@ def _wait_for_signal( D-Bus specification restricts plain ``arg0=`` match rules to arguments of type STRING, and this one is an OBJECT_PATH, which is the same shape of silent non-delivery all over again. + + A payload that does not match the spec's ``(o session_handle, a{sv} + options)`` shape raises :class:`PortalProtocolError` rather than being + unpacked on faith -- see that class for why the alternative was not an + exception but a hang. """ loop = GLib.MainLoop() result: dict[str, Any] = {} + malformed: dict[str, Any] = {} timed_out = False session_closed = False + def _settled() -> bool: + """Whether some terminal outcome has already been recorded. + + GLib dispatches every source ready in one main-context iteration, + regardless of an earlier ``loop.quit()``, so two outcomes -- a + signal and the timeout, a signal and Closed -- can both fire in the + same poll. Every callback checks this first so the *first* recorded + outcome wins and the post-loop raise order is never handed a second + one to misreport (a delivered activation dropped for a timeout, a + protocol fault overwritten by session-closed). + """ + return bool(result) or bool(malformed) or timed_out or session_closed + def on_closed(*_args: Any) -> None: """End the wait: a closed session can never deliver the signal. @@ -1076,7 +1218,7 @@ def on_closed(*_args: Any) -> None: that merely had not fired yet. """ nonlocal session_closed - if result: + if _settled(): return logger.debug("session %s closed while waiting for %s", session_handle, signal) session_closed = True @@ -1092,21 +1234,22 @@ def on_signal( *_a: Any, ) -> None: """Record the first matching signal; anything else is logged and dropped.""" - if result: # a subscription that outlives its own wait can fire twice + if _settled(): # a subscription outliving its wait fires twice return args = params.unpack() - if args[0] != session_handle: - # Logged, not silently dropped: this filter can hide a signal - # that *did* arrive just as effectively as the wrong-path - # subscription above did, and the two are indistinguishable - # from the outside -- both look exactly like a compositor that - # never fired. One debug line is what tells them apart. - logger.debug( - "ignoring %s for session %s while waiting for %s", - signal, - args[0], - session_handle, - ) + # The verdict is computed by `_classify_signal_payload`, but ACTED + # on here and the error raised only after the loop, because this + # runs inside a GLib callback: PyGI prints an exception raised here + # to stderr and swallows it, so a bare raise on a malformed payload + # would leave the loop running -- a timeout at best, an unbounded + # hang with timeout=None, both indistinguishable from a compositor + # that never fired. + verdict = _classify_signal_payload(args, session_handle, signal) + if verdict == "drop": + return + if verdict == "malformed": + malformed["args"] = args + loop.quit() return logger.debug("received %s for session %s", signal, session_handle) result["args"] = args @@ -1115,6 +1258,11 @@ def on_signal( def on_timeout() -> bool: """Stop the loop and record that it timed out rather than finished.""" nonlocal timed_out + if _settled(): + # A signal delivered in the same poll as the deadline has + # already recorded its outcome; the timeout must not overwrite + # a real activation with PortalTimeoutError. + return False timed_out = True loop.quit() return False @@ -1148,7 +1296,7 @@ def on_timeout() -> bool: session_handle, ) try: - if not result and not session_closed: + if not result and not session_closed and not malformed: timeout_source = None if timeout is not None: timeout_source = GLib.timeout_add(int(timeout * 1000), on_timeout) @@ -1169,8 +1317,31 @@ def on_timeout() -> bool: finally: connection.signal_unsubscribe(subscription) connection.signal_unsubscribe(closed_subscription) + return _signal_outcome( + signal, timeout, result, malformed, timed_out, session_closed + ) + + +def _signal_outcome( + signal: str, + timeout: float | None, + result: dict[str, Any], + malformed: dict[str, Any], + timed_out: bool, + session_closed: bool, +) -> tuple[Any, ...]: + """Raise for the terminal outcome `_wait_for_signal` recorded, or return it. + + Order is load-bearing and matches the callbacks' `_settled` guard: + whichever outcome was recorded first is the only one set, so this order + only ever decides between genuinely simultaneous dispatches, where a + session that has closed or a payload that was malformed is the more + useful answer than "timed out". + """ if session_closed: raise PortalSessionClosedError(signal) + if malformed: + raise PortalProtocolError(signal, malformed["args"]) if timed_out: # timed_out is only ever set inside on_timeout, itself only ever # registered when timeout is not None -- so this always holds, but @@ -1497,12 +1668,7 @@ def wait_for_activation(self, timeout: float | None = None) -> Activation: self.session_handle, timeout, ) - cursor = options.get("cursor_position") - return Activation( - activation_id=int(options.get("activation_id", 0)), - cursor_position=tuple(cursor) if cursor is not None else None, - barrier_id=options.get("barrier_id"), - ) + return _activation_from_options(options, "Activated") def wait_for_deactivation(self, timeout: float | None = None) -> int: """Block until the current capture ends, returning its activation_id.""" @@ -1520,7 +1686,7 @@ def wait_for_deactivation(self, timeout: float | None = None) -> int: self.session_handle, timeout, ) - return int(options.get("activation_id", 0)) + return _deactivation_id(options, "Deactivated") def close(self) -> None: """End the portal session, and close the EIS fd if unclaimed. diff --git a/tests/test_inputcapture.py b/tests/test_inputcapture.py index b3b04fc..6be1c63 100644 --- a/tests/test_inputcapture.py +++ b/tests/test_inputcapture.py @@ -84,6 +84,8 @@ def __init__( pending_deactivated: dict[str, Any] | None = None, signal_session_handle: str | None = None, pending_closed: bool = False, + pending_activated_raw: tuple[Any, ...] | None = None, + pending_deactivated_raw: tuple[Any, ...] | None = None, ) -> None: self.session_handle = session_handle self.signal_session_handle = signal_session_handle or session_handle @@ -107,6 +109,12 @@ def __init__( self._pending_activated = pending_activated self._pending_deactivated = pending_deactivated self._pending_closed = pending_closed + # Delivered VERBATIM as the signal's whole parameter tuple, unlike + # pending_activated, which is an options dict the fake wraps in the + # correct (session_handle, options) shape -- this is how a test + # hands the waiter a payload a spec-conforming portal cannot send. + self._pending_activated_raw = pending_activated_raw + self._pending_deactivated_raw = pending_deactivated_raw # A permanent log, unlike _subscriptions: signal_unsubscribe removes # an entry from that (correctly -- see its own docstring), so a test # checking *what was subscribed to* after the fact needs a record @@ -178,10 +186,20 @@ def signal_subscribe( self._pending_reply = None _path, code, results = pending callback(None, None, path, None, "Response", FakeReply((code, results))) + elif signal == "Activated" and self._pending_activated_raw is not None: + raw = self._pending_activated_raw + self._pending_activated_raw = None + callback(None, None, portal._OBJECT_PATH, None, "Activated", FakeReply(raw)) elif signal == "Activated" and self._pending_activated is not None: payload = self._pending_activated self._pending_activated = None self._emit_session_signal(callback, "Activated", payload) + elif signal == "Deactivated" and self._pending_deactivated_raw is not None: + raw = self._pending_deactivated_raw + self._pending_deactivated_raw = None + callback( + None, None, portal._OBJECT_PATH, None, "Deactivated", FakeReply(raw) + ) elif signal == "Deactivated" and self._pending_deactivated is not None: payload = self._pending_deactivated self._pending_deactivated = None @@ -566,6 +584,166 @@ def test_wait_for_activation_tolerates_a_missing_barrier_id() -> None: assert activation.barrier_id is None +def test_a_malformed_activated_payload_raises_a_typed_error() -> None: + # An empty payload cannot even be matched to a session, so it is broken + # for every possible waiter. Before the shape checks this was an + # IndexError *inside* the GLib callback -- which PyGI prints and + # swallows, so the wait hung (timeout=None) or timed out, both + # indistinguishable from a compositor that never fired. + connection = FakeInputCaptureConnection(pending_activated_raw=()) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError) as excinfo: + session.wait_for_activation(timeout=1.0) + # `.step` is the attribute every sibling portal error raised from the + # same call site carries, so a caller that catches PortalError and reads + # `.step` works for this one too (PortalTimeoutError/SessionClosedError). + assert excinfo.value.step == "Activated" + assert excinfo.value.payload == () + # A shape fault, so no value-level detail. + assert excinfo.value.detail is None + + +def test_a_malformed_deactivated_payload_raises_a_typed_error() -> None: + # Same shape check, the other signal: wait_for_deactivation goes through + # the identical _wait_for_signal, and nothing else exercises its + # malformed branch (the timeout/closed paths test both signals, so this + # one should too). + connection = FakeInputCaptureConnection(pending_deactivated_raw=("/session/1",)) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError) as excinfo: + session.wait_for_deactivation(timeout=1.0) + assert excinfo.value.step == "Deactivated" + assert excinfo.value.payload == ("/session/1",) + + +def test_a_non_integer_activation_id_raises_a_typed_error() -> None: + # Shape-valid payload (a dict), but activation_id is not the `u` the + # spec promises -- this passes _wait_for_signal's shape check and used + # to crash the caller with ValueError on int(). It is now the same + # typed error as a shape violation, and carries a value-level detail so + # its message does not misdiagnose a correct shape. + connection = FakeInputCaptureConnection( + pending_activated={"activation_id": "not-a-number"} + ) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError) as excinfo: + session.wait_for_activation(timeout=1.0) + assert excinfo.value.step == "Activated" + assert excinfo.value.detail is not None + assert "shape" not in str(excinfo.value) + + +def test_a_non_iterable_cursor_position_raises_a_typed_error() -> None: + # cursor_position is `(dd)`; a scalar here would crash the caller with + # TypeError unpacking it. Guarded into PortalProtocolError too. + connection = FakeInputCaptureConnection( + pending_activated={"activation_id": 1, "cursor_position": 5} + ) + 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_a_wrong_arity_cursor_position_raises_a_typed_error() -> None: + # (dd) is exactly two: tuple("ab") would not raise, so the old guard let + # a wrong-arity or stringly-typed cursor through as a bad Activation. + # The explicit two-element unpack rejects it. + for bad in ("ab", (1.0,), (1.0, 2.0, 3.0)): + connection = FakeInputCaptureConnection( + pending_activated={"activation_id": 1, "cursor_position": bad} + ) + 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_a_non_numeric_cursor_component_raises_a_typed_error() -> None: + connection = FakeInputCaptureConnection( + pending_activated={"activation_id": 1, "cursor_position": ("x", "y")} + ) + 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_a_non_integer_barrier_id_raises_a_typed_error() -> None: + # barrier_id is a `u` the caller compares against the ids it armed; a + # string here used to pass straight through into a type-violating + # Activation that mismatched silently or crashed on arithmetic later. + connection = FakeInputCaptureConnection( + pending_activated={"activation_id": 1, "barrier_id": "b-3"} + ) + 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`. + connection = FakeInputCaptureConnection( + pending_activated={"activation_id": float("inf")} + ) + 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_a_non_integer_deactivation_id_raises_a_typed_error() -> None: + connection = FakeInputCaptureConnection( + pending_deactivated={"activation_id": "not-a-number"} + ) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError) as excinfo: + session.wait_for_deactivation(timeout=1.0) + assert excinfo.value.step == "Deactivated" + + +def test_an_options_payload_that_is_not_a_dict_raises_a_typed_error() -> None: + # The right session's signal, but options is not the a{sv} the spec + # promises -- before the shape checks this surfaced wherever the caller + # happened to poke the payload (an AttributeError on .get here). + connection = FakeInputCaptureConnection(pending_activated_raw=("/session/1", 42)) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError) as excinfo: + session.wait_for_activation(timeout=1.0) + assert "Activated" in str(excinfo.value) + assert excinfo.value.payload == ("/session/1", 42) + + +def test_a_non_string_session_handle_raises_a_typed_error() -> None: + connection = FakeInputCaptureConnection(pending_activated_raw=(7, {})) + 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_a_payload_with_an_extra_trailing_field_raises_a_typed_error() -> None: + # The right session and a valid options dict, but a third field the + # spec's (o, a{sv}) shape has no room for -- pins the `len(args) != 2` + # clause on its own, which the not-a-dict case above does not reach. + connection = FakeInputCaptureConnection( + pending_activated_raw=("/session/1", {}, "extra") + ) + with install_fake_gi(connection): + session = portal.InputCaptureSession.negotiate(connection=connection) + with pytest.raises(portal.PortalProtocolError) as excinfo: + session.wait_for_activation(timeout=1.0) + assert excinfo.value.payload == ("/session/1", {}, "extra") + + def test_wait_for_activation_times_out_with_no_signal() -> None: connection = FakeInputCaptureConnection() with install_fake_gi(connection):