Files
chandra/compositor/polkit/helper.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

228 lines
6.7 KiB
MoonBit

///| The PAM conversation, through polkit's helper.
///
/// polkit authenticates with `polkit-agent-helper-1` (part of polkit, run as root). An agent
/// talks to it one line at a time: the helper writes what PAM asks or says,
/// PAM_PROMPT_ECHO_OFF <prompt> (a password: answer with one line)
/// PAM_PROMPT_ECHO_ON <prompt> (a visible answer, say a user name or a one-time code)
/// PAM_ERROR_MSG <text> / PAM_TEXT_INFO <text> (messages, no answer)
/// SUCCESS / FAILURE (the end; on success the helper has told polkitd itself)
/// with the text escaped as g_strescape does. There are two ways to start it:
/// - polkit 126+ (systemd): connect to /run/polkit/agent-helper.socket and send the user name and
/// the cookie, one line each (socket activation; no setuid binary).
/// - otherwise run the setuid helper with the user name as its argument and send the cookie.
///| What the helper said.
pub(all) enum HelperEvent {
PromptEchoOff(String)
PromptEchoOn(String)
ErrorMsg(String)
TextInfo(String)
Success
Failure
} derive(Eq, Debug)
///| Undo g_strescape: \n \t \r \b \f \v \\ \" and octal \NNN (bytes, re-read as UTF-8).
pub fn unescape(s : String) -> String {
let out : Array[Byte] = []
let cs = chars_of(s)
let push_char = fn(c : Char) {
let b = @utf8.encode(c.to_string())
for i = 0; i < b.length(); i = i + 1 {
out.push(b[i])
}
}
let mut i = 0
while i < cs.length() {
let c = cs[i]
if c != '\\' || i + 1 >= cs.length() {
push_char(c)
i = i + 1
continue
}
let d = cs[i + 1]
if d >= '0' && d <= '7' {
let mut v = 0
let mut k = 0
while k < 3 && i + 1 + k < cs.length() && cs[i + 1 + k] >= '0' && cs[i + 1 + k] <= '7' {
v = v * 8 + (cs[i + 1 + k].to_int() - '0'.to_int())
k = k + 1
}
out.push((v & 0xff).to_byte())
i = i + 1 + k
continue
}
let r = match d {
'n' => '\n'
't' => '\t'
'r' => '\r'
'b' => '\b'
'f' => '\u{0c}'
'v' => '\u{0b}'
_ => d
}
push_char(r)
i = i + 2
}
@utf8.decode_lossy(Bytes::from_array(out))
}
///| Parse one line from the helper (without its newline). None for lines we don't know.
pub fn parse_helper_line(line : String) -> HelperEvent? {
let after = fn(p : String) { unescape(line[p.length():].to_string()) }
if line.has_prefix("PAM_PROMPT_ECHO_OFF ") {
Some(PromptEchoOff(after("PAM_PROMPT_ECHO_OFF ")))
} else if line.has_prefix("PAM_PROMPT_ECHO_ON ") {
Some(PromptEchoOn(after("PAM_PROMPT_ECHO_ON ")))
} else if line.has_prefix("PAM_ERROR_MSG ") {
Some(ErrorMsg(after("PAM_ERROR_MSG ")))
} else if line.has_prefix("PAM_TEXT_INFO ") {
Some(TextInfo(after("PAM_TEXT_INFO ")))
} else if line.has_prefix("SUCCESS") {
Some(Success)
} else if line.has_prefix("FAILURE") {
Some(Failure)
} else {
None
}
}
///| Where polkit installs the setuid helper, by distribution.
pub let helper_paths : Array[String] = [
"/usr/lib/polkit-1/polkit-agent-helper-1", "/usr/libexec/polkit-agent-helper-1", "/usr/libexec/polkit-1/polkit-agent-helper-1",
"/usr/lib/policykit-1/polkit-agent-helper-1",
]
///| The socket-activated helper (polkit 126+).
pub let helper_socket : String = "/run/polkit/agent-helper.socket"
///| How to reach the helper: a socket to connect to, or a program to run on a socket pair.
pub(all) enum HelperRoute {
Socket(String)
Program(String)
} derive(Eq, Debug)
///| One run of the helper: the connection and the bytes read but not yet a whole line.
pub struct HelperSession {
mut fd : Int
inbuf : Array[Byte]
/// Set once SUCCESS or FAILURE came, or the helper went away.
mut ended : Bool
}
///| Start the helper to authenticate `user` for `cookie` by the first route that works. None
/// when none does.
pub fn HelperSession::start_any(routes : Array[HelperRoute], user : String, cookie : String) -> HelperSession? {
for r in routes {
match HelperSession::start(r, user, cookie) {
Some(s) => return Some(s)
None => ()
}
}
None
}
///| Start the helper to authenticate `user` for `cookie`. None when it can't be started.
pub fn HelperSession::start(route : HelperRoute, user : String, cookie : String) -> HelperSession? {
let (fd, first) = match route {
Socket(path) => (@sys.unix_connect(path), user + "\n" + cookie + "\n")
Program(path) => (@sys.spawn_socket([path, user]), cookie + "\n")
}
if fd < 0 {
return None
}
let b = @utf8.encode(first)
if @sys.sendmsg_fd(fd, b, -1) != b.length() {
@sys.close_fd(fd)
return None
}
Some({ fd, inbuf: [], ended: false })
}
///| A session over an already-connected fd (tests).
pub fn HelperSession::over(fd : Int) -> HelperSession {
{ fd, inbuf: [], ended: false }
}
///| What arrived since the last call (non-blocking). The helper going away without an answer
/// reads as Failure.
pub fn HelperSession::read(self : HelperSession) -> Array[HelperEvent] {
let out : Array[HelperEvent] = []
if self.fd < 0 {
return out
}
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00')
let mut eof = false
while @sys.poll_read(self.fd, 0) > 0 {
let (n, extra) = @sys.recvmsg_fd(self.fd, buf, buf.length())
if extra >= 0 {
@sys.close_fd(extra)
}
if n == -1 {
break
}
if n <= 0 {
eof = true
break
}
for i = 0; i < n; i = i + 1 {
self.inbuf.push(buf[i])
}
}
while true {
let mut nl = -1
for i, b in self.inbuf {
if b == b'\n' {
nl = i
break
}
}
if nl < 0 {
break
}
let line = @utf8.decode_lossy(Bytes::from_array(self.inbuf[:nl].to_array()))
let rest = self.inbuf[nl + 1:].to_array()
self.inbuf.clear()
self.inbuf.append(rest)
match parse_helper_line(line) {
Some(ev) => {
out.push(ev)
if ev == Success || ev == Failure {
self.ended = true
}
}
None => ()
}
}
if eof {
if !self.ended {
out.push(Failure)
self.ended = true
}
self.close()
}
out
}
///| Answer the prompt with `answer` (its bytes then a newline); the caller zeroes its copy.
pub fn HelperSession::respond(self : HelperSession, answer : FixedArray[Byte]) -> Bool {
if self.fd < 0 {
return false
}
let n = answer.length()
let b = Bytes::makei(n + 1, i => if i < n { answer[i] } else { b'\n' })
@sys.sendmsg_fd(self.fd, b, -1) == b.length()
}
///| The connection, for the main loop to wait on (-1 once closed).
pub fn HelperSession::fd(self : HelperSession) -> Int {
self.fd
}
///| Stop: closing the connection ends the helper's PAM conversation.
pub fn HelperSession::close(self : HelperSession) -> Unit {
if self.fd >= 0 {
@sys.close_fd(self.fd)
self.fd = -1
}
}