Files
chandra/compositor/polkit/agent.mbt
T
Claude 0feea23a06
CI / test (push) Failing after 18s
Password dialog: Chandra is its own polkit agent, drawn in the shell layer
run0, pkexec and other polkit prompts used whatever third-party agent was
installed: a plain toolkit window saying "start transient unit
'run-p15802-i1990.service'". The compositor now registers as the session's
polkit authentication agent and asks in its own dialog:

- a centered card over a dimmed screen, above all windows and client menus,
  themed (dark/light follow the Dark mode switch), keyboard-first: Enter,
  Esc, Tab order, Alt+R show/hide, Alt+D details, Ctrl+U clear
- for run0 it shows the command it will run ("gparted /dev/sda", as root)
  from run0's command line (pid from polkit's details or the unit name),
  pkexec's command from its details, polkit's message otherwise; Details
  lists the requester, target user, unit and action id
- account picker when several admins can answer (group members expanded)
- the PAM conversation through polkit-agent-helper-1: polkit 126's socket
  first, else the setuid helper on a socket pair (new sys spawn-socket on the
  native, Rust and MoonBit hosts); password, echo-on prompts, info (fingerprint)
  and errors (faillock) shown as they come; wrong password shakes and retries;
  spinner while PAM checks; Caps Lock warning
- typing through the clients' xkb keymap (groups, Shift, AltGr, Caps Lock),
  US layout when there is none
- no client has keyboard focus or input while it is up; the password is
  wiped after sending and never logged

Settings > Session > "Chandra password dialog" (state.edn :auth-agent
:system when off) switches back to the third-party agent, which
chandra-session now finds and the compositor starts (also when polkit
refuses our agent). Tests: polkit_test (keymaps, helper protocol, run0
parsing, dialog states, the socket-pair route) and auth_test (mock polkit
Authority on a private dbus-daemon, mock helper; CHANDRA_AUTH_SHOTS writes
a PNG per state). Docs: docs/auth-dialog.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgkRPrAzXECBUGmNEE
2026-11-26 00:17:04 +00:00

332 lines
11 KiB
MoonBit

