Files
chandra/compositor/polkit/helper.mbt
T
Claude fa634956cc
CI / test (push) Successful in 2m1s
auth dialog: keep typed text when the polkit helper ends before asking
If polkit-agent-helper-1 exited (or the socket service refused) before
sending a PAM prompt, the dialog counted it as a wrong password, wiped the
field and restarted the helper immediately, in a tight loop, so typing
seemed to do nothing. Now such an early end keeps what was typed, shows
why, and retries after 1s/2s/4s (then on Enter). Every helper event and
route is logged as "chandra: polkit helper ..." (never the typed text).

Adds an end-to-end test that types through handle_input with a real
xkbcommon keymap, including Shift, across a helper that dies at once.

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

239 lines
7.0 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)
///| A route, for the log.
fn route_text(r : HelperRoute) -> String {
match r {
Socket(p) => "socket " + p
Program(p) => p
}
}
///| 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) => {
@sys.log("chandra: polkit helper for " + user + " via " + route_text(r))
return Some(s)
}
None => @sys.log("chandra: polkit helper not reachable via " + route_text(r))
}
}
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
}
}