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

+311
View File
@@ -0,0 +1,311 @@
///| chandra-polkit-agent's work (compositor/authagent is its main): be the session's polkit
/// agent and run each request's state machine, talking to the compositor over the link
/// (wire.mbt). In demo mode there is no polkit: one pretend request, then it exits.
///
/// Everything it logs goes to stderr, which is the session log; stdout is the link.
///| Log a line to stderr (the session log), never stdout (the link).
pub fn alog(msg : String) -> Unit {
eprintln("chandra-polkit-agent: " + msg)
}
///| `describe` with the real process lookups.
fn describe_default(r : AuthRequest) -> Description {
describe(r)
}
///| The agent's state.
pub struct AgentLoop {
link : LineConn
/// The polkit side; None in demo mode.
polkit : PolkitAgent?
/// Demo mode ("" for the real agent).
demo : String
start : Starter
describe : (AuthRequest) -> Description
/// The request being shown and its link id.
mut machine : AuthMachine?
mut id : String
mut next_id : Int
mut was_registered : Bool
/// Done: the main loop exits.
mut finished : Bool
}
///| The real agent on `link_fd`. `routes` reach polkit's helper (empty: the usual ones).
pub fn AgentLoop::new(
link_fd : Int,
polkit : PolkitAgent,
routes? : Array[HelperRoute] = [],
describer? : (AuthRequest) -> Description = describe_default,
) -> AgentLoop {
let start : Starter = fn(user, cookie) {
let rs = if routes.length() > 0 { routes } else { helper_routes() }
match HelperSession::start_any(rs, user, cookie) {
Ok(h) => Ok(h as &Conversation)
Err(e) => Err(e)
}
}
{
link: LineConn::new(link_fd),
polkit: Some(polkit),
demo: "",
start,
describe: describer,
machine: None,
id: "",
next_id: 1,
was_registered: false,
finished: false,
}
}
///| The demo agent on `link_fd`.
pub fn AgentLoop::new_demo(link_fd : Int, mode : String) -> AgentLoop {
let mode = if demo_modes.contains(mode) { mode } else { "password" }
{
link: LineConn::new(link_fd),
polkit: None,
demo: mode,
start: demo_starter(mode),
describe: describe_default,
machine: None,
id: "",
next_id: 1,
was_registered: false,
finished: false,
}
}
///| Begin: ask polkit to make us the session's agent (the answer comes in `step`), or open the
/// demo request. On failure the compositor is told why and the loop finishes.
pub fn AgentLoop::start(self : AgentLoop) -> Unit {
match self.polkit {
Some(p) =>
if p.start() {
alog("registering with polkit for this session")
} else {
self.give_up("polkit could not be asked: " + p.error())
}
None => {
ignore(self.link.send(["ready"]))
let (req, desc) = demo_request(self.demo)
alog("demo (" + self.demo + ")")
self.open(req, desc)
}
}
}
///| Tell the compositor why we can't serve, and finish.
fn AgentLoop::give_up(self : AgentLoop, why : String) -> Unit {
alog(why)
ignore(self.link.send(["error", why]))
self.finished = true
self.link.close()
}
///| Show `req`: its words, accounts, and first state; its check starts.
fn AgentLoop::open(self : AgentLoop, req : AuthRequest, desc : Description) -> Unit {
let id = self.next_id.to_string()
self.next_id = self.next_id + 1
self.id = id
let m = AuthMachine::new(req, desc, self.start)
self.machine = Some(m)
alog("request " + id + ": " + req.action_id + " (" + desc.title + ")")
ignore(self.link.send(["request", id, desc.title, desc.subtitle, desc.command, desc.program, req.icon_name, req.message]))
for d in desc.details {
ignore(self.link.send(["detail", id, d.0, d.1]))
}
for u in req.users {
ignore(self.link.send(["user", id, u.name, u.real_name, u.uid.to_string()]))
}
m.begin()
self.send_state()
}
///| Send the state if it changed.
fn AgentLoop::send_state(self : AgentLoop) -> Unit {
match self.machine {
Some(m) => if m.take_changed() { ignore(self.link.send(m.state_fields(self.id))) }
None => ()
}
}
///| The request is over: answer polkit, tell the compositor.
fn AgentLoop::close_request(self : AgentLoop, result : Result[Unit, String]?) -> Unit {
match self.machine {
Some(m) => {
m.cancel()
match (self.polkit, result) {
(Some(p), Some(r)) => p.finish(m.req.cookie, r)
_ => ()
}
alog(
"request " + self.id + " " +
(match result {
Some(Ok(_)) => "authorized"
Some(Err(_)) => "dismissed"
None => "withdrawn by polkit"
}),
)
ignore(self.link.send(["close", self.id]))
self.machine = None
if self.polkit is None {
// The demo shows one request.
self.finished = true
self.link.close()
}
}
None => ()
}
}
///| A message from the compositor.
fn AgentLoop::on_link(self : AgentLoop, line : FixedArray[Byte]) -> Unit {
let f = split_fields(line)
zero(line)
if f.length() < 2 {
return
}
let cmd = field_text(f[0])
let id = field_text(f[1])
let m = match self.machine {
Some(m) if id == self.id => m
_ => {
for b in f {
zero(b)
}
return
}
}
match cmd {
"answer" =>
if f.length() >= 3 {
m.answer(f[2])
}
"user" => m.pick_user(parse_uint(f.get(2).map(field_text).unwrap_or("")).unwrap_or(-1))
"retry" => m.retry()
"cancel" => {
self.close_request(Some(Err("The user dismissed the authentication dialog")))
return
}
_ => ()
}
for b in f {
zero(b)
}
}
///| The fds to wait on.
pub fn AgentLoop::fds(self : AgentLoop) -> Array[Int] {
let out = [self.link.fd()]
match self.polkit {
Some(p) => if p.fd() >= 0 { out.push(p.fd()) }
None => ()
}
match self.machine {
Some(m) => if m.fd() >= 0 { out.push(m.fd()) }
None => ()
}
out
}
///| How long to wait for the fds before stepping anyway (ms; -1: no limit).
pub fn AgentLoop::timeout(self : AgentLoop) -> Int {
match self.machine {
Some(m) if m.needs_timer() => 50
_ => -1
}
}
///| Serve whatever is ready.
pub fn AgentLoop::step(self : AgentLoop) -> Unit {
if self.finished {
return
}
for line in self.link.read_lines() {
self.on_link(line)
}
if self.link.eof {
// The compositor closed the link (the Settings switch, or the session ended).
alog("the compositor closed the link; stopping")
self.shutdown()
return
}
match self.polkit {
Some(p) => {
ignore(p.tick())
if p.registered() && !self.was_registered {
self.was_registered = true
alog("registered: polkit asks this agent for this session's passwords")
ignore(self.link.send(["ready"]))
}
if p.failed() {
self.close_request(None)
self.give_up(
if self.was_registered {
"lost the system bus: " + p.error()
} else {
"polkit refused the agent: " + p.error()
},
)
return
}
match self.machine {
Some(m) => if !p.waiting(m.req.cookie) { self.close_request(None) }
None => ()
}
}
None => ()
}
match self.machine {
Some(m) => {
m.pump()
self.send_state()
if m.phase == Done {
self.close_request(Some(if m.authorized { Ok(()) } else { Err("The user dismissed the authentication dialog") }))
}
}
None => ()
}
if self.machine is None && !self.finished {
match self.polkit {
Some(p) =>
match p.current() {
Some(req) => self.open(req, (self.describe)(req))
None => ()
}
None => ()
}
}
}
///| Stop: dismiss what waits, leave polkit, close the link.
pub fn AgentLoop::shutdown(self : AgentLoop) -> Unit {
match self.machine {
Some(m) => m.cancel()
None => ()
}
self.machine = None
match self.polkit {
Some(p) => p.stop()
None => ()
}
self.link.close()
self.finished = true
}
///| Whether the loop is done.
pub fn AgentLoop::finished(self : AgentLoop) -> Bool {
self.finished
}
///| Run until done (the agent's main).
pub fn AgentLoop::run(self : AgentLoop) -> Unit {
self.start()
while !self.finished {
ignore(@sys.wait_readable(self.fds(), self.timeout()))
self.step()
}
self.link.close()
}
+126
View File
@@ -0,0 +1,126 @@
///| `chandra-ctl auth-demo [MODE]`: the real dialog, link and state machine with a pretend
/// password check in place of polkit and PAM, so the dialog can be tried without root and
/// without anything actually running. The password is "demo".
///
/// Modes: password (the default), face (looks for a face, gives up, asks for the password),
/// face-ok (a face is recognized), die (the first check quits before asking, like a broken
/// polkit setup; Try again works), slow (asks after three seconds), users (two accounts).
///|
pub let demo_password : String = "demo"
///|
pub let demo_modes : Array[String] = ["password", "face", "face-ok", "die", "slow", "users"]
///| The pretend PAM conversation: events on a timer, and a verdict on the answer.
pub struct FakePam {
/// Events still to come: (due time in monotonic ms, event).
script : Array[(UInt64, HelperEvent)]
mut closed : Bool
}
///| A pretend check in `mode`; `attempt` counts from 0 (the `die` mode only fails the first).
pub fn FakePam::new(mode : String, attempt : Int) -> FakePam {
let now = @sys.monotonic_ms()
let at = fn(ms : Int, ev : HelperEvent) { (now + ms.to_uint64(), ev) }
let ask = PromptEchoOff("Password: ")
let script = match mode {
"face" =>
[
at(0, TextInfo("Face unlock: looking for your face")),
at(2500, ErrorMsg("Face unlock: face not recognized")),
at(2500, ask),
]
"face-ok" =>
[at(0, TextInfo("Face unlock: looking for your face")), at(2000, TextInfo("Face unlock: recognized")), at(2600, Success)]
"die" => if attempt == 0 { [at(400, Gone)] } else { [at(0, ask)] }
"slow" => [at(3000, ask)]
_ => [at(0, ask)]
}
{ script, closed: false }
}
///|
pub impl Conversation for FakePam with poll(self) {
let out : Array[HelperEvent] = []
if self.closed {
return out
}
let now = @sys.monotonic_ms()
while self.script.length() > 0 && self.script[0].0 <= now {
let ev = self.script.remove(0).1
out.push(ev)
if ev == Success || ev == Failure || ev == Gone {
self.closed = true
break
}
}
out
}
///|
pub impl Conversation for FakePam with answer(self, a) {
if self.closed {
return false
}
let ok = field_text(a) == demo_password
let now = @sys.monotonic_ms()
self.script.push((now + 700UL, if ok { Success } else { Failure }))
true
}
///|
pub impl Conversation for FakePam with fd(_self) {
-1
}
///|
pub impl Conversation for FakePam with close(self) {
self.closed = true
self.script.clear()
}
///| The account at the screen: $USER (with its real name from /etc/passwd when there).
fn demo_user() -> AuthUser {
let uid = own_uid()
let passwd = parse_passwd(@utf8.decode_lossy(@sys.read_file_bytes("/etc/passwd")))
match passwd.get(uid) {
Some((name, real)) => { uid, name, real_name: real }
None => {
let n = @sys.getenv("USER")
{ uid, name: if n != "" { n } else { "you" }, real_name: "" }
}
}
}
///| The demo request and how the dialog words it.
pub fn demo_request(mode : String) -> (AuthRequest, Description) {
let me = demo_user()
let users = if mode == "users" { [me, { uid: 0, name: "root", real_name: "root" }] } else { [me] }
let req : AuthRequest = {
action_id: "org.freedesktop.systemd1.manage-units",
message: "Authentication is required to start transient unit 'run-p1-i1.service'.",
icon_name: "",
details: {},
cookie: "demo",
users,
}
let desc : Description = {
title: "Run a command as root",
subtitle: "A demo: nothing runs. The password is \"" + demo_password + "\".",
command: "run0 systemctl restart chandra-demo.service",
program: "",
details: [("Demo", "chandra-ctl auth-demo " + mode), ("Runs as", "root"), ("Action", req.action_id)],
}
(req, desc)
}
///| Starts the demo's pretend checks, counting attempts.
pub fn demo_starter(mode : String) -> Starter {
let attempts : Ref[Int] = { val: 0 }
fn(_user, _cookie) {
let n = attempts.val
attempts.val = n + 1
Ok(FakePam::new(mode, n) as &Conversation)
}
}
-546
View File
@@ -1,546 +0,0 @@
///| The authentication dialog's state, apart from how it is drawn: what PAM asked, what was
/// typed (kept as characters so it can be wiped), which control has the keyboard, the last
/// error. The compositor draws it (compositor/host/auth.mbt) and runs the helper.
///| Where the conversation is.
pub(all) enum Phase {
/// The helper was started and hasn't asked anything yet.
Starting
/// PAM asked for an answer (`prompt`); the field takes typing.
Prompt
/// The answer went to PAM; waiting for the verdict.
Checking
/// PAM only said something (say "Place your finger on the reader") and waits on its own.
Waiting
} derive(Eq, Debug)
///| Face unlock (docs/face-unlock.md): what the face module in the PAM stack said, for the
/// dialog's face row. Chandra's own pam_chandra_face.so says "Face unlock: ..."; Howdy's
/// pam_howdy.so says "Attempting facial authentication", "Identified face as ...", and its
/// failures as errors.
pub(all) enum FaceState {
/// No face module spoke in this attempt.
NoFace
/// Looking for the face; typing the password meanwhile still works (it goes in when PAM asks).
Scanning
/// Recognized: PAM is finishing.
Matched
/// Not this time, and why ("Face not recognized"); the password is next.
FaceFailed(String)
} derive(Eq, Debug)
///| What a PAM message means for face unlock, if it is about it: Some(state), else None.
pub fn face_message(m : String, is_error : Bool) -> FaceState? {
let t = m.trim(chars=" \n").to_string()
let low = t.to_lower()
let ours = low.has_prefix("face unlock:")
let body = if ours { t[12:].to_string().trim(chars=" ").to_string() } else { t }
let lbody = body.to_lower()
if ours {
if is_error {
let why = if lbody.has_prefix("face not recognized") || lbody == "" {
"Face not recognized"
} else {
upper_first(body)
}
return Some(FaceFailed(why))
}
if lbody.has_prefix("recognized") {
return Some(Matched)
}
return Some(Scanning)
}
// Howdy (pam_howdy.so).
if low.has_prefix("attempting facial authentication") || low.has_prefix("attempting face detection") {
return Some(Scanning)
}
if low.has_prefix("identified face as") {
return Some(Matched)
}
if is_error && (low.has_prefix("failure, timeout reached") || low.has_prefix("failure, not a single face")) {
return Some(FaceFailed("Face not recognized"))
}
if is_error && low.has_prefix("face detection image too dark") {
return Some(FaceFailed("The camera picture is too dark"))
}
None
}
///| "camera not available" -> "Camera not available".
fn upper_first(s : String) -> String {
if s.length() == 0 {
return s
}
s[:1].to_string().to_upper() + s[1:].to_string()
}
///| The dialog's controls, in Tab order.
pub(all) enum Focus {
Field
User
Reveal
Details
Cancel
Allow
} derive(Eq, Debug)
///| What the compositor has to do after an event.
pub(all) enum DialogEffect {
Nothing
/// Send these bytes to the helper as the answer (then zero them).
Answer(FixedArray[Byte])
/// Run the helper again (another user picked, or the last attempt failed).
Restart
/// The helper ended before anything was answered (it couldn't run, PAM refused at once, the
/// account is locked): run it again later, not at once, or a helper that fails straight away
/// restarts in a loop and wipes the field under the user's fingers.
RetryLater
/// The user dismissed the dialog.
Cancelled
/// The helper said SUCCESS.
Authorized
}
///| Evdev key codes the dialog knows.
pub let key_esc : UInt = 1
///|
pub let key_backspace : UInt = 14
///|
pub let key_tab : UInt = 15
///|
pub let key_enter : UInt = 28
///|
pub let key_kp_enter : UInt = 96
///|
pub let key_space : UInt = 57
///|
pub let key_left : UInt = 105
///|
pub let key_right : UInt = 106
///|
pub let key_up : UInt = 103
///|
pub let key_down : UInt = 108
///|
pub let key_u : UInt = 22
///|
pub let key_d : UInt = 32
///|
pub let key_r : UInt = 19
///| The dialog for one request.
pub(all) struct AuthDialog {
req : AuthRequest
desc : Description
mut user_sel : Int
mut phase : Phase
/// PAM's prompt, tidied ("Password: " -> "Password").
mut prompt : String
/// The prompt's answer is shown as typed (PAM_PROMPT_ECHO_ON).
mut echo : Bool
input : Array[Char]
/// Show the password instead of dots.
mut reveal : Bool
mut caps : Bool
/// The last error (PAM's message, or ours after a failed attempt); "" when none.
mut error : String
/// PAM's last information message.
mut info : String
mut details_open : Bool
mut failures : Int
/// When the last failure shook the card (monotonic ms), 0 for never.
mut shake_at : UInt64
mut focus : Focus
/// Enter came before PAM's prompt: answer as soon as it does.
mut submit_queued : Bool
/// An answer went to the helper in this attempt (a failure then means a wrong answer).
mut answered : Bool
/// Face unlock in this attempt (NoFace when no face module spoke).
mut face : FaceState
/// When face unlock started looking (monotonic ms; the scan animation's clock).
mut face_at : UInt64
}
///|
pub fn AuthDialog::new(req : AuthRequest, desc : Description) -> AuthDialog {
{
req,
desc,
user_sel: 0,
phase: Starting,
prompt: "Password",
echo: false,
input: [],
reveal: false,
caps: false,
error: if req.users.length() == 0 { "No account can approve this here." } else { "" },
info: "",
details_open: false,
failures: 0,
shake_at: 0UL,
focus: Field,
submit_queued: false,
answered: false,
face: NoFace,
face_at: 0UL,
}
}
///| The user answering, if any.
pub fn AuthDialog::user(self : AuthDialog) -> AuthUser? {
self.req.users.get(self.user_sel)
}
///| "Password: " -> "Password"; "Password for nandi: " stays readable.
pub fn tidy_prompt(p : String) -> String {
let t = p.trim(chars=" \t\n").to_string()
let t = if t.has_suffix(":") { t[:t.length() - 1].to_string().trim(chars=" ").to_string() } else { t }
if t == "" { "Password" } else { t }
}
///| Wipe what was typed.
pub fn AuthDialog::wipe(self : AuthDialog) -> Unit {
for i = 0; i < self.input.length(); i = i + 1 {
self.input[i] = '\u{0}'
}
self.input.clear()
}
///| What was typed, as UTF-8 bytes in a buffer the caller zeroes after use; the field is wiped.
fn AuthDialog::take_answer(self : AuthDialog) -> FixedArray[Byte] {
let n = self.input.fold(init=0, fn(acc, c) {
let v = c.to_int()
acc + (if v < 0x80 { 1 } else if v < 0x800 { 2 } else if v < 0x10000 { 3 } else { 4 })
})
let out : FixedArray[Byte] = FixedArray::make(n, b'\x00')
let mut k = 0
for c in self.input {
let v = c.to_int()
if v < 0x80 {
out[k] = v.to_byte()
k = k + 1
} else if v < 0x800 {
out[k] = (0xC0 | (v >> 6)).to_byte()
out[k + 1] = (0x80 | (v & 0x3F)).to_byte()
k = k + 2
} else if v < 0x10000 {
out[k] = (0xE0 | (v >> 12)).to_byte()
out[k + 1] = (0x80 | ((v >> 6) & 0x3F)).to_byte()
out[k + 2] = (0x80 | (v & 0x3F)).to_byte()
k = k + 3
} else {
out[k] = (0xF0 | (v >> 18)).to_byte()
out[k + 1] = (0x80 | ((v >> 12) & 0x3F)).to_byte()
out[k + 2] = (0x80 | ((v >> 6) & 0x3F)).to_byte()
out[k + 3] = (0x80 | (v & 0x3F)).to_byte()
k = k + 4
}
}
self.wipe()
out
}
///| Zero a buffer an answer was in.
pub fn zero(b : FixedArray[Byte]) -> Unit {
for i = 0; i < b.length(); i = i + 1 {
b[i] = b'\x00'
}
}
///| Send what was typed, if PAM is asking; else remember to once it does.
fn AuthDialog::submit(self : AuthDialog) -> DialogEffect {
match self.phase {
Prompt =>
if self.input.length() == 0 && !self.echo {
Nothing
} else {
self.phase = Checking
self.error = ""
self.answered = true
Answer(self.take_answer())
}
Starting | Waiting => {
self.submit_queued = self.input.length() > 0
Nothing
}
Checking => Nothing
}
}
///| Something from the helper. `now` is the monotonic clock (for the shake).
pub fn AuthDialog::helper(self : AuthDialog, ev : HelperEvent, now : UInt64) -> DialogEffect {
match ev {
TextInfo(m) | ErrorMsg(m) =>
match face_message(m, ev is ErrorMsg(_)) {
Some(f) => {
if f == Scanning && self.face != Scanning {
self.face_at = if now == 0UL { 1UL } else { now }
}
self.face = f
if self.phase == Starting {
self.phase = Waiting
}
return Nothing
}
None => ()
}
_ => ()
}
match ev {
PromptEchoOff(p) | PromptEchoOn(p) => {
// The face module gave up without saying why (a timeout, or Howdy's silent failures).
if self.face == Scanning {
self.face = FaceFailed("Face not recognized")
}
self.phase = Prompt
self.prompt = tidy_prompt(p)
self.echo = ev is PromptEchoOn(_)
self.info = ""
if self.submit_queued {
self.submit_queued = false
return self.submit()
}
Nothing
}
ErrorMsg(m) => {
self.error = m.trim(chars=" \n").to_string()
Nothing
}
TextInfo(m) => {
self.info = m.trim(chars=" \n").to_string()
if self.phase == Starting {
self.phase = Waiting
}
Nothing
}
Success => Authorized
Failure if !self.answered => {
// Nothing was asked or answered: not a wrong password. Keep what was typed.
if self.error == "" {
self.error = "The authentication service stopped before asking for a password."
}
self.phase = Starting
self.info = ""
if self.face == Scanning {
self.face = NoFace
}
RetryLater
}
Failure => {
self.answered = false
self.failures = self.failures + 1
self.shake_at = if now == 0UL { 1UL } else { now }
if self.error == "" {
self.error = if self.echo {
"That didn't work. Try again."
} else {
"Wrong password. Try again."
}
}
self.wipe()
self.submit_queued = false
self.phase = Starting
self.info = ""
self.face = NoFace
self.focus = Field
Restart
}
}
}
///| The controls Tab moves through, in order (the user picker only with several users).
pub fn AuthDialog::focus_order(self : AuthDialog) -> Array[Focus] {
let out : Array[Focus] = [Field]
if self.req.users.length() > 1 {
out.push(User)
}
out.push(Reveal)
out.push(Details)
out.push(Cancel)
out.push(Allow)
out
}
///| Move the keyboard focus by `delta` along the Tab order.
fn AuthDialog::move_focus(self : AuthDialog, delta : Int) -> Unit {
let order = self.focus_order()
let i = order.search(self.focus).unwrap_or(0)
let n = order.length()
self.focus = order[((i + delta) % n + n) % n]
}
///| Pick the user `delta` away (wrapping). Restart when it changed.
fn AuthDialog::cycle_user(self : AuthDialog, delta : Int) -> DialogEffect {
let n = self.req.users.length()
if n < 2 {
return Nothing
}
self.user_sel = ((self.user_sel + delta) % n + n) % n
self.wipe()
self.error = ""
self.info = ""
self.face = NoFace
self.phase = Starting
self.submit_queued = false
self.answered = false
Restart
}
///| Activate control `f` (Enter or Space on it, or a click).
pub fn AuthDialog::activate(self : AuthDialog, f : Focus) -> DialogEffect {
match f {
Field => {
self.focus = Field
Nothing
}
User => {
self.focus = User
self.cycle_user(1)
}
Reveal => {
self.focus = Reveal
self.reveal = !self.reveal
Nothing
}
Details => {
self.focus = Details
self.details_open = !self.details_open
Nothing
}
Cancel => Cancelled
Allow => self.submit()
}
}
///| A key press: `code` (evdev), the modifier state (Shift, Ctrl, Alt bits), and the character it
/// types on the current layout, if any.
pub fn AuthDialog::key(self : AuthDialog, code : UInt, mods : UInt, ch : Char?) -> DialogEffect {
let ctrl = (mods & mask_ctrl) != 0U
let shift = (mods & mask_shift) != 0U
let alt = (mods & mask_alt) != 0U
if code == key_esc {
return Cancelled
}
if code == key_tab {
self.move_focus(if shift { -1 } else { 1 })
return Nothing
}
if code == key_enter || code == key_kp_enter {
return match self.focus {
Field | Allow => self.submit()
other => self.activate(other)
}
}
// Alt+D details, Alt+R reveal: reachable from the field without leaving it.
if alt && code == key_d {
self.details_open = !self.details_open
return Nothing
}
if alt && code == key_r {
self.reveal = !self.reveal
return Nothing
}
if self.focus == User && (code == key_left || code == key_up) {
return self.cycle_user(-1)
}
if self.focus == User && (code == key_right || code == key_down) {
return self.cycle_user(1)
}
if code == key_space && self.focus != Field {
return self.activate(self.focus)
}
if self.phase == Checking {
return Nothing
}
if code == key_backspace || (ctrl && code == key_u) {
if ctrl {
self.wipe()
} else if self.input.length() > 0 {
let last = self.input.length() - 1
self.input[last] = '\u{0}'
ignore(self.input.pop())
}
self.focus = Field
return Nothing
}
if ctrl || alt {
return Nothing
}
match ch {
Some(c) => {
if self.input.length() < 512 {
self.input.push(c)
}
self.focus = Field
// Typing again after an error clears it.
if self.failures > 0 {
self.error = ""
}
Nothing
}
None => Nothing
}
}
///| Horizontal offset of the card while it shakes after a failure (0 when still).
pub fn AuthDialog::shake_offset(self : AuthDialog, now : UInt64) -> Int {
if self.shake_at == 0UL || now < self.shake_at {
return 0
}
let t = (now - self.shake_at).to_int()
let dur = 420
if t >= dur {
return 0
}
// Three swings, fading out.
let period = dur / 6
let phase = t % period
let tri = if phase < period / 2 { phase * 4 - period } else { 3 * period - phase * 4 }
let amp = 12 * (dur - t) / dur
tri * amp / period
}
///| What the face row says, "" when there is none.
pub fn AuthDialog::face_text(self : AuthDialog) -> String {
match self.face {
NoFace => ""
Scanning => "Looking for your face…"
Matched => "Face recognized"
FaceFailed(why) => why + ". Use your password."
}
}
///| Whether the card is still shaking.
pub fn AuthDialog::shaking(self : AuthDialog, now : UInt64) -> Bool {
self.shake_at != 0UL && now >= self.shake_at && now - self.shake_at < 420UL
}
///| The field's text as shown: the answer (echo or revealed) or one dot per character.
pub fn AuthDialog::field_text(self : AuthDialog) -> String {
if self.echo || self.reveal {
String::from_array(self.input)
} else {
let sb = StringBuilder::new()
for _ in self.input {
sb.write_char('●')
}
sb.to_string()
}
}
///| The number of characters typed.
pub fn AuthDialog::typed(self : AuthDialog) -> Int {
self.input.length()
}
+59
View File
@@ -0,0 +1,59 @@
///| Face unlock (docs/face-unlock.md): what the face module in the PAM stack said, for the
/// dialog's face row. Chandra's own pam_chandra_face.so says "Face unlock: ..."; Howdy's
/// pam_howdy.so says "Attempting facial authentication", "Identified face as ...", and its
/// failures as errors.
pub(all) enum FaceState {
/// No face module spoke in this attempt.
NoFace
/// Looking for the face; typing the password meanwhile still works (it goes in when PAM asks).
Scanning
/// Recognized: PAM is finishing.
Matched
/// Not this time, and why ("Face not recognized"); the password is next.
FaceFailed(String)
} derive(Eq, Debug)
///| What a PAM message means for face unlock, if it is about it: Some(state), else None.
pub fn face_message(m : String, is_error : Bool) -> FaceState? {
let t = m.trim(chars=" \n").to_string()
let low = t.to_lower()
let ours = low.has_prefix("face unlock:")
let body = if ours { t[12:].to_string().trim(chars=" ").to_string() } else { t }
let lbody = body.to_lower()
if ours {
if is_error {
let why = if lbody.has_prefix("face not recognized") || lbody == "" {
"Face not recognized"
} else {
upper_first(body)
}
return Some(FaceFailed(why))
}
if lbody.has_prefix("recognized") {
return Some(Matched)
}
return Some(Scanning)
}
// Howdy (pam_howdy.so).
if low.has_prefix("attempting facial authentication") || low.has_prefix("attempting face detection") {
return Some(Scanning)
}
if low.has_prefix("identified face as") {
return Some(Matched)
}
if is_error && (low.has_prefix("failure, timeout reached") || low.has_prefix("failure, not a single face")) {
return Some(FaceFailed("Face not recognized"))
}
if is_error && low.has_prefix("face detection image too dark") {
return Some(FaceFailed("The camera picture is too dark"))
}
None
}
///| "camera not available" -> "Camera not available".
fn upper_first(s : String) -> String {
if s.length() == 0 {
return s
}
s[:1].to_string().to_upper() + s[1:].to_string()
}
+64 -81
View File
@@ -19,6 +19,9 @@ pub(all) enum HelperEvent {
TextInfo(String)
Success
Failure
/// The helper went away without saying SUCCESS or FAILURE (it crashed, was refused, or
/// couldn't run PAM at all).
Gone
} derive(Eq, Debug)
///| Undo g_strescape: \n \t \r \b \f \v \\ \" and octal \NNN (bytes, re-read as UTF-8).
@@ -101,138 +104,118 @@ pub(all) enum HelperRoute {
Program(String)
} derive(Eq, Debug)
///| A route, for the log.
fn route_text(r : HelperRoute) -> String {
///| A route, for the log and for errors.
pub fn route_text(r : HelperRoute) -> String {
match r {
Socket(p) => "socket " + p
Program(p) => p
}
}
///| One run of the helper: the connection and the bytes read but not yet a whole line.
///| A PAM conversation: polkit's helper, or the demo's stand-in (demo.mbt).
pub(open) trait Conversation {
/// What was said since the last call (non-blocking); ends with Success, Failure or Gone.
poll(Self) -> Array[HelperEvent]
/// Answer the prompt (the bytes, without a newline); false when it can't be sent.
answer(Self, FixedArray[Byte]) -> Bool
/// The fd to wait on, -1 for none (the caller then polls on a timer).
fd(Self) -> Int
/// End the conversation.
close(Self) -> Unit
}
///| One run of polkit-agent-helper-1.
pub struct HelperSession {
mut fd : Int
inbuf : Array[Byte]
/// Set once SUCCESS or FAILURE came, or the helper went away.
conn : LineConn
/// SUCCESS, FAILURE or Gone was reported.
mut ended : Bool
}
///| Start the helper to authenticate `user` for `cookie` by the first route that works. None
/// when none does.
pub fn HelperSession::start_any(routes : Array[HelperRoute], user : String, cookie : String) -> HelperSession? {
///| Start the helper to authenticate `user` for `cookie` by the first route that works; Err
/// says which routes were tried and how each failed.
pub fn HelperSession::start_any(routes : Array[HelperRoute], user : String, cookie : String) -> Result[HelperSession, String] {
let tried : Array[String] = []
for r in routes {
match HelperSession::start(r, user, cookie) {
Some(s) => {
@sys.log("chandra: polkit helper for " + user + " via " + route_text(r))
return Some(s)
alog("password check for " + user + " via " + route_text(r))
return Ok(s)
}
None => @sys.log("chandra: polkit helper not reachable via " + route_text(r))
None => tried.push(route_text(r))
}
}
None
if tried.length() == 0 {
Err("polkit's password checker (polkit-agent-helper-1) is not installed")
} else {
Err("polkit's password checker could not be started (tried " + tried.join(", ") + ")")
}
}
///| Start the helper to authenticate `user` for `cookie`. None when it can't be started.
///| Start the helper to authenticate `user` for `cookie`. None when it can't be reached.
pub fn HelperSession::start(route : HelperRoute, user : String, cookie : String) -> HelperSession? {
let (fd, first) = match route {
Socket(path) => (@sys.unix_connect(path), user + "\n" + cookie + "\n")
Program(path) => (@sys.spawn_socket([path, user]), cookie + "\n")
Program(path) => if @sys.has_exe(path) { (@sys.spawn_socket([path, user]), cookie + "\n") } else { (-1, "") }
}
if fd < 0 {
return None
}
let b = @utf8.encode(first)
if @sys.sendmsg_fd(fd, b, -1) != b.length() {
@sys.close_fd(fd)
let conn = LineConn::new(fd)
if !conn.send_raw(@utf8.encode(first)) {
conn.close()
return None
}
Some({ fd, inbuf: [], ended: false })
Some({ conn, ended: false })
}
///| A session over an already-connected fd (tests).
pub fn HelperSession::over(fd : Int) -> HelperSession {
{ fd, inbuf: [], ended: false }
{ conn: LineConn::new(fd), ended: false }
}
///| What arrived since the last call (non-blocking). The helper going away without an answer
/// reads as Failure.
pub fn HelperSession::read(self : HelperSession) -> Array[HelperEvent] {
///|
pub impl Conversation for HelperSession with poll(self) {
let out : Array[HelperEvent] = []
if self.fd < 0 {
if self.ended {
return out
}
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00')
let mut eof = false
while @sys.poll_read(self.fd, 0) > 0 {
let (n, extra) = @sys.recvmsg_fd(self.fd, buf, buf.length())
if extra >= 0 {
@sys.close_fd(extra)
}
if n == -1 {
break
}
if n <= 0 {
eof = true
break
}
for i = 0; i < n; i = i + 1 {
self.inbuf.push(buf[i])
}
}
while true {
let mut nl = -1
for i, b in self.inbuf {
if b == b'\n' {
nl = i
break
}
}
if nl < 0 {
break
}
let line = @utf8.decode_lossy(Bytes::from_array(self.inbuf[:nl].to_array()))
let rest = self.inbuf[nl + 1:].to_array()
self.inbuf.clear()
self.inbuf.append(rest)
match parse_helper_line(line) {
for line in self.conn.read_lines() {
match parse_helper_line(field_text(line)) {
Some(ev) => {
out.push(ev)
if ev == Success || ev == Failure {
self.ended = true
self.conn.close()
return out
}
}
None => ()
}
}
if eof {
if !self.ended {
out.push(Failure)
self.ended = true
}
self.close()
if self.conn.eof {
out.push(Gone)
self.ended = true
self.conn.close()
}
out
}
///| Answer the prompt with `answer` (its bytes then a newline); the caller zeroes its copy.
pub fn HelperSession::respond(self : HelperSession, answer : FixedArray[Byte]) -> Bool {
if self.fd < 0 {
return false
}
let n = answer.length()
let b = Bytes::makei(n + 1, i => if i < n { answer[i] } else { b'\n' })
@sys.sendmsg_fd(self.fd, b, -1) == b.length()
///|
pub impl Conversation for HelperSession with answer(self, a) {
let n = a.length()
let b = FixedArray::makei(n + 1, i => if i < n { a[i] } else { b'\n' })
let ok = self.conn.send_raw(Bytes::makei(b.length(), i => b[i]))
zero(b)
ok
}
///| The connection, for the main loop to wait on (-1 once closed).
pub fn HelperSession::fd(self : HelperSession) -> Int {
self.fd
///|
pub impl Conversation for HelperSession with fd(self) {
self.conn.fd()
}
///| Stop: closing the connection ends the helper's PAM conversation.
pub fn HelperSession::close(self : HelperSession) -> Unit {
if self.fd >= 0 {
@sys.close_fd(self.fd)
self.fd = -1
}
///| Closing the connection ends the helper's PAM conversation.
pub impl Conversation for HelperSession with close(self) {
self.ended = true
self.conn.close()
}
+398
View File
@@ -0,0 +1,398 @@
///| One authentication request, from the moment polkit asks until it is answered: the one state
/// machine of Chandra's password dialog. It runs in the agent process (agent_loop.mbt); the
/// compositor only shows its state and sends back what the user typed or picked.
///
/// Starting --prompt--> Asking --answer--> Checking --SUCCESS--> Done
/// | ^ |
/// | +---- a new check <--+ FAILURE: wrong password (shake, count it)
/// +--- the check ends without asking, can't start, or quits while checking ---> Failed
/// Failed --retry (Enter, or the Try again button)--> Starting
/// any --cancel--> Done
///
/// Nothing is retried behind the user's back: a check that ends before PAM asked anything is
/// shown as Failed with the reason, and only the user starts it again. A wrong password starts
/// the next check at once, because the user just answered and is waiting for the next prompt.
///| Where the request is.
pub(all) enum Phase {
/// The password check (PAM, through polkit's helper) runs and hasn't asked anything yet; it
/// may be looking for a face or a fingerprint meanwhile.
Starting
/// PAM asked (`prompt`); the answer is being typed.
Asking
/// The answer went to PAM; waiting for the verdict.
Checking
/// The check stopped without a verdict on the answer; `error` says why. Waits for the user.
Failed
/// Over: authorized, or dismissed.
Done
} derive(Eq, Debug)
///| The phase's name on the link.
pub fn phase_name(p : Phase) -> String {
match p {
Starting => "starting"
Asking => "asking"
Checking => "checking"
Failed => "failed"
Done => "done"
}
}
///| The phase a link name stands for.
pub fn phase_of(s : String) -> Phase {
match s {
"asking" => Asking
"checking" => Checking
"failed" => Failed
"done" => Done
_ => Starting
}
}
///| Starts a conversation for (user, cookie), or says why it can't.
pub type Starter = (String, String) -> Result[&Conversation, String]
///| The request and where it is.
pub struct AuthMachine {
req : AuthRequest
desc : Description
start : Starter
mut user_sel : Int
mut phase : Phase
/// PAM's prompt, tidied ("Password: " -> "Password").
mut prompt : String
/// The answer is shown as typed (PAM_PROMPT_ECHO_ON: a user name, a one-time code).
mut echo : Bool
mut error : String
mut info : String
mut face : FaceState
/// Wrong answers so far.
mut failures : Int
/// An answer typed before PAM asked (while a face was being looked for): sent when it asks.
mut queued : FixedArray[Byte]?
mut conv : &Conversation?
/// Done, and authorized.
mut authorized : Bool
/// Something changed since `take_changed`.
mut changed : Bool
}
///| A machine for `req`; `begin` starts it.
pub fn AuthMachine::new(req : AuthRequest, desc : Description, start : Starter) -> AuthMachine {
{
req,
desc,
start,
user_sel: 0,
phase: Starting,
prompt: "Password",
echo: false,
error: "",
info: "",
face: NoFace,
failures: 0,
queued: None,
conv: None,
authorized: false,
changed: true,
}
}
///| "Password: " -> "Password"; "Password for nandi: " stays readable.
pub fn tidy_prompt(p : String) -> String {
let t = p.trim(chars=" \t\n").to_string()
let t = if t.has_suffix(":") { t[:t.length() - 1].to_string().trim(chars=" ").to_string() } else { t }
if t == "" {
"Password"
} else {
t
}
}
///| The account answering, if any.
pub fn AuthMachine::user(self : AuthMachine) -> AuthUser? {
self.req.users.get(self.user_sel)
}
///| Drop the conversation and any queued answer.
fn AuthMachine::stop_conv(self : AuthMachine) -> Unit {
match self.conv {
Some(c) => c.close()
None => ()
}
self.conv = None
match self.queued {
Some(q) => zero(q)
None => ()
}
self.queued = None
}
///| Start a password check for the selected account: Starting, or Failed when it can't start.
pub fn AuthMachine::begin(self : AuthMachine) -> Unit {
self.stop_conv()
self.changed = true
self.info = ""
self.face = NoFace
self.prompt = "Password"
self.echo = false
let user = match self.user() {
Some(u) => u
None => {
self.fail("No account that can approve this is known here.")
return
}
}
match (self.start)(user.name, self.req.cookie) {
Ok(c) => {
self.conv = Some(c)
self.phase = Starting
}
Err(why) => self.fail(why)
}
}
///| Stop with `why` (and log it): the user decides what next.
fn AuthMachine::fail(self : AuthMachine, why : String) -> Unit {
self.stop_conv()
self.phase = Failed
self.error = why
if self.face == Scanning {
self.face = NoFace
}
self.changed = true
alog(why)
}
///| Send `a` to PAM now (it is asking) and zero it.
fn AuthMachine::send_answer(self : AuthMachine, a : FixedArray[Byte]) -> Unit {
let ok = match self.conv {
Some(c) => c.answer(a)
None => false
}
zero(a)
if ok {
self.phase = Checking
self.error = ""
self.info = ""
} else {
self.fail("The password check quit before it got the answer.")
}
self.changed = true
}
///| The user's answer (the machine zeroes it). Asking: it goes to PAM. Starting: it waits for
/// PAM's prompt. Failed: a new check starts and gets it.
pub fn AuthMachine::answer(self : AuthMachine, given : FixedArray[Byte]) -> Unit {
// Our own copy: the caller's buffer is wiped when it is done with it.
let a = FixedArray::makei(given.length(), i => given[i])
zero(given)
match self.phase {
Asking => self.send_answer(a)
Starting => {
match self.queued {
Some(q) => zero(q)
None => ()
}
self.queued = Some(a)
}
Failed => {
self.begin()
if self.phase == Starting {
self.queued = Some(a)
} else {
zero(a)
}
}
Checking | Done => zero(a)
}
}
///| Answer as account `i` instead: a new check for it.
pub fn AuthMachine::pick_user(self : AuthMachine, i : Int) -> Unit {
if i < 0 || i >= self.req.users.length() || i == self.user_sel || self.phase == Done {
return
}
self.user_sel = i
self.error = ""
self.failures = 0
self.begin()
}
///| Start again after Failed.
pub fn AuthMachine::retry(self : AuthMachine) -> Unit {
if self.phase == Failed {
self.error = ""
self.begin()
}
}
///| The user dismissed it.
pub fn AuthMachine::cancel(self : AuthMachine) -> Unit {
self.stop_conv()
self.phase = Done
self.authorized = false
self.changed = true
}
///| Read what PAM said and move on.
pub fn AuthMachine::pump(self : AuthMachine) -> Unit {
let c = match self.conv {
Some(c) => c
None => return
}
for ev in c.poll() {
alog(
"PAM " +
(match ev {
PromptEchoOff(t) => "asks (hidden) \"" + t + "\""
PromptEchoOn(t) => "asks (shown) \"" + t + "\""
ErrorMsg(t) => "error \"" + t + "\""
TextInfo(t) => "info \"" + t + "\""
Success => "SUCCESS"
Failure => "FAILURE"
Gone => "check ended without a verdict"
}),
)
self.event(ev)
if self.conv is None {
return
}
}
}
///| One thing PAM said.
pub fn AuthMachine::event(self : AuthMachine, ev : HelperEvent) -> Unit {
self.changed = true
match ev {
TextInfo(m) | ErrorMsg(m) =>
match face_message(m, ev is ErrorMsg(_)) {
Some(f) => {
self.face = f
return
}
None => ()
}
_ => ()
}
match ev {
PromptEchoOff(p) | PromptEchoOn(p) => {
// The face module gave up without saying why (a timeout, or Howdy's silent failures).
if self.face == Scanning {
self.face = FaceFailed("Face not recognized")
}
self.phase = Asking
self.prompt = tidy_prompt(p)
self.echo = ev is PromptEchoOn(_)
self.info = ""
match self.queued {
Some(q) => {
self.queued = None
self.send_answer(q)
}
None => ()
}
}
ErrorMsg(m) => self.error = m.trim(chars=" \n").to_string()
TextInfo(m) => self.info = m.trim(chars=" \n").to_string()
Success => {
self.stop_conv()
self.phase = Done
self.authorized = true
}
Failure if self.phase == Checking => {
// A wrong answer: count it and ask again with a new check.
self.failures = self.failures + 1
let pam_said = self.error
let was_echo = self.echo
self.begin()
if self.phase == Starting {
self.error = if pam_said != "" {
pam_said
} else if was_echo {
"That didn't work. Try again."
} else {
"Wrong password. Try again."
}
}
}
Failure =>
self.fail(
if self.error != "" {
self.error
} else {
"The password check ended before asking for a password."
},
)
Gone =>
self.fail(
if self.phase == Checking {
"The password check quit while checking the password."
} else {
"The password check quit before asking for a password."
},
)
}
}
///| The fd to wait on (-1: none, or a conversation without one).
pub fn AuthMachine::fd(self : AuthMachine) -> Int {
match self.conv {
Some(c) => c.fd()
None => -1
}
}
///| Whether a conversation without an fd runs (the main loop polls it on a timer).
pub fn AuthMachine::needs_timer(self : AuthMachine) -> Bool {
match self.conv {
Some(c) => c.fd() < 0
None => false
}
}
///| Whether something changed since the last call.
pub fn AuthMachine::take_changed(self : AuthMachine) -> Bool {
let c = self.changed
self.changed = false
c
}
///| The face state's name and text on the link.
pub fn face_fields(f : FaceState) -> (String, String) {
match f {
NoFace => ("", "")
Scanning => ("scanning", "")
Matched => ("matched", "")
FaceFailed(why) => ("failed", why)
}
}
///| The face state a link name and text stand for.
pub fn face_of(name : String, text : String) -> FaceState {
match name {
"scanning" => Scanning
"matched" => Matched
"failed" => FaceFailed(text)
_ => NoFace
}
}
///| The `state` message for request `id`.
pub fn AuthMachine::state_fields(self : AuthMachine, id : String) -> Array[String] {
let (f, ft) = face_fields(self.face)
[
"state",
id,
phase_name(self.phase),
self.prompt,
if self.echo { "1" } else { "0" },
self.error,
self.info,
f,
ft,
self.failures.to_string(),
self.user_sel.to_string(),
]
}
+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)
}
+412
View File
@@ -0,0 +1,412 @@
///| The dialog as the compositor sees it: the request and state the agent sent (wire.mbt), plus
/// what only the screen needs: the typed text (kept as characters so it can be wiped, and
/// never sent anywhere but the agent), the show/hide toggle, Caps Lock, which control has the
/// keyboard, Details open or not, and the shake after a wrong password.
///
/// It decides nothing about the password check: Enter sends the answer (or asks for a retry
/// when the check failed) and the agent's state machine (machine.mbt) does the rest.
///| The dialog's controls, in Tab order.
pub(all) enum Focus {
Field
User
Reveal
Details
Cancel
Allow
} derive(Eq, Debug)
///| What the compositor sends the agent after a key or a click.
pub(all) enum ViewAction {
Nothing
/// Send the typed answer (take it with `take_answer`).
Submit
/// Start the check again (it failed).
Retry
/// Answer as account n.
PickUser(Int)
/// The user dismissed the dialog.
Dismiss
} derive(Eq, Debug)
///| Evdev key codes the dialog knows.
pub let key_esc : UInt = 1
///|
pub let key_backspace : UInt = 14
///|
pub let key_tab : UInt = 15
///|
pub let key_enter : UInt = 28
///|
pub let key_kp_enter : UInt = 96
///|
pub let key_space : UInt = 57
///|
pub let key_left : UInt = 105
///|
pub let key_right : UInt = 106
///|
pub let key_up : UInt = 103
///|
pub let key_down : UInt = 108
///|
pub let key_u : UInt = 22
///|
pub let key_d : UInt = 32
///|
pub let key_r : UInt = 19
///| The dialog for one request.
pub(all) struct AuthView {
id : String
title : String
subtitle : String
command : String
program : String
icon_name : String
message : String
details : Array[(String, String)]
users : Array[AuthUser]
/// The first state arrived: the dialog is shown.
mut shown : Bool
// From the agent.
mut phase : Phase
mut prompt : String
mut echo : Bool
mut error : String
mut info : String
mut face : FaceState
/// When the face scan started (monotonic ms; the animation's clock).
mut face_at : UInt64
mut failures : Int
mut user_sel : Int
// The screen's own.
input : Array[Char]
mut reveal : Bool
mut caps : Bool
mut details_open : Bool
mut focus : Focus
/// When the last wrong password shook the card (monotonic ms), 0 for never.
mut shake_at : UInt64
}
///| A view from a `request` message's fields (after "request").
pub fn AuthView::from_request(f : Array[String]) -> AuthView {
let g = fn(i : Int) { f.get(i).unwrap_or("") }
{
id: g(1),
title: g(2),
subtitle: g(3),
command: g(4),
program: g(5),
icon_name: g(6),
message: g(7),
details: [],
users: [],
shown: false,
phase: Starting,
prompt: "Password",
echo: false,
error: "",
info: "",
face: NoFace,
face_at: 0UL,
failures: 0,
user_sel: 0,
input: [],
reveal: false,
caps: false,
details_open: false,
focus: Field,
shake_at: 0UL,
}
}
///| Take a `detail`, `user` or `state` message for this request. `now`: monotonic ms.
pub fn AuthView::apply(self : AuthView, f : Array[String], now : UInt64) -> Unit {
let g = fn(i : Int) { f.get(i).unwrap_or("") }
match g(0) {
"detail" => self.details.push((g(2), g(3)))
"user" => self.users.push({ name: g(2), real_name: g(3), uid: parse_uint(g(4)).unwrap_or(-1) })
"state" => {
let phase = phase_of(g(2))
let failures = parse_uint(g(9)).unwrap_or(0)
let user_sel = parse_uint(g(10)).unwrap_or(0)
let face = face_of(g(7), g(8))
if failures > self.failures {
// A wrong password: shake, and start over in the field.
self.shake_at = if now == 0UL { 1UL } else { now }
self.wipe()
self.focus = Field
}
if user_sel != self.user_sel {
self.wipe()
}
if face == Scanning && self.face != Scanning {
self.face_at = if now == 0UL { 1UL } else { now }
}
self.shown = true
self.phase = phase
self.prompt = g(3)
self.echo = g(4) == "1"
self.error = g(5)
self.info = g(6)
self.face = face
self.failures = failures
self.user_sel = user_sel
}
_ => ()
}
}
///| The account answering, if any.
pub fn AuthView::user(self : AuthView) -> AuthUser? {
self.users.get(self.user_sel)
}
///| Wipe what was typed.
pub fn AuthView::wipe(self : AuthView) -> Unit {
for i = 0; i < self.input.length(); i = i + 1 {
self.input[i] = '\u{0}'
}
self.input.clear()
}
///| What was typed, as UTF-8 bytes in a buffer the caller zeroes after use; the field is wiped.
pub fn AuthView::take_answer(self : AuthView) -> FixedArray[Byte] {
let n = self.input.fold(init=0, fn(acc, c) {
let v = c.to_int()
acc + (if v < 0x80 { 1 } else if v < 0x800 { 2 } else if v < 0x10000 { 3 } else { 4 })
})
let out : FixedArray[Byte] = FixedArray::make(n, b'\x00')
let mut k = 0
for c in self.input {
let v = c.to_int()
if v < 0x80 {
out[k] = v.to_byte()
k = k + 1
} else if v < 0x800 {
out[k] = (0xC0 | (v >> 6)).to_byte()
out[k + 1] = (0x80 | (v & 0x3F)).to_byte()
k = k + 2
} else if v < 0x10000 {
out[k] = (0xE0 | (v >> 12)).to_byte()
out[k + 1] = (0x80 | ((v >> 6) & 0x3F)).to_byte()
out[k + 2] = (0x80 | (v & 0x3F)).to_byte()
k = k + 3
} else {
out[k] = (0xF0 | (v >> 18)).to_byte()
out[k + 1] = (0x80 | ((v >> 12) & 0x3F)).to_byte()
out[k + 2] = (0x80 | ((v >> 6) & 0x3F)).to_byte()
out[k + 3] = (0x80 | (v & 0x3F)).to_byte()
k = k + 4
}
}
self.wipe()
out
}
///| Whether the field takes typing (not while PAM checks the answer, nor once it's over).
pub fn AuthView::editable(self : AuthView) -> Bool {
self.phase != Checking && self.phase != Done
}
///| What the main button does now: Retry after a failure with nothing typed, else Submit.
fn AuthView::submit(self : AuthView) -> ViewAction {
match self.phase {
Failed => if self.input.length() == 0 { Retry } else { Submit }
Asking => if self.input.length() == 0 && !self.echo { Nothing } else { Submit }
// Typed while a face is looked for: it goes in when PAM asks.
Starting => if self.input.length() > 0 { Submit } else { Nothing }
Checking | Done => Nothing
}
}
///| The main button's label.
pub fn AuthView::main_label(self : AuthView) -> String {
if self.phase == Failed && self.input.length() == 0 {
"Try again"
} else {
"Authenticate"
}
}
///| Whether the main button does anything now.
pub fn AuthView::main_enabled(self : AuthView) -> Bool {
self.submit() != Nothing
}
///| The controls Tab moves through, in order (the account picker only with several).
pub fn AuthView::focus_order(self : AuthView) -> Array[Focus] {
let out : Array[Focus] = [Field]
if self.users.length() > 1 {
out.push(User)
}
out.push(Reveal)
out.push(Details)
out.push(Cancel)
out.push(Allow)
out
}
///| Move the keyboard focus by `delta` along the Tab order.
fn AuthView::move_focus(self : AuthView, delta : Int) -> Unit {
let order = self.focus_order()
let i = order.search(self.focus).unwrap_or(0)
let n = order.length()
self.focus = order[((i + delta) % n + n) % n]
}
///| The account `delta` away (wrapping).
fn AuthView::cycle_user(self : AuthView, delta : Int) -> ViewAction {
let n = self.users.length()
if n < 2 {
return Nothing
}
PickUser(((self.user_sel + delta) % n + n) % n)
}
///| Activate control `f` (Enter or Space on it, or a click).
pub fn AuthView::activate(self : AuthView, f : Focus) -> ViewAction {
match f {
Field => {
self.focus = Field
Nothing
}
User => {
self.focus = User
self.cycle_user(1)
}
Reveal => {
self.focus = Reveal
self.reveal = !self.reveal
Nothing
}
Details => {
self.focus = Details
self.details_open = !self.details_open
Nothing
}
Cancel => Dismiss
Allow => self.submit()
}
}
///| A key press: `code` (evdev), the modifiers (mask_shift, mask_ctrl, mask_alt bits), and the
/// character it types on the current layout, if any.
pub fn AuthView::key(self : AuthView, code : UInt, mods : UInt, ch : Char?) -> ViewAction {
let ctrl = (mods & mask_ctrl) != 0U
let shift = (mods & mask_shift) != 0U
let alt = (mods & mask_alt) != 0U
if code == key_esc {
return Dismiss
}
if code == key_tab {
self.move_focus(if shift { -1 } else { 1 })
return Nothing
}
if code == key_enter || code == key_kp_enter {
return match self.focus {
Field | Allow => self.submit()
other => self.activate(other)
}
}
// Alt+D details, Alt+R reveal: reachable from the field without leaving it.
if alt && code == key_d {
self.details_open = !self.details_open
return Nothing
}
if alt && code == key_r {
self.reveal = !self.reveal
return Nothing
}
if self.focus == User && (code == key_left || code == key_up) {
return self.cycle_user(-1)
}
if self.focus == User && (code == key_right || code == key_down) {
return self.cycle_user(1)
}
if code == key_space && self.focus != Field {
return self.activate(self.focus)
}
if !self.editable() {
return Nothing
}
if code == key_backspace || (ctrl && code == key_u) {
if ctrl {
self.wipe()
} else if self.input.length() > 0 {
let last = self.input.length() - 1
self.input[last] = '\u{0}'
ignore(self.input.pop())
}
self.focus = Field
return Nothing
}
if ctrl || alt {
return Nothing
}
match ch {
Some(c) => {
if self.input.length() < 512 {
self.input.push(c)
}
self.focus = Field
Nothing
}
None => Nothing
}
}
///| Horizontal offset of the card while it shakes after a wrong password (0 when still).
pub fn AuthView::shake_offset(self : AuthView, now : UInt64) -> Int {
if self.shake_at == 0UL || now < self.shake_at {
return 0
}
let t = (now - self.shake_at).to_int()
let dur = 420
if t >= dur {
return 0
}
// Three swings, fading out.
let period = dur / 6
let phase = t % period
let tri = if phase < period / 2 { phase * 4 - period } else { 3 * period - phase * 4 }
let amp = 12 * (dur - t) / dur
tri * amp / period
}
///| Whether the card is still shaking.
pub fn AuthView::shaking(self : AuthView, now : UInt64) -> Bool {
self.shake_at != 0UL && now >= self.shake_at && now - self.shake_at < 420UL
}
///| The field's text as shown: the answer (echo or revealed) or one dot per character.
pub fn AuthView::field_text(self : AuthView) -> String {
if self.echo || self.reveal {
String::from_array(self.input)
} else {
let sb = StringBuilder::new()
for _ in self.input {
sb.write_char('●')
}
sb.to_string()
}
}
///| The number of characters typed.
pub fn AuthView::typed(self : AuthView) -> Int {
self.input.length()
}
+214
View File
@@ -0,0 +1,214 @@
///| The link between Chandra's polkit agent (chandra-polkit-agent, agent_loop.mbt) and the
/// compositor that draws its dialog (compositor/host/auth.mbt).
///
/// One message per line; fields are separated by tabs, and a backslash, tab or newline inside a
/// field is written \\, \t or \n. The compositor starts the agent on a socket pair (sys
/// spawn_socket): the agent's stdin and stdout are the compositor's end, so no other program
/// can open the dialog or read what is typed into it.
///
/// Agent to compositor:
/// ready registered with polkit; requests may follow
/// error <text> the agent can't serve (polkit refused, no bus); it exits
/// request <id> <title> <subtitle> <command> <program> <icon> <polkit message>
/// detail <id> <label> <value> a Details row (repeated)
/// user <id> <login> <real name> <uid> an account that may answer (repeated)
/// state <id> <phase> <prompt> <echo 0|1> <error> <info> <face> <face text> <failures> <user>
/// close <id> the request is over (answered, cancelled, withdrawn)
/// Compositor to agent:
/// answer <id> <text> what was typed (the field is wiped once it is sent)
/// user <id> <index> answer as another account
/// retry <id> start the password check again after it failed
/// cancel <id> the user dismissed the dialog
///| Append field byte `b`, escaped.
fn push_escaped(out : Array[Byte], b : Byte) -> Unit {
if b == b'\\' {
out.push(b'\\')
out.push(b'\\')
} else if b == b'\t' {
out.push(b'\\')
out.push(b't')
} else if b == b'\n' {
out.push(b'\\')
out.push(b'n')
} else {
out.push(b)
}
}
///| One message: the fields, escaped, joined by tabs, and a newline.
pub fn encode_line(fields : Array[String]) -> Bytes {
let out : Array[Byte] = []
for i, f in fields {
if i > 0 {
out.push(b'\t')
}
let b = @utf8.encode(f)
for k = 0; k < b.length(); k = k + 1 {
push_escaped(out, b[k])
}
}
out.push(b'\n')
Bytes::from_array(out)
}
///| `head` fields then `secret` as the last field, in a buffer the caller zeroes after sending.
pub fn encode_secret_line(head : Array[String], secret : FixedArray[Byte]) -> FixedArray[Byte] {
let out : Array[Byte] = []
for f in head {
let b = @utf8.encode(f)
for k = 0; k < b.length(); k = k + 1 {
push_escaped(out, b[k])
}
out.push(b'\t')
}
for k = 0; k < secret.length(); k = k + 1 {
push_escaped(out, secret[k])
}
out.push(b'\n')
let buf = FixedArray::makei(out.length(), i => out[i])
for k = 0; k < out.length(); k = k + 1 {
out[k] = b'\x00'
}
buf
}
///| A line's fields as raw bytes (escapes undone), each in its own buffer.
pub fn split_fields(line : FixedArray[Byte]) -> Array[FixedArray[Byte]] {
let out : Array[FixedArray[Byte]] = []
let cur : Array[Byte] = []
let flush = fn() {
out.push(FixedArray::makei(cur.length(), i => cur[i]))
for k = 0; k < cur.length(); k = k + 1 {
cur[k] = b'\x00'
}
cur.clear()
}
let mut i = 0
while i < line.length() {
let b = line[i]
if b == b'\t' {
flush()
} else if b == b'\\' && i + 1 < line.length() {
let n = line[i + 1]
cur.push(if n == b't' { b'\t' } else if n == b'n' { b'\n' } else { n })
i = i + 1
} else {
cur.push(b)
}
i = i + 1
}
flush()
out
}
///| A field as text.
pub fn field_text(b : FixedArray[Byte]) -> String {
@utf8.decode_lossy(Bytes::makei(b.length(), i => b[i]))
}
///| A line's fields as text.
pub fn decode_line(line : FixedArray[Byte]) -> Array[String] {
split_fields(line).map(field_text)
}
///| A stream socket read and written one line at a time, without blocking on reads.
pub struct LineConn {
mut fd : Int
inbuf : Array[Byte]
/// The other end closed it.
mut eof : Bool
}
///|
pub fn LineConn::new(fd : Int) -> LineConn {
{ fd, inbuf: [], eof: fd < 0 }
}
///| Whole lines that arrived (without their newlines); sets `eof` when the other end closed.
/// The bytes read are wiped from the buffer as lines are taken (answers pass through here).
pub fn LineConn::read_lines(self : LineConn) -> Array[FixedArray[Byte]] {
let out : Array[FixedArray[Byte]] = []
if self.fd < 0 {
return out
}
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00')
while @sys.poll_read(self.fd, 0) > 0 {
let (n, extra) = @sys.recvmsg_fd(self.fd, buf, buf.length())
if extra >= 0 {
@sys.close_fd(extra)
}
if n == -1 {
break
}
if n <= 0 {
self.eof = true
break
}
for i = 0; i < n; i = i + 1 {
self.inbuf.push(buf[i])
buf[i] = b'\x00'
}
}
let mut start = 0
for i = 0; i < self.inbuf.length(); i = i + 1 {
if self.inbuf[i] == b'\n' {
out.push(FixedArray::makei(i - start, k => self.inbuf[start + k]))
start = i + 1
}
}
if start > 0 {
for k = 0; k < start; k = k + 1 {
self.inbuf[k] = b'\x00'
}
let rest = self.inbuf[start:].to_array()
self.inbuf.clear()
self.inbuf.append(rest)
}
out
}
///| Send raw bytes (a whole line). False when the other end is gone.
pub fn LineConn::send_raw(self : LineConn, b : Bytes) -> Bool {
if self.fd < 0 {
return false
}
@sys.sendmsg_fd(self.fd, b, -1) == b.length()
}
///| Send one message.
pub fn LineConn::send(self : LineConn, fields : Array[String]) -> Bool {
self.send_raw(encode_line(fields))
}
///| Send a line built by `encode_secret_line`, then zero it.
pub fn LineConn::send_secret(self : LineConn, line : FixedArray[Byte]) -> Bool {
let b = Bytes::makei(line.length(), i => line[i])
let ok = self.send_raw(b)
zero(line)
ok
}
///| The socket (-1 once closed).
pub fn LineConn::fd(self : LineConn) -> Int {
self.fd
}
///|
pub fn LineConn::close(self : LineConn) -> Unit {
if self.fd >= 0 {
@sys.close_fd(self.fd)
self.fd = -1
}
for k = 0; k < self.inbuf.length(); k = k + 1 {
self.inbuf[k] = b'\x00'
}
self.inbuf.clear()
}
///| Zero a buffer a password was in.
pub fn zero(b : FixedArray[Byte]) -> Unit {
for i = 0; i < b.length(); i = i + 1 {
b[i] = b'\x00'
}
}