///| Chandra's polkit authentication agent: registers with polkitd on the system bus for this
/// login session and queues the BeginAuthentication calls it gets, which the compositor answers
/// with its own dialog.
///
/// polkitd calls org.freedesktop.PolicyKit1.AuthenticationAgent.BeginAuthentication on the
/// agent registered for the session of whoever needs authorizing (run0, pkexec, udisks, ...).
/// The call stays unanswered until the user is done: an empty reply once the helper said
/// SUCCESS (the helper itself told polkitd who authenticated), or the error
/// org.freedesktop.PolicyKit1.Error.Cancelled when they dismissed it. polkitd can withdraw a
/// request with CancelAuthentication(cookie) (the asking process went away).
///|
pub let agent_path : String = "/org/chandra/PolicyKit1/AuthenticationAgent"
///|
pub let agent_iface : String = "org.freedesktop.PolicyKit1.AuthenticationAgent"
///|
pub let authority_name : String = "org.freedesktop.PolicyKit1"
///|
pub let authority_path : String = "/org/freedesktop/PolicyKit1/Authority"
///|
pub let authority_iface : String = "org.freedesktop.PolicyKit1.Authority"
///|
pub let err_cancelled : String = "org.freedesktop.PolicyKit1.Error.Cancelled"
///|
pub let err_failed : String = "org.freedesktop.PolicyKit1.Error.Failed"
///|
let agent_introspection : String =
#|<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
#| "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
#|<node>
#| <interface name="org.freedesktop.PolicyKit1.AuthenticationAgent">
#| <method name="BeginAuthentication">
#| <arg type="s" name="action_id" direction="in"/>
#| <arg type="s" name="message" direction="in"/>
#| <arg type="s" name="icon_name" direction="in"/>
#| <arg type="a{ss}" name="details" direction="in"/>
#| <arg type="s" name="cookie" direction="in"/>
#| <arg type="a(sa{sv})" name="identities" direction="in"/>
#| </method>
#| <method name="CancelAuthentication"><arg type="s" name="cookie" direction="in"/></method>
#| </interface>
#| <interface name="org.freedesktop.DBus.Introspectable">
#| <method name="Introspect"><arg type="s" direction="out"/></method>
#| </interface>
#| <interface name="org.freedesktop.DBus.Peer"><method name="Ping"/></interface>
#|</node>
///| A request waiting for the user, with the call to answer.
pub(all) struct Pending {
req : AuthRequest
call : @network.DMessage
}
///| The agent.
pub struct PolkitAgent {
mut bus : @network.DBus?
/// The system bus socket to use; "" finds it from the environment.
bus_path : String
mut registered : Bool
/// RegisterAuthenticationAgent was sent and not answered yet.
mut registering : Bool
/// Why registering failed (or the bus went away), "" when it didn't.
mut error : String
/// The subject to register for; None: this login session.
subject : @network.DValue?
/// Requests in the order they came; the dialog shows the first.
queue : Array[Pending]
/// Turns BeginAuthentication's arguments into a request (tests swap the passwd lookup).
make_request : (Array[@network.DValue]) -> AuthRequest?
}
///|
pub fn PolkitAgent::new(
bus_path? : String = "",
subject? : @network.DValue,
make_request? : (Array[@network.DValue]) -> AuthRequest? = AuthRequest::from_args,
) -> PolkitAgent {
{ bus: None, bus_path, registered: false, registering: false, error: "", subject, queue: [], make_request }
}
///| The subject the agent registers for: this login session (XDG_SESSION_ID, else logind's
/// session of our pid).
fn session_subject(bus : @network.DBus) -> @network.DValue? {
let mut id = @sys.getenv("XDG_SESSION_ID")
if id == "" {
let r = bus.call_sync(
@network.DMessage::call(
"org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "GetSessionByPID",
[U32(@sys.getpid().reinterpret_as_uint())],
),
1000,
)
match r {
Some({ mtype: 2, body: [Path(p)], .. }) => {
let g = bus.call_sync(
@network.DMessage::call(
"org.freedesktop.login1", p, "org.freedesktop.DBus.Properties", "Get",
[Str("org.freedesktop.login1.Session"), Str("Id")],
),
1000,
)
match g {
Some({ mtype: 2, body: [Variant(Str(s))], .. }) => id = s
_ => ()
}
}
_ => ()
}
}
if id == "" {
None
} else {
Some(Struct([Str("unix-session"), @network.dict("v", [("session-id", Variant(Str(id)))])]))
}
}
///| Connect to the system bus and ask polkitd to make us this session's agent. The answer
/// comes later (`tick`): `registered`, or `failed` with `error` (no polkit, or another agent
/// already has the session). False (with `error`) when there is no bus or session to ask for.
pub fn PolkitAgent::start(self : PolkitAgent) -> Bool {
if self.registered || self.registering {
return true
}
let path = if self.bus_path != "" { self.bus_path } else { @network.system_bus_path() }
let bus = match @network.DBus::open(path) {
Some(b) => b
None => {
self.error = "no system bus at " + path
return false
}
}
let subject = match self.subject {
Some(s) => s
None =>
match session_subject(bus) {
Some(s) => s
None => {
self.error = "no login session (XDG_SESSION_ID unset and logind doesn't know us)"
bus.close()
return false
}
}
}
bus.set_on_call(fn(m) { self.on_call(bus, m) })
let lang = if @sys.getenv("LANG") != "" { @sys.getenv("LANG") } else { "en_US.UTF-8" }
self.bus = Some(bus)
self.registering = true
self.error = ""
let serial = bus.call(
@network.DMessage::call(authority_name, authority_path, authority_iface, "RegisterAuthenticationAgent", [
subject,
Str(lang),
Str(agent_path),
]),
on_reply=fn(m) {
self.registering = false
if m.mtype == @network.method_return {
self.registered = true
} else {
self.error = m.error_text()
bus.close()
}
},
)
if serial == 0 {
self.registering = false
self.error = "could not reach polkit"
self.bus = None
return false
}
true
}
///| Registering failed or the agent lost the bus (see `error`).
pub fn PolkitAgent::failed(self : PolkitAgent) -> Bool {
!self.registered && !self.registering
}
///| Answer a call to the agent object.
fn PolkitAgent::on_call(self : PolkitAgent, bus : @network.DBus, m : @network.DMessage) -> Unit {
match (m.iface, m.meth) {
("org.freedesktop.DBus.Peer", "Ping") => bus.reply(m, [])
("org.freedesktop.DBus.Introspectable", "Introspect") =>
bus.reply(m, [Str(if m.path == agent_path { agent_introspection } else { "<node/>" })])
(i, "BeginAuthentication") if i == agent_iface || i == "" =>
if m.path != agent_path {
bus.reply_error(m, "org.freedesktop.DBus.Error.UnknownObject", "no object " + m.path)
} else {
match (self.make_request)(m.body) {
Some(req) =>
if req.users.length() == 0 {
bus.reply_error(m, err_failed, "No user to authenticate as")
} else {
self.queue.push({ req, call: m })
}
None => bus.reply_error(m, "org.freedesktop.DBus.Error.InvalidArgs", "bad arguments")
}
}
(i, "CancelAuthentication") if i == agent_iface || i == "" =>
match m.body {
[Str(cookie)] => {
self.finish(cookie, Err("Authentication was cancelled"))
bus.reply(m, [])
}
_ => bus.reply_error(m, "org.freedesktop.DBus.Error.InvalidArgs", "bad arguments")
}
_ => bus.reply_error(m, "org.freedesktop.DBus.Error.UnknownMethod", "unknown method " + m.iface + "." + m.meth)
}
}
///| Serve calls that arrived. False once the bus went away (polkitd forgets the agent then).
pub fn PolkitAgent::tick(self : PolkitAgent) -> Bool {
match self.bus {
Some(b) => {
b.pump()
if !b.alive {
self.bus = None
self.registered = false
self.registering = false
self.queue.clear()
if self.error == "" {
self.error = "the system bus went away"
}
return false
}
true
}
None => false
}
}
///| The request to show, if any.
pub fn PolkitAgent::current(self : PolkitAgent) -> AuthRequest? {
self.queue.get(0).map(p => p.req)
}
///| Whether request `cookie` is still waiting (polkitd may have cancelled it).
pub fn PolkitAgent::waiting(self : PolkitAgent, cookie : String) -> Bool {
self.queue.iter().any(p => p.req.cookie == cookie)
}
///| Answer request `cookie`: Ok once authorized, Err(message) when it was dismissed.
pub fn PolkitAgent::finish(self : PolkitAgent, cookie : String, result : Result[Unit, String]) -> Unit {
match self.queue.search_by(p => p.req.cookie == cookie) {
Some(i) => {
let p = self.queue.remove(i)
match self.bus {
Some(b) =>
match result {
Ok(_) => b.reply(p.call, [])
Err(text) => b.reply_error(p.call, err_cancelled, text)
}
None => ()
}
}
None => ()
}
}
///| The bus socket, for the main loop to wake on (-1 when not connected).
pub fn PolkitAgent::fd(self : PolkitAgent) -> Int {
match self.bus {
Some(b) => b.fd()
None => -1
}
}
///| Whether polkitd has us as the session's agent.
pub fn PolkitAgent::registered(self : PolkitAgent) -> Bool {
self.registered
}
///| Why the last start failed ("" when it didn't).
pub fn PolkitAgent::error(self : PolkitAgent) -> String {
self.error
}
///| Stop being the agent: dismiss what waits, unregister, leave the bus.
pub fn PolkitAgent::stop(self : PolkitAgent) -> Unit {
let cookies = self.queue.map(p => p.req.cookie)
for c in cookies {
self.finish(c, Err("The authentication agent stopped"))
}
match self.bus {
Some(b) => {
match (match self.subject { Some(s) => Some(s); None => session_subject(b) }) {
Some(subject) =>
ignore(
b.call_sync(
@network.DMessage::call(authority_name, authority_path, authority_iface, "UnregisterAuthenticationAgent", [
subject,
Str(agent_path),
]),
1000,
),
)
None => ()
}
b.close()
}
None => ()
}
self.bus = None
self.registered = false
self.registering = false
}
///| Ways to reach the helper, to try in order: polkit 126's socket (when
/// polkit-agent-helper.socket is enabled; connecting fails otherwise), then the setuid program.
/// CHANDRA_POLKIT_HELPER names one instead (`socket:/path` or a program path).
pub fn helper_routes() -> Array[HelperRoute] {
let h = @sys.getenv("CHANDRA_POLKIT_HELPER")
if h != "" {
return [if h.has_prefix("socket:") { Socket(h[7:].to_string()) } else { Program(h) }]
}
let out : Array[HelperRoute] = [Socket(helper_socket)]
for p in helper_paths {
if @sys.has_exe(p) {
out.push(Program(p))
break
}
}
out
}