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

208 lines
5.9 KiB
MoonBit

///| What polkit asks the agent to authenticate (BeginAuthentication), and who could answer.
///| A user who can authenticate: uid, login name and real name (from the passwd database).
pub(all) struct AuthUser {
uid : Int
name : String
real_name : String
} derive(Eq, Debug)
///| One BeginAuthentication call.
pub(all) struct AuthRequest {
action_id : String
/// polkit's translated message ("Authentication is required to ...").
message : String
icon_name : String
details : Map[String, String]
cookie : String
/// The users that may answer (unix-user identities, and the members of unix-group ones).
users : Array[AuthUser]
}
///| A detail by key, "" when absent.
pub fn AuthRequest::detail(self : AuthRequest, key : String) -> String {
self.details.get(key).unwrap_or("")
}
///| A passwd/group database line split on ':'.
fn fields(line : String) -> Array[String] {
line.split(":").map(v => v.to_string()).to_array()
}
///| Parse /etc/passwd text: uid -> (name, real name). The real name is GECOS up to its first ','.
pub fn parse_passwd(text : String) -> Map[Int, (String, String)] {
let out : Map[Int, (String, String)] = {}
for raw in text.split("\n") {
let f = fields(raw.to_string())
if f.length() < 5 {
continue
}
let uid = match parse_uint(f[2]) {
Some(v) => v
None => continue
}
let gecos = match f[4].find(",") {
Some(i) => f[4][:i].to_string()
None => f[4]
}
if !out.contains(uid) {
out.set(uid, (f[0], gecos))
}
}
out
}
///| Parse /etc/group text: gid -> member names.
pub fn parse_group(text : String) -> Map[Int, Array[String]] {
let out : Map[Int, Array[String]] = {}
for raw in text.split("\n") {
let f = fields(raw.to_string())
if f.length() < 4 {
continue
}
let gid = match parse_uint(f[2]) {
Some(v) => v
None => continue
}
let members = f[3].split(",").map(v => v.to_string().trim(chars=" ").to_string()).filter(v => v != "").to_array()
out.set(gid, members)
}
out
}
///| A decimal number.
fn parse_uint(s : String) -> Int? {
if s.length() == 0 || s.length() > 10 {
return None
}
let mut v = 0
for c in s {
if c < '0' || c > '9' {
return None
}
v = v * 10 + (c.to_int() - '0'.to_int())
}
Some(v)
}
///| The users polkit's identities (a(sa{sv}): ("unix-user", {uid}) or ("unix-group", {gid}))
/// stand for, in order, without repeats; a group stands for its members. `self_uid` (the user
/// at the screen) is listed first when it is among them, as other agents do.
pub fn users_for_identities(
identities : Array[@network.DValue],
passwd : Map[Int, (String, String)],
groups : Map[Int, Array[String]],
self_uid : Int,
) -> Array[AuthUser] {
let out : Array[AuthUser] = []
let by_name : Map[String, Int] = {}
for uid, e in passwd {
by_name.set(e.0, uid)
}
let add = fn(uid : Int) {
if out.iter().any(u => u.uid == uid) {
return
}
let (name, real_name) = match passwd.get(uid) {
Some(e) => e
None => (uid.to_string(), "")
}
out.push({ uid, name, real_name })
}
let num = fn(v : @network.DValue) -> Int? {
match v {
Variant(inner) =>
match inner {
U32(x) => Some(x.reinterpret_as_int())
I32(x) => Some(x)
_ => None
}
U32(x) => Some(x.reinterpret_as_int())
I32(x) => Some(x)
_ => None
}
}
for id in identities {
match id {
Struct([Str(kind), Arr(_, entries)]) =>
for e in entries {
match e {
Entry(Str(k), v) =>
match (kind, k, num(v)) {
("unix-user", "uid", Some(uid)) => add(uid)
("unix-group", "gid", Some(gid)) =>
for m in groups.get(gid).unwrap_or([]) {
match by_name.get(m) {
Some(uid) => add(uid)
None => ()
}
}
_ => ()
}
_ => ()
}
}
_ => ()
}
}
// The user at the screen first.
match out.search_by(u => u.uid == self_uid) {
Some(i) if i > 0 => {
let me = out.remove(i)
out.insert(0, me)
}
_ => ()
}
out
}
///| A string-to-string dict (a{ss}) as a map.
pub fn string_dict(v : @network.DValue) -> Map[String, String] {
let out : Map[String, String] = {}
match v {
Arr(_, entries) =>
for e in entries {
match e {
Entry(Str(k), Str(x)) => out.set(k, x)
_ => ()
}
}
_ => ()
}
out
}
///| Our uid, from /proc/self/status ("Uid:\treal\teffective..."); -1 when unknown.
pub fn own_uid() -> Int {
let text = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/self/status"))
for line in text.split("\n") {
let l = line.to_string()
if l.has_prefix("Uid:") {
let parts = l[4:].to_string().trim(chars=" \t").to_string().split("\t").to_array()
if parts.length() > 0 {
return parse_uint(parts[0].to_string().trim(chars=" ").to_string()).unwrap_or(-1)
}
}
}
-1
}
///| The request BeginAuthentication's arguments describe (s s s a{ss} s a(sa{sv})); None when
/// they don't match. Users come from /etc/passwd and /etc/group.
pub fn AuthRequest::from_args(args : Array[@network.DValue]) -> AuthRequest? {
match args {
[Str(action_id), Str(message), Str(icon_name), details, Str(cookie), Arr(_, ids)] => {
let passwd = parse_passwd(@utf8.decode_lossy(@sys.read_file_bytes("/etc/passwd")))
let groups = parse_group(@utf8.decode_lossy(@sys.read_file_bytes("/etc/group")))
let me = own_uid()
// Users outside /etc/passwd (systemd-homed, LDAP): the one at the screen is $USER.
if me >= 0 && !passwd.contains(me) && @sys.getenv("USER") != "" {
passwd.set(me, (@sys.getenv("USER"), ""))
}
let users = users_for_identities(ids, passwd, groups, me)
Some({ action_id, message, icon_name, details: string_dict(details), cookie, users })
}
_ => None
}
}