diff --git a/CHANGELOG.md b/CHANGELOG.md index 0130add..2eacc9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,117 @@ All notable changes to python-libei are recorded here. The format follows ## [Unreleased] +## [0.8.2] - 2026-11-13 + +### Added + +- **Round-trip coverage for the socket backend, `SEAT_BIND` and + `scroll_stop`/`scroll_cancel`.** Three more groups of public names that + no test reached, found the same way as 0.8.1's sweep. + `create_for_socket()` on both sides is a whole *transport* the fd-backend + tests never take, and the only one that can answer `eis.Client.pid` — + `eis_backend_socket_get_client_pid` reads a live `SO_PEERCRED` + credential, so with client and server in one process the reported pid has + to be exactly `os.getpid()`. That symbol is libei 1.5+ while the + transport itself is on the 1.0.0 floor, so the round trip runs + everywhere and only the pid read is version-gated. `SEAT_BIND` exercises + `eis_event_seat_has_capability` at the value level, with the offer and + the bind each passing their capabilities in a different order so the + asserted result can match neither by accident. + `scroll_stop`/`scroll_cancel` set their two axes asymmetrically, so a + getter wired to the wrong axis symbol disagrees with what was sent. + +### Documented + +- **`*_get_context()` is not quite as unbound as the docs said.** The + "deliberately unbound" list in `docs/developers/architecture.md` and the + matching bullet in `docs/vs-snegg.md` both claimed the whole + `*_get_context()` family has nothing to hand back and is therefore not + bound. The two *device* variants are in fact bound and used internally: + when the caller gives `frame()` no `timestamp`, it reads the device's own + context to get one, because `ei_now()` needs a context. What is true of + all of them is that none is ever *surfaced* — a context only ever + reaches Python through its own `create_for_*()`, never wrapped from a raw + pointer — which is the claim the docs now make. The seat, keymap and + client variants stay genuinely unbound. + +- **There is no C-level logging for liboeffis.** `docs/recipes.md`'s + Logging section listed `libei.oeffis` alongside `libei.ei` and + `libei.eis` as a logger carrying routed C diagnostics. liboeffis exposes + no log-handler entry point to hook, so nothing of the sort reaches it; + that logger carries only this package's own messages. Named explicitly + rather than quietly dropped from the list, since "no output on that + logger" is otherwise indistinguishable from a library that has gone + quiet. + +### Fixed + +- **The `version` property reply is checked before it is believed.** Both + portals' version reads unpacked a `Properties.Get` reply on faith. As + everywhere in this module, `_call_sync` is given no `reply_type`, so + GDBus validates nothing about the shape that comes back — which is why + every other reply-consuming site here checks the unpacked value first. + These two did not: a reply that did not unpack to a single value raised + `ValueError` out of the tuple assignment, and a non-numeric `version` + raised `TypeError` from `int()`, both bare built-ins escaping the + `except PortalError` that `docs/troubleshooting.md` promises covers the + negotiation. They now raise `PortalProtocolError` with the reply as the + payload, like the `Response` and fd-index faults beside them. A `True` is + refused too rather than read as version 1 — `bool` is an `int`, so it + would otherwise have been reported as a portal too old for + `ConnectToEIS`, blaming the version for a reply that was nonsense. + Verified against a live portal rather than a stub: on Ubuntu 26.10 + (GNOME/Wayland) the real `org.freedesktop.portal.Desktop` answered + RemoteDesktop version 2 through this path, and six malformed shapes — + two values, none, a non-tuple, a string, a `True` and a `None` — each + arrived as a `PortalProtocolError` catchable as `PortalError`. With the + check removed, the same six produced a bare `ValueError`/`TypeError` or + silently returned the nonsense as a version. Reading a property needs no + session and so no consent dialog, which is what makes this path + reachable over a plain login. +- **A failed second signal subscription no longer leaks the first.** + `_wait_for_signal` took its two `signal_subscribe()` handles into locals + before the `try`/`finally` that unsubscribes them, so a failure in the + second left the first registered for the life of the connection with + nothing holding its handle. Collected into a list as they are made and + unsubscribed from that list, which is what `_request` already does. + +- **`ConnectToEIS`'s fd reply was trusted in three ways it should not have + been, one of which handed out `-1` as the EIS fd.** The reply is `(h)` — + an *index* into an fd list carried out-of-band — and `_call_for_fd()` + passed the index straight to `g_unix_fd_list_get()`. Measured against + GLib 2.90.1 and the Gio-2.0.gir contract, that is wrong three times + over: + + - The out fd list is **nullable**. A well-formed reply that attached no + fds arrives as `None`, and dereferencing it raised `AttributeError` + ('NoneType' object has no attribute 'get') — a name no + `except PortalError` catches. + - A bad index is a **programmer error**, not a runtime failure. + `g_unix_fd_list_get()` asserts `index >= 0 && index < nfd`, logs + `GLib-GIO-CRITICAL`, and returns `-1` *without raising and without + setting a `GError`*. So the previous attempt at hardening this — an + `except GLib.Error` around the `get()`, reporting "no matching fd" — + could never fire for the case it was written for. The `-1` flowed out + as the session's `eis_fd` instead, into an + `ei.Sender.create_for_fd()` that has no guard against a negative one, + with `close()`'s `os.close(-1)` swallowing the resulting `EBADF` at + debug level. The fix is the bounds check the GIR itself prescribes, + against `get_length()` — `lookup()` would do it in one call but is + GLib 2.90+ only. + - The one failure `get()` *does* raise for is the dup it performs to + hand back an owned fd, i.e. running out of file descriptors. That is + still caught, and the message now says so rather than blaming the + index. + + All three now raise `PortalProtocolError`, carrying the index as + `.payload`, so a caller's `except PortalError` covers the fd leg of the + negotiation as it already covered the signal payloads. The suite's + `FakeUnixFDList` grew the real semantics to match — it holds a list of + fds, returns `-1` for an out-of-range index and never raises — because + the old one ignored its index entirely, which made every index valid and + was why the gap went unnoticed. + ## [0.8.1] - 2026-11-11 ### Added diff --git a/README.md b/README.md index 39e60d3..2aa3eea 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ and why, is in ## Status -Beta (`0.8.1`), published on [PyPI](https://pypi.org/project/python-libei/) +Beta (`0.8.2`), 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/architecture.md b/docs/developers/architecture.md index 8cf906d..b9a3726 100644 --- a/docs/developers/architecture.md +++ b/docs/developers/architecture.md @@ -51,9 +51,18 @@ deliberate: instead, so text containing a NUL is not truncated. - `ei_new()` — superseded by `ei_new_sender()` / `ei_new_receiver()`. - `*_clock_set_now_func()`. -- The `*_get_context()` accessors, which have nothing to hand back: a context - is only ever created by its own `create_for_*()`, never wrapped from a raw - pointer. + +One accessor pair sits on the line between bound and not. Of the +`*_get_context()` accessors the headers export, the two device variants — +`ei_device_get_context` and `eis_device_get_context` — *are* bound and *are* +used internally: when the caller gives `frame()` no `timestamp`, it reads +the device's own context to get one (`ei_now()` needs a context). A caller +who passes a timestamp never reaches the accessor. The seat, keymap and +client variants stay unbound, and what the +package never does with the two it binds is *wrap* the returned pointer into +a `Context` object: a context only ever reaches Python through its own +`create_for_*()`, never from a raw pointer, so there is no public +`Device.context` accessor to hand one back. The gesture and stylus functions that libei's `main` branch adds -- 46 in libei and 51 in libeis against 1.6.0's headers, counted 2026-09-30: the diff --git a/docs/developers/verification.md b/docs/developers/verification.md index e3af5a4..1aa2e9a 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.1`) and the API is not frozen — expect renames +The package is beta (`0.8.2`) 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 3231484..ce151ef 100644 --- a/docs/recipes.md +++ b/docs/recipes.md @@ -337,10 +337,10 @@ against the real library. ## Logging -libei's own diagnostics are routed into Python's `logging` — the `libei.ei`, -`libei.eis` and `libei.oeffis` loggers — rather than being written to stderr -by the C library. This is how you see the warnings that otherwise look like -nothing happening at all, `device is not an absolute pointer` among them: +libei's and libeis's own diagnostics are routed into Python's `logging` — the +`libei.ei` and `libei.eis` loggers — rather than being written to stderr by the +C library. This is how you see the warnings that otherwise look like nothing +happening at all, `device is not an absolute pointer` among them: ```python import logging @@ -352,3 +352,8 @@ At `DEBUG` this is a full protocol trace (every object, message and signature, both directions — a few hundred lines for a single connect and one pointer motion), which makes it the first thing to reach for when a negotiation stalls. `WARNING` gets you just libei's complaints. + +There is no equivalent for liboeffis: it exposes no log-handler entry point to +hook, so no C-library diagnostics reach the `libei.oeffis` logger. That logger +carries only this package's own messages — a single `DEBUG` line when an oeffis +event of an unrecognised type arrives — never routed C diagnostics. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 62b50e6..e77e542 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -88,7 +88,7 @@ import each from the module that raises it. | `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.portal` | `PortalProtocolError` | What the portal sent back does not match the spec. Either a signal's payload — the `(session_handle, options)` shape, or a value inside it (`activation_id`, `cursor_position`, `barrier_id`) — or `ConnectToEIS`'s fd reply: no fd list attached to it at all, an fd index outside the list it did attach, or the dup of that fd failing because the process is out of descriptors. Carries `.step`, `.payload` (the fd index, for the fd-reply cases), and `.detail` (`None` for a signal-shape fault, a phrase naming the field or the fd fault otherwise) | | `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 diff --git a/docs/vs-snegg.md b/docs/vs-snegg.md index 43ccf33..f858a8c 100644 --- a/docs/vs-snegg.md +++ b/docs/vs-snegg.md @@ -78,11 +78,15 @@ mechanism ended up shaped the way they did. logging-context accessors, `*_event_type_to_string()`, the NUL-terminated `*_device_text_utf8()` (the `_with_length` form is bound instead, so a str containing a NUL isn't silently truncated), and the - `*_get_context()` accessors, which have nothing to return: a context is - only ever created by its own `create_for_*()`, never wrapped from a raw - pointer. The README's "What's implemented" section says the same in - user-facing terms, so a caller finds out from the docs rather than from - an `AttributeError`. + seat, keymap and client `*_get_context()` accessors. (The two *device* + variants are bound and used internally by `frame()`, but none of the + family is ever surfaced: a context is only ever created by its own + `create_for_*()`, never wrapped from a raw pointer.) The README's + "What's implemented" section covers the same ground in user-facing + terms, so a caller finds out from the docs rather than from an + `AttributeError`; which of these are bound-but-internal rather than + unbound is spelled out in + [developers/architecture.md](developers/architecture.md). - **Accessors check the event type.** libei's data accessors don't report a mismatch to the caller: `ei_event_keyboard_get_key()` on a pointer event diff --git a/pyproject.toml b/pyproject.toml index 3bbcfc4..a91b114 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "python-libei" -version = "0.8.1" +version = "0.8.2" 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 6edd5f1..324c2d5 100644 --- a/src/libei/__init__.py +++ b/src/libei/__init__.py @@ -31,6 +31,6 @@ Beta: the API is not frozen. """ -__version__ = "0.8.1" +__version__ = "0.8.2" __all__ = ["__version__"] diff --git a/src/libei/portal.py b/src/libei/portal.py index 01e2174..5419602 100644 --- a/src/libei/portal.py +++ b/src/libei/portal.py @@ -215,6 +215,15 @@ class PortalProtocolError(PortalError): ``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. + + :func:`_call_for_fd` -- both portals' ``ConnectToEIS``, whose reply is + an *index* into a separate out fd list -- raises it for + the three ways that pair can disagree: no fd list attached at all + (the out list is nullable), an index outside the list, and the dup + ``g_unix_fd_list_get()`` does failing on fd exhaustion. ``payload`` is + the index in each case. Those used to reach the caller as an + ``AttributeError``, a silent ``-1`` fd, and a raw ``GLib.Error`` + respectively -- none of them catchable as a ``PortalError``. """ def __init__(self, step: str, payload: object, detail: str | None = None) -> None: @@ -671,6 +680,27 @@ def _call_for_fd( wait on and nothing here beyond the call itself -- but it is a call to the same portal that just made the caller wait on a consent dialog, so it is bounded by the same ``timeout`` rather than by GIO's default. + + The reply carries only an *index* into a separate out fd list, and both + halves have to be checked before the index is used, because + `g_unix_fd_list_get()` will not check them for us: + + * The out fd list is **nullable** -- ``call_with_unix_fd_list_sync()`` + is specified to hand back ``NULL`` for it, so a well-formed ``(h)`` + reply with no fds attached arrives here as ``None``. Dereferencing + that raised ``AttributeError`` at the caller, outside every + ``except PortalError``. + * A bad index is a **programmer error**, not a runtime failure: + ``g_unix_fd_list_get()`` asserts ``index >= 0 && index < nfd``, + logs ``GLib-GIO-CRITICAL`` and **returns -1 without raising and + without setting a GError** (measured on GLib 2.90.1). So an + out-of-range index cannot be caught by an ``except GLib.Error``; the + -1 just flows out as the EIS fd. Gio-2.0.gir says as much and names + the two fixes: ``lookup()``, which is GLib 2.90+ only, or a bounds + check against ``get_length()`` -- the portable one, used below. + + The one real ``GLib.Error`` from ``get()`` is the dup itself failing on + an fd the list does hold, i.e. EMFILE/ENFILE. """ try: reply, fd_list = connection.call_with_unix_fd_list_sync( @@ -690,7 +720,82 @@ def _call_for_fd( raise PortalTimeoutError(method, timeout) from exc raise PortalError(f"{method} failed on the D-Bus: {exc}") from exc (handle_index,) = reply.unpack() - return fd_list.get(handle_index) + # Each of the three checks below turns something that used to escape a + # caller's `except PortalError` -- an AttributeError, a silent -1, a raw + # GLib.Error -- into the same typed protocol error _request() raises for a + # malformed Response. See this function's docstring for the GLib contract + # they are reading. + if fd_list is None: + raise PortalProtocolError( + method, + handle_index, + "it returned an fd index but attached no fd list to the reply", + ) + length = fd_list.get_length() + if handle_index < 0 or handle_index >= length: + raise PortalProtocolError( + method, + handle_index, + "the fd index it returned is out of range for the reply's fd list " + f"(index {handle_index}, {length} fd(s) attached)", + ) + try: + fd = fd_list.get(handle_index) + except _glib_error(GLib) as exc: + # The index is in range, so this is not a lookup failure: the only + # thing left for g_unix_fd_list_get() to fail at is the dup() it does + # to hand back an owned fd. + raise PortalProtocolError( + method, + handle_index, + "duplicating the fd it returned failed -- this process is out of " + f"file descriptors ({exc})", + ) from exc + if fd < 0: + # Unreachable via the bounds check above, which is the only documented + # way to get the -1 sentinel; kept so a future GLib that returns it for + # some other reason surfaces as a typed error rather than as a negative + # fd handed to ei.Sender.create_for_fd(), which does not check for one. + raise PortalProtocolError( + method, + handle_index, + f"its fd list returned no usable fd for index {handle_index} (got {fd})", + ) + return fd + + +def _portal_version(reply: Any, interface: str) -> int: + """The ``version`` property out of a `Properties.Get` reply, as an int. + + `_call_sync` is given no ``reply_type``, here as everywhere else in this + module, so GDBus validates nothing about the shape of what comes back -- + which is why every other reply-consuming site checks the unpacked value + before trusting it. These two did not: a reply that unpacked to anything + but a one-element tuple raised `ValueError`, and a ``version`` that was + not a number raised `TypeError`, both bare built-ins escaping the + `except PortalError` that `docs/troubleshooting.md` promises covers the + negotiation. + """ + unpacked = reply.unpack() + try: + (version,) = unpacked + except (ValueError, TypeError) as exc: + raise PortalProtocolError( + "Get", + unpacked, + f"{interface}'s version property is specified as a single " + f"value, and this reply is not that shape", + ) from exc + # bool before int, because bool *is* an int: a True would otherwise read + # as version 1 and be refused as "too old", blaming the portal's version + # for a reply that was nonsense. + if isinstance(version, bool) or not isinstance(version, int): + raise PortalProtocolError( + "Get", + unpacked, + f"{interface} reported a non-numeric version {version!r}", + ) + return version def _remote_desktop_version( @@ -709,8 +814,7 @@ def _remote_desktop_version( None, int(timeout * 1000), ) - (version,) = reply.unpack() - return int(version) + return _portal_version(reply, _REMOTE_DESKTOP) class RemoteDesktopSession: @@ -1092,8 +1196,7 @@ def _input_capture_version( None, int(timeout * 1000), ) - (version,) = reply.unpack() - return int(version) + return _portal_version(reply, _INPUT_CAPTURE) def _create_input_capture_session_v1( @@ -1388,35 +1491,44 @@ def on_timeout() -> bool: loop.quit() return False - subscription = connection.signal_subscribe( - busname, - interface, - signal, - _OBJECT_PATH, - None, - Gio.DBusSignalFlags.NONE, - on_signal, - None, - ) - closed_subscription = connection.signal_subscribe( - busname, - _SESSION_INTERFACE, - "Closed", - session_handle, - None, - Gio.DBusSignalFlags.NONE, - on_closed, - None, - ) - logger.debug( - "waiting up to %s for %s.%s on %s for session %s", - "forever" if timeout is None else f"{timeout:g}s", - interface, - signal, - _OBJECT_PATH, - session_handle, - ) + # Collected as they are made, and unsubscribed from the list, for + # `_request`'s reason: taking them into two locals before the try meant + # a failure in the second subscribe left the first one registered for + # the life of the connection, with nothing holding a handle to it. + subscriptions: list[Any] = [] try: + subscriptions.append( + connection.signal_subscribe( + busname, + interface, + signal, + _OBJECT_PATH, + None, + Gio.DBusSignalFlags.NONE, + on_signal, + None, + ) + ) + subscriptions.append( + connection.signal_subscribe( + busname, + _SESSION_INTERFACE, + "Closed", + session_handle, + None, + Gio.DBusSignalFlags.NONE, + on_closed, + None, + ) + ) + logger.debug( + "waiting up to %s for %s.%s on %s for session %s", + "forever" if timeout is None else f"{timeout:g}s", + interface, + signal, + _OBJECT_PATH, + session_handle, + ) if not result and not session_closed and not malformed: timeout_source = None if timeout is not None: @@ -1441,8 +1553,8 @@ def on_timeout() -> bool: if timeout_source is not None and not timeout_fired: GLib.source_remove(timeout_source) finally: - connection.signal_unsubscribe(subscription) - connection.signal_unsubscribe(closed_subscription) + for subscription in subscriptions: + connection.signal_unsubscribe(subscription) return _signal_outcome( signal, timeout, result, malformed, timed_out, session_closed ) diff --git a/tests/test_inputcapture.py b/tests/test_inputcapture.py index 2aad124..df096b8 100644 --- a/tests/test_inputcapture.py +++ b/tests/test_inputcapture.py @@ -247,6 +247,8 @@ def call_with_unix_fd_list_sync( ) -> tuple[FakeReply, FakeUnixFDList]: self.calls.append((method, parameters.value)) self.call_targets.append((method, bus_name, object_path, timeout)) + # Index 0 against a one-fd list: the only in-range pair, and now it + # has to be, since FakeUnixFDList models the real -1-on-bad-index. return FakeReply((0,)), FakeUnixFDList(self.fd_responses[method]) diff --git a/tests/test_integration_socketpair.py b/tests/test_integration_socketpair.py index d2f3800..dfe72f3 100644 --- a/tests/test_integration_socketpair.py +++ b/tests/test_integration_socketpair.py @@ -1,19 +1,28 @@ -"""End-to-end test against the real libei/libeis, entirely in-process. - -Uses the fd backend on both sides (``Eis.create_for_fd()`` + ``add_client()`` -on the server, ``ei.Sender.create_for_fd()`` on the client) -- the same -mechanism xdg-desktop-portal's RemoteDesktop implementation uses to hand a -client its EI fd, but without needing a live portal/compositor/user-consent -dialog. It's what makes this package's core injection path testable in CI -rather than only against a live desktop session -- see -``_capi/libeis.py``'s module docstring and docs/vs-snegg.md for how this -path's real signatures were worked out. +"""End-to-end tests against the real libei/libeis, entirely in-process. + +Most of these use the fd backend on both sides (``Eis.create_for_fd()`` + +``add_client()`` on the server, ``ei.Sender.create_for_fd()`` on the client) +-- the same mechanism xdg-desktop-portal's RemoteDesktop implementation uses +to hand a client its EI fd, but without needing a live +portal/compositor/user-consent dialog. It's what makes this package's core +injection path testable in CI rather than only against a live desktop session +-- see ``_capi/libeis.py``'s module docstring and docs/vs-snegg.md for how +this path's real signatures were worked out. + +``test_socket_backend_round_trips_and_reports_client_pid`` is the exception: +it drives the *socket* backend (``create_for_socket()`` on both sides), the +transport no fd-backend test can reach, and reads a client's pid off the live +peer credential -- which only the socket backend can answer. """ from __future__ import annotations +import os import select +import shutil +import tempfile import time +from pathlib import Path import pytest @@ -44,6 +53,13 @@ _SENT_EMULATING_SEQUENCE if has_symbol("libeis.so.1", "eis_set_flag") else 0 ) +# eis_backend_socket_get_client_pid is libei 1.5+; the socket transport itself +# is on the 1.0.0 floor. So test_socket_backend_round_trips_and_reports_client_pid +# runs on every version and only the pid read is gated -- the same has_symbol +# branch as above, rather than a mark that would skip the whole test on an older +# library that can still prove the transport. +_HAS_CLIENT_PID = has_symbol("libeis.so.1", "eis_backend_socket_get_client_pid") + def test_client_connects() -> None: server = eis.Eis.create_for_fd() @@ -304,3 +320,231 @@ def test_the_accessors_no_other_test_reaches_round_trip() -> None: # member of the enum is claimed. assert seen["device_type"] in tuple(eis.DeviceType) assert seen["height"] == 0 + + +def test_seat_bind_reports_the_capabilities_the_client_bound() -> None: + """``eis.Event.seat_capabilities``, read off a real SEAT_BIND event. + + The binding behind it -- ``eis_event_seat_has_capability`` -- is a + per-capability probe no other test calls at the value level, and the + ``SEAT_BIND`` accessor the suite's earlier round-trip pass missed. A wrong + symbol name or ``restype`` on it would return plausible booleans in + isolation; this catches that by having the server offer exactly three + capabilities, the client bind exactly those three, and the ``SEAT_BIND`` + event name all three and nothing else. The offer and the bind each pass + the three in a *different* non-declaration order, so the asserted result + -- (POINTER, SCROLL, BUTTON), ``DeviceCapability`` declaration order, + which is how the accessor assembles the tuple -- can match neither of + them by accident. + """ + server = eis.Eis.create_for_fd() + client_fd = server.add_client() + sender = ei.Sender.create_for_fd(client_fd, name="seatbind-probe") + + offered = ( + eis.DeviceCapability.SCROLL, + eis.DeviceCapability.BUTTON, + eis.DeviceCapability.POINTER, + ) + requested = ( + ei.DeviceCapability.BUTTON, + ei.DeviceCapability.POINTER, + ei.DeviceCapability.SCROLL, + ) + bound: tuple[eis.DeviceCapability, ...] | None = None + + deadline = time.monotonic() + 10.0 + fds: dict[int, eis.Eis | ei.Sender] = {server.fd: server, sender.fd: sender} + while bound is None and time.monotonic() < deadline: + ready, _, _ = select.select(list(fds), [], [], 0.2) + for fd in ready: + fds[fd].dispatch() + for server_event in server.events: + if server_event.event_type is eis.EventType.CLIENT_CONNECT: + server_event.client.connect() + seat = server_event.client.new_seat("seatbind-seat") + seat.configure_capabilities(offered) + seat.add() + elif server_event.event_type is eis.EventType.SEAT_BIND: + bound = server_event.seat_capabilities + for sender_event in sender.events: + if ( + sender_event.event_type is ei.EventType.SEAT_ADDED + and sender_event.seat is not None + ): + sender_event.seat.bind(requested) + + assert bound is not None, "server never saw a SEAT_BIND event" + assert bound == ( + eis.DeviceCapability.POINTER, + eis.DeviceCapability.SCROLL, + eis.DeviceCapability.BUTTON, + ) + + +def test_scroll_stop_and_cancel_round_trip() -> None: + """``scroll_stop``/``scroll_cancel`` send, and the event read on the server. + + Four C symbols no other test exercises at the value level: the client's + ``ei.Device.scroll_stop()``/``scroll_cancel()`` send path + (``ei_device_scroll_stop`` / ``ei_device_scroll_cancel``) and the server's + read of the resulting events (``eis_event_scroll_get_stop_x`` / + ``eis_event_scroll_get_stop_y``, which ``scroll_stop_event`` accepts for + both SCROLL_STOP and SCROLL_CANCEL). The two axes are set asymmetrically -- + stop on y only, cancel on x only -- so a getter wired to the wrong axis + symbol, or an accessor that read a SCROLL_CANCEL as a stop, would disagree + with the value sent. + """ + server = eis.Eis.create_for_fd() + client_fd = server.add_client() + sender = ei.Sender.create_for_fd(client_fd, name="scrollstop-probe") + + scroll_caps = (eis.DeviceCapability.POINTER, eis.DeviceCapability.SCROLL) + client_scroll_caps = (ei.DeviceCapability.POINTER, ei.DeviceCapability.SCROLL) + device_created = False + emitted = False + stop_event: eis.ScrollStopEvent | None = None + cancel_event: eis.ScrollStopEvent | None = None + + deadline = time.monotonic() + 15.0 + fds: dict[int, eis.Eis | ei.Sender] = {server.fd: server, sender.fd: sender} + while (stop_event is None or cancel_event is None) and time.monotonic() < deadline: + ready, _, _ = select.select(list(fds), [], [], 0.2) + for fd in ready: + fds[fd].dispatch() + for server_event in server.events: + kind = server_event.event_type + if kind is eis.EventType.CLIENT_CONNECT: + server_event.client.connect() + seat = server_event.client.new_seat("scrollstop-seat") + seat.configure_capabilities(scroll_caps) + seat.add() + elif kind is eis.EventType.SEAT_BIND and not device_created: + device_created = True + assert server_event.seat is not None + device = server_event.seat.new_device() + device.configure(name="scrollstop-device", capabilities=scroll_caps) + device.add() + device.resume() + elif kind is eis.EventType.SCROLL_STOP: + stop_event = server_event.scroll_stop_event + elif kind is eis.EventType.SCROLL_CANCEL: + cancel_event = server_event.scroll_stop_event + for sender_event in sender.events: + kind = sender_event.event_type + if kind is ei.EventType.SEAT_ADDED and sender_event.seat is not None: + sender_event.seat.bind(client_scroll_caps) + elif ( + # DEVICE_RESUMED, not DEVICE_ADDED: a device arrives paused, + # and ei_device_start_emulating() silently returns unless the + # device's state is RESUMED. Both events are in flight here, + # so keying off ADDED happens to work whenever one dispatch + # batch carries both -- and sends nothing at all the moment + # they split across batches. + kind is ei.EventType.DEVICE_RESUMED + and sender_event.device is not None + and ei.DeviceCapability.SCROLL in sender_event.device.capabilities + and not emitted + ): + emitted = True + client_device = sender_event.device + # scroll_stop/scroll_cancel describe the *end* of a scroll, so + # each follows a scroll_delta on the same axis within its own + # frame -- the shape libei's header documents. + client_device.start_emulating() + client_device.scroll_delta(0.0, 5.0) + client_device.scroll_stop(False, True) + client_device.frame() + client_device.scroll_delta(5.0, 0.0) + client_device.scroll_cancel(True, False) + client_device.frame() + client_device.stop_emulating() + + assert stop_event is not None, "server never received a SCROLL_STOP event" + assert cancel_event is not None, "server never received a SCROLL_CANCEL event" + assert stop_event == eis.ScrollStopEvent(stop_x=False, stop_y=True) + assert cancel_event == eis.ScrollStopEvent(stop_x=True, stop_y=False) + + +def test_socket_backend_round_trips_and_reports_client_pid() -> None: + """The socket backend -- the transport the fd-backend tests never take. + + ``eis.Eis.create_for_socket()`` + ``ei.Sender.create_for_socket()`` drive + ``eis_setup_backend_socket`` and ``ei_setup_backend_socket``, which no other + integration test reaches. A pointer motion over the socket proves it + carries real input, and -- on libei 1.5+, which added the symbol -- + ``eis.Client.pid`` reads ``eis_backend_socket_get_client_pid`` off the live + ``SO_PEERCRED`` credential. Client and server share this process, so the + reported pid must be exactly ``os.getpid()``; the fd backend has no peer + socket to ask and could not test this path at all. + """ + tmpdir = tempfile.mkdtemp(prefix="eis") + + device_created = False + client_pid: int | None = None + received_motion: eis.PointerEvent | None = None + + try: + # A short dir under the system temp root keeps the bind path well + # under the AF_UNIX sun_path limit (108 bytes), which a pytest + # tmp_path can approach. Both create_for_socket() calls belong inside + # the try: either can fail -- a bind refused, a connect refused -- and + # by then libeis may already have put the socket and its .lock in the + # dir, so a raise out here would leak the whole thing. + socket_path = Path(tmpdir, "s") + server = eis.Eis.create_for_socket(socket_path) + sender = ei.Sender.create_for_socket(socket_path, name="socket-probe") + + deadline = time.monotonic() + 15.0 + fds: dict[int, eis.Eis | ei.Sender] = {server.fd: server, sender.fd: sender} + while received_motion is None and time.monotonic() < deadline: + ready, _, _ = select.select(list(fds), [], [], 0.2) + for fd in ready: + fds[fd].dispatch() + for server_event in server.events: + kind = server_event.event_type + if kind is eis.EventType.CLIENT_CONNECT: + if _HAS_CLIENT_PID: + client_pid = server_event.client.pid + server_event.client.connect() + seat = server_event.client.new_seat("socket-seat") + seat.configure_capabilities((eis.DeviceCapability.POINTER,)) + seat.add() + elif kind is eis.EventType.SEAT_BIND and not device_created: + device_created = True + assert server_event.seat is not None + device = server_event.seat.new_device() + device.configure( + name="socket-pointer", + capabilities=(eis.DeviceCapability.POINTER,), + ) + device.add() + device.resume() + elif kind is eis.EventType.POINTER_MOTION: + received_motion = server_event.pointer_event + for sender_event in sender.events: + kind = sender_event.event_type + if kind is ei.EventType.SEAT_ADDED and sender_event.seat is not None: + sender_event.seat.bind((ei.DeviceCapability.POINTER,)) + elif ( + # DEVICE_RESUMED, not DEVICE_ADDED -- see the same branch + # in test_scroll_stop_and_cancel_round_trip: + # start_emulating() no-ops on a device that is still + # paused, which is how every device first arrives. + kind is ei.EventType.DEVICE_RESUMED + and sender_event.device is not None + and ei.DeviceCapability.POINTER in sender_event.device.capabilities + ): + sender_event.device.start_emulating().pointer_motion( + 9, 4 + ).frame().stop_emulating() + finally: + # rmtree, not rmdir: libeis leaves both the socket and a sibling + # ``.lock`` file behind, and unlinking an open AF_UNIX socket is fine + # on Linux. + shutil.rmtree(tmpdir, ignore_errors=True) + + assert received_motion is not None, "no pointer motion arrived over the socket" + assert received_motion == eis.PointerEvent(dx=9, dy=4) + if _HAS_CLIENT_PID: + assert client_pid == os.getpid() diff --git a/tests/test_portal.py b/tests/test_portal.py index aeaad6b..d477da8 100644 --- a/tests/test_portal.py +++ b/tests/test_portal.py @@ -48,11 +48,28 @@ def unpack(self) -> Any: class FakeUnixFDList: - def __init__(self, fd: int) -> None: - self._fd = fd + """Stands in for `Gio.UnixFDList`, with its real index semantics. + + `g_unix_fd_list_get()` treats a bad index as a *programmer error*: it + asserts `index >= 0 && index < nfd`, logs `GLib-GIO-CRITICAL` and + returns **-1**, without raising and without setting a `GError` + (measured on GLib 2.90.1). An earlier version of this fake ignored its + index and always handed back the one fd it held, which made every + index equally valid and hid exactly the bug `_call_for_fd`'s bounds + check exists for. `get_length()` is what that check reads -- the + portable alternative to `lookup()`, which is GLib 2.90+ only. + """ + + def __init__(self, *fds: int) -> None: + self._fds = list(fds) + + def get_length(self) -> int: + return len(self._fds) - def get(self, _index: int) -> int: - return self._fd + def get(self, index: int) -> int: + if index < 0 or index >= len(self._fds): + return -1 + return self._fds[index] class FakeGLibError(Exception): @@ -70,6 +87,19 @@ def __init__(self, message: str = "", domain: str = "", code: int = 0) -> None: self.code = code +class FailingDupUnixFDList(FakeUnixFDList): + """A list that holds the fd but cannot dup it: EMFILE/ENFILE. + + The *only* way a real `g_unix_fd_list_get()` raises `GLib.Error` for an + in-range index -- it dups the fd to hand back an owned one, and that + dup can fail when the process is out of descriptors. Kept separate from + FakeUnixFDList so the common fake stays honest about never raising. + """ + + def get(self, index: int) -> int: + raise FakeGLibError("Too many open files") + + _OPEN_PIPES: list[tuple[int, int]] = [] @@ -271,6 +301,8 @@ def call_with_unix_fd_list_sync( ) -> tuple[FakeReply, FakeUnixFDList]: self.calls.append((method, parameters.value)) self.call_targets.append((method, bus_name, object_path, timeout)) + # Index 0 against a one-fd list: the only in-range pair, and now it + # has to be, since FakeUnixFDList models the real -1-on-bad-index. return FakeReply((0,)), FakeUnixFDList(self.fd_responses[method]) @@ -371,6 +403,48 @@ def test_old_remote_desktop_version_is_refused() -> None: ] +def test_a_non_numeric_version_property_raises_a_portal_error() -> None: + # `_call_sync` is given no reply_type -- as everywhere in this module -- + # so GDBus validates nothing about the shape that comes back, and every + # other reply-consuming site checks the unpacked value before trusting + # it. These two did not: `int(version)` on a string raised a bare + # TypeError/ValueError, escaping the `except PortalError` that + # docs/troubleshooting.md promises covers the negotiation. + connection = FakeConnection(version="three") # type: ignore[arg-type] + with install_fake_gi(connection): + with pytest.raises(portal.PortalProtocolError) as excinfo: + portal.RemoteDesktopSession.negotiate(connection=connection) + assert "non-numeric version" in str(excinfo.value) + assert excinfo.value.step == "Get" + + +def test_a_version_reply_of_the_wrong_shape_raises_a_portal_error() -> None: + # The other half: a reply that does not unpack to a one-element tuple + # raised ValueError out of the tuple assignment itself. + class WrongShape(FakeConnection): + def call_sync(self, *args: Any, **kwargs: Any) -> FakeReply: + if args[3] == "Get": + self.calls.append(("Get", None)) + return FakeReply(()) + return super().call_sync(*args, **kwargs) + + connection = WrongShape() + with install_fake_gi(connection): + with pytest.raises(portal.PortalProtocolError) as excinfo: + portal.RemoteDesktopSession.negotiate(connection=connection) + assert "not that shape" in str(excinfo.value) + + +def test_a_bool_is_not_accepted_as_a_version() -> None: + # bool is an int subclass, so a `True` would otherwise read as version 1 + # and be refused with the wrong error -- a version check that says "too + # old" about a portal that answered nonsense. + connection = FakeConnection(version=True) + with install_fake_gi(connection): + with pytest.raises(portal.PortalProtocolError): + portal.RemoteDesktopSession.negotiate(connection=connection) + + def test_declined_create_session_raises_portal_denied_error() -> None: connection = FakeConnection(responses={"CreateSession": (1, {})}) with install_fake_gi(connection): @@ -1005,6 +1079,123 @@ def call_with_unix_fd_list_sync( assert _closed_sessions(connection) == ["/session/1"] +class _FixedFdReplyConnection(FakeConnection): + """A FakeConnection whose ConnectToEIS reply is dictated per test. + + `ConnectToEIS` is specified as returning `(h)` -- an *index* into an fd + list the reply carries out-of-band -- and the three ways that pair can + disagree are what the tests below drive. Each subclass fixes + `reply_index` and `out_fd_list` (`None` modelling the nullable out + list) and changes nothing else about the negotiation, so what the + assertion sees is only the fd-reply handling. + """ + + reply_index: int = 0 + out_fd_list: Any = None + + def call_with_unix_fd_list_sync( + self, + bus_name: Any, + object_path: Any, + interface: Any, + method: str, + parameters: FakeVariant, + reply_type: Any, + flags: Any, + timeout: Any, + fd_list: Any, + cancellable: Any, + ) -> tuple[FakeReply, Any]: + self.calls.append((method, parameters.value)) + self.call_targets.append((method, bus_name, object_path, timeout)) + return FakeReply((self.reply_index,)), self.out_fd_list + + +def test_connect_to_eis_with_no_out_fd_list_raises_typed() -> None: + # GDBusProxy/GDBusConnection's out fd list is nullable: a well-formed + # `(h)` reply that attached no fds at all arrives as None. Dereferencing + # that used to raise AttributeError ('NoneType' object has no attribute + # 'get') from inside negotiate(), which no `except PortalError` catches. + class NoFdListConnection(_FixedFdReplyConnection): + out_fd_list = None + + connection = NoFdListConnection() + with install_fake_gi(connection): + with pytest.raises(portal.PortalProtocolError) as excinfo: + portal.RemoteDesktopSession.negotiate(connection=connection) + assert excinfo.value.step == "ConnectToEIS" + assert excinfo.value.payload == 0 + assert "attached no fd list" in str(excinfo.value) + # The session was approved before this failed, so it still has to be + # closed on the way out. + assert _closed_sessions(connection) == ["/session/1"] + + +def test_connect_to_eis_with_an_out_of_range_fd_index_raises_typed() -> None: + # The case the previous version of this test got wrong. An out-of-range + # index is a *programmer error* to g_unix_fd_list_get(): it logs + # GLib-GIO-CRITICAL and returns -1 without raising and without setting a + # GError (measured, GLib 2.90.1). So nothing is thrown to catch -- the -1 + # simply flowed out as the EIS fd, and ei.Sender.create_for_fd() has no + # guard against a negative one. Only a bounds check against get_length() + # catches this, which is why this test fails against the pre-fix + # _call_for_fd: it returned -1 and negotiate() succeeded. + class OutOfRangeConnection(_FixedFdReplyConnection): + reply_index = 1 # one past the end of the one-fd list below + + connection = OutOfRangeConnection() + connection.out_fd_list = FakeUnixFDList(_fresh_fd()) + with install_fake_gi(connection): + with pytest.raises(portal.PortalProtocolError) as excinfo: + portal.RemoteDesktopSession.negotiate(connection=connection) + assert excinfo.value.step == "ConnectToEIS" + assert excinfo.value.payload == 1 + # The message has to name both numbers: an index alone does not say + # whether it was one past the end or wildly wrong. + assert "index 1, 1 fd(s) attached" in str(excinfo.value) + assert _closed_sessions(connection) == ["/session/1"] + + +def test_connect_to_eis_raises_typed_when_duplicating_the_fd_fails() -> None: + # The one real GLib.Error from an *in-range* get(): the function dups the + # fd to hand back an owned one, and the dup fails at EMFILE/ENFILE. Left + # bare it would reach the caller as the raw GLib type, past every + # `except PortalError`. The message must say what it is -- fd exhaustion + # -- and not "no matching fd", which is the case the bounds check above + # already took. + class ExhaustedFdConnection(_FixedFdReplyConnection): + reply_index = 0 + + connection = ExhaustedFdConnection() + connection.out_fd_list = FailingDupUnixFDList(_fresh_fd()) + with install_fake_gi(connection): + with pytest.raises(portal.PortalProtocolError) as excinfo: + portal.RemoteDesktopSession.negotiate(connection=connection) + assert excinfo.value.step == "ConnectToEIS" + assert excinfo.value.payload == 0 + assert "out of file descriptors" in str(excinfo.value) + assert _closed_sessions(connection) == ["/session/1"] + + +def test_connect_to_eis_resolves_the_index_against_the_fd_list() -> None: + # The happy path, with the index doing real work: two fds attached and + # the reply naming the *second*, so an implementation that bounds-checked + # and then returned the wrong element -- or hardcoded index 0, which + # every other test in this file would still pass -- is caught. + wanted = _fresh_fd() + + class TwoFdConnection(_FixedFdReplyConnection): + reply_index = 1 + + connection = TwoFdConnection() + connection.out_fd_list = FakeUnixFDList(_fresh_fd(), wanted) + with install_fake_gi(connection): + session = portal.RemoteDesktopSession.negotiate(connection=connection) + assert session.eis_fd == wanted + session.close() + assert _closed_sessions(connection) == ["/session/1"] + + def test_an_interrupted_consent_dialog_closes_the_portal_session() -> None: # Why the cleanup catches BaseException: Start blocks on a user, so # Ctrl-C during that wait is a routine way out of negotiate() -- and it