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

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

323 lines
9.0 KiB
MoonBit

///| 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
}