Face unlock: a Howdy-style PAM module, shown in the password dialog and set up in Settings
CI / test (push) Successful in 2m6s

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
This commit is contained in:
Claude committed 2026-11-26 01:19:29 +00:00
1 parent 0f71779819
commit 932fca627e
47 files changed
+2781 -29

No files matched your search

+69 -2
View File
@@ -335,7 +335,7 @@ fn ChandraCompositor::auth_cursor(self : ChandraCompositor, ui : AuthUi) -> UInt
///| Whether the dialog animates (a failed attempt shakes it; a spinner while PAM checks).
fn ChandraCompositor::auth_animating(self : ChandraCompositor) -> Bool {
match self.auth {
Some(ui) => ui.dialog.shaking(@sys.monotonic_ms()) || ui.dialog.phase == Checking
Some(ui) => ui.dialog.shaking(@sys.monotonic_ms()) || ui.dialog.phase == Checking || ui.dialog.face == Scanning
None => false
}
}
@@ -445,6 +445,24 @@ fn auth_button(
}
}
///| 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 {
@@ -563,6 +581,55 @@ fn ChandraCompositor::auth_ops(self : ChandraCompositor) -> Array[@scene.DrawOp]
}
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
@@ -592,7 +659,7 @@ fn ChandraCompositor::auth_ops(self : ChandraCompositor) -> Array[@scene.DrawOp]
if d.typed() == 0 {
let hint = match d.phase {
Starting => "Preparing…"
Waiting => "Waiting…"
Waiting => if d.face == Scanning { "Type your password" } else { "Waiting…" }
_ => 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))
+8
View File
@@ -348,8 +348,16 @@ test "Escape dismisses: polkitd hears Cancelled; polkitd withdrawing a request c
assert_eq(comp.auth_dialog().unwrap().user().map(u => u.name), Some("ada"))
let (h2, hello) = helper_accept(listen, comp, a)
assert_eq(hello, "ada|c1")
// 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…")
assert_true(settle(comp, a, fn() { comp.auth_dialog().map(d => d.face == Scanning).unwrap_or(false) }))
assert_eq(comp.auth_dialog().unwrap().info, "") // the fingerprint message went with nandi's attempt
auth_shot(comp, "14-face-scanning")
helper_say(h2, "PAM_ERROR_MSG Face unlock: face not recognized")
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_eq(comp.auth_dialog().unwrap().face, FaceFailed("Face not recognized"))
auth_shot(comp, "15-face-failed")
auth_shot(comp, "12-other-account")
auth_press(comp, 1U) // Escape
assert_true(settle(comp, a, fn() { a.answers.length() == 1 }))
+2 -1
View File
@@ -641,7 +641,8 @@ pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool {
self.auth_animating() ||
self.thumbs_pending() ||
self.overview_animating() ||
self.shell.animating()
self.shell.animating() ||
self.shell.face_busy()
}
///| How long an idle main loop may sleep: `idle_ms` (until the wall clock's next second), or
+122
View File
@@ -0,0 +1,122 @@
///| Face unlock in Settings > Session (docs/face-unlock.md), against a fake chandra-face: a shell
/// script that answers `status` from files and changes them for enroll / remove / pam, the way
/// the real one does after run0 or pkexec. CHANDRA_AUTH_SHOTS=dir also saves a PNG of the tab.
///| Write the fake tool into `dir` and return its path.
fn fake_face_tool(dir : String) -> String {
let script =
#|#!/bin/sh
#|S="$(dirname "$0")"
#|case "$1" in
#|status)
#| echo "backend opencv"; echo "device /dev/video2"
#| echo "pam $(cat "$S/pam" 2>/dev/null)"
#| cat "$S/faces" 2>/dev/null ;;
#|enroll)
#| echo "info Look at the camera…"
#| for i in 1 2 3 4 5; do echo "progress $i/5"; done
#| printf 'face 2\tFace 2\t2026-11-26\n' >> "$S/faces"
#| echo "done Added Face 2" ;;
#|remove)
#| grep -v "^face $2 " "$S/faces" > "$S/faces.new"; mv "$S/faces.new" "$S/faces"
#| echo "done Removed face $2" ;;
#|pam)
#| if [ "$2" = enable ]; then echo "polkit-1,sudo" > "$S/pam"; else : > "$S/pam"; fi
#| echo "done ok" ;;
#|esac
ignore(@sys.mkdir_p(dir))
let tool = dir + "/chandra-face"
ignore(@sys.write_file_bytes(tool, @sys.str_to_utf8_bytes(script)))
ignore(@sys.write_file_bytes(dir + "/faces", @sys.str_to_utf8_bytes("face 1\tDesk\t2026-11-20\n")))
tool
}
///| Compose frames until `cond` holds (the tool runs on a socket), at most ~3 s.
fn face_settle(comp : @host.ChandraCompositor, cond : () -> Bool) -> Bool {
for i = 0; i < 300; i = i + 1 {
ignore(comp.compose_frame())
if cond() {
return true
}
@sys.sleep_ms(10)
}
false
}
///| The popup's texts.
fn face_texts(comp : @host.ChandraCompositor) -> Array[String] {
let slot = comp.shell.slot_of("session-settings")
comp.shell.slot_popup_texts(slot).map(t => t.0)
}
///| Click the popup text `label`.
fn face_click(comp : @host.ChandraCompositor, label : String, t : UInt) -> Unit raise {
let slot = comp.shell.slot_of("session-settings")
let pr = comp.shell.slot_popup_rect(slot)
match comp.shell.slot_popup_texts(slot).iter().find_first(x => x.0 == label) {
Some((_, x, y)) => {
comp.handle_input(@nested.InputEvent::PointerMove((pr.x + x + 4).to_double(), (pr.y + y).to_double()), t)
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), t + 1U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), t + 2U)
ignore(comp.compose_frame())
}
None => fail("no \"" + label + "\" in the popup")
}
}
///|
test "Settings > Session: face unlock lists faces, adds one, turns it on, removes one" {
let dir = "/tmp/chandra-face-test-" + @sys.getpid().to_string()
let tool = fake_face_tool(dir)
let comp = new_comp("face")
// spawn-socket runs a program; the script has no x bit (sys has no chmod): through sh.
comp.shell.set_face_tool(["/bin/sh", tool])
assert_true(comp.shell.open_settings(Session))
assert_true(face_settle(comp, fn() { face_texts(comp).contains("Desk") }))
let texts = face_texts(comp)
assert_true(texts.contains("Face unlock"))
assert_true(texts.contains("Use my face for passwords"))
assert_true(texts.contains("added 2026-11-20"))
assert_true(texts.contains("Add a face…"))
assert_false(comp.shell.face.in_use())
// Add a face: the tool's progress shows, then the new face.
face_click(comp, "Add a face…", 10U)
assert_true(face_settle(comp, fn() { face_texts(comp).contains("Face 2") }))
assert_true(face_texts(comp).contains("Added Face 2"))
// The switch: polkit-1 and sudo try the face first.
face_click(comp, "Use my face for passwords", 20U)
assert_true(face_settle(comp, fn() { comp.shell.face.in_use() }))
let shots = @sys.getenv("CHANDRA_AUTH_SHOTS")
if shots != "" {
ignore(@sys.write_file_bytes(shots + "/16-settings-face.png", @renderer.encode_png_compressed(comp.compose_frame())))
}
// Remove takes a second click.
face_click(comp, "Remove", 30U)
assert_true(face_texts(comp).contains("Click again to remove"))
assert_eq(comp.shell.face.faces.length(), 2)
face_click(comp, "Click again to remove", 40U)
assert_true(face_settle(comp, fn() { comp.shell.face.faces.length() == 1 }))
assert_eq(comp.shell.face.faces[0].1, "Face 2")
comp.close()
}
///|
test "face unlock status lines" {
let f = @shell.FaceUnlock::new()
f.apply_status([
"backend opencv", "device /dev/video0", "problem python3-opencv is not installed", "pam polkit-1,sudo",
"howdy login,gdm-password", "face 3\tGlasses\t2026-11-01",
])
assert_true(f.installed)
assert_eq(f.problem, "python3-opencv is not installed")
assert_true(f.in_use())
assert_eq(f.howdy, "login, gdm-password")
assert_eq(f.faces, [("3", "Glasses", "2026-11-01")])
// No tool: nothing is installed, whatever else was said.
f.apply_status([])
assert_false(f.installed)
assert_false(f.in_use())
assert_eq(@shell.face_progress("progress 2/5"), Some("Look at the camera… 2/5"))
assert_eq(@shell.face_progress("error couldn't see a face clearly"), Some("Couldn't see a face clearly"))
assert_eq(@shell.face_progress("face 1\tDesk\t2026-11-20"), None)
}
+2 -1
View File
@@ -1694,7 +1694,8 @@ test "open_settings opens the settings module on the tab asked for" {
assert_eq(pr.h, 40 + (1 + 4 + 6) * 28 + 6)
assert_true(comp.shell.open_settings(Session))
ignore(comp.compose_frame())
assert_eq(comp.shell.slot_popup_rect(slot).h, 40 + 4 * 28 + 6) // the four settings
// The four settings, then Face unlock (a heading; chandra-face isn't installed in tests).
assert_eq(comp.shell.slot_popup_rect(slot).h, 40 + 6 * 28 + 6)
}
///|
+99
View File
@@ -14,6 +14,66 @@ pub(all) enum Phase {
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
@@ -101,6 +161,10 @@ pub(all) struct AuthDialog {
mut focus : Focus
/// Enter came before PAM's prompt: answer as soon as it does.
mut submit_queued : 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
}
///|
@@ -122,6 +186,8 @@ pub fn AuthDialog::new(req : AuthRequest, desc : Description) -> AuthDialog {
shake_at: 0UL,
focus: Field,
submit_queued: false,
face: NoFace,
face_at: 0UL,
}
}
@@ -207,8 +273,29 @@ fn AuthDialog::submit(self : AuthDialog) -> DialogEffect {
///| 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(_)
@@ -245,6 +332,7 @@ pub fn AuthDialog::helper(self : AuthDialog, ev : HelperEvent, now : UInt64) ->
self.submit_queued = false
self.phase = Starting
self.info = ""
self.face = NoFace
self.focus = Field
Restart
}
@@ -282,6 +370,7 @@ fn AuthDialog::cycle_user(self : AuthDialog, delta : Int) -> DialogEffect {
self.wipe()
self.error = ""
self.info = ""
self.face = NoFace
self.phase = Starting
self.submit_queued = false
Restart
@@ -401,6 +490,16 @@ pub fn AuthDialog::shake_offset(self : AuthDialog, now : UInt64) -> Int {
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
+52
View File
@@ -325,3 +325,55 @@ test "the setuid route: the helper runs on a socket pair and speaks the protocol
s.close()
@sys.unlink(script)
}
///|
test "face unlock: Chandra's and Howdy's PAM messages" {
assert_eq(@polkit.face_message("Face unlock: looking for nandi…", false), Some(Scanning))
assert_eq(@polkit.face_message("Face unlock: recognized nandi", false), Some(Matched))
assert_eq(@polkit.face_message("Face unlock: face not recognized", true), Some(FaceFailed("Face not recognized")))
assert_eq(@polkit.face_message("Face unlock: the camera picture is too dark\n", true), Some(FaceFailed("The camera picture is too dark")))
assert_eq(@polkit.face_message("Attempting facial authentication", false), Some(Scanning))
assert_eq(@polkit.face_message("Identified face as nandi", false), Some(Matched))
assert_eq(@polkit.face_message("Failure, timeout reached", true), Some(FaceFailed("Face not recognized")))
assert_eq(@polkit.face_message("Face detection image too dark", true), Some(FaceFailed("The camera picture is too dark")))
assert_eq(@polkit.face_message("Place your finger on the fingerprint reader", false), None)
assert_eq(@polkit.face_message("The account is locked due to 3 failed logins.", true), None)
}
///|
test "dialog: face unlock scans, the password typed meanwhile goes in when it fails" {
let d = dialog(1)
ignore(d.helper(TextInfo("Face unlock: looking for nandi…"), 50UL))
assert_eq(d.face, Scanning)
assert_eq(d.face_at, 50UL)
assert_eq(d.phase, Waiting)
assert_eq(d.info, "") // the face row says it, not the info line
// Typing while it looks is kept, and Enter waits for the password prompt.
for c in "hunter2" {
ignore(d.key(0U, 0U, Some(c)))
}
assert_true(d.key(@polkit.key_enter, 0U, None) is Nothing)
ignore(d.helper(ErrorMsg("Face unlock: face not recognized"), 60UL))
assert_eq(d.face, FaceFailed("Face not recognized"))
assert_eq(d.error, "")
assert_eq(d.face_text(), "Face not recognized. Use your password.")
assert_eq(answer_text(d.helper(PromptEchoOff("Password: "), 70UL)), "hunter2")
// A wrong password restarts the conversation: the face is tried again.
assert_true(d.helper(Failure, 80UL) is Restart)
assert_eq(d.face, NoFace)
// Recognized: PAM finishes without a password.
ignore(d.helper(TextInfo("Attempting facial authentication"), 90UL))
assert_eq(d.face, Scanning)
ignore(d.helper(TextInfo("Identified face as nandi"), 95UL))
assert_eq(d.face, Matched)
assert_true(d.helper(Success, 99UL) is Authorized)
}
///|
test "dialog: a face module that gives up silently still shows as not recognized" {
let d = dialog(1)
ignore(d.helper(TextInfo("Attempting facial authentication"), 1UL))
ignore(d.helper(PromptEchoOff("Password: "), 2UL))
assert_eq(d.face, FaceFailed("Face not recognized"))
assert_eq(d.phase, Prompt)
}
+322
View File
@@ -0,0 +1,322 @@
///| The `face-unlock` capability (docs/face-unlock.md): Settings > Session lists the session
/// user's enrolled faces and whether the password dialog and sudo try the face first. The shell
/// gets all of it from `chandra-face` (face/chandra-face), run on a socket so the compositor
/// never waits on it: `status` as the user (labels only, no face data), and enroll / remove /
/// `pam enable|disable` the same way, which re-run themselves through run0 or pkexec, so polkit
/// asks for an administrator's password (in Chandra's own dialog) before anything changes. The
/// camera pictures stay inside that root process.
///| What the shell knows about face unlock, and the chandra-face run in progress.
pub(all) struct FaceUnlock {
/// How to run the tool: its path (CHANDRA_FACE_TOOL, else the installed helper; none in tests
/// unless set), or an interpreter and the path.
mut tool : Array[String]
/// The last status said "backend ..." (the tool runs).
mut installed : Bool
mut problem : String
/// PAM services using pam_chandra_face.so / Howdy's pam_howdy.so.
mut pam : Array[String]
mut howdy : String
/// (id, label, added) of each enrolled face.
mut faces : Array[(String, String, String)]
/// What the running change said last, or how the last one ended.
mut message : String
/// The run in progress: our end of its socket, what it has said so far, and whether it is a
/// change (the status is read again after one).
mut fd : Int
inbuf : Array[Byte]
mut lines : Array[String]
mut change : Bool
/// Runs waiting their turn (one at a time): (argv, is a change).
queue : Array[(Array[String], Bool)]
/// The status was read at least once.
mut loaded : Bool
mut dirty : Bool
}
///|
pub fn FaceUnlock::new() -> FaceUnlock {
let env = @sys.getenv("CHANDRA_FACE_TOOL")
{
tool: [
if env != "" {
env
} else if @sys.getenv("CHANDRA_TEST_CONFIG") != "" {
"/nonexistent/chandra-face" // tests don't see a chandra-face installed on the machine
} else {
"/usr/local/lib/chandra/chandra-face"
},
],
installed: false,
problem: "",
pam: [],
howdy: "",
faces: [],
message: "",
fd: -1,
inbuf: [],
lines: [],
change: false,
queue: [],
loaded: false,
dirty: true,
}
}
///| Run chandra-face as `argv` (tests: a fake, `["/bin/sh", script]`) and read the status again.
pub fn DesktopShell::set_face_tool(self : DesktopShell, argv : Array[String]) -> Unit {
self.face.tool = argv
self.face.loaded = false
self.face.refresh()
}
///| Whether the password dialog (polkit-1) tries the face first.
pub fn FaceUnlock::in_use(self : FaceUnlock) -> Bool {
self.pam.contains("polkit-1")
}
///| A change is running or waiting.
pub fn FaceUnlock::busy(self : FaceUnlock) -> Bool {
(self.fd >= 0 && self.change) || self.queue.iter().any(q => q.1)
}
///| Run `args` of the tool (after the one in progress).
fn FaceUnlock::run(self : FaceUnlock, args : Array[String], change : Bool) -> Unit {
let argv = self.tool.copy()
argv.append(args)
argv.push("--machine")
self.queue.push((argv, change))
self.next()
}
///| Start the next queued run when none is in progress.
fn FaceUnlock::next(self : FaceUnlock) -> Unit {
if self.fd >= 0 || self.queue.length() == 0 {
return
}
let (argv, change) = self.queue.remove(0)
self.lines = []
self.inbuf.clear()
self.change = change
self.fd = @sys.spawn_socket(argv)
if self.fd < 0 {
if change {
self.message = "Couldn't run chandra-face"
}
self.installed = false
self.loaded = true
self.dirty = true
self.next()
}
}
///| Read the status again.
pub fn FaceUnlock::refresh(self : FaceUnlock) -> Unit {
if self.queue.iter().any(q => !q.1) {
return
}
self.run(["status"], false)
}
///| Read what the run in progress said (non-blocking); finish it at EOF.
pub fn FaceUnlock::poll(self : FaceUnlock) -> Unit {
if self.fd < 0 {
return
}
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00')
let mut eof = false
while @sys.poll_read(self.fd, 0) > 0 {
let (n, extra) = @sys.recvmsg_fd(self.fd, buf, buf.length())
if extra >= 0 {
@sys.close_fd(extra)
}
if n == -1 {
break
}
if n <= 0 {
eof = true
break
}
for i = 0; i < n; i = i + 1 {
self.inbuf.push(buf[i])
}
}
// Whole lines; a change shows its latest one as it goes.
while true {
let nl = self.inbuf.search(b'\n').unwrap_or(-1)
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)
self.lines.push(line)
if self.change {
match face_progress(line) {
Some(m) => {
self.message = m
self.dirty = true
}
None => ()
}
}
}
if !eof {
return
}
@sys.close_fd(self.fd)
self.fd = -1
if self.change {
if !self.lines.iter().any(l => l.has_prefix("done ") || l.has_prefix("error ")) {
// run0 / pkexec refused (no password, or it was cancelled) before the tool ran.
self.message = "Nothing changed"
}
self.change = false
self.dirty = true
self.refresh()
} else {
self.apply_status(self.lines)
}
self.next()
}
///| What a change's line means for the Settings row ("Look at the camera… 3/5"), if anything.
pub fn face_progress(line : String) -> String? {
let (kind, text) = match line.find(" ") {
Some(i) => (line[:i].to_string(), line[i + 1:].to_string())
None => (line, "")
}
match kind {
"info" | "done" => Some(upper_first(text))
"error" => Some(upper_first(text))
"progress" => Some("Look at the camera… " + text)
_ => None
}
}
///|
fn upper_first(s : String) -> String {
if s.length() == 0 {
s
} else {
s[:1].to_string().to_upper() + s[1:].to_string()
}
}
///| Take in `chandra-face status --machine` output.
pub fn FaceUnlock::apply_status(self : FaceUnlock, lines : Array[String]) -> Unit {
let mut installed = false
let mut problem = ""
let mut howdy = ""
let pam : Array[String] = []
let faces : Array[(String, String, String)] = []
for line in lines {
let (kind, text) = match line.find(" ") {
Some(i) => (line[:i].to_string(), line[i + 1:].to_string())
None => (line, "")
}
match kind {
"backend" => installed = true
"problem" => problem = text
"howdy" => howdy = text.replace_all(old=",", new=", ")
"pam" =>
for s in text.split(",") {
if s != "" {
pam.push(s.to_string())
}
}
"face" => {
let f = text.split("\t").map(s => s.to_string()).to_array()
if f.length() == 3 {
faces.push((f[0], f[1], f[2]))
}
}
_ => ()
}
}
self.installed = installed
self.problem = if installed { problem } else { "" }
self.howdy = howdy
self.pam = pam
self.faces = faces
self.loaded = true
self.dirty = true
}
///| A face-unlock request: a face index removes it; -1 refresh, -2 enroll, -3 / -4 stop / start
/// using it for the password dialog and sudo.
pub fn FaceUnlock::request(self : FaceUnlock, code : Int) -> Unit {
if code == -1 {
self.refresh()
return
}
if self.busy() {
return // one change at a time
}
match code {
-2 => {
self.message = "Waiting for the password…"
self.run(["enroll"], true)
}
-3 => {
self.message = "Waiting for the password…"
self.run(["pam", "disable"], true)
}
-4 => {
self.message = "Waiting for the password…"
self.run(["pam", "enable"], true)
}
i if i >= 0 && i < self.faces.length() => {
self.message = "Waiting for the password…"
self.run(["remove", self.faces[i].0], true)
}
_ => return
}
self.dirty = true
}
///| Stop reading the run in progress (the shell is closing).
pub fn FaceUnlock::close(self : FaceUnlock) -> Unit {
if self.fd >= 0 {
@sys.close_fd(self.fd)
self.fd = -1
}
self.queue.clear()
}
///| Publish the face unlock tables (24: status, 25: faces) while a module imports `face-unlock`.
/// Nothing runs until the module asks (`refresh`, when Settings opens on the Session tab).
fn DesktopShell::publish_face_unlock(self : DesktopShell) -> Unit {
if !self.any_cap("face-unlock") {
return
}
let f = self.face
f.poll()
if !f.dirty {
return
}
f.dirty = false
let st = @wasm.Table::new()
st.str(f.problem)
st.str(f.howdy)
st.str(f.message)
st.int(if f.installed { 1 } else { 0 })
st.int(if f.in_use() { 1 } else { 0 })
st.int(if f.busy() { 1 } else { 0 })
st.end_row()
@wasm.publish(FaceStatus, st)
let ft = @wasm.Table::new()
for face in f.faces {
ft.str(face.1)
ft.str(face.2)
ft.end_row()
}
@wasm.publish(Faces, ft)
}
///| Whether a chandra-face run is in progress: the main loop keeps its frame pace meanwhile, so
/// what it says shows up (it runs seconds, while the camera looks).
pub fn DesktopShell::face_busy(self : DesktopShell) -> Bool {
self.face.fd >= 0
}
+3
View File
@@ -297,6 +297,8 @@ pub(all) struct DesktopShell {
mut handler_apps : Map[String, HandlerApp]?
mut default_apps : Array[CategoryChoices]
mut default_apps_dirty : Bool
/// Face unlock (face.mbt): what `chandra-face` said, for Settings > Session.
face : FaceUnlock
/// The terminal chosen in the Apps tab (desktop id; "" for none), saved as state.edn :terminal.
mut terminal : String
/// Desktop ids of Terminal=true apps, started inside the terminal.
@@ -452,6 +454,7 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
handler_apps: None,
default_apps: [],
default_apps_dirty: true,
face: FaceUnlock::new(),
terminal: "",
terminal_apps,
desk_set: false,
+2
View File
@@ -700,6 +700,7 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
if self.any_cap("default-apps") {
self.publish_default_apps()
}
self.publish_face_unlock()
if self.any_cap("screenshot") {
@wasm.publish_screenshot(self.screenshot_state)
}
@@ -841,6 +842,7 @@ fn DesktopShell::process_requests(self : DesktopShell) -> Unit {
Some(SetSuspendAfter(m)) => self.set_power_timeouts(self.screen_off_min, m)
Some(Shortcut(code)) => self.shortcut_request(code)
Some(DefaultApp(code)) => self.default_app_request(code)
Some(FaceUnlock(code)) => self.face.request(code)
Some(PowerAction(a)) => if a >= 0 && a <= 2 { self.actions.push(SystemPower(a)) }
Some(Network(code, ssid, password)) => self.network_request(code, ssid, password)
Some(SetInspector(on)) => self.set_inspecting(on)
+10
View File
@@ -331,6 +331,10 @@ pub(all) enum HostTable {
AppChoices
/// What can fill the desktop (s: name), served by `wallpaper.desktops`.
Desktops
/// Face unlock status (sssiii: problem howdy message installed in-use busy; one row).
FaceStatus
/// Enrolled faces (ss: label added).
Faces
}
///|
@@ -359,6 +363,8 @@ pub fn publish(which : HostTable, t : Table) -> Unit {
AppCategories => 11U
AppChoices => 12U
Desktops => 20U
FaceStatus => 24U
Faces => 25U
}
// Most tables are republished every frame unchanged: skip the copy into the host then.
let slot = id.reinterpret_as_int()
@@ -446,6 +452,9 @@ pub(all) enum HostRequest {
ReloadSession
/// The wallpaper capability's `set-desktop`: an index into the Desktops table.
SetDesktop(Int)
/// The face-unlock capability: a face index removes it; -1 refresh, -2 enroll, -3 / -4 stop /
/// start using it for the password dialog and sudo.
FaceUnlock(Int)
} derive(Eq, Debug)
///|
@@ -472,6 +481,7 @@ pub fn next_request() -> HostRequest? {
Some(DefaultApp(code)) => Some(DefaultApp(code))
Some(ReloadSession) => Some(ReloadSession)
Some(SetDesktop(i)) => Some(SetDesktop(i))
Some(FaceUnlock(i)) => Some(FaceUnlock(i))
}
}
+10
View File
@@ -739,6 +739,10 @@ pub(all) enum HostTable {
AppChoices
/// What can fill the desktop (s: name), served by `wallpaper.desktops`.
Desktops
/// Face unlock status (sssiii: problem howdy message installed in-use busy; one row).
FaceStatus
/// Enrolled faces (ss: label added).
Faces
}
///| Publish `t` as the data behind `which` for every module's next call.
@@ -758,6 +762,8 @@ pub fn publish(which : HostTable, t : Table) -> Unit {
AppCategories => 11
AppChoices => 12
Desktops => 20
FaceStatus => 24
Faces => 25
}
let out : Array[Byte] = []
for k = 0; k < 4; k = k + 1 {
@@ -844,6 +850,9 @@ pub(all) enum HostRequest {
ReloadSession
/// The wallpaper capability's `set-desktop`: an index into the Desktops table.
SetDesktop(Int)
/// The face-unlock capability: a face index removes it; -1 refresh, -2 enroll, -3 / -4 stop /
/// start using it for the password dialog and sudo.
FaceUnlock(Int)
} derive(Eq, Debug)
///|
@@ -886,6 +895,7 @@ pub fn next_request() -> HostRequest? {
18 => Some(Shortcut(c_host_req_int()))
19 => Some(DefaultApp(c_host_req_int()))
40 => Some(SetDesktop(c_host_req_int()))
44 => Some(FaceUnlock(c_host_req_int()))
_ => None
}
}
+18 -2
View File
@@ -66,7 +66,8 @@ enum {
K_NET_SET_AIRPLANE,
K_SC_LIST, K_SC_CAPTURE, K_SC_CANCEL, K_SC_RESET, K_SC_RESET_ALL,
K_DA_CATS, K_DA_APPS, K_DA_SET, K_DA_REFRESH,
K_DESKTOPS, K_DESKTOP_CUR, K_SET_DESKTOP
K_DESKTOPS, K_DESKTOP_CUR, K_SET_DESKTOP,
K_FU_STATUS, K_FU_FACES, K_FU_ENROLL, K_FU_REMOVE, K_FU_SET_IN_USE, K_FU_REFRESH
};
typedef struct Env { Inst *inst; int kind; } Env;
@@ -75,7 +76,7 @@ typedef struct Env { Inst *inst; int kind; } Env;
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_ICONS,
T_NET_STATUS, T_NET_NETWORKS, T_SHORTCUTS, T_APP_CATS, T_APP_CHOICES,
/* fixed numbers from here (wit/host/plasmoids.wit publish-table) */
T_DESKTOPS = 20, T_N = 32 };
T_DESKTOPS = 20, T_FACE_STATUS = 24, T_FACES = 25, T_N = 32 };
typedef struct { uint8_t *data; size_t len; } Blob;
static Blob tables[T_N];
static int32_t host_ints[24] = {[7] = -1}; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
@@ -387,6 +388,15 @@ static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[20]);
break;
case K_SET_DESKTOP: push_req(40, a0, NULL); break;
/* Face unlock: status from table 24 (problem howdy message installed in-use busy), faces from
* table 25 (label added); request 44 is a face index to remove, or -1 refresh, -2 enroll,
* -3 / -4 stop / start using it. */
case K_FU_STATUS: build_record(in, T_FACE_STATUS, "sssbbb", a0); break;
case K_FU_FACES: build_list(in, T_FACES, "ss", a0); break;
case K_FU_ENROLL: push_req(44, -2, NULL); break;
case K_FU_REMOVE: if (a0 >= 0 && a0 < 1000) push_req(44, a0, NULL); break;
case K_FU_SET_IN_USE: push_req(44, a0 ? -4 : -3, NULL); break;
case K_FU_REFRESH: push_req(44, -1, NULL); break;
case K_SESSION_SET: push_req(a1 ? 11 : 10, a0, NULL); break; /* 10 off, 11 on */
/* Request 12 carries the screenshot code: 0-3 take, 10-12 record, 20 stop, 30/31 pointer. */
case K_SHOT_TAKE: if (a0 >= 0 && a0 <= 3) push_req(12, a0, NULL); break;
@@ -604,6 +614,12 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "desktops")) return K_DESKTOPS;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "current-desktop")) return K_DESKTOP_CUR;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "set-desktop")) return K_SET_DESKTOP;
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "status")) return K_FU_STATUS;
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "faces")) return K_FU_FACES;
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "enroll")) return K_FU_ENROLL;
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "remove")) return K_FU_REMOVE;
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "set-in-use")) return K_FU_SET_IN_USE;
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "refresh")) return K_FU_REFRESH;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "settings")) return K_SESSION_SETTINGS;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "is-on")) return K_SESSION_IS_ON;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "set-setting")) return K_SESSION_SET;
+1
View File
@@ -243,6 +243,7 @@ test "the settings module's Panel tab lists host modules and asks to load, move,
ignore(p.on_event(true, PointerDown(20, 190))) // add the moon
ignore(p.on_event(true, PointerDown(160, 285))) // browse
assert_eq(drain(), [
FaceUnlock(-1), // opening on the Session tab reads the face unlock status
MoveInstance("w1", 1),
UnloadInstance("w2"),
LoadModule("/m/moon-disc.wasm"),