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

328 lines
14 KiB
MoonBit
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
///| Keymaps, the helper protocol, request descriptions and the dialog's states.
///|
fn type_keys(km : @polkit.Keymap, keys : Array[(UInt, UInt)]) -> String {
let sb = StringBuilder::new()
for k in keys {
match km.char_for(k.0, k.1, 0U) {
Some(c) => sb.write_char(c)
None => ()
}
}
sb.to_string()
}
///|
test "the built-in US layout types letters, shifted symbols and Caps Lock letters" {
let km = @polkit.Keymap::us()
// h i ! with shift on 1, then 'a' with Caps Lock, '1' with Caps Lock stays a digit.
assert_eq(type_keys(km, [(35U, 0U), (23U, 0U), (2U, 1U), (30U, 2U), (2U, 2U), (30U, 3U)]), "hi!A1a")
assert_eq(km.char_for(57U, 0U, 0U), Some(' '))
assert_eq(km.char_for(1U, 0U, 0U), None) // Escape types nothing
}
///| What xkbcommon's xkb_keymap_get_as_string writes (abridged), German layout in group 2.
let xkb_text : String =
#|xkb_keymap {
#|xkb_keycodes "evdev+aliases(qwertz)" {
#| minimum = 8;
#| maximum = 255;
#| <AE01> = 10;
#| <AD06> = 29;
#| <AB01> = 52;
#| <AC11> = 48;
#| alias <ALT1> = <AE01>;
#|};
#|xkb_types "complete" {
#| type "ALPHABETIC" { modifiers= Shift+Lock; };
#|};
#|xkb_symbols "pc+us+de:2" {
#| name[Group1]="English (US)";
#| key <AE01> { [ 1, exclam ], [ 1, exclam, onesuperior, exclamdown ] };
#| key <AD06> {
#| type= "ALPHABETIC",
#| symbols[1]= [ y, Y ],
#| symbols[2]= [ z, Z ]
#| };
#| key <AB01> {
#| type[Group1]= "ALPHABETIC",
#| symbols[Group1]= [ z, Z ],
#| symbols[Group2]= [ y, Y, guillemotright, U203A ]
#| };
#| key <AC11> { [ apostrophe, quotedbl ], [ adiaeresis, Adiaeresis, dead_circumflex, dead_caron ] };
#| modifier_map Shift { <LFSH> };
#|};
#|};
///|
test "an xkbcommon keymap: groups, levels, AltGr and Latin-1 keysyms" {
let km = @polkit.Keymap::from_text(xkb_text)
assert_eq(km.char_for(21U, 0U, 0U), Some('y')) // AD06, group 1
assert_eq(km.char_for(21U, 0U, 1U), Some('z')) // group 2 (German)
assert_eq(km.char_for(21U, 1U, 1U), Some('Z'))
assert_eq(km.char_for(44U, 0U, 1U), Some('y')) // AB01 in group 2
assert_eq(km.char_for(44U, 0x80U, 1U), Some('»')) // AltGr: level 3
assert_eq(km.char_for(44U, 0x81U, 1U), Some('›')) // AltGr+Shift: level 4, U203A
assert_eq(km.char_for(40U, 0U, 1U), Some('ä'))
assert_eq(km.char_for(40U, 2U, 1U), Some('Ä')) // Caps Lock
assert_eq(km.char_for(40U, 0x80U, 1U), None) // a dead key types nothing by itself
assert_eq(km.char_for(2U, 1U, 0U), Some('!'))
// Keys the keymap doesn't have type nothing.
assert_eq(km.char_for(30U, 0U, 0U), None)
}
///|
test "keysym names" {
assert_eq(@polkit.keysym_char("at"), Some('@'))
assert_eq(@polkit.keysym_char("EuroSign"), Some('€'))
assert_eq(@polkit.keysym_char("U0431"), Some('б'))
assert_eq(@polkit.keysym_char("0x10020ac"), Some('€'))
assert_eq(@polkit.keysym_char("Shift_L"), None)
}
///|
test "helper lines are unescaped as g_strcompress does" {
assert_eq(@polkit.parse_helper_line("PAM_PROMPT_ECHO_OFF Password: "), Some(PromptEchoOff("Password: ")))
assert_eq(@polkit.parse_helper_line("PAM_PROMPT_ECHO_ON Verification code:"), Some(PromptEchoOn("Verification code:")))
assert_eq(
@polkit.parse_helper_line("PAM_ERROR_MSG The account is locked due to 3 failed logins.\\n(5 minutes left to unlock)"),
Some(ErrorMsg("The account is locked due to 3 failed logins.\n(5 minutes left to unlock)")),
)
assert_eq(@polkit.parse_helper_line("PAM_TEXT_INFO Place your finger on the \\\"reader\\\""), Some(TextInfo("Place your finger on the \"reader\"")))
// Octal escapes are bytes of UTF-8.
assert_eq(@polkit.unescape("caf\\303\\251"), "café")
assert_eq(@polkit.parse_helper_line("SUCCESS"), Some(Success))
assert_eq(@polkit.parse_helper_line("FAILURE"), Some(Failure))
assert_eq(@polkit.parse_helper_line("polkit-agent-helper-1: noise"), None)
}
///|
test "run0 command lines" {
assert_eq(@polkit.parse_run0(["run0", "gparted"]), ("root", ["gparted"]))
assert_eq(@polkit.parse_run0(["/usr/bin/run0", "-u", "nandi", "--setenv", "A=1", "ls", "-la", "/root"]), ("nandi", ["ls", "-la", "/root"]))
assert_eq(@polkit.parse_run0(["run0", "--user=postgres", "--", "psql", "-c", "select 1"]), ("postgres", ["psql", "-c", "select 1"]))
assert_eq(@polkit.parse_run0(["run0", "--background=41"]), ("root", []))
assert_eq(@polkit.command_text(["psql", "-c", "select 1", "it's"]), "psql -c 'select 1' 'it'\\''s'")
assert_eq(@polkit.run0_unit_pid("run-p15802-i1990.service"), Some(15802))
assert_eq(@polkit.run0_unit_pid("run-u12.service"), None)
assert_eq(@polkit.quoted_in("Authentication is required to start transient unit 'run-p15802-i1990.service'."), "run-p15802-i1990.service")
}
///|
fn request(action : String, message : String, details : Map[String, String]) -> @polkit.AuthRequest {
{
action_id: action,
message,
icon_name: "",
details,
cookie: "3-abc-1-def",
users: [{ uid: 1000, name: "nandi", real_name: "Nandi" }],
}
}
///|
test "describe: run0 shows the command it will run, not the unit name" {
let req = request(
"org.freedesktop.systemd1.manage-units",
"Authentication is required to start transient unit 'run-p15802-i1990.service'.",
{ "unit": "run-p15802-i1990.service", "verb": "start", "polkit.subject-pid": "15802", "polkit.caller-pid": "1" },
)
let d = @polkit.describe(req, cmdline=pid => if pid == 15802 { ["run0", "gparted", "/dev/sda"] } else { [] }, who=pid => "run0 (pid " + pid.to_string() + ")")
assert_eq(d.title, "Run a command as root")
assert_eq(d.subtitle, "run0 needs your password to run this as root:")
assert_eq(d.command, "gparted /dev/sda")
assert_eq(d.program, "gparted")
assert_eq(d.details, [("Requested by", "run0 (pid 15802)"), ("Runs as", "root"), ("Unit", "run-p15802-i1990.service"), ("Action", "org.freedesktop.systemd1.manage-units")])
// Without details (older systemd), the unit name in the message still finds run0.
let bare = request("org.freedesktop.systemd1.manage-units", req.message, {})
let d2 = @polkit.describe(bare, cmdline=pid => if pid == 15802 { ["run0"] } else { [] }, who=_ => "")
assert_eq(d2.title, "Open a shell as root")
assert_eq(d2.command, "")
}
///|
test "describe: pkexec and other actions" {
let pk = request("org.freedesktop.policykit.exec", "Authentication is needed to run `/usr/bin/gparted' as the super user", {
"program": "/usr/bin/gparted",
"command_line": "/usr/bin/gparted",
"user": "root",
})
let d = @polkit.describe(pk, cmdline=_ => [], who=_ => "")
assert_eq(d.title, "Run a program as root")
assert_eq(d.command, "/usr/bin/gparted")
assert_eq(d.program, "gparted")
let other = request("org.freedesktop.udisks2.filesystem-mount-system", "Authentication is required to mount the drive", {})
let d3 = @polkit.describe(other, cmdline=_ => [], who=_ => "")
assert_eq(d3.title, "Authentication is required to mount the drive")
assert_eq(d3.command, "")
assert_eq(d3.details, [("Action", "org.freedesktop.udisks2.filesystem-mount-system")])
}
///|
test "identities: users, group members, the user at the screen first" {
let passwd = @polkit.parse_passwd("root:x:0:0:root:/root:/bin/bash\nnandi:x:1000:1000:Nandi Devi,,,:/home/nandi:/bin/bash\nada:x:1001:1001::/home/ada:/bin/sh\n")
let groups = @polkit.parse_group("root:x:0:\nwheel:x:10:ada,nandi\n")
let ids : Array[@network.DValue] = [
Struct([Str("unix-user"), @network.dict("v", [("uid", Variant(U32(0)))])]),
Struct([Str("unix-group"), @network.dict("v", [("gid", Variant(U32(10)))])]),
]
let users = @polkit.users_for_identities(ids, passwd, groups, 1000)
assert_eq(users.map(u => u.name), ["nandi", "root", "ada"])
assert_eq(users[0].real_name, "Nandi Devi")
}
///|
fn dialog(users : Int) -> @polkit.AuthDialog {
let us : Array[@polkit.AuthUser] = [{ uid: 1000, name: "nandi", real_name: "Nandi" }, { uid: 0, name: "root", real_name: "root" }]
let req = { ..request("a", "m", {}), users: us[:users].to_array() }
@polkit.AuthDialog::new(req, @polkit.describe(req, cmdline=_ => [], who=_ => ""))
}
///|
fn answer_text(e : @polkit.DialogEffect) -> String {
match e {
Answer(b) => {
let s = @utf8.decode_lossy(Bytes::makei(b.length(), i => b[i]))
@polkit.zero(b)
s
}
_ => "<none>"
}
}
///|
test "dialog: type, submit, wrong password, retry, success" {
let d = dialog(1)
let km = @polkit.Keymap::us()
let type_str = fn(s : String) {
for c in s {
ignore(d.key(0U, 0U, Some(c)))
}
}
// Typing before PAM's prompt is kept; Enter waits for it.
type_str("hunter")
assert_true(d.key(@polkit.key_enter, 0U, None) is Nothing)
assert_eq(answer_text(d.helper(PromptEchoOff("Password: "), 10UL)), "hunter")
assert_eq(d.phase, Checking)
assert_eq(d.typed(), 0) // wiped once sent
// Typing is ignored while PAM checks.
ignore(d.key(30U, 0U, km.char_for(30U, 0U, 0U)))
assert_eq(d.typed(), 0)
// Wrong: error, shake, field cleared, the helper restarts.
assert_true(d.helper(Failure, 100UL) is Restart)
assert_eq(d.error, "Wrong password. Try again.")
assert_eq(d.failures, 1)
assert_true(d.shaking(200UL))
assert_false(d.shaking(600UL))
assert_true(d.shake_offset(100UL + 35UL) != 0)
assert_eq(d.phase, Starting)
assert_true(d.helper(PromptEchoOff("Password: "), 700UL) is Nothing)
assert_eq(d.prompt, "Password")
type_str("hunter2")
assert_eq(d.error, "") // typing again clears it
assert_eq(d.field_text(), "●●●●●●●")
ignore(d.activate(Reveal))
d.activate(Field) |> ignore
assert_eq(d.field_text(), "hunter2")
// Backspace, then Enter sends.
ignore(d.key(@polkit.key_backspace, 0U, None))
type_str("2")
assert_eq(answer_text(d.key(@polkit.key_enter, 0U, None)), "hunter2")
assert_true(d.helper(Success, 900UL) is Authorized)
}
///|
test "dialog: PAM messages, lockout, echo-on prompts, fingerprint" {
let d = dialog(1)
// A fingerprint module only informs; the dialog waits with its message.
ignore(d.helper(TextInfo("Place your finger on the fingerprint reader"), 1UL))
assert_eq(d.phase, Waiting)
assert_eq(d.info, "Place your finger on the fingerprint reader")
// Then falls back to a password.
ignore(d.helper(PromptEchoOff("Password: "), 2UL))
assert_eq(d.phase, Prompt)
assert_eq(d.info, "")
// An error from PAM (faillock) is shown as is after the failure.
ignore(d.helper(ErrorMsg("The account is locked due to 3 failed logins."), 3UL))
ignore(d.helper(Failure, 4UL))
assert_eq(d.error, "The account is locked due to 3 failed logins.")
// A visible prompt (a one-time code): typed text is shown, even empty answers go.
ignore(d.helper(PromptEchoOn("Verification code: "), 5UL))
assert_true(d.echo)
ignore(d.key(0U, 0U, Some('4')))
assert_eq(d.field_text(), "4")
assert_eq(answer_text(d.key(@polkit.key_kp_enter, 0U, None)), "4")
}
///|
test "dialog: keyboard focus, Escape, Space toggles, user picker" {
let d = dialog(2)
assert_eq(d.focus, Field)
assert_eq(d.focus_order(), [Field, User, Reveal, Details, Cancel, Allow])
ignore(d.key(@polkit.key_tab, 0U, None))
assert_eq(d.focus, User)
assert_true(d.key(@polkit.key_right, 0U, None) is Restart)
assert_eq(d.user().map(u => u.name), Some("root"))
ignore(d.key(@polkit.key_tab, 0U, None))
ignore(d.key(@polkit.key_space, 0U, None))
assert_true(d.reveal)
ignore(d.key(@polkit.key_tab, 0U, None))
ignore(d.key(@polkit.key_enter, 0U, None))
assert_true(d.details_open)
ignore(d.key(@polkit.key_tab, 1U, None)) // Shift+Tab goes back
assert_eq(d.focus, Reveal)
// Typing anywhere goes to the field.
ignore(d.key(0U, 0U, Some('x')))
assert_eq(d.focus, Field)
// Alt+D toggles details from the field; Ctrl+U clears it.
ignore(d.key(@polkit.key_d, 8U, Some('d')))
assert_false(d.details_open)
ignore(d.key(@polkit.key_u, 4U, Some('u')))
assert_eq(d.typed(), 0)
assert_true(d.key(@polkit.key_esc, 0U, None) is Cancelled)
// One user: no picker in the Tab order.
assert_eq(dialog(1).focus_order(), [Field, Reveal, Details, Cancel, Allow])
}
///|
test "the setuid route: the helper runs on a socket pair and speaks the protocol" {
// A stand-in for polkit-agent-helper-1: user name as argv[1], cookie then answer on stdin.
let script = "/tmp/chandra-fake-helper-" + @sys.getpid().to_string()
ignore(
@sys.write_file_bytes(
script,
@utf8.encode(
"#!/bin/sh\nread cookie\n[ \"$1\" = nandi ] && [ \"$cookie\" = c-1 ] || { echo FAILURE; exit 1; }\necho 'PAM_TEXT_INFO hello\\\\tthere'\necho 'PAM_PROMPT_ECHO_OFF Password: '\nread pw\nif [ \"$pw\" = 'pässword' ]; then echo SUCCESS; else echo FAILURE; fi\n",
),
),
)
ignore(@sys.spawn("chmod +x " + script, ""))
@sys.sleep_ms(200)
let s = @polkit.HelperSession::start(Program(script), "nandi", "c-1").unwrap()
let got : Array[@polkit.HelperEvent] = []
for i = 0; i < 200 && got.length() < 2; i = i + 1 {
ignore(@sys.poll_read(s.fd(), 10))
got.append(s.read())
}
assert_eq(got, [TextInfo("hello\tthere"), PromptEchoOff("Password: ")])
let answer : FixedArray[Byte] = FixedArray::make(9, b'\x00')
let b = @utf8.encode("pässword")
for i = 0; i < b.length(); i = i + 1 {
answer[i] = b[i]
}
assert_true(s.respond(answer))
let end : Array[@polkit.HelperEvent] = []
for i = 0; i < 200 && end.length() < 1; i = i + 1 {
ignore(@sys.poll_read(s.fd(), 10))
end.append(s.read())
}
assert_eq(end, [Success])
// The helper exits: the session notices without inventing a second verdict.
for i = 0; i < 50 && s.fd() >= 0; i = i + 1 {
ignore(@sys.poll_read(s.fd(), 10))
assert_eq(s.read(), [])
}
s.close()
@sys.unlink(script)
}