Access dbus SessionBus in background service

I need to access the session bus of the currently logged user. Technically that could be the user that created /tmp/.X11-unix/X($DISPLAY) (ignore the colon in $DISPLAY for now but you get it).

I actually need to be able to lock my computer screen and check if its already locked from a background service (running as root) using dbus (there is an interface for that).

My current, hard-coded approach is to os.seteuid(1000) before calling dbus.SessionBus() in my code but this approach won’t work when my snap is fully confined. https://github.com/om26er/screen-brightness-server/blob/e16206de0ebce5646b11e5c96c85e21877337136/sbs/controller.py#L167

This makes me wonder if there is a need for user specific background services to avoid all that hassle.

Could this instead by an autostarted session service? That would obviate the need to drop from root to the user to talk to the session bus (not something you’d typically want to do since the user might be able to manipulate the root service since the session is under the user’s control. While on distros that support strict snaps, this is less of a problem, it would be on those distros that don’t. If the root background service must be root, then your best bet is to have a session service that talks to the server over some IPC mechanism, like a socket in SNAP_COMMON (but code your root service carefully!!).

You mean a systemd service created manually ? I had considered that but it would be a step back from my current goal: just install and go. Ultimately, I might have to go that way though.

In general, services running as root should not be directly accessing the user session: you’re generally better off running in the user session. If you still need to do some work as root, consider a daemon running on the D-Bus system bus, and an agent in the user session that communicates with it.

As far as user session services go, I’ve been working on this PR that might fit the bill for what you’re after:

https://github.com/snapcore/snapd/pull/5822

I’ve primarily been working on this to support D-Bus service activation, but the code supports general purpose systemd user session daemons with the same syntax as we support system daemons. It is still in the process of being reviewed though, so if it is close to what you need but not quite, I’d appreciate feedback.