Files
chandra/compositor/polkit/polkit_test.mbt
T
nandi 851c39d827
CI / test (push) Failing after 52s
Auth dialog: OSK auto-open, hex keysyms, and remote text input
- Show the on-screen keyboard when the password dialog opens or reopens, and hide it on submit. Tapping the password field reopens it after a manual Hide.
- Route Chandra Remote text commits (including Enter, Tab, and Backspace) into the password dialog while it is up.
- Keymap: read hex keysyms (`0x31`, `0x20ac`, `0xffb7`) from libxkbcommon text-v1 keymaps, and accept `0x01000000`-range Unicode keysyms.
- Keymap: keypad keys produce digits when NumLock (Mod2) is active.
- Tests cover hex keysym parsing, NumLock keypad mapping, and the OSK/remote-text flow.
2026-11-28 18:51:15 -08:00

597 lines
24 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, the link, the state machine and the view.
///|
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("0x010020ac"), Some('€'))
assert_eq(@polkit.keysym_char("0x1000431"), Some('б'))
assert_eq(@polkit.keysym_char("Shift_L"), None)
// Numeric hex keysyms emitted by libxkbcommon's text v1 serialization.
assert_eq(@polkit.keysym_char("0x64"), Some('d'))
assert_eq(@polkit.keysym_char("0x44"), Some('D'))
assert_eq(@polkit.keysym_char("0x31"), Some('1'))
assert_eq(@polkit.keysym_char("0x21"), Some('!'))
assert_eq(@polkit.keysym_char("0x20"), Some(' '))
assert_eq(@polkit.keysym_char("0X7e"), Some('~'))
assert_eq(@polkit.keysym_char("0xe4"), Some('ä'))
assert_eq(@polkit.keysym_char("0xc4"), Some('Ä'))
assert_eq(@polkit.keysym_char("0x20ac"), Some('€'))
assert_eq(@polkit.keysym_char("0xffb7"), Some('7'))
assert_eq(@polkit.keysym_char("0xffae"), Some('.'))
assert_eq(@polkit.keysym_char("0xffab"), Some('+'))
// Non-printable X11 keysyms (editing, modifiers, dead keys, XF86 media keys, controls).
assert_eq(@polkit.keysym_char("0xff08"), None)
assert_eq(@polkit.keysym_char("0xff0d"), None)
assert_eq(@polkit.keysym_char("0xff1b"), None)
assert_eq(@polkit.keysym_char("0xffe1"), None)
assert_eq(@polkit.keysym_char("0xfe52"), None)
assert_eq(@polkit.keysym_char("0x1008ff11"), None)
assert_eq(@polkit.keysym_char("0x1005ff70"), None)
assert_eq(@polkit.keysym_char("0x000a"), None)
assert_eq(@polkit.keysym_char("0x007f"), None)
}
///| Hex keysyms as emitted by libxkbcommon 1.13's xkb_keymap_get_as_string(XKB_KEYMAP_FORMAT_TEXT_V1).
let xkb_hex_text : String =
#|xkb_keymap {
#|xkb_keycodes "evdev_aliases(qwerty)" {
#| minimum = 8;
#| maximum = 255;
#| <AE01> = 10;
#| <BKSP> = 22;
#| <AD03> = 26;
#| <RTRN> = 36;
#| <AC03> = 40;
#| <AC11> = 48;
#| <SPCE> = 65;
#| <KP7> = 79;
#|};
#|xkb_symbols "pc_us_inet(evdev)" {
#| key <AE01> { [ 0x31, 0x21 ] };
#| key <BKSP> { [ 0xff08, 0xff08 ] };
#| key <AD03> { [ 0x65, 0x45, 0x20ac, 0x20ac ] };
#| key <RTRN> { [ 0xff0d ] };
#| key <AC03> { [ 0x64, 0x44 ] };
#| key <AC11> { [ 0xe4, 0xc4 ] };
#| key <SPCE> { [ 0x20 ] };
#| key <KP7> { [ 0xff95, 0xffb7 ] };
#|};
#|};
///|
test "libxkbcommon hex keysym keymap: ASCII, Shift, Caps Lock, AltGr, NumLock and non-printable keys" {
let km = @polkit.Keymap::from_text(xkb_hex_text)
assert_eq(km.char_for(32U, 0U, 0U), Some('d'))
assert_eq(km.char_for(32U, @polkit.mask_shift, 0U), Some('D'))
assert_eq(km.char_for(32U, @polkit.mask_lock, 0U), Some('D'))
assert_eq(km.char_for(32U, @polkit.mask_shift | @polkit.mask_lock, 0U), Some('d'))
assert_eq(km.char_for(2U, 0U, 0U), Some('1'))
assert_eq(km.char_for(2U, @polkit.mask_shift, 0U), Some('!'))
assert_eq(km.char_for(2U, @polkit.mask_lock, 0U), Some('1'))
assert_eq(km.char_for(18U, 0U, 0U), Some('e'))
assert_eq(km.char_for(18U, @polkit.mask_altgr, 0U), Some('€'))
assert_eq(km.char_for(40U, 0U, 0U), Some('ä'))
assert_eq(km.char_for(40U, @polkit.mask_lock, 0U), Some('Ä'))
assert_eq(km.char_for(57U, 0U, 0U), Some(' '))
// Keypad 7: Home without NumLock, '7' with NumLock, back to Home with NumLock+Shift.
assert_eq(km.char_for(71U, 0U, 0U), None)
assert_eq(km.char_for(71U, @polkit.mask_numlock, 0U), Some('7'))
assert_eq(km.char_for(71U, @polkit.mask_numlock | @polkit.mask_shift, 0U), None)
// Non-printable editing keys stay None.
assert_eq(km.char_for(14U, 0U, 0U), None)
assert_eq(km.char_for(28U, 0U, 0U), 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")
}
///| A scripted PAM conversation: events the test queues, answers it got.
struct Script {
events : Array[@polkit.HelperEvent]
answers : Array[String]
mut closed : Bool
}
///|
impl @polkit.Conversation for Script with poll(self) {
let out = self.events.copy()
self.events.clear()
out
}
///|
impl @polkit.Conversation for Script with answer(self, a) {
self.answers.push(@polkit.field_text(a))
!self.closed
}
///|
impl @polkit.Conversation for Script with fd(_self) {
-1
}
///|
impl @polkit.Conversation for Script with close(self) {
self.closed = true
}
///| A machine whose checks are Scripts (the last one started is `runs.last()`); `fail_start`
/// makes starting fail.
fn machine(users : Int, runs : Array[Script], fail_start? : Ref[String] = { val: "" }) -> @polkit.AuthMachine {
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() }
let m = @polkit.AuthMachine::new(req, @polkit.describe(req, cmdline=_ => [], who=_ => ""), fn(_u, _c) {
if fail_start.val != "" {
return Err(fail_start.val)
}
let s = { events: [], answers: [], closed: false }
runs.push(s)
Ok(s as &@polkit.Conversation)
})
m.begin()
m
}
///| Bytes of `s` in a fresh buffer.
fn secret(s : String) -> FixedArray[Byte] {
let b = @utf8.encode(s)
FixedArray::makei(b.length(), i => b[i])
}
///| Feed `evs` to the last run and pump.
fn say(m : @polkit.AuthMachine, runs : Array[Script], evs : Array[@polkit.HelperEvent]) -> Unit {
runs[runs.length() - 1].events.append(evs)
m.pump()
}
///|
test "machine: ask, wrong password starts a new check at once, then success" {
let runs : Array[Script] = []
let m = machine(1, runs)
assert_eq(m.phase, Starting)
say(m, runs, [PromptEchoOff("Password: ")])
assert_eq(m.phase, Asking)
assert_eq(m.prompt, "Password")
let a = secret("hunter")
m.answer(a)
assert_eq(a.iter().all(b => b == b'\x00'), true) // zeroed once sent
assert_eq(runs[0].answers, ["hunter"])
assert_eq(m.phase, Checking)
say(m, runs, [Failure])
// A wrong answer: counted, a new check, the reason shown.
assert_eq(m.failures, 1)
assert_eq(runs.length(), 2)
assert_true(runs[0].closed)
assert_eq(m.phase, Starting)
assert_eq(m.error, "Wrong password. Try again.")
say(m, runs, [PromptEchoOff("Password: ")])
m.answer(secret("hunter2"))
say(m, runs, [Success])
assert_eq(m.phase, Done)
assert_true(m.authorized)
}
///|
test "machine: a check that ends before asking is Failed, with no retry until the user asks" {
let runs : Array[Script] = []
let m = machine(1, runs)
say(m, runs, [Gone])
assert_eq(m.phase, Failed)
assert_eq(m.error, "The password check quit before asking for a password.")
assert_eq(runs.length(), 1) // nothing restarted it
m.pump()
assert_eq(runs.length(), 1)
// FAILURE before any answer: PAM's own words when it gave some (an account lockout).
m.retry()
assert_eq(runs.length(), 2)
assert_eq(m.phase, Starting)
assert_eq(m.error, "")
say(m, runs, [ErrorMsg("The account is locked due to 3 failed logins."), Failure])
assert_eq(m.phase, Failed)
assert_eq(m.error, "The account is locked due to 3 failed logins.")
assert_eq(m.failures, 0)
// Enter with a password typed after a failure: a new check, which gets it when it asks.
m.answer(secret("pw"))
assert_eq(runs.length(), 3)
say(m, runs, [PromptEchoOff("Password: ")])
assert_eq(runs[2].answers, ["pw"])
assert_eq(m.phase, Checking)
// Quitting while checking is not a wrong password either.
say(m, runs, [Gone])
assert_eq(m.phase, Failed)
assert_eq(m.error, "The password check quit while checking the password.")
assert_eq(m.failures, 0)
}
///|
test "machine: a checker that can't start is Failed with the reason" {
let runs : Array[Script] = []
let why : Ref[String] = { val: "polkit's password checker could not be started (tried socket /run/polkit/agent-helper.socket)" }
let m = machine(1, runs, fail_start=why)
assert_eq(m.phase, Failed)
assert_eq(m.error, why.val)
why.val = ""
m.retry()
assert_eq(m.phase, Starting)
}
///|
test "machine: face unlock scans, the password typed meanwhile goes in when it fails" {
let runs : Array[Script] = []
let m = machine(1, runs)
say(m, runs, [TextInfo("Face unlock: looking for nandi…")])
assert_eq(m.face, Scanning)
assert_eq(m.phase, Starting)
assert_eq(m.info, "") // the face row says it, not the info line
m.answer(secret("hunter2"))
assert_eq(runs[0].answers, [])
say(m, runs, [ErrorMsg("Face unlock: face not recognized")])
assert_eq(m.face, FaceFailed("Face not recognized"))
assert_eq(m.error, "")
say(m, runs, [PromptEchoOff("Password: ")])
assert_eq(runs[0].answers, ["hunter2"])
// A face module that gives up silently still shows as not recognized.
say(m, runs, [Failure])
say(m, runs, [TextInfo("Attempting facial authentication"), PromptEchoOff("Password: ")])
assert_eq(m.face, FaceFailed("Face not recognized"))
// Recognized: PAM finishes without a password.
m.answer(secret("x"))
say(m, runs, [Failure])
say(m, runs, [TextInfo("Attempting facial authentication"), TextInfo("Identified face as nandi")])
assert_eq(m.face, Matched)
say(m, runs, [Success])
assert_true(m.authorized)
}
///|
test "machine: echo-on prompts, picking another account, cancel" {
let runs : Array[Script] = []
let m = machine(2, runs)
say(m, runs, [PromptEchoOn("Verification code: ")])
assert_true(m.echo)
m.answer(secret("4"))
say(m, runs, [Failure])
assert_eq(m.error, "That didn't work. Try again.")
m.pick_user(1)
assert_eq(m.user().map(u => u.name), Some("root"))
assert_eq(runs.length(), 3)
assert_eq(m.failures, 0)
m.cancel()
assert_eq(m.phase, Done)
assert_false(m.authorized)
assert_true(runs[2].closed)
}
///|
test "the link: fields with tabs, newlines and backslashes survive, secrets too" {
let f = ["state", "1", "a\tb", "line\nnext", "back\\slash", ""]
let line = @polkit.encode_line(f)
assert_eq(line[line.length() - 1], b'\n')
let body = FixedArray::makei(line.length() - 1, i => line[i])
assert_eq(@polkit.decode_line(body), f)
let s = @polkit.encode_secret_line(["answer", "3"], secret("p\tw\\"))
let fields = @polkit.split_fields(FixedArray::makei(s.length() - 1, i => s[i]))
assert_eq(@polkit.field_text(fields[2]), "p\tw\\")
}
///|
test "the machine's state reaches the view: phase, prompt, error, face, failures" {
let runs : Array[Script] = []
let m = machine(1, runs)
let v = @polkit.AuthView::from_request(["request", "7", "Run a command as root", "sub", "run0 ls", "ls", "", "msg"])
v.apply(m.state_fields("7"), 10UL)
assert_true(v.shown)
assert_eq(v.phase, Starting)
say(m, runs, [TextInfo("Face unlock: looking for nandi…")])
v.apply(m.state_fields("7"), 20UL)
assert_eq(v.face, Scanning)
assert_eq(v.face_at, 20UL)
say(m, runs, [PromptEchoOff("Password: ")])
v.apply(m.state_fields("7"), 30UL)
assert_eq(v.phase, Asking)
assert_eq(v.face, FaceFailed("Face not recognized"))
for c in "abc" {
ignore(v.key(0U, 0U, Some(c)))
}
m.answer(v.take_answer())
assert_eq(v.typed(), 0)
say(m, runs, [Failure])
v.apply(m.state_fields("7"), 100UL)
assert_eq(v.failures, 1)
assert_eq(v.error, "Wrong password. Try again.")
assert_true(v.shaking(200UL))
assert_false(v.shaking(600UL))
assert_true(v.shake_offset(135UL) != 0)
}
///| A view with `users` accounts, asking.
fn view(users : Int) -> @polkit.AuthView {
let v = @polkit.AuthView::from_request(["request", "1", "t", "s", "", "", "", ""])
v.apply(["user", "1", "nandi", "Nandi", "1000"], 0UL)
if users > 1 {
v.apply(["user", "1", "root", "root", "0"], 0UL)
}
v.apply(["state", "1", "asking", "Password", "0", "", "", "", "", "0", "0"], 0UL)
v
}
///|
test "view: Enter submits, Try again after a failure, typing blocked while checking" {
let v = view(1)
assert_true(v.key(@polkit.key_enter, 0U, None) is Nothing) // nothing typed
ignore(v.key(0U, 0U, Some('x')))
assert_eq(v.field_text(), "●")
ignore(v.activate(Reveal))
assert_eq(v.field_text(), "x")
assert_true(v.key(@polkit.key_enter, 0U, None) is Nothing) // focus on Show: toggles
ignore(v.activate(Field))
assert_true(v.key(@polkit.key_kp_enter, 0U, None) is Submit)
ignore(v.take_answer())
v.apply(["state", "1", "checking", "Password", "0", "", "", "", "", "0", "0"], 0UL)
ignore(v.key(0U, 0U, Some('y')))
assert_eq(v.typed(), 0)
v.apply(["state", "1", "failed", "Password", "0", "The password check quit.", "", "", "", "0", "0"], 0UL)
assert_eq(v.main_label(), "Try again")
assert_true(v.key(@polkit.key_enter, 0U, None) is Retry)
ignore(v.key(0U, 0U, Some('z')))
assert_eq(v.main_label(), "Authenticate")
assert_true(v.key(@polkit.key_enter, 0U, None) is Submit)
}
///|
test "view: keyboard focus, Escape, Space toggles, account picker" {
let v = view(2)
assert_eq(v.focus_order(), [Field, User, Reveal, Details, Cancel, Allow])
ignore(v.key(@polkit.key_tab, 0U, None))
assert_eq(v.focus, User)
assert_eq(v.key(@polkit.key_right, 0U, None), PickUser(1))
assert_eq(v.key(@polkit.key_left, 0U, None), PickUser(1)) // wraps
ignore(v.key(@polkit.key_tab, 0U, None))
ignore(v.key(@polkit.key_space, 0U, None))
assert_true(v.reveal)
ignore(v.key(@polkit.key_tab, 0U, None))
ignore(v.key(@polkit.key_enter, 0U, None))
assert_true(v.details_open)
ignore(v.key(@polkit.key_tab, 1U, None)) // Shift+Tab goes back
assert_eq(v.focus, Reveal)
ignore(v.key(0U, 0U, Some('x')))
assert_eq(v.focus, Field)
ignore(v.key(@polkit.key_d, 8U, Some('d'))) // Alt+D
assert_false(v.details_open)
ignore(v.key(@polkit.key_u, 4U, Some('u'))) // Ctrl+U
assert_eq(v.typed(), 0)
assert_eq(v.key(@polkit.key_esc, 0U, None), Dismiss)
assert_eq(view(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 c = s as &@polkit.Conversation
let got : Array[@polkit.HelperEvent] = []
for i = 0; i < 200 && got.length() < 2; i = i + 1 {
ignore(@sys.poll_read(c.fd(), 10))
got.append(c.poll())
}
assert_eq(got, [TextInfo("hello\tthere"), PromptEchoOff("Password: ")])
assert_true(c.answer(secret("pässword")))
let end : Array[@polkit.HelperEvent] = []
for i = 0; i < 200 && end.length() < 1; i = i + 1 {
ignore(@sys.poll_read(c.fd(), 10))
end.append(c.poll())
}
assert_eq(end, [Success])
assert_eq(c.fd(), -1)
assert_eq(c.poll(), []) // no second verdict
@sys.unlink(script)
}
///|
test "the helper going away without a verdict reads as Gone" {
let script = "/tmp/chandra-fake-helper-gone-" + @sys.getpid().to_string()
ignore(@sys.write_file_bytes(script, @utf8.encode("#!/bin/sh\nread cookie\nexit 1\n")))
ignore(@sys.spawn("chmod +x " + script, ""))
@sys.sleep_ms(200)
let c = @polkit.HelperSession::start(Program(script), "nandi", "c-1").unwrap() as &@polkit.Conversation
let got : Array[@polkit.HelperEvent] = []
for i = 0; i < 200 && got.length() < 1; i = i + 1 {
ignore(@sys.poll_read(c.fd(), 10))
got.append(c.poll())
}
assert_eq(got, [Gone])
// No route at all: the reason names what was tried.
match @polkit.HelperSession::start_any([Socket("/nonexistent/sock"), Program("/nonexistent/helper")], "nandi", "c") {
Err(e) => assert_eq(e, "polkit's password checker could not be started (tried socket /nonexistent/sock, /nonexistent/helper)")
Ok(_) => fail("started")
}
@sys.unlink(script)
}
///|
test "face unlock: Chandra's and Howdy's PAM messages" {
assert_eq(@polkit.face_message("Face unlock: looking for nandi…", false), Some(Scanning))
assert_eq(@polkit.face_message("Face unlock: recognized nandi", false), Some(Matched))
assert_eq(@polkit.face_message("Face unlock: face not recognized", true), Some(FaceFailed("Face not recognized")))
assert_eq(@polkit.face_message("Face unlock: the camera picture is too dark\n", true), Some(FaceFailed("The camera picture is too dark")))
assert_eq(@polkit.face_message("Attempting facial authentication", false), Some(Scanning))
assert_eq(@polkit.face_message("Identified face as nandi", false), Some(Matched))
assert_eq(@polkit.face_message("Failure, timeout reached", true), Some(FaceFailed("Face not recognized")))
assert_eq(@polkit.face_message("Face detection image too dark", true), Some(FaceFailed("The camera picture is too dark")))
assert_eq(@polkit.face_message("Place your finger on the fingerprint reader", false), None)
assert_eq(@polkit.face_message("The account is locked due to 3 failed logins.", true), None)
}