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
353 lines
15 KiB
Python
353 lines
15 KiB
Python
#!/usr/bin/env python3
|
|
"""Tests for face unlock (docs/face-unlock.md), headless: a fake camera of PGM images and the fake
|
|
recognizer, so no camera, OpenCV or models are needed.
|
|
|
|
python3 face/test_face.py # chandra-face itself
|
|
python3 face/test_face.py --pam # also build pam_chandra_face.so and run it through
|
|
# pamtester (root, libpam headers and pamtester needed)
|
|
|
|
With CHANDRA_FACE_MODELS=DIR (holding the two ONNX models) and OpenCV installed, the OpenCV
|
|
backend is checked too, on synthetic pictures it must not take for a face.
|
|
"""
|
|
import importlib.machinery
|
|
import importlib.util
|
|
import io
|
|
import json
|
|
import os
|
|
import shutil
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from contextlib import redirect_stdout
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
TOOL = os.path.join(HERE, "chandra-face")
|
|
loader = importlib.machinery.SourceFileLoader("chandra_face", TOOL)
|
|
spec = importlib.util.spec_from_loader("chandra_face", loader)
|
|
cf = importlib.util.module_from_spec(spec)
|
|
loader.exec_module(cf)
|
|
ME = __import__("pwd").getpwuid(os.getuid()).pw_name
|
|
|
|
|
|
def slurp(path):
|
|
with open(path) as fh:
|
|
return fh.read()
|
|
|
|
|
|
def pgm(path, rows):
|
|
h, w = len(rows), len(rows[0])
|
|
with open(path, "wb") as fh:
|
|
fh.write(b"P5\n%d %d\n255\n" % (w, h))
|
|
fh.write(bytes(v for r in rows for v in r))
|
|
|
|
|
|
def pattern(kind, w=32, h=32):
|
|
"""A "face" the fake recognizer tells apart: a bright-left or bright-top split, a flat frame
|
|
(no face), or a dark frame (IR emitter not lit yet)."""
|
|
if kind == "alice":
|
|
return [[220 if x < w // 2 else 40 for x in range(w)] for y in range(h)]
|
|
if kind == "alice2": # the same face, a bit darker and noisier
|
|
return [[(200 if x < w // 2 else 50) + (x * y) % 7 for x in range(w)] for y in range(h)]
|
|
if kind == "bob":
|
|
return [[220 if y < h // 2 else 40 for x in range(w)] for y in range(h)]
|
|
if kind == "flat":
|
|
return [[128] * w for _ in range(h)]
|
|
if kind == "dark":
|
|
return [[3 if x % 2 else 8 for x in range(w)] for y in range(h)]
|
|
raise ValueError(kind)
|
|
|
|
|
|
class Env:
|
|
"""A temporary store, PAM dir, config and camera."""
|
|
|
|
def __init__(self):
|
|
self.dir = tempfile.mkdtemp(prefix="chandra-face-test-")
|
|
os.chmod(self.dir, 0o755)
|
|
self.store = os.path.join(self.dir, "store")
|
|
self.pam = os.path.join(self.dir, "pam.d")
|
|
os.makedirs(self.pam)
|
|
self.conf = os.path.join(self.dir, "face.conf")
|
|
self.camera(["alice"])
|
|
|
|
def camera(self, kinds, **extra):
|
|
cam = os.path.join(self.dir, "cam")
|
|
if os.path.isdir(cam):
|
|
shutil.rmtree(cam)
|
|
os.makedirs(cam)
|
|
for i, k in enumerate(kinds):
|
|
pgm(os.path.join(cam, "%03d.pgm" % i), pattern(k))
|
|
opts = {"backend": "fake", "device": "images:" + cam, "store": self.store,
|
|
"pam_dir": self.pam, "timeout": "5", "enroll_frames": "3", "matches": "2",
|
|
"threshold": "0.9"}
|
|
opts.update(extra)
|
|
with open(self.conf, "w") as fh:
|
|
fh.write("[face]\n" + "".join("%s = %s\n" % kv for kv in opts.items()))
|
|
os.chmod(self.conf, 0o644)
|
|
|
|
def run(self, *args):
|
|
buf = io.StringIO()
|
|
with redirect_stdout(buf):
|
|
rc = cf.main(["--config", self.conf, "--machine", "--no-elevate", "--user", ME] + list(args))
|
|
return rc, buf.getvalue().splitlines()
|
|
|
|
def close(self):
|
|
shutil.rmtree(self.dir)
|
|
|
|
|
|
class FaceTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.env = Env()
|
|
|
|
def tearDown(self):
|
|
self.env.close()
|
|
|
|
def enroll(self, *kinds, label="Desk"):
|
|
self.env.camera(list(kinds))
|
|
rc, out = self.env.run("enroll", "--label", label)
|
|
self.assertEqual(rc, 0, out)
|
|
return out
|
|
|
|
def test_nothing_enrolled_is_quiet_and_unavailable(self):
|
|
rc, out = self.env.run("compare")
|
|
self.assertEqual(rc, 2)
|
|
self.assertEqual(out, [])
|
|
|
|
def test_enroll_writes_private_vectors_and_a_public_label_list(self):
|
|
out = self.enroll("dark", "alice", "flat", "alice", "alice")
|
|
self.assertEqual(out[0], "info Look at the camera…")
|
|
self.assertIn("progress 3/3", out)
|
|
self.assertEqual(out[-1], "done Added Desk")
|
|
d = os.path.join(self.env.store, ME)
|
|
faces = os.path.join(d, "faces.json")
|
|
self.assertEqual(stat.S_IMODE(os.stat(faces).st_mode), 0o600)
|
|
self.assertEqual(stat.S_IMODE(os.stat(os.path.join(d, "faces.list")).st_mode), 0o644)
|
|
data = json.loads(slurp(faces))
|
|
self.assertEqual(len(data["faces"][0]["vectors"]), 3)
|
|
listed = slurp(os.path.join(d, "faces.list"))
|
|
self.assertRegex(listed, r"^1\tDesk\t\d{4}-\d\d-\d\d\n$")
|
|
self.assertNotIn("vectors", listed)
|
|
|
|
def test_enroll_without_a_face_fails_and_stores_nothing(self):
|
|
self.env.camera(["flat", "dark", "flat"])
|
|
rc, out = self.env.run("enroll")
|
|
self.assertEqual(rc, 1)
|
|
self.assertTrue(out[-1].startswith("error couldn't see a face"), out)
|
|
self.assertFalse(os.path.exists(os.path.join(self.env.store, ME, "faces.json")))
|
|
|
|
def test_the_same_face_is_recognized(self):
|
|
self.enroll("alice", "alice", "alice")
|
|
self.env.camera(["dark", "alice2", "alice2"])
|
|
rc, out = self.env.run("compare")
|
|
self.assertEqual(rc, 0, out)
|
|
self.assertEqual(out, ["info Face unlock: looking for %s…" % ME, "info Face unlock: recognized %s" % ME])
|
|
|
|
def test_one_matching_frame_is_not_enough(self):
|
|
self.enroll("alice", "alice", "alice")
|
|
self.env.camera(["alice", "bob", "bob"], enroll_frames="3")
|
|
rc, out = self.env.run("compare")
|
|
self.assertEqual(rc, 1)
|
|
|
|
def test_someone_else_is_not_recognized(self):
|
|
self.enroll("alice", "alice", "alice")
|
|
self.env.camera(["bob", "bob", "bob"])
|
|
rc, out = self.env.run("compare")
|
|
self.assertEqual(rc, 1)
|
|
self.assertEqual(out[-1], "error Face unlock: face not recognized")
|
|
|
|
def test_reasons_for_failing(self):
|
|
self.enroll("alice", "alice", "alice")
|
|
self.env.camera(["dark", "dark"])
|
|
self.assertEqual(self.env.run("compare")[1][-1], "error Face unlock: the camera picture is too dark")
|
|
self.env.camera(["flat", "dark"])
|
|
self.assertEqual(self.env.run("compare")[1][-1], "error Face unlock: no face in view")
|
|
self.env.camera([])
|
|
self.assertEqual(self.env.run("compare")[1][-1], "error Face unlock: the camera gave no picture")
|
|
|
|
def test_turned_off_in_the_config(self):
|
|
self.enroll("alice", "alice", "alice")
|
|
self.env.camera(["alice"] * 3, enabled="no")
|
|
self.assertEqual(self.env.run("compare"), (2, []))
|
|
|
|
def test_a_store_others_can_write_is_refused(self):
|
|
self.enroll("alice", "alice", "alice")
|
|
self.env.camera(["alice"] * 3)
|
|
d = os.path.join(self.env.store, ME)
|
|
os.chmod(d, 0o777)
|
|
rc, out = self.env.run("compare")
|
|
self.assertEqual(rc, 2)
|
|
self.assertIn("can be written by others", out[-1])
|
|
os.chmod(d, 0o755)
|
|
os.chmod(os.path.join(d, "faces.json"), 0o666)
|
|
self.assertEqual(self.env.run("compare")[0], 2)
|
|
|
|
def test_bad_user_names_are_refused(self):
|
|
with redirect_stdout(io.StringIO()):
|
|
rc = cf.main(["--config", self.env.conf, "--machine", "--no-elevate", "--user", "../etc", "compare"])
|
|
self.assertEqual(rc, 2)
|
|
|
|
def test_list_remove_clear(self):
|
|
self.enroll("alice", "alice", "alice", label="Desk")
|
|
self.enroll("alice", "alice", "alice", label="Glasses")
|
|
rc, out = self.env.run("status")
|
|
faces = [l for l in out if l.startswith("face ")]
|
|
self.assertEqual(len(faces), 2)
|
|
self.assertTrue(faces[1].startswith("face 2\tGlasses\t"))
|
|
self.assertIn("backend fake", out)
|
|
self.assertEqual(self.env.run("remove", "1")[0], 0)
|
|
self.assertEqual([l.split("\t")[1] for l in self.env.run("list")[1]], ["Glasses"])
|
|
self.assertEqual(self.env.run("remove", "7")[0], 1)
|
|
self.assertEqual(self.env.run("clear")[0], 0)
|
|
self.assertEqual(self.env.run("list")[1], [])
|
|
self.assertFalse(os.path.exists(os.path.join(self.env.store, ME)))
|
|
|
|
def test_pam_enable_disable(self):
|
|
p = os.path.join(self.env.pam, "sudo")
|
|
original = "#%PAM-1.0\n# comment\nauth include system-auth\naccount include system-auth\n"
|
|
with open(p, "w") as fh:
|
|
fh.write(original)
|
|
with open(os.path.join(self.env.pam, "login"), "w") as fh:
|
|
fh.write("auth sufficient pam_howdy.so\nauth include system-auth\n")
|
|
self.assertEqual(self.env.run("pam", "enable", "sudo")[0], 0)
|
|
lines = slurp(p).split("\n")
|
|
self.assertEqual(lines[2], cf.PAM_LINE)
|
|
self.assertEqual(lines[3], "auth include system-auth")
|
|
self.assertTrue(os.path.exists(p + ".chandra-face.bak"))
|
|
# Twice is once.
|
|
self.env.run("pam", "enable", "sudo")
|
|
self.assertEqual(slurp(p).count("pam_chandra_face.so"), 1)
|
|
rc, out = self.env.run("status")
|
|
self.assertIn("pam sudo", out)
|
|
self.assertIn("howdy login", out)
|
|
self.env.run("pam", "disable", "sudo")
|
|
self.assertEqual(slurp(p), original)
|
|
# Debian: no auth line, only @include common-auth (after a session line).
|
|
deb = os.path.join(self.env.pam, "sudo-deb")
|
|
with open(deb, "w") as fh:
|
|
fh.write("#%PAM-1.0\nsession required pam_limits.so\n@include common-auth\n@include common-account\n")
|
|
self.env.run("pam", "enable", "sudo-deb")
|
|
self.assertEqual(slurp(deb).split("\n")[2:4], [cf.PAM_LINE, "@include common-auth"])
|
|
self.assertEqual(self.env.run("pam", "enable", "no-such-service")[0], 1)
|
|
self.assertEqual(self.env.run("pam", "enable", "../passwd")[0], 1)
|
|
|
|
def test_status_names_what_is_missing(self):
|
|
self.env.camera([], backend="opencv", models=os.path.join(self.env.dir, "nomodels"))
|
|
rc, out = self.env.run("status")
|
|
self.assertEqual(rc, 0)
|
|
self.assertTrue(any(l.startswith("problem ") for l in out), out)
|
|
self.env.camera([], device="/dev/no-such-camera")
|
|
self.assertIn("problem no camera at /dev/no-such-camera", self.env.run("status")[1])
|
|
|
|
|
|
@unittest.skipUnless(os.environ.get("CHANDRA_FACE_MODELS"), "CHANDRA_FACE_MODELS not set")
|
|
class OpenCVTests(unittest.TestCase):
|
|
def test_no_face_in_noise_or_flat_frames(self):
|
|
env = Env()
|
|
try:
|
|
env.camera(["flat", "bob"], backend="opencv", models=os.environ["CHANDRA_FACE_MODELS"])
|
|
# Nothing enrolled: unavailable without touching the camera.
|
|
self.assertEqual(env.run("compare")[0], 2)
|
|
rc, out = env.run("enroll")
|
|
self.assertEqual(rc, 1)
|
|
finally:
|
|
env.close()
|
|
|
|
|
|
@unittest.skipUnless("--pam" in sys.argv, "pass --pam to test the PAM module")
|
|
class PamTests(unittest.TestCase):
|
|
"""pam_chandra_face.so through pamtester, with a throwaway service in /etc/pam.d."""
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
if os.geteuid() != 0 or not shutil.which("pamtester"):
|
|
raise unittest.SkipTest("needs root and pamtester")
|
|
cls.build = tempfile.mkdtemp(prefix="pam-face-")
|
|
os.chmod(cls.build, 0o755)
|
|
cls.so = os.path.join(cls.build, "pam_chandra_face.so")
|
|
subprocess.check_call(["cc", "-Wall", "-Werror", "-O2", "-shared", "-fPIC", "-o", cls.so,
|
|
os.path.join(HERE, "pam_chandra_face.c"), "-lpam"])
|
|
cls.helper = os.path.join(cls.build, "chandra-face")
|
|
shutil.copyfile(TOOL, cls.helper)
|
|
os.chmod(cls.helper, 0o755)
|
|
cls.service = "chandra-face-test-%d" % os.getpid()
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
p = "/etc/pam.d/" + cls.service
|
|
if os.path.exists(p):
|
|
os.unlink(p)
|
|
shutil.rmtree(cls.build)
|
|
|
|
def setUp(self):
|
|
self.env = Env()
|
|
|
|
def tearDown(self):
|
|
self.env.close()
|
|
|
|
def pam(self, user="root", helper=None, args="", env=None):
|
|
with open("/etc/pam.d/" + self.service, "w") as fh:
|
|
fh.write("-auth sufficient %s helper=%s python=%s config=%s %s\nauth required pam_deny.so\n"
|
|
% (self.so, helper or self.helper, sys.executable, self.env.conf, args))
|
|
p = subprocess.run(["pamtester", self.service, user, "authenticate"], input="", capture_output=True,
|
|
text=True, timeout=60, env=env)
|
|
return p.returncode, p.stdout + p.stderr
|
|
|
|
def enroll_root(self):
|
|
self.env.camera(["alice"] * 3)
|
|
rc = cf.main(["--config", self.env.conf, "--no-elevate", "--user", "root", "enroll"])
|
|
self.assertEqual(rc, 0)
|
|
|
|
def test_match_succeeds_and_says_so(self):
|
|
with redirect_stdout(io.StringIO()):
|
|
self.enroll_root()
|
|
self.env.camera(["alice2"] * 3)
|
|
rc, out = self.pam()
|
|
self.assertEqual(rc, 0, out)
|
|
self.assertIn("Face unlock: looking for root…", out)
|
|
self.assertIn("Face unlock: recognized root", out)
|
|
|
|
def test_no_match_falls_through_to_the_next_module(self):
|
|
with redirect_stdout(io.StringIO()):
|
|
self.enroll_root()
|
|
self.env.camera(["bob"] * 3)
|
|
rc, out = self.pam()
|
|
self.assertNotEqual(rc, 0)
|
|
self.assertIn("Face unlock: face not recognized", out)
|
|
|
|
def test_remote_and_unenrolled_users_are_skipped_quietly(self):
|
|
with redirect_stdout(io.StringIO()):
|
|
self.enroll_root()
|
|
self.env.camera(["alice"] * 3)
|
|
rc, out = self.pam(env=dict(os.environ, SSH_CONNECTION="10.0.0.1 1 10.0.0.2 22"))
|
|
self.assertNotEqual(rc, 0)
|
|
self.assertNotIn("Face unlock", out)
|
|
rc, out = self.pam(user="nobody")
|
|
self.assertNotEqual(rc, 0)
|
|
self.assertNotIn("Face unlock", out)
|
|
|
|
def test_a_helper_that_hangs_is_killed(self):
|
|
hang = os.path.join(self.build, "hang")
|
|
with open(hang, "w") as fh:
|
|
fh.write("import time\nprint('info Face unlock: looking', flush=True)\ntime.sleep(60)\n")
|
|
os.chmod(hang, 0o755)
|
|
rc, out = self.pam(helper=hang, args="timeout=1")
|
|
self.assertNotEqual(rc, 0)
|
|
self.assertIn("Face unlock: took too long", out)
|
|
|
|
def test_a_helper_others_can_write_is_not_run(self):
|
|
bad = os.path.join(self.build, "writable")
|
|
shutil.copyfile(TOOL, bad)
|
|
os.chmod(bad, 0o777)
|
|
with redirect_stdout(io.StringIO()):
|
|
self.enroll_root()
|
|
self.env.camera(["alice"] * 3)
|
|
rc, out = self.pam(helper=bad)
|
|
self.assertNotEqual(rc, 0)
|
|
self.assertNotIn("Face unlock", out)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
argv = [a for a in sys.argv if a != "--pam"]
|
|
unittest.main(argv=argv)
|