Password dialog rebuilt: a separate polkit agent, one state machine, explicit errors
CI / test (push) Canceled after 21m14s

The first version ran polkit registration, polkit-agent-helper-1, the PAM
conversation and the drawing inside the compositor's frame loop, with
overlapping state in two layers. A helper that quit before asking was taken
for a wrong password and restarted in a loop that wiped the field (typing
seemed dead), a refused registration quietly started a third-party agent,
and the dialog and the Face unlock window each grabbed the keyboard.

Now:
- chandra-polkit-agent (compositor/authagent, /usr/local/lib/chandra) does
  polkit and PAM. Each request runs one state machine (polkit/machine.mbt:
  starting, asking, checking, failed, done). A check that quits or can't
  start is Failed with the reason and waits for Try again; only a wrong
  password starts the next check by itself. It logs each step to stderr
  (the session log), never the typed text.
- The compositor starts it on a socket pair and only draws what it says
  (host/auth.mbt, auth_draw.mbt; line protocol in polkit/wire.mbt). One
  input owner (grab_input): the dialog, else the Face unlock window.
- No silent fallback: if the agent can't run, polkit refuses it, polkit
  doesn't answer in 10 s, or it dies, a notice on screen says why (a crash
  after it ran restarts it, up to 3 times, and says so). The third-party
  agent runs only when the Settings switch is off.
- chandra-ctl auth-demo [password|face|face-ok|die|slow|users] shows the
  real dialog with a pretend check (password "demo"), no root needed;
  chandra-ctl auth-status says whether the agent is registered.
- just install builds and installs the agent (just auth-agent).

Tests: polkit_test (link, machine, view, helper Gone) and auth_test end to
end through handle_input: the agent loop in-process against a mock polkit
on a private dbus-daemon plus a mock helper, and the real agent program
spawned by the compositor (demo, and registered with the mock polkit).
Typing on a real xkb keymap, wrong password, cancel, withdrawal, helper
quitting early or missing, polkit refusing, agent not starting or crashing,
demo modes, Face unlock Apply. 170/170 host and 20/20 polkit tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgkRPrAzXECBUGmNEE
This commit is contained in:
Claude committed 2026-11-26 05:09:49 +00:00
1 parent 2c33c4a847
commit 80af76fb15
22 files changed
+3462 -1806

No files matched your search

+292 -151
View File
@@ -1,4 +1,4 @@
///| Keymaps, the helper protocol, request descriptions and the dialog's states.
///| 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 {
@@ -171,117 +171,283 @@ test "identities: users, group members, the user at the screen first" {
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
}
///|
fn dialog(users : Int) -> @polkit.AuthDialog {
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() }
@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
let m = @polkit.AuthMachine::new(req, @polkit.describe(req, cmdline=_ => [], who=_ => ""), fn(_u, _c) {
if fail_start.val != "" {
return Err(fail_start.val)
}
_ => "<none>"
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)
}
///|
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)))
}
///| 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)
}
// 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)
v.apply(["state", "1", "asking", "Password", "0", "", "", "", "", "0", "0"], 0UL)
v
}
///|
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 "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 "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 "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])
}
///|
@@ -299,30 +465,43 @@ test "the setuid route: the helper runs on a socket pair and speaks the protocol
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(s.fd(), 10))
got.append(s.read())
ignore(@sys.poll_read(c.fd(), 10))
got.append(c.poll())
}
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))
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(s.fd(), 10))
end.append(s.read())
ignore(@sys.poll_read(c.fd(), 10))
end.append(c.poll())
}
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(), [])
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")
}
s.close()
@sys.unlink(script)
}
@@ -339,41 +518,3 @@ test "face unlock: Chandra's and Howdy's PAM messages" {
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)
}