Files
chandra/compositor/polkit/polkit_test.mbt
T
Claude 932fca627e
CI / test (push) Successful in 2m6s
Face unlock: a Howdy-style PAM module, shown in the password dialog and set up in Settings
- face/pam_chandra_face.so (`-auth sufficient`): runs `chandra-face compare` as root with a clean
  environment, forwards what it says as PAM_TEXT_INFO / PAM_ERROR_MSG, and maps its exit status
  to success / auth error / unavailable, so the password always still works. Skips remote
  sessions (PAM_RHOST, SSH_CONNECTION), a closed lid and users without faces; refuses a helper
  that isn't root's; kills one that hangs (timeout + 6 s).
- face/chandra-face (Python + OpenCV): YuNet finds the face, SFace embeds it, cosine similarity
  against the enrolled embeddings (threshold 0.42, two matching frames, dark IR warm-up frames
  skipped, optional require_ir). enroll / list / remove / clear / test / status / pam
  enable|disable / fetch-models (sha256-pinned opencv_zoo models). Embeddings only, in
  /var/lib/chandra-face/USER/faces.json (root, 0600); labels in faces.list (0644). Store, config
  and models must be root's and not writable by others. Root commands re-run through run0 (or
  pkexec), so polkit asks first. Settings in /etc/chandra/face.conf.
- `just install-face [--pam]`, `just uninstall-face [--purge]` (face/install.py; uninstall takes
  the module out of every PAM service first). `pam enable` inserts before the first auth or
  @include line (Debian's sudo has only @include common-auth), keeping a .bak.
- Password dialog: a face row ("Looking for your face…" with a sweeping ring, "Face
  recognized", or why not, "Type your password instead"); typing and Enter during the scan go in
  when PAM asks for the password. Howdy's pam_howdy.so messages are understood too.
- Settings > Session > Face unlock: "Use my face for passwords" (polkit-1 + sudo), the enrolled
  faces (Remove takes a second click), "Add a face…", and the tool's progress. New `face-unlock`
  capability: tables 24 (status) and 25 (faces), request 44, in the wasmer/wasmtime stub, the Rust
  host, the MoonBit wasmhost and chandra:host/plasmoids. compositor/shell/face.mbt runs the tool
  on a socket so the compositor never waits.
- Tests: face/test_face.py (fake camera of PGM frames + fake recognizer; --pam builds the module
  and runs it through pamtester), dialog states and message parsing (polkit_test), the dialog via
  a mock helper (auth_test, shots 14/15), Settings against a fake chandra-face (face_test).
  scripts/test.sh runs them (compositor/polkit was missing from its native list), CI installs
  libpam0g-dev + pamtester. Also regenerated two stale desktop-module bindings (doc comments).
- docs/face-unlock.md, including the limits of 2D face recognition.

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

380 lines
16 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)
}
///|
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)
}
///|
test "dialog: face unlock scans, the password typed meanwhile goes in when it fails" {
let d = dialog(1)
ignore(d.helper(TextInfo("Face unlock: looking for nandi…"), 50UL))
assert_eq(d.face, Scanning)
assert_eq(d.face_at, 50UL)
assert_eq(d.phase, Waiting)
assert_eq(d.info, "") // the face row says it, not the info line
// Typing while it looks is kept, and Enter waits for the password prompt.
for c in "hunter2" {
ignore(d.key(0U, 0U, Some(c)))
}
assert_true(d.key(@polkit.key_enter, 0U, None) is Nothing)
ignore(d.helper(ErrorMsg("Face unlock: face not recognized"), 60UL))
assert_eq(d.face, FaceFailed("Face not recognized"))
assert_eq(d.error, "")
assert_eq(d.face_text(), "Face not recognized. Use your password.")
assert_eq(answer_text(d.helper(PromptEchoOff("Password: "), 70UL)), "hunter2")
// A wrong password restarts the conversation: the face is tried again.
assert_true(d.helper(Failure, 80UL) is Restart)
assert_eq(d.face, NoFace)
// Recognized: PAM finishes without a password.
ignore(d.helper(TextInfo("Attempting facial authentication"), 90UL))
assert_eq(d.face, Scanning)
ignore(d.helper(TextInfo("Identified face as nandi"), 95UL))
assert_eq(d.face, Matched)
assert_true(d.helper(Success, 99UL) is Authorized)
}
///|
test "dialog: a face module that gives up silently still shows as not recognized" {
let d = dialog(1)
ignore(d.helper(TextInfo("Attempting facial authentication"), 1UL))
ignore(d.helper(PromptEchoOff("Password: "), 2UL))
assert_eq(d.face, FaceFailed("Face not recognized"))
assert_eq(d.phase, Prompt)
}