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
+3447 -1791

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
///| chandra-polkit-agent: Chandra's polkit authentication agent. The compositor starts it on a
/// socket pair (its stdin and stdout) and draws the dialog it asks for; see
/// compositor/polkit/agent_loop.mbt and docs/auth-dialog.md. It logs to stderr (the session log).
///
/// chandra-polkit-agent be this session's polkit agent
/// chandra-polkit-agent --demo MODE one pretend request (chandra-ctl auth-demo), then exit
///|
fn main {
let args = @env.args()
let i = args.search("--demo")
let agent = match i {
Some(k) => @polkit.AgentLoop::new_demo(0, args.get(k + 1).unwrap_or("password"))
None => @polkit.AgentLoop::new(0, @polkit.PolkitAgent::new())
}
agent.run()
}
+9
View File
@@ -0,0 +1,9 @@
import {
"moonbitlang/core/builtin",
"moonbitlang/core/env",
"chandra/desktop/compositor/polkit" @polkit,
}
supported_targets = "-all+native"
pkgtype(kind: "executable")
+350 -723
View File
File diff suppressed because it is too large. Load diff
+503
View File
@@ -0,0 +1,503 @@
///| Drawing the password dialog (auth.mbt) and its notice.
///| Colours the palette has no slot for: errors and warnings, readable on the card.
fn auth_colors(p : @scene.ThemePalette) -> (@scene.Rgba, @scene.Rgba) {
// A light card (bright foreground means dark theme).
let dark = p.foreground.r.to_int() + p.foreground.g.to_int() + p.foreground.b.to_int() > 384
if dark {
(@scene.Rgba::from_hex("#f87171"), @scene.Rgba::from_hex("#fbbf24"))
} else {
(@scene.Rgba::from_hex("#c62828"), @scene.Rgba::from_hex("#8a5a00"))
}
}
///| `text` broken into lines no wider than `max_w`, at word boundaries (long words by character).
fn wrap_text(text : String, size : Int, bold : Bool, mono : Bool, max_w : Int) -> Array[String] {
let out : Array[String] = []
for para in text.split("\n") {
let mut line = ""
for w in para.split(" ") {
let word = w.to_string()
let cand = if line == "" { word } else { line + " " + word }
if @renderer.text_width(cand, size, bold, mono) <= max_w {
line = cand
continue
}
if line != "" {
out.push(line)
line = ""
}
// A word wider than the line: split it.
let mut part = ""
for c in word {
let next = part + c.to_string()
if @renderer.text_width(next, size, bold, mono) > max_w && part != "" {
out.push(part)
part = c.to_string()
} else {
part = next
}
}
line = part
}
out.push(line)
}
out
}
///| A padlock, for requests without an app icon.
fn lock_glyph(x : Int, y : Int, s : Int, c : @scene.Rgba, bg : @scene.Rgba, ops : Array[@scene.DrawOp]) -> Unit {
let bw = s * 5 / 8
let bh = s / 2
let bx = x + (s - bw) / 2
let by = y + s - bh - s / 10
let sw = bw * 5 / 8
let shx = x + (s - sw) / 2
ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(shx, by - bh * 3 / 4, sw, bh), c, s / 12 + 1, sw / 2))
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(bx, by, bw, bh), c, s / 10))
ops.push(@scene.DrawOp::Circle(x + s / 2, by + bh * 2 / 5, s / 14 + 1, bg, true))
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x + s / 2 - 1, by + bh * 2 / 5, 3, bh / 3), bg, 1))
}
///| A button: filled (the default action) or outlined; with a focus ring.
fn auth_button(
r : @scene.Rect,
label : String,
primary : Bool,
focused : Bool,
hover : Bool,
enabled : Bool,
p : @scene.ThemePalette,
fs : Int,
rad : Int,
ops : Array[@scene.DrawOp],
) -> Unit {
if primary {
let a = p.accent
let alpha = if enabled { if hover { 230 } else { 255 } } else { 120 }
ops.push(@scene.DrawOp::FillRect(r, @scene.Rgba::new(a.r.to_int(), a.g.to_int(), a.b.to_int(), alpha), rad))
ops.push(@scene.DrawOp::Text(r.x + r.w / 2, r.y + r.h / 2, label, fs, p.accent_foreground, @scene.TextAlign::Center, true))
} else {
if hover {
ops.push(@scene.DrawOp::FillRect(r, p.surface_hover, rad))
}
ops.push(@scene.DrawOp::StrokeRect(r, p.border, 1, rad))
ops.push(@scene.DrawOp::Text(r.x + r.w / 2, r.y + r.h / 2, label, fs, p.foreground, @scene.TextAlign::Center, false))
}
if focused {
ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(r.x - 3, r.y - 3, r.w + 6, r.h + 6), p.accent, 2, rad + 3))
}
}
///| A face outline (head, eyes, smile) centred at (cx, cy), `r` the head's radius.
fn face_glyph(cx : Int, cy : Int, r : Int, c : @scene.Rgba, ops : Array[@scene.DrawOp]) -> Unit {
ops.push(@scene.DrawOp::Circle(cx, cy, r, c, false))
ops.push(@scene.DrawOp::Circle(cx - r * 2 / 5, cy - r / 4, r / 8 + 1, c, true))
ops.push(@scene.DrawOp::Circle(cx + r * 2 / 5, cy - r / 4, r / 8 + 1, c, true))
ops.push(@scene.DrawOp::Line(cx - r / 2, cy + r / 4, cx - r / 5, cy + r / 2, c, 2))
ops.push(@scene.DrawOp::Line(cx - r / 5, cy + r / 2, cx + r / 5, cy + r / 2, c, 2))
ops.push(@scene.DrawOp::Line(cx + r / 5, cy + r / 2, cx + r / 2, cy + r / 4, c, 2))
}
///| Point `k` of 12 on a circle of radius `r` (clockwise from the top).
fn ring_point(k : Int, r : Int) -> (Int, Int) {
// sin and cos of k * 30 degrees, times 1000.
let s = [0, 500, 866, 1000, 866, 500, 0, -500, -866, -1000, -866, -500]
let c = [1000, 866, 500, 0, -500, -866, -1000, -866, -500, 0, 500, 866]
(s[k % 12] * r / 1000, -c[k % 12] * r / 1000)
}
///| A right-pointing (`down`: down-pointing) chevron centred at (cx, cy).
fn chevron(cx : Int, cy : Int, s : Int, down : Bool, left : Bool, c : @scene.Rgba, ops : Array[@scene.DrawOp]) -> Unit {
if down {
ops.push(@scene.DrawOp::Line(cx - s, cy - s / 2, cx, cy + s / 2, c, 2))
ops.push(@scene.DrawOp::Line(cx, cy + s / 2, cx + s, cy - s / 2, c, 2))
} else if left {
ops.push(@scene.DrawOp::Line(cx + s / 2, cy - s, cx - s / 2, cy, c, 2))
ops.push(@scene.DrawOp::Line(cx - s / 2, cy, cx + s / 2, cy + s, c, 2))
} else {
ops.push(@scene.DrawOp::Line(cx - s / 2, cy - s, cx + s / 2, cy, c, 2))
ops.push(@scene.DrawOp::Line(cx + s / 2, cy, cx - s / 2, cy + s, c, 2))
}
}
///| Draw the dialog (everything below it dimmed) and note where its controls are.
fn ChandraCompositor::auth_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] {
let ops : Array[@scene.DrawOp] = []
let ui = match self.auth {
Some(u) => u
None => return ops
}
let d = ui.view
let now = @sys.monotonic_ms()
let p = self.theme.palette
let (err_c, warn_c) = auth_colors(p)
let fs = self.theme.font_size
let rad = self.theme.radius + 2
let sw = self.output_w
let sh = self.output_h
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, sw, sh), @scene.Rgba::new(0, 0, 0, 150), 0))
let w = (sw - 32).min(460)
let pad = 24
let inner = w - pad * 2
let hover = self.auth_hit(ui)
// Lay out top to bottom into `body` (card-relative y), then place the card.
let body : Array[@scene.DrawOp] = []
let hits : Array[(@scene.Rect, @polkit.Focus)] = []
let mut y = pad
// Header: icon, overline, title, subtitle.
let icon_s = 48
let tx = pad + icon_s + 16
let tw = w - tx - pad
let header_top = y
let mut hy = y
body.push(@scene.DrawOp::Text(tx, hy + 7, "AUTHENTICATION REQUIRED", fs - 3, p.accent, @scene.TextAlign::Left, true))
hy = hy + 18
let title_lines = wrap_text(d.title, fs + 3, true, false, tw)
for l in title_lines {
body.push(@scene.DrawOp::Text(tx, hy + (fs + 8) / 2, l, fs + 3, p.foreground, @scene.TextAlign::Left, true))
hy = hy + fs + 8
}
hy = hy + 2
for l in wrap_text(d.subtitle, fs - 1, false, false, tw) {
body.push(@scene.DrawOp::Text(tx, hy + (fs + 4) / 2, l, fs - 1, p.foreground_muted, @scene.TextAlign::Left, false))
hy = hy + fs + 4
}
// Icon tile.
let ix = pad
let iy = header_top + 2
body.push(@scene.DrawOp::FillRect(@scene.Rect::new(ix, iy, icon_s, icon_s), p.surface_hover, 12))
if ui.icon != 0U {
body.push(@scene.DrawOp::Image(@scene.Rect::new(ix + 6, iy + 6, icon_s - 12, icon_s - 12), ui.icon))
} else {
lock_glyph(ix + 8, iy + 8, icon_s - 16, p.accent, p.surface_hover, body)
}
y = hy.max(iy + icon_s) + 14
// The command, as a shell would read it.
if d.command != "" {
let mfs = fs - 1
let lines = wrap_text(d.command, mfs, false, true, inner - 24)
let shown = if lines.length() > 4 { lines[:4].to_array() } else { lines }
if lines.length() > 4 {
shown[3] = shown[3] + " …"
}
let lh = mfs + 6
let bh = shown.length() * lh + 16
body.push(@scene.DrawOp::FillRect(@scene.Rect::new(pad, y, inner, bh), p.surface_hover, rad))
body.push(@scene.DrawOp::FillRect(@scene.Rect::new(pad, y, 3, bh), p.accent, 1))
for i, l in shown {
body.push(@scene.DrawOp::MonoText(pad + 14, y + 8 + i * lh + lh / 2, l, mfs, p.foreground, @scene.TextAlign::Left, false))
}
y = y + bh + 14
}
// Who authenticates.
match d.user() {
Some(u) => {
let rh = 40
let r = @scene.Rect::new(pad, y, inner, rh)
let many = d.users.length() > 1
if many {
if hover == Some(User) {
body.push(@scene.DrawOp::FillRect(r, p.surface_hover, rad))
}
hits.push((r, User))
}
let initial = if u.real_name != "" { u.real_name[:1].to_string() } else { u.name[:1].to_string() }
body.push(@scene.DrawOp::Circle(pad + 20, y + rh / 2, 15, p.accent, true))
body.push(@scene.DrawOp::Text(pad + 20, y + rh / 2, initial.to_upper(), fs, p.accent_foreground, @scene.TextAlign::Center, true))
let name = if u.real_name != "" && u.real_name != u.name { u.real_name } else { u.name }
body.push(@scene.DrawOp::Text(pad + 44, y + rh / 2 - 8, name, fs, p.foreground, @scene.TextAlign::Left, true))
let login = if u.uid == 0 { "root" } else { u.name }
let sub = if many {
login + " · account " + (d.user_sel + 1).to_string() + " of " + d.users.length().to_string()
} else {
login
}
body.push(@scene.DrawOp::Text(pad + 44, y + rh / 2 + 9, sub, fs - 2, p.foreground_muted, @scene.TextAlign::Left, false))
if many {
chevron(pad + inner - 34, y + rh / 2, 5, false, true, p.foreground_muted, body)
chevron(pad + inner - 14, y + rh / 2, 5, false, false, p.foreground_muted, body)
if d.focus == User {
body.push(@scene.DrawOp::StrokeRect(r, p.accent, 2, rad))
}
}
y = y + rh + 12
}
None => ()
}
// Face unlock: what the face module in the PAM stack is doing (docs/face-unlock.md).
if d.face != NoFace {
let rh = 48
let cx = pad + 25
let cy = y + rh / 2
let tint = match d.face {
FaceFailed(_) => warn_c
_ => p.accent
}
body.push(@scene.DrawOp::FillRect(@scene.Rect::new(pad, y, inner, rh), p.surface_hover, rad))
face_glyph(cx, cy, 13, if d.face is FaceFailed(_) { p.foreground_muted } else { p.foreground }, body)
match d.face {
Scanning => {
// A ring of dots sweeping round the face.
let t = ((now - d.face_at) / 70UL).to_int()
for k = 0; k < 12; k = k + 1 {
let a = (k + t) % 12
let (dx, dy) = ring_point(a, 19)
let alpha = 40 + k * 18
body.push(@scene.DrawOp::Circle(cx + dx, cy + dy, 2, @scene.Rgba::new(p.accent.r.to_int(), p.accent.g.to_int(), p.accent.b.to_int(), alpha), true))
}
}
Matched => {
body.push(@scene.DrawOp::Circle(cx + 13, cy + 11, 8, p.accent, true))
body.push(@scene.DrawOp::Line(cx + 9, cy + 11, cx + 12, cy + 14, p.accent_foreground, 2))
body.push(@scene.DrawOp::Line(cx + 12, cy + 14, cx + 17, cy + 8, p.accent_foreground, 2))
}
FaceFailed(_) => {
body.push(@scene.DrawOp::Circle(cx + 13, cy + 11, 8, warn_c, true))
body.push(@scene.DrawOp::Line(cx + 10, cy + 8, cx + 16, cy + 14, p.surface_popup, 2))
body.push(@scene.DrawOp::Line(cx + 16, cy + 8, cx + 10, cy + 14, p.surface_popup, 2))
}
NoFace => ()
}
let (title, sub) = match d.face {
Scanning => ("Looking for your face…", "Or type your password")
Matched => ("Face recognized", "")
FaceFailed(why) => (why, "Type your password instead")
NoFace => ("", "")
}
let tx = pad + 54
if sub == "" {
body.push(@scene.DrawOp::Text(tx, cy, title, fs, tint, @scene.TextAlign::Left, true))
} else {
body.push(@scene.DrawOp::Text(tx, cy - 8, title, fs, tint, @scene.TextAlign::Left, true))
body.push(@scene.DrawOp::Text(tx, cy + 10, sub, fs - 2, p.foreground_muted, @scene.TextAlign::Left, false))
}
y = y + rh + 12
}
// The prompt and the field.
body.push(@scene.DrawOp::Text(pad, y + 7, d.prompt, fs - 1, p.foreground_muted, @scene.TextAlign::Left, true))
y = y + 20
let fh = 40
let field = @scene.Rect::new(pad, y, inner, fh)
let enabled = d.editable()
body.push(@scene.DrawOp::FillRect(field, p.surface, rad))
let edge = if d.error != "" && d.typed() == 0 { err_c } else if d.focus == Field { p.accent } else { p.border }
body.push(@scene.DrawOp::StrokeRect(field, edge, if d.focus == Field || d.error != "" { 2 } else { 1 }, rad))
hits.push((@scene.Rect::new(pad, y, inner - 70, fh), Field))
// Show / Hide (not for prompts that show the answer anyway).
let text_right = if d.echo { pad + inner - 12 } else { pad + inner - 76 }
if !d.echo {
let rr = @scene.Rect::new(pad + inner - 68, y + 6, 60, fh - 12)
if hover == Some(Reveal) || d.focus == Reveal {
body.push(@scene.DrawOp::FillRect(rr, p.surface_hover, rad - 2))
}
if d.focus == Reveal {
body.push(@scene.DrawOp::StrokeRect(rr, p.accent, 2, rad - 2))
}
body.push(@scene.DrawOp::Text(rr.x + rr.w / 2, rr.y + rr.h / 2, if d.reveal { "Hide" } else { "Show" }, fs - 1, p.accent, @scene.TextAlign::Center, true))
hits.push((rr, Reveal))
}
body.push(@scene.DrawOp::PushClip(@scene.Rect::new(pad + 8, y, text_right - pad - 8, fh)))
let cy = y + fh / 2
let mut caret_x = pad + 13
if d.typed() == 0 {
let hint = match d.phase {
Starting => if d.face == Scanning { "Type your password" } else { "Preparing…" }
Failed => "Type your password, or press Enter to try again"
_ => if d.echo { "Type your answer" } else { "Type your password" }
}
body.push(@scene.DrawOp::Text(pad + 18, cy, hint, fs, @scene.Rgba::new(p.foreground_muted.r.to_int(), p.foreground_muted.g.to_int(), p.foreground_muted.b.to_int(), 150), @scene.TextAlign::Left, false))
} else if d.echo || d.reveal {
// Keep the end of long text in view.
let t = d.field_text()
let tw2 = @renderer.text_width(t, fs + 1, false, false)
let avail = text_right - pad - 22
let x0 = if tw2 > avail { pad + 14 - (tw2 - avail) } else { pad + 14 }
body.push(@scene.DrawOp::Text(x0, cy, t, fs + 1, if enabled { p.foreground } else { p.foreground_muted }, @scene.TextAlign::Left, false))
caret_x = x0 + tw2 + 2
} else {
let n = d.typed()
let step = 14
let avail = text_right - pad - 22
let total = n * step
let x0 = if total > avail { pad + 14 - (total - avail) } else { pad + 14 }
for i = 0; i < n; i = i + 1 {
body.push(@scene.DrawOp::Circle(x0 + i * step + 5, cy, 4, if enabled { p.foreground } else { p.foreground_muted }, true))
}
caret_x = x0 + total + 2
}
if d.focus == Field && enabled {
body.push(@scene.DrawOp::FillRect(@scene.Rect::new(caret_x, cy - fs / 2 - 2, 2, fs + 4), p.accent, 0))
}
body.push(@scene.DrawOp::PopClip)
y = y + fh + 10
// Status: busy, Caps Lock, error, PAM's information.
let status : Array[(String, @scene.Rgba, Bool)] = []
if d.phase == Checking {
status.push(("Checking…", p.foreground_muted, true))
}
if d.caps && !d.echo {
status.push(("Caps Lock is on", warn_c, false))
}
if d.error != "" {
status.push((d.error, err_c, false))
}
if d.phase == Failed {
status.push(("Nothing was checked. Press Enter or Try again to start over.", p.foreground_muted, false))
}
if d.info != "" {
status.push((d.info, p.foreground, false))
}
for s in status {
let lines = wrap_text(s.0, fs - 1, false, false, inner - 22)
// A marker: a spinner while busy, else a dot in the line's colour.
if s.2 {
let t = ((now - ui.opened) / 90UL).to_int()
for k = 0; k < 8; k = k + 1 {
let ang = (k + t) % 8
let (dx, dy) = match ang {
0 => (0, -6)
1 => (4, -4)
2 => (6, 0)
3 => (4, 4)
4 => (0, 6)
5 => (-4, 4)
6 => (-6, 0)
_ => (-4, -4)
}
let a = 50 + k * 29
body.push(@scene.DrawOp::Circle(pad + 6 + dx, y + 9 + dy, 2, @scene.Rgba::new(p.accent.r.to_int(), p.accent.g.to_int(), p.accent.b.to_int(), a), true))
}
} else {
body.push(@scene.DrawOp::Circle(pad + 6, y + 9, 3, s.1, true))
}
for l in lines {
body.push(@scene.DrawOp::Text(pad + 18, y + 9, l, fs - 1, s.1, @scene.TextAlign::Left, false))
y = y + fs + 5
}
y = y + 3
}
y = y + 6
// Details.
if d.details_open {
let rows : Array[(String, String)] = d.details.copy()
if d.message != "" && d.title != d.message {
rows.push(("polkit says", d.message))
}
let lw = 104
let dh0 = y
y = y + 10
let rows_ops : Array[@scene.DrawOp] = []
for r in rows {
let vl = wrap_text(r.1, fs - 2, false, r.0 == "Action" || r.0 == "Unit", inner - lw - 24)
rows_ops.push(@scene.DrawOp::Text(pad + 12, y + 8, r.0, fs - 2, p.foreground_muted, @scene.TextAlign::Left, true))
for l in vl {
if r.0 == "Action" || r.0 == "Unit" {
rows_ops.push(@scene.DrawOp::MonoText(pad + 12 + lw, y + 8, l, fs - 2, p.foreground, @scene.TextAlign::Left, false))
} else {
rows_ops.push(@scene.DrawOp::Text(pad + 12 + lw, y + 8, l, fs - 2, p.foreground, @scene.TextAlign::Left, false))
}
y = y + fs + 3
}
y = y + 4
}
y = y + 6
body.push(@scene.DrawOp::FillRect(@scene.Rect::new(pad, dh0, inner, y - dh0), p.surface_hover, rad))
body.append(rows_ops)
y = y + 12
}
// Bottom row: Details toggle on the left, Cancel and Authenticate on the right.
let bh = 36
let dl = if d.details_open { "Hide details" } else { "Details" }
let dw = @renderer.text_width(dl, fs - 1, false, false) + 30
let dr = @scene.Rect::new(pad - 6, y, dw, bh)
if hover == Some(Details) {
body.push(@scene.DrawOp::FillRect(dr, p.surface_hover, rad))
}
chevron(pad + 6, y + bh / 2, 4, d.details_open, false, p.foreground_muted, body)
body.push(@scene.DrawOp::Text(pad + 18, y + bh / 2, dl, fs - 1, p.foreground_muted, @scene.TextAlign::Left, false))
if d.focus == Details {
body.push(@scene.DrawOp::StrokeRect(dr, p.accent, 2, rad))
}
hits.push((dr, Details))
let main = d.main_label()
let allow_w = @renderer.text_width(main, fs, true, false) + 32
let cancel_w = @renderer.text_width("Cancel", fs, false, false) + 32
let ar = @scene.Rect::new(pad + inner - allow_w, y, allow_w, bh)
let cr = @scene.Rect::new(ar.x - 10 - cancel_w, y, cancel_w, bh)
auth_button(cr, "Cancel", false, d.focus == Cancel, hover == Some(Cancel), true, p, fs, rad, body)
auth_button(ar, main, true, d.focus == Allow, hover == Some(Allow), d.main_enabled(), p, fs, rad, body)
hits.push((cr, Cancel))
hits.push((ar, Allow))
y = y + bh + pad
// Place the card in the middle (shaking after a failure) with a soft shadow.
let h = y
let cx = (sw - w) / 2 + d.shake_offset(now)
let cyy = ((sh - h) / 2).max(8)
for k = 1; k <= 4; k = k + 1 {
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(cx - k * 2, cyy - k * 2 + 6, w + k * 4, h + k * 4), @scene.Rgba::new(0, 0, 0, 22), rad + 6 + k * 2))
}
let opaque = @scene.Rgba::new(p.surface_popup.r.to_int(), p.surface_popup.g.to_int(), p.surface_popup.b.to_int(), 255)
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(cx, cyy, w, h), opaque, rad + 6))
ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(cx, cyy, w, h), p.border, 1, rad + 6))
ops.append(offset_ops_all(body, cx, cyy))
ui.hits.clear()
for hit in hits {
let r = hit.0
ui.hits.push((@scene.Rect::new(r.x + cx, r.y + cyy, r.w, r.h), hit.1))
}
ops
}
///| Move every op by (dx, dy).
fn offset_ops_all(ops : Array[@scene.DrawOp], dx : Int, dy : Int) -> Array[@scene.DrawOp] {
let mv = fn(r : @scene.Rect) { @scene.Rect::new(r.x + dx, r.y + dy, r.w, r.h) }
ops.map(op => match op {
FillRect(r, c, rad) => @scene.DrawOp::FillRect(mv(r), c, rad)
StrokeRect(r, c, w, rad) => @scene.DrawOp::StrokeRect(mv(r), c, w, rad)
Line(x0, y0, x1, y1, c, w) => @scene.DrawOp::Line(x0 + dx, y0 + dy, x1 + dx, y1 + dy, c, w)
Circle(x, y, r, c, f) => @scene.DrawOp::Circle(x + dx, y + dy, r, c, f)
Text(x, y, t, s, c, a, b) => @scene.DrawOp::Text(x + dx, y + dy, t, s, c, a, b)
MonoText(x, y, t, s, c, a, b) => @scene.DrawOp::MonoText(x + dx, y + dy, t, s, c, a, b)
PushClip(r) => @scene.DrawOp::PushClip(mv(r))
PopClip => PopClip
Image(r, h) => @scene.DrawOp::Image(mv(r), h)
})
}
///| The notice about the dialog itself (it couldn't start, it stopped), at the top of the screen.
fn ChandraCompositor::auth_notice_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] {
let ops : Array[@scene.DrawOp] = []
let n = match self.auth_notice {
Some(n) => n
None => return ops
}
let p = self.theme.palette
let (err_c, _) = auth_colors(p)
let fs = self.theme.font_size
let rad = self.theme.radius + 4
let w = (self.output_w - 32).min(560)
let pad = 16
let lines = wrap_text(n.text, fs, false, false, w - pad * 2 - 28)
let lh = fs + 6
let h = pad * 2 + 20 + lines.length() * lh + 6 + fs
let x = (self.output_w - w) / 2
let y = 16
for k = 1; k <= 3; k = k + 1 {
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x - k * 2, y - k * 2 + 4, w + k * 4, h + k * 4), @scene.Rgba::new(0, 0, 0, 22), rad + k * 2))
}
let opaque = @scene.Rgba::new(p.surface_popup.r.to_int(), p.surface_popup.g.to_int(), p.surface_popup.b.to_int(), 255)
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x, y, w, h), opaque, rad))
ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(x, y, w, h), err_c, 2, rad))
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x, y, 4, h), err_c, 2))
lock_glyph(x + pad, y + pad - 2, 20, err_c, opaque, ops)
ops.push(@scene.DrawOp::Text(x + pad + 28, y + pad + 8, "PASSWORD DIALOG", fs - 3, err_c, @scene.TextAlign::Left, true))
let mut ty = y + pad + 20
for l in lines {
ops.push(@scene.DrawOp::Text(x + pad + 28, ty + lh / 2, l, fs, p.foreground, @scene.TextAlign::Left, false))
ty = ty + lh
}
ops.push(@scene.DrawOp::Text(x + pad + 28, ty + 6 + fs / 2, "Click to dismiss", fs - 2, p.foreground_muted, @scene.TextAlign::Left, false))
n.rect = @scene.Rect::new(x, y, w, h)
ops
}
+492 -215
View File
@@ -1,7 +1,8 @@
///| Chandra's polkit agent and its dialog, against a mock polkit Authority on a private bus ///| Chandra's password dialog end to end: the compositor, chandra-polkit-agent's loop (run
/// (a real dbus-daemon) and a mock polkit-agent-helper-1 on a socket (the protocol polkit 126's /// in-process on a socket pair, and as the real program), a mock polkit Authority on a private
/// socket-activated helper speaks). Set CHANDRA_AUTH_SHOTS to a folder to get a PNG of each /// bus (a real dbus-daemon) and a mock polkit-agent-helper-1 on a socket (the protocol polkit
/// dialog state. /// 126's socket-activated helper speaks). Set CHANDRA_AUTH_SHOTS to a folder to get a PNG of
/// each dialog state.
///| A private message bus for the test (dbus-daemon's session config), its socket path. ///| A private message bus for the test (dbus-daemon's session config), its socket path.
fn auth_bus(tag : String) -> String? { fn auth_bus(tag : String) -> String? {
@@ -72,9 +73,9 @@ fn MockAuthority::new(path : String) -> MockAuthority {
} }
///| Ask the agent to authenticate, like polkitd does for run0. ///| Ask the agent to authenticate, like polkitd does for run0.
fn MockAuthority::begin(self : MockAuthority, cookie : String, details : Array[(String, String)]) -> Unit { fn MockAuthority::begin(self : MockAuthority, cookie : String, details : Array[(String, String)], uid? : UInt = 1000) -> Unit {
let ids : Array[@network.DValue] = [ let ids : Array[@network.DValue] = [
Struct([Str("unix-user"), @network.dict("v", [("uid", Variant(U32(1000)))])]), Struct([Str("unix-user"), @network.dict("v", [("uid", Variant(U32(uid)))])]),
Struct([Str("unix-group"), @network.dict("v", [("gid", Variant(U32(10)))])]), Struct([Str("unix-group"), @network.dict("v", [("gid", Variant(U32(10)))])]),
] ]
ignore( ignore(
@@ -112,28 +113,85 @@ fn fake_request(args : Array[@network.DValue]) -> @polkit.AuthRequest? {
} }
} }
///| A compositor with the agent on `bus` and the helper at `helper` (a socket we listen on). ///| A connected pair of stream sockets: (the compositor's end, the agent's end).
fn auth_comp(tag : String, bus : String, helper : String) -> @host.ChandraCompositor { fn sock_pair(tag : String) -> (Int, Int) {
let path = "/tmp/chandra-auth-link-" + tag + "-" + @sys.getpid().to_string()
@sys.unlink(path)
let l = @sys.unix_listen(path)
let c = @sys.unix_connect(path)
let mut s = -1
for i = 0; i < 100 && s < 0; i = i + 1 {
s = @sys.unix_accept(l)
if s < 0 {
@sys.sleep_ms(5)
}
}
@sys.close_fd(l)
@sys.unlink(path)
(c, s)
}
///| A compositor, the mock polkitd (when there is a bus), and the agents it started in-process.
struct Rig {
comp : @host.ChandraCompositor
a : MockAuthority?
agents : Array[@polkit.AgentLoop]
}
///| A compositor whose agents run in this process: the session's on `bus` with the helper at
/// `helper` (a socket the test listens on), demos as `chandra-ctl auth-demo` starts them.
fn rig(tag : String, bus : String?, helper : String) -> Rig {
let comp = new_comp("auth-" + tag) let comp = new_comp("auth-" + tag)
comp.auth_routes = [Socket(helper)] comp.login_session = true
comp.auth_describe = Some(fn(req) { let a = bus.map(b => MockAuthority::new(b))
let agents : Array[@polkit.AgentLoop] = []
let n : Ref[Int] = { val: 0 }
comp.auth_spawner = Some(fn(args) {
n.val = n.val + 1
let (mine, theirs) = sock_pair(tag + "-" + n.val.to_string())
let ag = match args {
["--demo", mode] => @polkit.AgentLoop::new_demo(theirs, mode)
_ => {
let subject = @network.DValue::Struct([Str("unix-session"), @network.dict("v", [("session-id", Variant(Str("2")))])])
@polkit.AgentLoop::new(
theirs,
@polkit.PolkitAgent::new(bus_path=bus.unwrap_or("/nonexistent/bus"), subject~, make_request=fake_request),
routes=[Socket(helper)],
describer=fn(req) {
@polkit.describe( @polkit.describe(
req, req,
cmdline=pid => if pid == 15802 { ["run0", "gparted", "/dev/nvme0n1"] } else { [] }, cmdline=pid => if pid == 15802 { ["run0", "gparted", "/dev/nvme0n1"] } else { [] },
who=pid => "run0 (pid " + pid.to_string() + "), started from konsole", who=pid => "run0 (pid " + pid.to_string() + "), started from konsole",
) )
},
)
}
}
ag.start()
agents.push(ag)
mine
}) })
let subject = @network.DValue::Struct([Str("unix-session"), @network.dict("v", [("session-id", Variant(Str("2")))])]) { comp, a, agents }
comp.polkit = Some(@polkit.PolkitAgent::new(bus_path=bus, subject~, make_request=fake_request))
comp.start_auth_agent()
comp
} }
///| Run both ends until `cond` holds (or about two seconds pass). ///| One pass of everything: polkitd, the agents, the compositor.
fn settle(comp : @host.ChandraCompositor, a : MockAuthority, cond : () -> Bool) -> Bool { fn Rig::pass(self : Rig) -> Unit {
for i = 0; i < 200; i = i + 1 { match self.a {
a.bus.pump() Some(a) => a.bus.pump()
comp.step() None => ()
}
for ag in self.agents {
if !ag.finished() {
ag.step()
}
}
self.comp.step()
}
///| Run everything until `cond` holds (or about six seconds pass).
fn Rig::settle(self : Rig, cond : () -> Bool) -> Bool {
for i = 0; i < 600; i = i + 1 {
self.pass()
if cond() { if cond() {
return true return true
} }
@@ -142,10 +200,25 @@ fn settle(comp : @host.ChandraCompositor, a : MockAuthority, cond : () -> Bool)
false false
} }
///| The mock helper's side of one session: accept, read the user and cookie lines. ///| The session's agent registered with polkit.
fn helper_accept(listen : Int, comp : @host.ChandraCompositor, a : MockAuthority) -> (Int, String) { fn Rig::ready(self : Rig) -> Bool {
self.comp.auth_agent.map(l => l.ready).unwrap_or(false)
}
///| The mock polkitd.
fn Rig::authority(self : Rig) -> MockAuthority {
self.a.unwrap()
}
///| The dialog's view (aborts when none is up).
fn Rig::view(self : Rig) -> @polkit.AuthView {
self.comp.auth_view().unwrap()
}
///| The mock helper's side of one check: accept, read the user and cookie lines.
fn Rig::helper_accept(self : Rig, listen : Int) -> (Int, String) {
let fd : Ref[Int] = { val: -1 } let fd : Ref[Int] = { val: -1 }
ignore(settle(comp, a, fn() { ignore(self.settle(fn() {
if fd.val < 0 { if fd.val < 0 {
fd.val = @sys.unix_accept(listen) fd.val = @sys.unix_accept(listen)
} }
@@ -157,7 +230,7 @@ fn helper_accept(listen : Int, comp : @host.ChandraCompositor, a : MockAuthority
(fd.val, helper_lines(fd.val, 2)) (fd.val, helper_lines(fd.val, 2))
} }
///| Read `n` lines from the agent (joined with '|'). ///| Read `n` lines (joined with '|').
fn helper_lines(fd : Int, n : Int) -> String { fn helper_lines(fd : Int, n : Int) -> String {
let buf : FixedArray[Byte] = FixedArray::make(1024, b'\x00') let buf : FixedArray[Byte] = FixedArray::make(1024, b'\x00')
let got : Array[Byte] = [] let got : Array[Byte] = []
@@ -216,14 +289,30 @@ fn auth_press(comp : @host.ChandraCompositor, code : UInt) -> Unit {
comp.handle_input(@nested.InputEvent::Key(code, false), 1U) comp.handle_input(@nested.InputEvent::Key(code, false), 1U)
} }
///| Alt+key.
fn auth_alt(comp : @host.ChandraCompositor, code : UInt) -> Unit {
comp.handle_input(@nested.InputEvent::Modifiers(8U, 0U, 0U, 0U), 1U)
auth_press(comp, code)
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
}
///| Click the dialog's control `f`.
fn auth_click(comp : @host.ChandraCompositor, f : @polkit.Focus) -> Unit {
ignore(comp.compose_frame())
let r = comp.auth.unwrap().hits.filter(x => x.1 == f)[0].0
comp.handle_input(@nested.InputEvent::PointerMove((r.x + 4).to_double(), (r.y + 4).to_double()), 1U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 2U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 3U)
}
///| Save the screen as `<CHANDRA_AUTH_SHOTS>/<name>.png` when that is set. ///| Save the screen as `<CHANDRA_AUTH_SHOTS>/<name>.png` when that is set.
fn auth_shot(comp : @host.ChandraCompositor, name : String) -> Unit { fn auth_shot(comp : @host.ChandraCompositor, name : String) -> Unit {
let dir = @sys.getenv("CHANDRA_AUTH_SHOTS") let dir = @sys.getenv("CHANDRA_AUTH_SHOTS")
if dir == "" { if dir == "" {
return return
} }
match comp.auth_dialog() { match comp.auth_view() {
Some(d) => d.shake_at = 0UL // the card at rest Some(v) => v.shake_at = 0UL // the card at rest
None => () None => ()
} }
comp.damage.mark_full() comp.damage.mark_full()
@@ -240,87 +329,90 @@ let run0_details : Array[(String, String)] = [
("polkit.caller-pid", "1"), ("polkit.caller-pid", "1"),
] ]
///| A private bus and a listening mock helper socket for test `tag`.
fn helper_socket(tag : String) -> (String, Int) {
let hpath = "/tmp/chandra-auth-helper-" + tag + "-" + @sys.getpid().to_string()
@sys.unlink(hpath)
(hpath, @sys.unix_listen(hpath))
}
///| ///|
test "polkit asks for run0: the dialog shows the command, a wrong password shakes, the right one authorizes" { test "polkit asks for run0: the dialog shows the command, a wrong password shakes, the right one authorizes" {
let bus = match auth_bus("ok") { let bus = match auth_bus("ok") {
Some(b) => b Some(b) => b
None => return // no dbus-daemon here None => return // no dbus-daemon here
} }
let a = MockAuthority::new(bus) let (hpath, listen) = helper_socket("ok")
let hpath = "/tmp/chandra-auth-helper-ok-" + @sys.getpid().to_string() let r = rig("ok", Some(bus), hpath)
let listen = @sys.unix_listen(hpath) r.comp.start_auth_agent()
let comp = auth_comp("ok", bus, hpath) assert_true(r.settle(fn() { r.ready() }))
assert_true(settle(comp, a, fn() { comp.polkit.map(p => p.registered()).unwrap_or(false) })) let a = r.authority()
assert_true(a.agent != "") assert_true(a.agent != "")
a.begin("cookie-1", run0_details) a.begin("cookie-1", run0_details)
assert_true(settle(comp, a, fn() { comp.auth_dialog() is Some(_) })) assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
let d = comp.auth_dialog().unwrap() let d = r.view()
assert_eq(d.desc.title, "Run a command as root") assert_eq(d.title, "Run a command as root")
assert_eq(d.desc.command, "gparted /dev/nvme0n1") assert_eq(d.command, "gparted /dev/nvme0n1")
// The user at the screen comes first; the wheel group adds ada. // The user at the screen comes first; the wheel group adds ada.
assert_eq(d.req.users.map(u => u.name), ["nandi", "ada"]) assert_eq(d.users.map(u => u.name), ["nandi", "ada"])
// The helper is asked for nandi with polkit's cookie. // The helper is asked for nandi with polkit's cookie.
let (h, hello) = helper_accept(listen, comp, a) let (h, hello) = r.helper_accept(listen)
assert_eq(hello, "nandi|cookie-1") assert_eq(hello, "nandi|cookie-1")
auth_shot(comp, "01-starting") auth_shot(r.comp, "01-starting")
helper_say(h, "PAM_PROMPT_ECHO_OFF Password: ") helper_say(h, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(settle(comp, a, fn() { d.phase == Prompt })) assert_true(r.settle(fn() { d.phase == Asking }))
auth_shot(comp, "02-idle") auth_shot(r.comp, "02-idle")
auth_type(comp, "Hunter2") auth_type(r.comp, "Hunter2")
assert_eq(d.typed(), 7) assert_eq(d.typed(), 7)
auth_shot(comp, "03-typing") auth_shot(r.comp, "03-typing")
// Caps Lock on shows a warning. // Caps Lock on shows a warning.
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 2U, 0U), 1U) r.comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 2U, 0U), 1U)
assert_true(d.caps) assert_true(d.caps)
auth_shot(comp, "04-caps-lock") auth_shot(r.comp, "04-caps-lock")
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U) r.comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
auth_press(comp, 28U) // Enter auth_press(r.comp, 28U) // Enter
assert_eq(d.typed(), 0) // wiped once sent
assert_true(r.settle(fn() { d.phase == Checking }))
assert_eq(helper_lines(h, 1), "Hunter2") assert_eq(helper_lines(h, 1), "Hunter2")
assert_eq(d.phase, Checking) auth_shot(r.comp, "05-busy")
auth_shot(comp, "05-busy") // Wrong: the helper fails and exits; the dialog shakes, says so, and a new check starts.
// Wrong: the helper fails and exits; the dialog says so and starts a new session.
helper_say(h, "FAILURE") helper_say(h, "FAILURE")
@sys.close_fd(h) @sys.close_fd(h)
assert_true(settle(comp, a, fn() { d.failures == 1 })) assert_true(r.settle(fn() { d.failures == 1 }))
assert_eq(d.error, "Wrong password. Try again.") assert_eq(d.error, "Wrong password. Try again.")
let (h2, hello2) = helper_accept(listen, comp, a) assert_true(d.shake_at != 0UL)
let (h2, hello2) = r.helper_accept(listen)
assert_eq(hello2, "nandi|cookie-1") assert_eq(hello2, "nandi|cookie-1")
helper_say(h2, "PAM_PROMPT_ECHO_OFF Password: ") helper_say(h2, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(settle(comp, a, fn() { d.phase == Prompt })) assert_true(r.settle(fn() { d.phase == Asking }))
auth_shot(comp, "06-wrong-password") auth_shot(r.comp, "06-wrong-password")
// Details, then the right password. // Details, then the right password.
comp.handle_input(@nested.InputEvent::Modifiers(8U, 0U, 0U, 0U), 1U) auth_alt(r.comp, 32U) // Alt+D
auth_press(comp, 32U) // Alt+D
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
assert_true(d.details_open) assert_true(d.details_open)
auth_type(comp, "hunter2") auth_type(r.comp, "hunter2")
auth_shot(comp, "07-details") auth_shot(r.comp, "07-details")
// Revealed text, then the light theme. auth_alt(r.comp, 19U) // Alt+R: show it
comp.handle_input(@nested.InputEvent::Modifiers(8U, 0U, 0U, 0U), 1U)
auth_press(comp, 19U) // Alt+R
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
assert_true(d.reveal) assert_true(d.reveal)
auth_shot(comp, "08-revealed") auth_shot(r.comp, "08-revealed")
comp.theme = @scene.ThemeTokens::moon_day() r.comp.theme = @scene.ThemeTokens::moon_day()
auth_shot(comp, "09-light") auth_shot(r.comp, "09-light")
comp.handle_input(@nested.InputEvent::Modifiers(8U, 0U, 0U, 0U), 1U) auth_alt(r.comp, 19U)
auth_press(comp, 19U) auth_press(r.comp, 32U) // Alt is up: 'd' goes into the field
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U) auth_press(r.comp, 14U) // and Backspace takes it out
auth_press(comp, 32U) // Alt is up: 'd' goes into the field auth_shot(r.comp, "10-light-details")
auth_press(comp, 14U) // and Backspace takes it out auth_press(r.comp, 96U) // keypad Enter
auth_shot(comp, "10-light-details") assert_true(r.settle(fn() { d.phase == Checking }))
auth_press(comp, 96U) // keypad Enter
assert_eq(helper_lines(h2, 1), "hunter2") assert_eq(helper_lines(h2, 1), "hunter2")
helper_say(h2, "SUCCESS") helper_say(h2, "SUCCESS")
assert_true(settle(comp, a, fn() { comp.auth_dialog() is None })) assert_true(r.settle(fn() { r.comp.auth_view() is None && a.answers.length() == 1 }))
assert_true(settle(comp, a, fn() { a.answers.length() == 1 }))
assert_eq(a.answers, ["ok"]) assert_eq(a.answers, ["ok"])
// Key releases after the dialog closed don't leak to clients (nothing swallowed is left). // Key releases after the dialog closed don't leak to clients (nothing swallowed is left).
assert_eq(comp.auth_swallow.length(), 0) assert_eq(r.comp.auth_swallow.length(), 0)
assert_true(r.comp.auth_notice_text() is None)
@sys.close_fd(h2) @sys.close_fd(h2)
@sys.close_fd(listen) @sys.close_fd(listen)
@sys.unlink(hpath) @sys.unlink(hpath)
comp.close() r.comp.close()
} }
///| ///|
@@ -329,89 +421,339 @@ test "Escape dismisses: polkitd hears Cancelled; polkitd withdrawing a request c
Some(b) => b Some(b) => b
None => return None => return
} }
let a = MockAuthority::new(bus) let (hpath, listen) = helper_socket("cancel")
let hpath = "/tmp/chandra-auth-helper-cancel-" + @sys.getpid().to_string() let r = rig("cancel", Some(bus), hpath)
let listen = @sys.unix_listen(hpath) r.comp.start_auth_agent()
let comp = auth_comp("cancel", bus, hpath) assert_true(r.settle(fn() { r.ready() }))
assert_true(settle(comp, a, fn() { comp.polkit.map(p => p.registered()).unwrap_or(false) })) let a = r.authority()
a.begin("c1", run0_details) a.begin("c1", run0_details)
a.begin("c2", []) a.begin("c2", [])
assert_true(settle(comp, a, fn() { comp.auth_dialog() is Some(_) })) assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
let (h, _) = helper_accept(listen, comp, a) let (h, _) = r.helper_accept(listen)
// A fingerprint reader: PAM informs and waits. // A fingerprint reader: PAM informs and waits.
helper_say(h, "PAM_TEXT_INFO Place your finger on the fingerprint reader") helper_say(h, "PAM_TEXT_INFO Place your finger on the fingerprint reader")
assert_true(settle(comp, a, fn() { comp.auth_dialog().map(d => d.phase == Waiting).unwrap_or(false) })) assert_true(r.settle(fn() { r.view().info != "" }))
auth_shot(comp, "11-fingerprint") assert_eq(r.view().phase, Starting)
// Two accounts can answer: Tab to the picker, Right picks ada and restarts the helper. auth_shot(r.comp, "11-fingerprint")
auth_press(comp, 15U) // Two accounts can answer: Tab to the picker, Right picks ada and starts a check for her.
auth_press(comp, 106U) auth_press(r.comp, 15U)
assert_eq(comp.auth_dialog().unwrap().user().map(u => u.name), Some("ada")) auth_press(r.comp, 106U)
let (h2, hello) = helper_accept(listen, comp, a) let (h2, hello) = r.helper_accept(listen)
assert_eq(hello, "ada|c1") assert_eq(hello, "ada|c1")
assert_true(r.settle(fn() { r.view().user().map(u => u.name) == Some("ada") }))
// Face unlock (pam_chandra_face.so): the face row scans, then gives way to the password. // Face unlock (pam_chandra_face.so): the face row scans, then gives way to the password.
helper_say(h2, "PAM_TEXT_INFO Face unlock: looking for ada…") helper_say(h2, "PAM_TEXT_INFO Face unlock: looking for ada…")
assert_true(settle(comp, a, fn() { comp.auth_dialog().map(d => d.face == Scanning).unwrap_or(false) })) assert_true(r.settle(fn() { r.view().face == Scanning }))
assert_eq(comp.auth_dialog().unwrap().info, "") // the fingerprint message went with nandi's attempt assert_eq(r.view().info, "") // the fingerprint message went with nandi's attempt
auth_shot(comp, "14-face-scanning") auth_shot(r.comp, "14-face-scanning")
helper_say(h2, "PAM_ERROR_MSG Face unlock: face not recognized") helper_say(h2, "PAM_ERROR_MSG Face unlock: face not recognized")
helper_say(h2, "PAM_PROMPT_ECHO_OFF Password: ") helper_say(h2, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(settle(comp, a, fn() { comp.auth_dialog().map(d => d.phase == Prompt).unwrap_or(false) })) assert_true(r.settle(fn() { r.view().phase == Asking }))
assert_eq(comp.auth_dialog().unwrap().face, FaceFailed("Face not recognized")) assert_eq(r.view().face, FaceFailed("Face not recognized"))
auth_shot(comp, "15-face-failed") auth_shot(r.comp, "15-face-failed")
auth_shot(comp, "12-other-account") auth_shot(r.comp, "12-other-account")
auth_press(comp, 1U) // Escape auth_press(r.comp, 1U) // Escape
assert_true(settle(comp, a, fn() { a.answers.length() == 1 })) assert_true(r.comp.auth_view() is None || r.view().id != "1")
assert_true(r.settle(fn() { a.answers.length() == 1 }))
assert_eq(a.answers, ["org.freedesktop.PolicyKit1.Error.Cancelled"]) assert_eq(a.answers, ["org.freedesktop.PolicyKit1.Error.Cancelled"])
// The second request comes up next; polkitd withdraws it. // The second request comes up next; polkitd withdraws it.
assert_true(settle(comp, a, fn() { comp.auth_dialog().map(d => d.req.cookie == "c2").unwrap_or(false) })) assert_true(r.settle(fn() { r.comp.auth_view().map(v => v.id == "2").unwrap_or(false) }))
let d2 = comp.auth_dialog().unwrap() assert_eq(r.view().title, "Run a command as root") // the unit name in the message still finds run0
assert_eq(d2.desc.title, "Run a command as root") // the unit name in the message still finds run0
ignore(a.bus.call(@network.DMessage::call(a.agent, @polkit.agent_path, @polkit.agent_iface, "CancelAuthentication", [Str("c2")]))) ignore(a.bus.call(@network.DMessage::call(a.agent, @polkit.agent_path, @polkit.agent_iface, "CancelAuthentication", [Str("c2")])))
assert_true(settle(comp, a, fn() { comp.auth_dialog() is None })) assert_true(r.settle(fn() { r.comp.auth_view() is None }))
assert_true(settle(comp, a, fn() { a.answers.length() == 2 })) assert_true(r.settle(fn() { a.answers.length() == 2 }))
assert_eq(a.answers[1], "org.freedesktop.PolicyKit1.Error.Cancelled") assert_eq(a.answers[1], "org.freedesktop.PolicyKit1.Error.Cancelled")
@sys.close_fd(h) @sys.close_fd(h)
@sys.close_fd(h2) @sys.close_fd(h2)
@sys.close_fd(listen) @sys.close_fd(listen)
@sys.unlink(hpath) @sys.unlink(hpath)
comp.close() r.comp.close()
} }
///| ///|
test "another agent already has the session: ours steps aside" { test "polkit refuses the agent: a notice says why, and no other agent takes over" {
let bus = match auth_bus("refuse") { let bus = match auth_bus("refuse") {
Some(b) => b Some(b) => b
None => return None => return
} }
let a = MockAuthority::new(bus) let r = rig("refuse", Some(bus), "/nonexistent")
a.refuse = "An authentication agent already exists for the given subject" r.authority().refuse = "An authentication agent already exists for the given subject"
let comp = auth_comp("refuse", bus, "/nonexistent") r.comp.start_auth_agent()
assert_true(settle(comp, a, fn() { comp.polkit is None })) assert_true(r.settle(fn() { r.comp.auth_notice_text() is Some(_) }))
comp.close() assert_eq(
r.comp.auth_notice_text().unwrap(),
"Chandra's password dialog couldn't start: polkit refused the agent: An authentication agent already exists for the given subject.",
)
assert_true(r.comp.auth_agent is None)
assert_false(r.comp.fallback_agent_started)
let (out, ok) = r.comp.control_command("auth-status")
assert_true(ok)
assert_eq(out[0], "agent: not running")
auth_shot(r.comp, "16-notice")
// A click on it dismisses it.
ignore(r.comp.compose_frame())
r.comp.handle_input(@nested.InputEvent::PointerMove(640.0, 40.0), 1U)
r.comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 2U)
r.comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 3U)
assert_true(r.comp.auth_notice_text() is None)
r.comp.close()
} }
///| ///|
test "the helper can't be reached: the dialog says so instead of hanging" { test "the agent can't be started, or quits at start: a notice says so" {
// No program to run.
let r = rig("nostart", None, "")
r.comp.auth_spawner = Some(fn(_) { -1 })
r.comp.start_auth_agent()
assert_eq(r.comp.auth_notice_text(), Some("Chandra's password dialog couldn't start: could not run chandra-polkit-agent."))
r.comp.close()
// Started, but polkit can't even be asked (no system bus): its error is the notice.
let r2 = rig("nobus", None, "")
r2.comp.start_auth_agent()
assert_true(r2.settle(fn() { r2.comp.auth_notice_text() is Some(_) }))
assert_true(r2.comp.auth_notice_text().unwrap().has_prefix("Chandra's password dialog couldn't start: polkit could not be asked: no system bus at /nonexistent/bus"))
r2.comp.close()
// It crashes before saying anything.
let r3 = rig("crash", None, "")
r3.comp.auth_spawner = Some(fn(_) {
let (mine, theirs) = sock_pair("crash")
@sys.close_fd(theirs)
mine
})
r3.comp.start_auth_agent()
assert_true(r3.settle(fn() { r3.comp.auth_notice_text() is Some(_) }))
assert_eq(
r3.comp.auth_notice_text().unwrap(),
"Chandra's password dialog couldn't start: chandra-polkit-agent stopped unexpectedly (see ~/.local/state/chandra/session.log).",
)
r3.comp.close()
}
///|
test "the agent stops after it was registered: it is started again, and a notice says so" {
let bus = match auth_bus("restart") {
Some(b) => b
None => return
}
let r = rig("restart", Some(bus), "/nonexistent")
r.comp.start_auth_agent()
assert_true(r.settle(fn() { r.ready() }))
let first = r.agents[0]
first.shutdown() // as if it crashed: its end of the link closes
assert_true(r.settle(fn() { r.comp.auth_notice_text() is Some(_) }))
assert_true(r.comp.auth_notice_text().unwrap().has_prefix("Chandra's password dialog stopped and was restarted"))
assert_true(r.settle(fn() { r.ready() }))
assert_eq(r.agents.length(), 2)
r.comp.close()
}
///|
test "polkit's helper can't be reached: the dialog says why and waits; Try again, then Cancel" {
let bus = match auth_bus("nohelper") { let bus = match auth_bus("nohelper") {
Some(b) => b Some(b) => b
None => return None => return
} }
let a = MockAuthority::new(bus) let r = rig("nohelper", Some(bus), "/nonexistent/helper.socket")
let comp = auth_comp("nohelper", bus, "/nonexistent/helper.socket") r.comp.start_auth_agent()
assert_true(settle(comp, a, fn() { comp.polkit.map(p => p.registered()).unwrap_or(false) })) assert_true(r.settle(fn() { r.ready() }))
let a = r.authority()
a.begin("c1", run0_details) a.begin("c1", run0_details)
assert_true(settle(comp, a, fn() { comp.auth_dialog() is Some(_) })) assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
assert_eq(comp.auth_dialog().unwrap().error, "polkit's authentication helper could not be started.") let d = r.view()
assert_eq(d.phase, Failed)
assert_eq(d.error, "polkit's password checker could not be started (tried socket /nonexistent/helper.socket)")
assert_eq(d.main_label(), "Try again")
auth_shot(r.comp, "17-failed")
// Enter tries again (and says the same).
auth_press(r.comp, 28U)
assert_true(r.settle(fn() { d.phase == Failed }))
// Clicking Cancel dismisses it. // Clicking Cancel dismisses it.
ignore(comp.compose_frame()) auth_click(r.comp, Cancel)
let ui = comp.auth.unwrap() assert_true(r.comp.auth_view() is None)
let cancel = ui.hits.filter(h => h.1 == Cancel)[0].0 assert_true(r.settle(fn() { a.answers.length() == 1 }))
comp.handle_input(@nested.InputEvent::PointerMove((cancel.x + 5).to_double(), (cancel.y + 5).to_double()), 1U) r.comp.close()
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 2U) }
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 3U)
assert_true(settle(comp, a, fn() { a.answers.length() == 1 })) ///|
assert_true(comp.auth_dialog() is None) test "typing reaches the dialog through handle_input on a real keymap; a check that quits early is not retried behind the user's back" {
let bus = match auth_bus("typing") {
Some(b) => b
None => return
}
let (hpath, listen) = helper_socket("typing")
let r = rig("typing", Some(bus), hpath)
// The keymap the real session hands clients (xkbcommon's text format), not the US fallback.
r.comp.server.set_keymap(@utf8.encode(real_keymap))
r.comp.start_auth_agent()
assert_true(r.settle(fn() { r.ready() }))
let a = r.authority()
a.begin("t1", run0_details)
assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
let d = r.view()
// The helper goes away without a word (socket helper refusing, account locked, ...).
let (h, _) = r.helper_accept(listen)
@sys.close_fd(h)
assert_true(r.settle(fn() { d.phase == Failed }))
assert_eq(d.error, "The password check quit before asking for a password.")
assert_eq(d.failures, 0) // not a wrong password
// Nothing starts another check on its own.
for i = 0; i < 30; i = i + 1 {
r.pass()
@sys.sleep_ms(10)
}
assert_true(@sys.unix_accept(listen) < 0)
// Typing lands in the field and stays there.
auth_type(r.comp, "Secret9")
assert_eq(d.typed(), 7)
// Shift+digit through the real keymap: '(' on 9.
r.comp.handle_input(@nested.InputEvent::Modifiers(1U, 0U, 0U, 0U), 1U)
auth_press(r.comp, 10U)
r.comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
assert_eq(d.typed(), 8)
// Enter starts a new check, which gets the password when it asks.
auth_press(r.comp, 28U)
let (h2, hello) = r.helper_accept(listen)
assert_eq(hello, "nandi|t1")
helper_say(h2, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(r.settle(fn() { d.phase == Checking }))
assert_eq(helper_lines(h2, 1), "Secret9(")
helper_say(h2, "SUCCESS")
assert_true(r.settle(fn() { a.answers == ["ok"] }))
@sys.close_fd(h2)
@sys.close_fd(listen)
@sys.unlink(hpath)
r.comp.close()
}
///|
test "chandra-ctl auth-demo: the dialog without root; wrong, then the demo password" {
let r = rig("demo", None, "")
let (out, ok) = r.comp.control_command("auth-demo")
assert_true(ok)
assert_eq(out, ["ok the demo dialog opens; the password is \"demo\""])
assert_true(r.settle(fn() { r.comp.auth_view().map(v => v.phase == Asking).unwrap_or(false) }))
let d = r.view()
assert_eq(d.command, "run0 systemctl restart chandra-demo.service")
auth_type(r.comp, "nope")
auth_press(r.comp, 28U)
assert_true(r.settle(fn() { d.failures == 1 }))
assert_eq(d.error, "Wrong password. Try again.")
assert_true(r.settle(fn() { d.phase == Asking }))
auth_type(r.comp, "demo")
auth_click(r.comp, Allow)
assert_true(r.settle(fn() { r.comp.auth_view() is None && r.comp.auth_demos.length() == 0 }))
assert_true(r.comp.auth_notice_text() is None)
assert_eq(r.comp.control_command("auth-demo bogus").1, false)
r.comp.close()
}
///|
test "auth-demo die and face: a check that quits shows why until Try again; the face row" {
let r = rig("demo-die", None, "")
ignore(r.comp.control_command("auth-demo die"))
assert_true(r.settle(fn() { r.comp.auth_view().map(v => v.phase == Failed).unwrap_or(false) }))
let d = r.view()
assert_eq(d.error, "The password check quit before asking for a password.")
auth_click(r.comp, Allow) // "Try again"
assert_true(r.settle(fn() { d.phase == Asking }))
assert_eq(d.error, "")
auth_press(r.comp, 1U) // Escape
assert_true(r.settle(fn() { r.comp.auth_demos.length() == 0 }))
ignore(r.comp.control_command("auth-demo face"))
assert_true(r.settle(fn() { r.comp.auth_view().map(v => v.face == Scanning).unwrap_or(false) }))
// Typed while it looks: goes in when PAM asks.
auth_type(r.comp, "demo")
auth_press(r.comp, 28U)
assert_true(r.settle(fn() { r.comp.auth_view() is None && r.comp.auth_demos.length() == 0 }))
r.comp.close()
}
///| The agent program the build made (release or debug), "" when it wasn't built.
fn built_agent() -> String {
for p in ["_build/native/release/build/compositor/authagent/authagent.exe", "_build/native/debug/build/compositor/authagent/authagent.exe"] {
if @sys.has_exe(p) {
return p
}
}
""
}
///| Run everything with the agent out of process: polkitd and the compositor.
fn settle_out(comp : @host.ChandraCompositor, a : MockAuthority?, cond : () -> Bool) -> Bool {
for i = 0; i < 500; i = i + 1 {
match a {
Some(a) => a.bus.pump()
None => ()
}
ignore(@sys.wait_readable(comp.auth_fds(), 10))
comp.step()
if cond() {
return true
}
}
false
}
///|
test "the real chandra-polkit-agent program: demo, and registered with (mock) polkit through its own process" {
let bin = built_agent()
if bin == "" {
println("skipped: build compositor/authagent first (just auth-agent)")
return
}
// The demo, started by the compositor itself through spawn_socket.
let comp = new_comp("auth-real-demo")
assert_true(comp.start_auth_demo("password") is Ok(_))
assert_true(settle_out(comp, None, fn() { comp.auth_view().map(v => v.phase == Asking).unwrap_or(false) }))
auth_type(comp, "demo")
auth_press(comp, 28U)
assert_true(settle_out(comp, None, fn() { comp.auth_view() is None && comp.auth_demos.length() == 0 }))
comp.close() comp.close()
// The session agent: the system bus, session and helper socket point at the test's mocks.
let bus = match auth_bus("real") {
Some(b) => b
None => return
}
let a = MockAuthority::new(bus)
let (hpath, listen) = helper_socket("real")
let comp2 = new_comp("auth-real")
comp2.login_session = true
comp2.auth_spawner = Some(fn(args) {
@sys.spawn_socket(
[
"/usr/bin/env", "DBUS_SYSTEM_BUS_ADDRESS=unix:path=" + bus, "XDG_SESSION_ID=2", "CHANDRA_POLKIT_HELPER=socket:" + hpath,
bin, ..args,
],
)
})
comp2.start_auth_agent()
assert_true(settle_out(comp2, Some(a), fn() { comp2.auth_agent.map(l => l.ready).unwrap_or(false) }))
a.begin("r1", run0_details, uid=@polkit.own_uid().reinterpret_as_uint())
assert_true(settle_out(comp2, Some(a), fn() { comp2.auth_view() is Some(_) }))
let fd : Ref[Int] = { val: -1 }
assert_true(settle_out(comp2, Some(a), fn() {
if fd.val < 0 {
fd.val = @sys.unix_accept(listen)
}
fd.val >= 0
}))
ignore(helper_lines(fd.val, 2))
helper_say(fd.val, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(settle_out(comp2, Some(a), fn() { comp2.auth_view().map(v => v.phase == Asking).unwrap_or(false) }))
auth_type(comp2, "Right1")
auth_press(comp2, 28U)
assert_true(settle_out(comp2, Some(a), fn() { comp2.auth_view().map(v => v.phase == Checking).unwrap_or(false) }))
assert_eq(helper_lines(fd.val, 1), "Right1")
helper_say(fd.val, "SUCCESS")
assert_true(settle_out(comp2, Some(a), fn() { a.answers == ["ok"] }))
// Turning the switch off stops it (it unregisters and exits) and says there's no other agent.
comp2.shell.set_session_setting(3, false)
comp2.auth_agent_setting_changed()
assert_true(comp2.auth_agent is None)
@sys.close_fd(fd.val)
@sys.close_fd(listen)
@sys.unlink(hpath)
comp2.close()
} }
///| ///|
@@ -431,61 +773,6 @@ test "Settings > Session lists the password dialog switch, saved as :auth-agent
comp.close() comp.close()
} }
///|
test "typing reaches the dialog through handle_input, and a helper that dies at once doesn't wipe it in a loop" {
let bus = match auth_bus("typing") {
Some(b) => b
None => return
}
let a = MockAuthority::new(bus)
let hpath = "/tmp/chandra-auth-helper-typing-" + @sys.getpid().to_string()
let listen = @sys.unix_listen(hpath)
let comp = auth_comp("typing", bus, hpath)
// The keymap the real session hands clients (xkbcommon's text format), not the US fallback.
comp.server.set_keymap(@utf8.encode(real_keymap))
assert_true(settle(comp, a, fn() { comp.polkit.map(p => p.registered()).unwrap_or(false) }))
a.begin("t1", run0_details)
assert_true(settle(comp, a, fn() { comp.auth_dialog() is Some(_) }))
let d = comp.auth_dialog().unwrap()
// The helper goes away without a word (socket helper refusing, account locked, ...).
let (h, _) = helper_accept(listen, comp, a)
@sys.close_fd(h)
assert_true(settle(comp, a, fn() { d.error != "" }))
assert_eq(d.failures, 0) // not a wrong password
// Typing still lands in the field and stays there.
auth_type(comp, "Secret9")
for i = 0; i < 20; i = i + 1 {
a.bus.pump()
comp.step()
}
assert_eq(d.typed(), 7)
// Shift+digit through the real keymap: '(' on 9.
comp.handle_input(@nested.InputEvent::Modifiers(1U, 0U, 0U, 0U), 1U)
auth_press(comp, 10U)
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 1U)
assert_eq(d.typed(), 8)
auth_press(comp, 28U) // Enter: kept until PAM asks
// A second later the helper is started again; this time it asks.
let (h2, hello) = helper_accept(listen, comp, a)
assert_eq(hello, "nandi|t1")
helper_say(h2, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(settle(comp, a, fn() { d.phase == Checking }))
assert_eq(helper_lines(h2, 1), "Secret9(")
// The pointer works too: a click on Cancel dismisses it.
helper_say(h2, "FAILURE")
assert_true(settle(comp, a, fn() { d.failures == 1 }))
ignore(comp.compose_frame())
let cancel = comp.auth.unwrap().hits.filter(x => x.1 == Cancel)[0].0
comp.handle_input(@nested.InputEvent::PointerMove((cancel.x + 4).to_double(), (cancel.y + 4).to_double()), 1U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 2U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 3U)
assert_true(settle(comp, a, fn() { a.answers.length() == 1 }))
@sys.close_fd(h2)
@sys.close_fd(listen)
@sys.unlink(hpath)
comp.close()
}
///| An xkbcommon 1.6 keymap (xkbcli compile-keymap --layout us), cut down to what typing needs. ///| An xkbcommon 1.6 keymap (xkbcli compile-keymap --layout us), cut down to what typing needs.
let real_keymap : String = let real_keymap : String =
#|xkb_keymap { #|xkb_keymap {
@@ -564,19 +851,7 @@ let real_keymap : String =
#| #|
#|}; #|};
///| `settle`, composing frames too (the Face unlock window and Settings follow their tool there).
fn fsettle(comp : @host.ChandraCompositor, a : MockAuthority, cond : () -> Bool) -> Bool {
for i = 0; i < 300; i = i + 1 {
a.bus.pump()
comp.step()
ignore(comp.compose_frame())
if cond() {
return true
}
@sys.sleep_ms(10)
}
false
}
///| ///|
test "Face unlock window: snaps, Apply, then the password dialog gets the keyboard and the click" { test "Face unlock window: snaps, Apply, then the password dialog gets the keyboard and the click" {
@@ -584,27 +859,33 @@ test "Face unlock window: snaps, Apply, then the password dialog gets the keyboa
Some(b) => b Some(b) => b
None => return None => return
} }
let a = MockAuthority::new(bus) let (hpath, listen) = helper_socket("faceapply")
let hpath = "/tmp/chandra-auth-helper-faceapply-" + @sys.getpid().to_string() let r = rig("faceapply", Some(bus), hpath)
let listen = @sys.unix_listen(hpath) let comp = r.comp
let comp = auth_comp("faceapply", bus, hpath)
comp.server.set_keymap(@utf8.encode(real_keymap)) comp.server.set_keymap(@utf8.encode(real_keymap))
assert_true(fsettle(comp, a, fn() { comp.polkit.map(p => p.registered()).unwrap_or(false) })) comp.start_auth_agent()
let fsettle = fn(cond : () -> Bool) {
r.settle(fn() {
ignore(comp.compose_frame())
cond()
})
}
assert_true(fsettle(fn() { r.ready() }))
let a = r.authority()
let dir = "/tmp/chandra-face-apply-" + @sys.getpid().to_string() let dir = "/tmp/chandra-face-apply-" + @sys.getpid().to_string()
let tool = fake_face_tool(dir) let tool = fake_face_tool(dir)
ignore(@sys.write_file_bytes(dir + "/wait", b"")) ignore(@sys.write_file_bytes(dir + "/wait", b""))
comp.shell.set_face_tool(["/bin/sh", tool]) comp.shell.set_face_tool(["/bin/sh", tool])
assert_true(comp.shell.open_settings(Session)) assert_true(comp.shell.open_settings(Session))
assert_true(fsettle(comp, a, fn() { face_texts(comp).contains("Desk") })) assert_true(fsettle(fn() { face_texts(comp).contains("Desk") }))
face_click(comp, "Add or remove faces…", 10U) face_click(comp, "Add or remove faces…", 10U)
assert_true(fsettle(comp, a, fn() { comp.shell.face.window.map(w => w.picture != 0U).unwrap_or(false) })) assert_true(fsettle(fn() { comp.shell.face.window.map(w => w.picture != 0U).unwrap_or(false) }))
let w = comp.shell.face.window.unwrap() let w = comp.shell.face.window.unwrap()
face_key(comp, 57U, 20U) face_key(comp, 57U, 20U)
assert_true(fsettle(comp, a, fn() { w.snaps.length() == 1 })) assert_true(fsettle(fn() { w.snaps.length() == 1 }))
face_key(comp, 57U, 30U) face_key(comp, 57U, 30U)
assert_true(fsettle(comp, a, fn() { w.snaps.length() == 2 })) assert_true(fsettle(fn() { w.snaps.length() == 2 }))
// Enter: Apply; the root step asks polkit, which asks us. Meanwhile the window steps aside: // Enter: Apply; the root step asks polkit, which asks us. Meanwhile the window steps aside.
// no dimming card, no input of its own (another agent's password window must be reachable).
face_key(comp, 28U, 40U) face_key(comp, 28U, 40U)
assert_true(w.applying) assert_true(w.applying)
ignore(comp.compose_frame()) ignore(comp.compose_frame())
@@ -612,11 +893,11 @@ test "Face unlock window: snaps, Apply, then the password dialog gets the keyboa
comp.handle_input(@nested.InputEvent::Key(57U, false), 1U) comp.handle_input(@nested.InputEvent::Key(57U, false), 1U)
assert_eq(w.snaps.length(), 2) assert_eq(w.snaps.length(), 2)
a.begin("f1", run0_details) a.begin("f1", run0_details)
assert_true(fsettle(comp, a, fn() { comp.auth_dialog() is Some(_) })) assert_true(fsettle(fn() { comp.auth_view() is Some(_) }))
let d = comp.auth_dialog().unwrap() let d = r.view()
let (h, _) = helper_accept(listen, comp, a) let (h, _) = r.helper_accept(listen)
helper_say(h, "PAM_PROMPT_ECHO_OFF Password: ") helper_say(h, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(fsettle(comp, a, fn() { d.phase == Prompt })) assert_true(fsettle(fn() { d.phase == Asking }))
auth_shot(comp, "18-face-apply-password") auth_shot(comp, "18-face-apply-password")
// Typing goes to the password dialog, not to the window under it (Space would snap). // Typing goes to the password dialog, not to the window under it (Space would snap).
auth_type(comp, "Secret9") auth_type(comp, "Secret9")
@@ -625,18 +906,14 @@ test "Face unlock window: snaps, Apply, then the password dialog gets the keyboa
assert_eq(d.typed(), 8) assert_eq(d.typed(), 8)
assert_eq(w.snaps.length(), 2) assert_eq(w.snaps.length(), 2)
// The Authenticate button takes the click. // The Authenticate button takes the click.
ignore(comp.compose_frame()) auth_click(comp, Allow)
let allow = comp.auth.unwrap().hits.filter(x => x.1 == Allow)[0].0 assert_true(fsettle(fn() { d.phase == Checking }))
comp.handle_input(@nested.InputEvent::PointerMove((allow.x + 4).to_double(), (allow.y + 4).to_double()), 1U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 2U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 3U)
assert_true(fsettle(comp, a, fn() { d.phase == Checking }))
assert_eq(helper_lines(h, 1), "Secret9 ") assert_eq(helper_lines(h, 1), "Secret9 ")
helper_say(h, "SUCCESS") helper_say(h, "SUCCESS")
assert_true(fsettle(comp, a, fn() { comp.auth_dialog() is None && a.answers.length() == 1 })) assert_true(fsettle(fn() { comp.auth_view() is None && a.answers.length() == 1 }))
// The root step goes on; the window closes with what it said. // The root step goes on; the window closes with what it said.
ignore(@sys.write_file_bytes(dir + "/go", b"")) ignore(@sys.write_file_bytes(dir + "/go", b""))
assert_true(fsettle(comp, a, fn() { comp.shell.face.window is None })) assert_true(fsettle(fn() { comp.shell.face.window is None }))
assert_eq(comp.shell.face.message, "Added Face 2 and removed 1 face") assert_eq(comp.shell.face.message, "Added Face 2 and removed 1 face")
@sys.close_fd(h) @sys.close_fd(h)
@sys.close_fd(listen) @sys.close_fd(listen)
+24 -24
View File
@@ -256,22 +256,26 @@ pub(all) struct ChandraCompositor {
mut last_recording : String mut last_recording : String
/// `--kiosk`: one fullscreen app, locked down (kiosk.mbt). None: a normal desktop. /// `--kiosk`: one fullscreen app, locked down (kiosk.mbt). None: a normal desktop.
mut kiosk : Kiosk? mut kiosk : Kiosk?
/// Chandra's polkit agent (auth.mbt), while it is registered; the system bus socket it uses /// The password dialog (auth.mbt): the session's chandra-polkit-agent and demo agents
/// ("" finds it); the dialog while it is up; key releases it swallows; how to reach polkit's /// (`chandra-ctl auth-demo`), the dialog while it is up, key releases the dialog or the Face
/// helper (empty: the usual routes; tests set their own); the keymap typing goes through. /// unlock window swallow, a notice about the dialog itself, how agents are started (tests run
mut polkit : @polkit.PolkitAgent? /// them in-process), restarts after crashes, and whether "still waiting for polkit" was said.
mut polkit_bus : String mut auth_agent : AuthLink?
auth_demos : Array[AuthLink]
mut auth : AuthUi? mut auth : AuthUi?
auth_swallow : Array[UInt] auth_swallow : Array[UInt]
mut auth_notice : AuthNotice?
mut auth_notice_press : Bool
mut auth_spawner : ((Array[String]) -> Int)?
mut auth_restarts : Int
mut auth_slow_said : Bool
/// The Face unlock window (face_window.mbt): where its controls were drawn, and the change of /// The Face unlock window (face_window.mbt): where its controls were drawn, and the change of
/// it last drawn. /// it last drawn.
face_hits : Array[(@scene.Rect, FaceHit)] face_hits : Array[(@scene.Rect, FaceHit)]
mut face_rev : Int mut face_rev : Int
mut auth_routes : Array[@polkit.HelperRoute] /// The keymap the dialog types through (parsed from the one clients get).
mut keymap : (Bytes, @polkit.Keymap)? mut keymap : (Bytes, @polkit.Keymap)?
/// How requests are put into words (tests pass their own process lookups); None: the usual. /// Another polkit agent was started (the Settings switch for Chandra's dialog is off).
mut auth_describe : ((@polkit.AuthRequest) -> @polkit.Description)?
/// A third-party polkit agent was started (when ours is off or couldn't register).
mut fallback_agent_started : Bool mut fallback_agent_started : Bool
/// The rest of the xkb modifier state (`mods` holds the depressed modifiers). /// The rest of the xkb modifier state (`mods` holds the depressed modifiers).
mut mods_latched : UInt mut mods_latched : UInt
@@ -313,15 +317,18 @@ pub fn ChandraCompositor::new(
theme, theme,
dark_theme: theme, dark_theme: theme,
sync_system_theme: false, sync_system_theme: false,
polkit: None, auth_agent: None,
polkit_bus: "", auth_demos: [],
auth: None, auth: None,
auth_swallow: [], auth_swallow: [],
auth_notice: None,
auth_notice_press: false,
auth_spawner: None,
auth_restarts: 0,
auth_slow_said: false,
face_hits: [], face_hits: [],
face_rev: -1, face_rev: -1,
auth_routes: [],
keymap: None, keymap: None,
auth_describe: None,
fallback_agent_started: false, fallback_agent_started: false,
mods_latched: 0U, mods_latched: 0U,
mods_locked: 0U, mods_locked: 0U,
@@ -447,11 +454,7 @@ pub fn ChandraCompositor::close(self : ChandraCompositor) -> Unit {
release_snapshot(win.surface) release_snapshot(win.surface)
} }
self.stop_control() self.stop_control()
self.close_auth(Some(Err("The session is ending"))) self.auth_shutdown()
match self.polkit {
Some(a) => a.stop()
None => ()
}
self.shell.shutdown() self.shell.shutdown()
match self.settings_portal { match self.settings_portal {
Some(p) => p.close() Some(p) => p.close()
@@ -1108,6 +1111,7 @@ fn ChandraCompositor::build_scene(
panel_ops.append(self.screenshot_ops()) panel_ops.append(self.screenshot_ops())
panel_ops.append(self.face_window_ops()) panel_ops.append(self.face_window_ops())
panel_ops.append(self.auth_ops()) panel_ops.append(self.auth_ops())
panel_ops.append(self.auth_notice_ops())
self.frames_built = self.frames_built + 1 self.frames_built = self.frames_built + 1
self.run_shell_actions() self.run_shell_actions()
// The wallpaper (the first ops) is cached by the renderer; the desktop card after it changes. // The wallpaper (the first ops) is cached by the renderer; the desktop card after it changes.
@@ -1869,12 +1873,8 @@ pub fn ChandraCompositor::handle_input(
} }
_ => () _ => ()
} }
// The authentication dialog takes all input while it is up. // The password dialog takes all input while it is up; else the Face unlock window does.
if self.auth_input(ev) { if self.grab_input(ev) {
return
}
// So does the Face unlock window (below the password dialog it opens on Apply).
if self.face_window_input(ev) {
return return
} }
match ev { match ev {
+36
View File
@@ -211,10 +211,46 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin
"shortcut ID do what shortcut ID does (launcher, overview, show-desktop, ...)", "shortcut ID do what shortcut ID does (launcher, overview, show-desktop, ...)",
"kiosk [lock|unlock|status] kiosk mode (--kiosk): lock it down or unlock it for admin work", "kiosk [lock|unlock|status] kiosk mode (--kiosk): lock it down or unlock it for admin work",
"windows each window: frame, layout, box, shadow, size limits; and what is under the pointer", "windows each window: frame, layout, box, shadow, size limits; and what is under the pointer",
"auth-demo [MODE] show the password dialog with a pretend check (password \"demo\"); MODE: " +
@polkit.demo_modes.join(", "),
"auth-status the password dialog's agent: running, registered, or why not",
"ok", "ok",
], ],
true, true,
) )
"auth-demo" => {
if words.length() > 2 {
return (["error usage: auth-demo [" + @polkit.demo_modes.join("|") + "]"], false)
}
match self.start_auth_demo(if words.length() == 2 { words[1] } else { "" }) {
Ok(_) => (["ok the demo dialog opens; the password is \"" + @polkit.demo_password + "\""], true)
Err(why) => (["error " + why], false)
}
}
"auth-status" => {
let out : Array[String] = []
match self.auth_agent {
Some(l) => out.push(if l.ready { "agent: registered with polkit" } else { "agent: started, waiting for polkit" })
None =>
out.push(
if self.fallback_agent_started {
"agent: off in Settings; another polkit agent was started"
} else {
"agent: not running"
},
)
}
match self.auth_notice {
Some(n) => out.push("notice: " + n.text)
None => ()
}
match self.auth {
Some(ui) => out.push("dialog: up (" + @polkit.phase_name(ui.view.phase) + ")")
None => out.push("dialog: not shown")
}
out.push("ok")
(out, true)
}
"list" => { "list" => {
let mods = self.shell.loaded_modules() let mods = self.shell.loaded_modules()
let out = mods.map(m => m.0 + " " + m.1 + " " + m.2) let out = mods.map(m => m.0 + " " + m.1 + " " + m.2)
+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()
}
+63 -80
View File
@@ -19,6 +19,9 @@ pub(all) enum HelperEvent {
TextInfo(String) TextInfo(String)
Success Success
Failure 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) } derive(Eq, Debug)
///| Undo g_strescape: \n \t \r \b \f \v \\ \" and octal \NNN (bytes, re-read as UTF-8). ///| 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) Program(String)
} derive(Eq, Debug) } derive(Eq, Debug)
///| A route, for the log. ///| A route, for the log and for errors.
fn route_text(r : HelperRoute) -> String { pub fn route_text(r : HelperRoute) -> String {
match r { match r {
Socket(p) => "socket " + p Socket(p) => "socket " + p
Program(p) => 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 { pub struct HelperSession {
mut fd : Int conn : LineConn
inbuf : Array[Byte] /// SUCCESS, FAILURE or Gone was reported.
/// Set once SUCCESS or FAILURE came, or the helper went away.
mut ended : Bool mut ended : Bool
} }
///| Start the helper to authenticate `user` for `cookie` by the first route that works. None ///| Start the helper to authenticate `user` for `cookie` by the first route that works; Err
/// when none does. /// says which routes were tried and how each failed.
pub fn HelperSession::start_any(routes : Array[HelperRoute], user : String, cookie : String) -> HelperSession? { pub fn HelperSession::start_any(routes : Array[HelperRoute], user : String, cookie : String) -> Result[HelperSession, String] {
let tried : Array[String] = []
for r in routes { for r in routes {
match HelperSession::start(r, user, cookie) { match HelperSession::start(r, user, cookie) {
Some(s) => { Some(s) => {
@sys.log("chandra: polkit helper for " + user + " via " + route_text(r)) alog("password check for " + user + " via " + route_text(r))
return Some(s) 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? { pub fn HelperSession::start(route : HelperRoute, user : String, cookie : String) -> HelperSession? {
let (fd, first) = match route { let (fd, first) = match route {
Socket(path) => (@sys.unix_connect(path), user + "\n" + cookie + "\n") 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 { if fd < 0 {
return None return None
} }
let b = @utf8.encode(first) let conn = LineConn::new(fd)
if @sys.sendmsg_fd(fd, b, -1) != b.length() { if !conn.send_raw(@utf8.encode(first)) {
@sys.close_fd(fd) conn.close()
return None return None
} }
Some({ fd, inbuf: [], ended: false }) Some({ conn, ended: false })
} }
///| A session over an already-connected fd (tests). ///| A session over an already-connected fd (tests).
pub fn HelperSession::over(fd : Int) -> HelperSession { 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 impl Conversation for HelperSession with poll(self) {
pub fn HelperSession::read(self : HelperSession) -> Array[HelperEvent] {
let out : Array[HelperEvent] = [] let out : Array[HelperEvent] = []
if self.fd < 0 { if self.ended {
return out return out
} }
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00') for line in self.conn.read_lines() {
let mut eof = false match parse_helper_line(field_text(line)) {
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) {
Some(ev) => { Some(ev) => {
out.push(ev) out.push(ev)
if ev == Success || ev == Failure { if ev == Success || ev == Failure {
self.ended = true self.ended = true
self.conn.close()
return out
} }
} }
None => () None => ()
} }
} }
if eof { if self.conn.eof {
if !self.ended { out.push(Gone)
out.push(Failure)
self.ended = true self.ended = true
} self.conn.close()
self.close()
} }
out 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 { pub impl Conversation for HelperSession with answer(self, a) {
if self.fd < 0 { let n = a.length()
return false 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]))
let n = answer.length() zero(b)
let b = Bytes::makei(n + 1, i => if i < n { answer[i] } else { b'\n' }) ok
@sys.sendmsg_fd(self.fd, b, -1) == b.length()
} }
///| The connection, for the main loop to wait on (-1 once closed). ///|
pub fn HelperSession::fd(self : HelperSession) -> Int { pub impl Conversation for HelperSession with fd(self) {
self.fd self.conn.fd()
} }
///| Stop: closing the connection ends the helper's PAM conversation. ///| Closing the connection ends the helper's PAM conversation.
pub fn HelperSession::close(self : HelperSession) -> Unit { pub impl Conversation for HelperSession with close(self) {
if self.fd >= 0 { self.ended = true
@sys.close_fd(self.fd) self.conn.close()
self.fd = -1
}
} }
+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(),
]
}
+291 -150
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 { 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") 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 us : Array[@polkit.AuthUser] = [{ uid: 1000, name: "nandi", real_name: "Nandi" }, { uid: 0, name: "root", real_name: "root" }]
let req = { ..request("a", "m", {}), users: us[:users].to_array() } let req = { ..request("a", "m", {}), users: us[:users].to_array() }
@polkit.AuthDialog::new(req, @polkit.describe(req, cmdline=_ => [], who=_ => "")) let m = @polkit.AuthMachine::new(req, @polkit.describe(req, cmdline=_ => [], who=_ => ""), fn(_u, _c) {
if fail_start.val != "" {
return Err(fail_start.val)
}
let s = { events: [], answers: [], closed: false }
runs.push(s)
Ok(s as &@polkit.Conversation)
})
m.begin()
m
}
///| Bytes of `s` in a fresh buffer.
fn secret(s : String) -> FixedArray[Byte] {
let b = @utf8.encode(s)
FixedArray::makei(b.length(), i => b[i])
}
///| Feed `evs` to the last run and pump.
fn say(m : @polkit.AuthMachine, runs : Array[Script], evs : Array[@polkit.HelperEvent]) -> Unit {
runs[runs.length() - 1].events.append(evs)
m.pump()
} }
///| ///|
fn answer_text(e : @polkit.DialogEffect) -> String { test "machine: ask, wrong password starts a new check at once, then success" {
match e { let runs : Array[Script] = []
Answer(b) => { let m = machine(1, runs)
let s = @utf8.decode_lossy(Bytes::makei(b.length(), i => b[i])) assert_eq(m.phase, Starting)
@polkit.zero(b) say(m, runs, [PromptEchoOff("Password: ")])
s assert_eq(m.phase, Asking)
} assert_eq(m.prompt, "Password")
_ => "<none>" 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 "dialog: type, submit, wrong password, retry, success" { test "machine: a check that ends before asking is Failed, with no retry until the user asks" {
let d = dialog(1) let runs : Array[Script] = []
let km = @polkit.Keymap::us() let m = machine(1, runs)
let type_str = fn(s : String) { say(m, runs, [Gone])
for c in s { assert_eq(m.phase, Failed)
ignore(d.key(0U, 0U, Some(c))) assert_eq(m.error, "The password check quit before asking for a password.")
} assert_eq(runs.length(), 1) // nothing restarted it
} m.pump()
// Typing before PAM's prompt is kept; Enter waits for it. assert_eq(runs.length(), 1)
type_str("hunter") // FAILURE before any answer: PAM's own words when it gave some (an account lockout).
assert_true(d.key(@polkit.key_enter, 0U, None) is Nothing) m.retry()
assert_eq(answer_text(d.helper(PromptEchoOff("Password: "), 10UL)), "hunter") assert_eq(runs.length(), 2)
assert_eq(d.phase, Checking) assert_eq(m.phase, Starting)
assert_eq(d.typed(), 0) // wiped once sent assert_eq(m.error, "")
// Typing is ignored while PAM checks. say(m, runs, [ErrorMsg("The account is locked due to 3 failed logins."), Failure])
ignore(d.key(30U, 0U, km.char_for(30U, 0U, 0U))) assert_eq(m.phase, Failed)
assert_eq(d.typed(), 0) assert_eq(m.error, "The account is locked due to 3 failed logins.")
// Wrong: error, shake, field cleared, the helper restarts. assert_eq(m.failures, 0)
assert_true(d.helper(Failure, 100UL) is Restart) // Enter with a password typed after a failure: a new check, which gets it when it asks.
assert_eq(d.error, "Wrong password. Try again.") m.answer(secret("pw"))
assert_eq(d.failures, 1) assert_eq(runs.length(), 3)
assert_true(d.shaking(200UL)) say(m, runs, [PromptEchoOff("Password: ")])
assert_false(d.shaking(600UL)) assert_eq(runs[2].answers, ["pw"])
assert_true(d.shake_offset(100UL + 35UL) != 0) assert_eq(m.phase, Checking)
assert_eq(d.phase, Starting) // Quitting while checking is not a wrong password either.
assert_true(d.helper(PromptEchoOff("Password: "), 700UL) is Nothing) say(m, runs, [Gone])
assert_eq(d.prompt, "Password") assert_eq(m.phase, Failed)
type_str("hunter2") assert_eq(m.error, "The password check quit while checking the password.")
assert_eq(d.error, "") // typing again clears it assert_eq(m.failures, 0)
assert_eq(d.field_text(), "●●●●●●●")
ignore(d.activate(Reveal))
d.activate(Field) |> ignore
assert_eq(d.field_text(), "hunter2")
// Backspace, then Enter sends.
ignore(d.key(@polkit.key_backspace, 0U, None))
type_str("2")
assert_eq(answer_text(d.key(@polkit.key_enter, 0U, None)), "hunter2")
assert_true(d.helper(Success, 900UL) is Authorized)
} }
///| ///|
test "dialog: PAM messages, lockout, echo-on prompts, fingerprint" { test "machine: a checker that can't start is Failed with the reason" {
let d = dialog(1) let runs : Array[Script] = []
// A fingerprint module only informs; the dialog waits with its message. let why : Ref[String] = { val: "polkit's password checker could not be started (tried socket /run/polkit/agent-helper.socket)" }
ignore(d.helper(TextInfo("Place your finger on the fingerprint reader"), 1UL)) let m = machine(1, runs, fail_start=why)
assert_eq(d.phase, Waiting) assert_eq(m.phase, Failed)
assert_eq(d.info, "Place your finger on the fingerprint reader") assert_eq(m.error, why.val)
// Then falls back to a password. why.val = ""
ignore(d.helper(PromptEchoOff("Password: "), 2UL)) m.retry()
assert_eq(d.phase, Prompt) assert_eq(m.phase, Starting)
assert_eq(d.info, "")
// An error from PAM (faillock) is shown as is after the failure.
ignore(d.helper(ErrorMsg("The account is locked due to 3 failed logins."), 3UL))
ignore(d.helper(Failure, 4UL))
assert_eq(d.error, "The account is locked due to 3 failed logins.")
// A visible prompt (a one-time code): typed text is shown, even empty answers go.
ignore(d.helper(PromptEchoOn("Verification code: "), 5UL))
assert_true(d.echo)
ignore(d.key(0U, 0U, Some('4')))
assert_eq(d.field_text(), "4")
assert_eq(answer_text(d.key(@polkit.key_kp_enter, 0U, None)), "4")
} }
///| ///|
test "dialog: keyboard focus, Escape, Space toggles, user picker" { test "machine: face unlock scans, the password typed meanwhile goes in when it fails" {
let d = dialog(2) let runs : Array[Script] = []
assert_eq(d.focus, Field) let m = machine(1, runs)
assert_eq(d.focus_order(), [Field, User, Reveal, Details, Cancel, Allow]) say(m, runs, [TextInfo("Face unlock: looking for nandi…")])
ignore(d.key(@polkit.key_tab, 0U, None)) assert_eq(m.face, Scanning)
assert_eq(d.focus, User) assert_eq(m.phase, Starting)
assert_true(d.key(@polkit.key_right, 0U, None) is Restart) assert_eq(m.info, "") // the face row says it, not the info line
assert_eq(d.user().map(u => u.name), Some("root")) m.answer(secret("hunter2"))
ignore(d.key(@polkit.key_tab, 0U, None)) assert_eq(runs[0].answers, [])
ignore(d.key(@polkit.key_space, 0U, None)) say(m, runs, [ErrorMsg("Face unlock: face not recognized")])
assert_true(d.reveal) assert_eq(m.face, FaceFailed("Face not recognized"))
ignore(d.key(@polkit.key_tab, 0U, None)) assert_eq(m.error, "")
ignore(d.key(@polkit.key_enter, 0U, None)) say(m, runs, [PromptEchoOff("Password: ")])
assert_true(d.details_open) assert_eq(runs[0].answers, ["hunter2"])
ignore(d.key(@polkit.key_tab, 1U, None)) // Shift+Tab goes back // A face module that gives up silently still shows as not recognized.
assert_eq(d.focus, Reveal) say(m, runs, [Failure])
// Typing anywhere goes to the field. say(m, runs, [TextInfo("Attempting facial authentication"), PromptEchoOff("Password: ")])
ignore(d.key(0U, 0U, Some('x'))) assert_eq(m.face, FaceFailed("Face not recognized"))
assert_eq(d.focus, Field) // Recognized: PAM finishes without a password.
// Alt+D toggles details from the field; Ctrl+U clears it. m.answer(secret("x"))
ignore(d.key(@polkit.key_d, 8U, Some('d'))) say(m, runs, [Failure])
assert_false(d.details_open) say(m, runs, [TextInfo("Attempting facial authentication"), TextInfo("Identified face as nandi")])
ignore(d.key(@polkit.key_u, 4U, Some('u'))) assert_eq(m.face, Matched)
assert_eq(d.typed(), 0) say(m, runs, [Success])
assert_true(d.key(@polkit.key_esc, 0U, None) is Cancelled) assert_true(m.authorized)
// One user: no picker in the Tab order. }
assert_eq(dialog(1).focus_order(), [Field, Reveal, Details, Cancel, Allow])
///|
test "machine: echo-on prompts, picking another account, cancel" {
let runs : Array[Script] = []
let m = machine(2, runs)
say(m, runs, [PromptEchoOn("Verification code: ")])
assert_true(m.echo)
m.answer(secret("4"))
say(m, runs, [Failure])
assert_eq(m.error, "That didn't work. Try again.")
m.pick_user(1)
assert_eq(m.user().map(u => u.name), Some("root"))
assert_eq(runs.length(), 3)
assert_eq(m.failures, 0)
m.cancel()
assert_eq(m.phase, Done)
assert_false(m.authorized)
assert_true(runs[2].closed)
}
///|
test "the link: fields with tabs, newlines and backslashes survive, secrets too" {
let f = ["state", "1", "a\tb", "line\nnext", "back\\slash", ""]
let line = @polkit.encode_line(f)
assert_eq(line[line.length() - 1], b'\n')
let body = FixedArray::makei(line.length() - 1, i => line[i])
assert_eq(@polkit.decode_line(body), f)
let s = @polkit.encode_secret_line(["answer", "3"], secret("p\tw\\"))
let fields = @polkit.split_fields(FixedArray::makei(s.length() - 1, i => s[i]))
assert_eq(@polkit.field_text(fields[2]), "p\tw\\")
}
///|
test "the machine's state reaches the view: phase, prompt, error, face, failures" {
let runs : Array[Script] = []
let m = machine(1, runs)
let v = @polkit.AuthView::from_request(["request", "7", "Run a command as root", "sub", "run0 ls", "ls", "", "msg"])
v.apply(m.state_fields("7"), 10UL)
assert_true(v.shown)
assert_eq(v.phase, Starting)
say(m, runs, [TextInfo("Face unlock: looking for nandi…")])
v.apply(m.state_fields("7"), 20UL)
assert_eq(v.face, Scanning)
assert_eq(v.face_at, 20UL)
say(m, runs, [PromptEchoOff("Password: ")])
v.apply(m.state_fields("7"), 30UL)
assert_eq(v.phase, Asking)
assert_eq(v.face, FaceFailed("Face not recognized"))
for c in "abc" {
ignore(v.key(0U, 0U, Some(c)))
}
m.answer(v.take_answer())
assert_eq(v.typed(), 0)
say(m, runs, [Failure])
v.apply(m.state_fields("7"), 100UL)
assert_eq(v.failures, 1)
assert_eq(v.error, "Wrong password. Try again.")
assert_true(v.shaking(200UL))
assert_false(v.shaking(600UL))
assert_true(v.shake_offset(135UL) != 0)
}
///| A view with `users` accounts, asking.
fn view(users : Int) -> @polkit.AuthView {
let v = @polkit.AuthView::from_request(["request", "1", "t", "s", "", "", "", ""])
v.apply(["user", "1", "nandi", "Nandi", "1000"], 0UL)
if users > 1 {
v.apply(["user", "1", "root", "root", "0"], 0UL)
}
v.apply(["state", "1", "asking", "Password", "0", "", "", "", "", "0", "0"], 0UL)
v
}
///|
test "view: Enter submits, Try again after a failure, typing blocked while checking" {
let v = view(1)
assert_true(v.key(@polkit.key_enter, 0U, None) is Nothing) // nothing typed
ignore(v.key(0U, 0U, Some('x')))
assert_eq(v.field_text(), "●")
ignore(v.activate(Reveal))
assert_eq(v.field_text(), "x")
assert_true(v.key(@polkit.key_enter, 0U, None) is Nothing) // focus on Show: toggles
ignore(v.activate(Field))
assert_true(v.key(@polkit.key_kp_enter, 0U, None) is Submit)
ignore(v.take_answer())
v.apply(["state", "1", "checking", "Password", "0", "", "", "", "", "0", "0"], 0UL)
ignore(v.key(0U, 0U, Some('y')))
assert_eq(v.typed(), 0)
v.apply(["state", "1", "failed", "Password", "0", "The password check quit.", "", "", "", "0", "0"], 0UL)
assert_eq(v.main_label(), "Try again")
assert_true(v.key(@polkit.key_enter, 0U, None) is Retry)
ignore(v.key(0U, 0U, Some('z')))
assert_eq(v.main_label(), "Authenticate")
assert_true(v.key(@polkit.key_enter, 0U, None) is Submit)
}
///|
test "view: keyboard focus, Escape, Space toggles, account picker" {
let v = view(2)
assert_eq(v.focus_order(), [Field, User, Reveal, Details, Cancel, Allow])
ignore(v.key(@polkit.key_tab, 0U, None))
assert_eq(v.focus, User)
assert_eq(v.key(@polkit.key_right, 0U, None), PickUser(1))
assert_eq(v.key(@polkit.key_left, 0U, None), PickUser(1)) // wraps
ignore(v.key(@polkit.key_tab, 0U, None))
ignore(v.key(@polkit.key_space, 0U, None))
assert_true(v.reveal)
ignore(v.key(@polkit.key_tab, 0U, None))
ignore(v.key(@polkit.key_enter, 0U, None))
assert_true(v.details_open)
ignore(v.key(@polkit.key_tab, 1U, None)) // Shift+Tab goes back
assert_eq(v.focus, Reveal)
ignore(v.key(0U, 0U, Some('x')))
assert_eq(v.focus, Field)
ignore(v.key(@polkit.key_d, 8U, Some('d'))) // Alt+D
assert_false(v.details_open)
ignore(v.key(@polkit.key_u, 4U, Some('u'))) // Ctrl+U
assert_eq(v.typed(), 0)
assert_eq(v.key(@polkit.key_esc, 0U, None), Dismiss)
assert_eq(view(1).focus_order(), [Field, Reveal, Details, Cancel, Allow])
} }
///| ///|
@@ -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, "")) ignore(@sys.spawn("chmod +x " + script, ""))
@sys.sleep_ms(200) @sys.sleep_ms(200)
let s = @polkit.HelperSession::start(Program(script), "nandi", "c-1").unwrap() let s = @polkit.HelperSession::start(Program(script), "nandi", "c-1").unwrap()
let c = s as &@polkit.Conversation
let got : Array[@polkit.HelperEvent] = [] let got : Array[@polkit.HelperEvent] = []
for i = 0; i < 200 && got.length() < 2; i = i + 1 { for i = 0; i < 200 && got.length() < 2; i = i + 1 {
ignore(@sys.poll_read(s.fd(), 10)) ignore(@sys.poll_read(c.fd(), 10))
got.append(s.read()) got.append(c.poll())
} }
assert_eq(got, [TextInfo("hello\tthere"), PromptEchoOff("Password: ")]) assert_eq(got, [TextInfo("hello\tthere"), PromptEchoOff("Password: ")])
let answer : FixedArray[Byte] = FixedArray::make(9, b'\x00') assert_true(c.answer(secret("pässword")))
let b = @utf8.encode("pässword")
for i = 0; i < b.length(); i = i + 1 {
answer[i] = b[i]
}
assert_true(s.respond(answer))
let end : Array[@polkit.HelperEvent] = [] let end : Array[@polkit.HelperEvent] = []
for i = 0; i < 200 && end.length() < 1; i = i + 1 { for i = 0; i < 200 && end.length() < 1; i = i + 1 {
ignore(@sys.poll_read(s.fd(), 10)) ignore(@sys.poll_read(c.fd(), 10))
end.append(s.read()) end.append(c.poll())
} }
assert_eq(end, [Success]) assert_eq(end, [Success])
// The helper exits: the session notices without inventing a second verdict. assert_eq(c.fd(), -1)
for i = 0; i < 50 && s.fd() >= 0; i = i + 1 { assert_eq(c.poll(), []) // no second verdict
ignore(@sys.poll_read(s.fd(), 10)) @sys.unlink(script)
assert_eq(s.read(), []) }
///|
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) @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("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) 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'
}
}
+106 -43
View File
@@ -2,60 +2,123 @@
When run0, pkexec, a disk mount or any other polkit-checked action needs an administrator's When run0, pkexec, a disk mount or any other polkit-checked action needs an administrator's
password, Chandra asks in its own dialog: a card in the middle of a dimmed screen, drawn by the password, Chandra asks in its own dialog: a card in the middle of a dimmed screen, drawn by the
compositor in the shell layer, above every window and client menu. compositor above every window and client menu.
## Try it
```sh
chandra-ctl auth-demo # the dialog with a pretend check: the password is "demo"
chandra-ctl auth-demo face # looks for a face, gives up, then asks for the password
chandra-ctl auth-demo die # the check quits before asking (a broken polkit setup); Try again
chandra-ctl auth-status # is the agent running and registered with polkit, or why not
run0 true # the real thing: your password, through polkit and PAM
```
Demo modes: `password` (default), `face`, `face-ok`, `die`, `slow`, `users`. A demo needs no
root and runs nothing; it uses the same agent program, link, state machine and drawing as a real
request, only the password check is pretend.
If something goes wrong, the session log says what happened step by step:
```sh
grep -E 'chandra-polkit-agent|password dialog' ~/.local/state/chandra/session.log
```
## What it shows
- **What it says.** For run0 the dialog shows the command that will run (`gparted /dev/sda`) and as - **What it says.** For run0 the dialog shows the command that will run (`gparted /dev/sda`) and as
whom, instead of polkit's "start transient unit 'run-p15802-i1990.service'": the unit name whom, instead of polkit's "start transient unit 'run-p15802-i1990.service'". pkexec's command
carries run0's pid, and run0's command line says what it runs. pkexec's command comes from comes from polkit's details. Everything else shows polkit's own message. Details (Alt+D) lists
polkit's details. Everything else shows polkit's own message. Details (Alt+D) lists who asked who asked, the target user, the unit and the polkit action id.
(process and its parent), the target user, the unit and the polkit action id.
- **Who answers.** The account polkit wants: you when you are an administrator, else one of the - **Who answers.** The account polkit wants: you when you are an administrator, else one of the
admins (members of `wheel`/`sudo` are expanded). With several, Tab to the account row and use admins (members of `wheel`/`sudo` are expanded). With several, Tab to the account row and use
← →. ← →.
- **Keyboard.** The field has the focus. Enter authenticates, Esc cancels, Tab / Shift+Tab move - **Keyboard.** The field has the focus. Enter authenticates, Esc cancels, Tab / Shift+Tab move
between the account, Show, Details, Cancel and Authenticate, Space or Enter activates them. between the account, Show, Details, Cancel and Authenticate, Space or Enter activates them.
Alt+R shows or hides the password, Ctrl+U clears it. Typing goes through the same xkb keymap Alt+R shows or hides the password, Ctrl+U clears it. Typing goes through the xkb keymap apps
apps get (groups, Shift, AltGr, Caps Lock), so the password is typed on your layout. Caps Lock get (groups, Shift, AltGr, Caps Lock), so the password is typed on your layout. Caps Lock on
on shows a warning. shows a warning.
- **PAM.** The dialog follows whatever PAM asks through polkit's helper: password prompts, visible - **PAM.** Password prompts, visible prompts (a one-time code), information (a fingerprint reader)
prompts (a one-time code), information (a fingerprint reader asking for a finger) and errors and errors (faillock's "account is locked") are shown as PAM says them. A wrong password shakes
(faillock's "account is locked"). A wrong password shakes the card, says so, and starts again. the card, says so, and PAM asks again. Face unlock gets its own row ("Looking for your face…",
Face unlock (pam_chandra_face.so, or Howdy's pam_howdy.so) gets its own row: "Looking for your then "Face recognized" or why not); the password can be typed meanwhile and goes in when PAM
face…" while the camera looks (the password can be typed meanwhile), then "Face recognized" or asks for it. See [face-unlock.md](face-unlock.md).
why not, before the password prompt; see [face-unlock.md](face-unlock.md). - **When the check fails without a verdict** (polkit's helper can't be reached, quits before
While PAM checks, the field is locked and a spinner shows. asking, or quits while checking), the dialog says exactly that and waits: the main button
becomes **Try again**. Nothing is retried behind your back.
- **Safety.** While the dialog is up no client has keyboard focus, input goes to the dialog only, - **Safety.** While the dialog is up no client has keyboard focus, input goes to the dialog only,
and client popups are hidden, so nothing can draw over it or read the keys. The password is kept and client popups are hidden. The password is kept as characters wiped after sending, the
as characters wiped after sending, the buffer sent to the helper is zeroed, and nothing of it is buffers it passes through are zeroed, and nothing of it is logged.
logged.
## How it works ## How it works
- `compositor/polkit/agent.mbt`: connects to the system bus with the compositor's own D-Bus code Two parts, one process each:
and calls `RegisterAuthenticationAgent` on `org.freedesktop.PolicyKit1.Authority` for the login
session (`XDG_SESSION_ID`, else logind's session of the compositor's pid). It serves - **`chandra-polkit-agent`** (`compositor/authagent`, installed in `/usr/local/lib/chandra/`)
`org.freedesktop.PolicyKit1.AuthenticationAgent` at `/org/chandra/PolicyKit1/AuthenticationAgent`: does everything polkit and PAM: it registers on the system bus as this login session's
`BeginAuthentication` calls queue up and are answered when the dialog is done (an empty reply authentication agent (`RegisterAuthenticationAgent` for `XDG_SESSION_ID`), serves
after success, `org.freedesktop.PolicyKit1.Error.Cancelled` when dismissed); `BeginAuthentication` / `CancelAuthentication` at `/org/chandra/PolicyKit1/AuthenticationAgent`,
`CancelAuthentication` closes the dialog. runs polkit's `polkit-agent-helper-1` (polkit 126's `/run/polkit/agent-helper.socket`, else the
- `compositor/polkit/helper.mbt`: the PAM conversation through `polkit-agent-helper-1`. With polkit setuid program), and keeps each request in **one state machine**
126+ it connects to `/run/polkit/agent-helper.socket` (socket activation) and sends the user name (`compositor/polkit/machine.mbt`):
and cookie; otherwise it runs the setuid helper (`/usr/lib/polkit-1/...` or
`/usr/libexec/...`) on a socket pair (`sys.spawn-socket`, implemented by all three hosts) and ```
sends the cookie. On success the helper tells polkitd itself. Starting --PAM asks--> Asking --answer--> Checking --SUCCESS--> Done
- `compositor/polkit/describe.mbt`, `keymap.mbt`, `dialog.mbt`: words for a request, the xkb ^ |
keymap parser, the dialog's states. `compositor/host/auth.mbt`: drawing and input. +---- new check <----+ FAILURE (wrong password: counted, card shakes)
- Only the login session (`--drm`) registers. The setting is state.edn `:auth-agent :system` when Starting/Checking --check quits, can't start, ends without asking--> Failed --Try again--> Starting
off. If polkit refuses (another agent already has the session) or there is no system bus, the any --cancel--> Done
compositor starts the third-party agent `chandra-session` found (`CHANDRA_POLKIT_FALLBACK`). ```
Turning the switch off live unregisters and starts that agent; turning it back on while that
agent runs takes effect at the next login (polkit allows one agent per session). It logs every step to stderr, which is the session log (never what was typed).
- Debug: `CHANDRA_POLKIT_HELPER=socket:/path` or `=/path/to/helper` picks the helper. - **The compositor** (`compositor/host/auth.mbt`, `auth_draw.mbt`) starts the agent on a socket
pair (its stdin/stdout), draws the dialog from the state the agent sends, owns the keyboard
and the pointer while it is up (`grab_input`: the dialog, else the Face unlock window, never
both), and sends back the answer, the account picked, Try again, or Cancel. The link is a
line protocol (`compositor/polkit/wire.mbt`); only the compositor holds the other end, so no
other program can open the dialog or read what is typed into it.
### When it can't work, you are told
There is no silent fallback. A notice at the top of the screen (click to dismiss) and the session
log say what happened:
- the agent program isn't installed or can't be run;
- polkit refused the agent (say, another agent already has the session) or there is no system
bus;
- polkit hasn't answered within 10 seconds;
- the agent stopped after it was running: it is started again (up to three times) and the notice
says so.
Settings > Session > **Chandra password dialog** off is the only way another polkit agent runs
(the first one `chandra-session` finds, passed as `CHANDRA_POLKIT_FALLBACK`); it is saved as
state.edn `:auth-agent :system`. Turning it back on while that agent runs takes effect at the next
login (polkit allows one agent per session), and the notice says so. `CHANDRA_POLKIT_AGENT=none`
starts no agent; `=PATH` starts that agent instead. `CHANDRA_POLKIT_AGENT_BIN` points at another
build of chandra-polkit-agent, and `CHANDRA_POLKIT_HELPER=socket:/path` or `=/path/to/helper`
picks polkit's helper (both for debugging).
### Why it was rebuilt (2026-11-26)
The first version ran polkit, the helper, PAM 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 tight loop that wiped the field, so typing seemed to do nothing; a
refused registration quietly started another agent; the dialog and the Face unlock window each
grabbed the keyboard. The split above gives one state machine, one input owner, and an explicit
error for every failure.
## Tests ## Tests
`compositor/polkit/polkit_test.mbt` (keymaps, helper lines, run0 parsing, descriptions, dialog - `compositor/polkit/polkit_test.mbt`: keymaps, helper lines (and `Gone` when the helper quits),
states) and `compositor/host/auth_test.mbt`, which runs the agent against a mock polkit Authority run0 parsing, descriptions, the link encoding, the state machine (wrong password, early quit,
on a private `dbus-daemon` and a mock helper on a socket. `CHANDRA_AUTH_SHOTS=/some/dir` writes a no retry until asked, face unlock, account picker) and the view (keys, Try again).
PNG of each dialog state. Not covered by tests: the real polkitd and PAM (registration for a real - `compositor/host/auth_test.mbt`, end to end through `handle_input`: the agent loop in-process
logind session, the real helper's socket and setuid paths). against a mock polkit Authority on a private `dbus-daemon` and a mock helper socket, and the
**real agent program** spawned by the compositor (demo, and registered with the mock polkit
through its own process). Covers typing on a real xkbcommon keymap, wrong password, cancel,
polkit withdrawing a request, the helper quitting early, the helper missing, polkit refusing the
agent, the agent not starting or crashing (notices), the demo modes, and Face unlock's Apply.
`CHANDRA_AUTH_SHOTS=/some/dir` writes a PNG of each state. Build the agent first
(`just auth-agent`), or the real-program test is skipped.
- Not covered: a real polkitd and PAM (a real logind session, the real helper's socket and setuid
paths). `run0 true` in the session is that test.
+4 -3
View File
@@ -82,11 +82,12 @@ the password in the terminal, as usual.
Started from a terminal, run0 asks there. Started from the launcher or a keyboard shortcut there is Started from a terminal, run0 asks there. Started from the launcher or a keyboard shortcut there is
no terminal, so run0 and pkexec need a **polkit authentication agent** in the session. Chandra is no terminal, so run0 and pkexec need a **polkit authentication agent** in the session. Chandra is
its own: the compositor registers with polkit and asks in a dialog it draws itself, showing the its own: the compositor starts chandra-polkit-agent and asks in a dialog it draws itself, showing
command run0 will run (see [auth-dialog.md](auth-dialog.md)). Turn off Settings → Session → the command run0 will run (see [auth-dialog.md](auth-dialog.md); `chandra-ctl auth-demo` shows it
without root). If it can't start, a notice on screen says why. Turn off Settings → Session →
"Chandra password dialog" to use a third-party agent instead; `chandra-session` finds the first one "Chandra password dialog" to use a third-party agent instead; `chandra-session` finds the first one
installed (polkit-gnome, mate-polkit, polkit-kde, hyprpolkitagent, xfce-polkit or lxpolkit) and installed (polkit-gnome, mate-polkit, polkit-kde, hyprpolkitagent, xfce-polkit or lxpolkit) and
the compositor starts it then, or whenever polkit won't take Chandra's agent. Set the compositor starts it then (only then). Set
`CHANDRA_POLKIT_AGENT=/path/to/agent` to always use that agent, or `CHANDRA_POLKIT_AGENT=none` if `CHANDRA_POLKIT_AGENT=/path/to/agent` to always use that agent, or `CHANDRA_POLKIT_AGENT=none` if
a systemd user unit already starts one. Its output goes to the session log. a systemd user unit already starts one. Its output goes to the session log.
+10 -2
View File
@@ -39,6 +39,14 @@ build:
build-release: build-release:
moon build --target native --release --warn-list -a compositor/bin moon build --target native --release --warn-list -a compositor/bin
# Chandra's polkit agent (the password dialog's other half; the compositor starts it): docs/auth-dialog.md.
auth-agent:
moon build --target native --release --warn-list -a compositor/authagent
# Show the password dialog in the running session with a pretend check (password "demo"); MODE: password, face, face-ok, die, slow, users.
auth-demo mode="password":
python3 session/chandra-ctl auth-demo {{mode}}
# Run the compositor, built as a wasm component, in a window on your current Wayland session (close the window or Ctrl-C to stop). Connect clients via `just client`. # Run the compositor, built as a wasm component, in a window on your current Wayland session (close the window or Ctrl-C to stop). Connect clients via `just client`.
run: compositor-wasm wasmhost modules run: compositor-wasm wasmhost modules
rm -f {{socket}} rm -f {{socket}}
@@ -92,11 +100,11 @@ run-drm-native: build-release modules
install *flags: install *flags:
#!/usr/bin/env bash #!/usr/bin/env bash
set -euo pipefail set -euo pipefail
builds="compositor-wasm wasmhost modules" builds="compositor-wasm wasmhost modules auth-agent"
face=1 face=1
for f in {{flags}}; do for f in {{flags}}; do
case "$f" in case "$f" in
--native) builds="build-release modules" ;; --native) builds="build-release modules auth-agent" ;;
--rust) echo "just install: --rust is gone: the Rust host was removed (2026-11-26); the MoonBit host is the only one" >&2; exit 2 ;; --rust) echo "just install: --rust is gone: the Rust host was removed (2026-11-26); the MoonBit host is the only one" >&2; exit 2 ;;
--no-face) face=0 ;; --no-face) face=0 ;;
--link|--pam|--no-models) ;; --link|--pam|--no-models) ;;
+4 -1
View File
@@ -8,6 +8,9 @@
chandra-ctl shortcut ID do what a keyboard shortcut does (overview, launcher, show-desktop...) chandra-ctl shortcut ID do what a keyboard shortcut does (overview, launcher, show-desktop...)
chandra-ctl kiosk [lock|unlock|status] kiosk mode (--kiosk, docs/kiosk.md) chandra-ctl kiosk [lock|unlock|status] kiosk mode (--kiosk, docs/kiosk.md)
chandra-ctl windows how Chandra sees each window, and what is under the pointer chandra-ctl windows how Chandra sees each window, and what is under the pointer
chandra-ctl auth-demo [MODE] show the password dialog with a pretend check (password "demo");
MODE: password, face, face-ok, die, slow, users (docs/auth-dialog.md)
chandra-ctl auth-status the password dialog's agent: registered with polkit, or why not
The socket is $XDG_RUNTIME_DIR/chandra/<wayland socket name>.sock (the session's is The socket is $XDG_RUNTIME_DIR/chandra/<wayland socket name>.sock (the session's is
wayland-moon-0.sock). It is found in this order: --socket PATH, $CHANDRA_CONTROL, the one for wayland-moon-0.sock). It is found in this order: --socket PATH, $CHANDRA_CONTROL, the one for
@@ -20,7 +23,7 @@ import os
import socket import socket
import sys import sys
USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | windows | help}" USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | windows | auth-demo [MODE] | auth-status | help}"
def runtime_dir(): def runtime_dir():
+5 -4
View File
@@ -170,10 +170,11 @@ if [ "$backend" = --drm ] && [ -n "$XDG_SESSION_ID" ] && command -v loginctl >/d
fi fi
# Password prompts for `chandra-root APP`, run0 and pkexec started from the launcher or a shortcut # Password prompts for `chandra-root APP`, run0 and pkexec started from the launcher or a shortcut
# (no terminal to ask in): the compositor is its own polkit authentication agent and asks in a # (no terminal to ask in): the compositor starts Chandra's polkit agent
# dialog it draws itself (compositor/host/auth.mbt; Settings > Session > "Chandra password # (/usr/local/lib/chandra/chandra-polkit-agent) and draws its dialog itself (docs/auth-dialog.md).
# dialog"). When that switch is off, or polkit won't take Chandra's agent, the compositor starts # If that can't start, a notice on screen says why; nothing else takes over. Only when the user
# the first third-party agent installed, found here and passed as CHANDRA_POLKIT_FALLBACK. # turns Settings > Session > "Chandra password dialog" off does the compositor start the first
# third-party agent installed, found here and passed as CHANDRA_POLKIT_FALLBACK.
# CHANDRA_POLKIT_AGENT=none starts no agent at all (say, when a systemd user unit already starts # CHANDRA_POLKIT_AGENT=none starts no agent at all (say, when a systemd user unit already starts
# one); a path starts that agent instead of Chandra's. # one); a path starts that agent instead of Chandra's.
fallback= fallback=
+13
View File
@@ -24,6 +24,8 @@ Installs:
/usr/local/bin/chandra (--native) release native compositor binary /usr/local/bin/chandra (--native) release native compositor binary
/usr/local/bin/chandra-session session launcher (starts the host if installed) /usr/local/bin/chandra-session session launcher (starts the host if installed)
/usr/local/bin/chandra-root run one graphical app as root in the session (run0) /usr/local/bin/chandra-root run one graphical app as root in the session (run0)
/usr/local/lib/chandra/chandra-polkit-agent the password dialog's polkit agent; the compositor
starts it (docs/auth-dialog.md)
/usr/local/bin/chandra-ctl talk to the running session: `chandra-ctl reload` loads /usr/local/bin/chandra-ctl talk to the running session: `chandra-ctl reload` loads
the panel modules again (docs/reloading.md) the panel modules again (docs/reloading.md)
/usr/local/bin/chandra-kde-colors Dark mode for KDE/Qt apps: copies a color scheme into /usr/local/bin/chandra-kde-colors Dark mode for KDE/Qt apps: copies a color scheme into
@@ -44,6 +46,9 @@ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
native = "--native" in sys.argv native = "--native" in sys.argv
linked = "--link" in sys.argv linked = "--link" in sys.argv
exe = os.path.join(root, "_build/native/release/build/compositor/bin/bin.exe") exe = os.path.join(root, "_build/native/release/build/compositor/bin/bin.exe")
# Chandra's polkit agent (just auth-agent): the compositor starts it for the password dialog.
auth_agent = os.path.join(root, "_build/native/release/build/compositor/authagent/authagent.exe")
auth_agent_dst = "/usr/local/lib/chandra/chandra-polkit-agent"
if "--rust" in sys.argv or "--rust-host" in sys.argv: if "--rust" in sys.argv or "--rust-host" in sys.argv:
sys.exit("install.py: --rust is gone: the Rust host (host-wasm) was removed on 2026-11-26; " sys.exit("install.py: --rust is gone: the Rust host (host-wasm) was removed on 2026-11-26; "
"the MoonBit host (build/wasmhost) is the only one, so drop the flag") "the MoonBit host (build/wasmhost) is the only one, so drop the flag")
@@ -57,6 +62,7 @@ targets = [
"/usr/local/bin/chandra-host", "/usr/local/bin/chandra-host",
"/usr/local/bin/chandra-session", "/usr/local/bin/chandra-session",
"/usr/local/bin/chandra-root", "/usr/local/bin/chandra-root",
"/usr/local/lib/chandra/chandra-polkit-agent",
"/usr/local/bin/chandra-ctl", "/usr/local/bin/chandra-ctl",
"/usr/local/bin/chandra-kde-colors", "/usr/local/bin/chandra-kde-colors",
"/usr/local/share/color-schemes/ChandraDark.colors", "/usr/local/share/color-schemes/ChandraDark.colors",
@@ -97,6 +103,8 @@ if "--remove" in sys.argv:
print("removed", share) print("removed", share)
sys.exit(1 if face_rc else 0) sys.exit(1 if face_rc else 0)
if not os.path.exists(auth_agent):
sys.exit("missing %s - run `just auth-agent` first (the password dialog needs it)" % auth_agent)
if native: if native:
if not os.path.exists(exe): if not os.path.exists(exe):
sys.exit("missing %s - run `just build-release` first" % exe) sys.exit("missing %s - run `just build-release` first" % exe)
@@ -159,6 +167,11 @@ if not native:
install(component, os.path.join(share, "compositor.wasm")) install(component, os.path.join(share, "compositor.wasm"))
install(os.path.join(root, "session/chandra-session"), "/usr/local/bin/chandra-session") install(os.path.join(root, "session/chandra-session"), "/usr/local/bin/chandra-session")
install(os.path.join(root, "session/chandra-root"), "/usr/local/bin/chandra-root") install(os.path.join(root, "session/chandra-root"), "/usr/local/bin/chandra-root")
# Executable wherever it lives (install() only marks /bin/ paths executable).
if linked:
link(auth_agent, auth_agent_dst)
else:
put(auth_agent, auth_agent_dst, 0o755)
install(os.path.join(root, "session/chandra-ctl"), "/usr/local/bin/chandra-ctl") install(os.path.join(root, "session/chandra-ctl"), "/usr/local/bin/chandra-ctl")
install(os.path.join(root, "session/chandra-kde-colors"), "/usr/local/bin/chandra-kde-colors") install(os.path.join(root, "session/chandra-kde-colors"), "/usr/local/bin/chandra-kde-colors")
for f in ("ChandraDark.colors", "ChandraLight.colors"): for f in ("ChandraDark.colors", "ChandraLight.colors"):