Files
chandra/face/test_face.py
T
Claude 2c2ce3f913
CI / test (push) Canceled after 3m23s
Face unlock window steps aside while Apply asks for the password
After Apply the window kept the keyboard and the pointer and its dimmed card
covered the screen, so a password dialog that isn't Chandra's own (another
polkit agent's window) couldn't be reached. While Apply waits, the window now
shows only a note at the top and takes no input. A refused or cancelled
password brings it back with the snaps and marks kept (chandra-face camera
restarts the camera instead of exiting) and says so.

Test: snaps, Enter, the password dialog gets typing (Space no longer snaps
underneath) and the Authenticate click, then the root step finishes.

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

478 lines
19 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])
class Session:
"""`chandra-face camera` as the "Add a face" window runs it: commands in, lines and pictures out."""
def __init__(self, env):
self.p = subprocess.Popen(
[sys.executable, "-I", TOOL, "camera", "--config", env.conf, "--machine", "--no-elevate",
"--user", ME], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
def send(self, line):
self.p.stdin.write(line.encode() + b"\n")
self.p.stdin.flush()
def next(self, kind):
"""Messages until one of `kind`: (header words, picture bytes or None)."""
while True:
line = self.p.stdout.readline()
if not line:
raise AssertionError("ended before %s" % kind)
words = line.decode().rstrip("\n").split(" ")
data = None
if words[0] in ("frame", "snap"):
data = self.p.stdout.read(int(words[-1]))
if words[0] == kind:
return words, data
def finish(self):
self.p.stdin.close()
rc = self.p.wait(10)
self.p.stdout.close()
return rc
class CameraWindowTests(unittest.TestCase):
def setUp(self):
self.env = Env()
def tearDown(self):
self.env.close()
def vectors(self):
f = os.path.join(self.env.store, ME, "faces.json")
return json.loads(slurp(f))["faces"] if os.path.exists(f) else []
def test_live_picture_snaps_and_one_apply(self):
self.env.camera(["alice"], frame_delay="0.01")
s = Session(self.env)
words, px = s.next("frame")
w, h = int(words[1]), int(words[2])
self.assertEqual((w, h), (32, 32))
self.assertEqual(len(px), w * h * 3)
self.assertEqual(words[3:7], ["0", "0", "32", "32"]) # the face box
s.send("snap")
words, px = s.next("snap")
self.assertEqual(words[1:4], ["1", "96", "96"])
self.assertEqual(len(px), 96 * 96 * 3)
s.send("snap")
s.next("snap")
s.send("drop 1")
self.assertEqual(self.vectors(), [], "nothing is saved before Apply")
s.send("apply ")
words, _ = s.next("applied")
self.assertEqual(words[1], "0")
self.assertEqual(s.finish(), 0)
faces = self.vectors()
self.assertEqual(len(faces), 1)
self.assertEqual(len(faces[0]["vectors"]), 1, "the dropped snap is not saved")
# The saved face is recognized.
self.env.camera(["alice", "alice"])
rc, out = self.env.run("compare")
self.assertEqual(rc, 0, out)
def test_a_snap_without_a_face_says_why(self):
self.env.camera(["flat"], frame_delay="0.01")
s = Session(self.env)
words, _ = s.next("frame")
self.assertEqual(words[3:7], ["-1"] * 4)
s.send("snap")
words, _ = s.next("error")
self.assertEqual(" ".join(words[1:]), "No face in view")
s.send("quit")
self.assertEqual(s.finish(), 0)
self.assertEqual(self.vectors(), [])
def test_apply_adds_and_removes_in_one_go(self):
self.env.camera(["alice", "alice", "alice"])
self.env.run("enroll", "--label", "Old")
self.env.camera(["bob"], frame_delay="0.01")
s = Session(self.env)
s.send("snap")
s.next("snap")
s.send("apply 1")
words, _ = s.next("done")
self.assertEqual(" ".join(words[1:]), "Added Face 2 and removed 1 face")
self.assertEqual(s.next("applied")[0][1], "0")
s.finish()
self.assertEqual([f["label"] for f in self.vectors()], ["Face 2"])
def test_a_failed_apply_keeps_the_snaps(self):
self.env.camera(["alice"], frame_delay="0.01")
s = Session(self.env)
s.send("snap")
s.next("snap")
s.send("apply 99")
words, _ = s.next("error")
self.assertEqual(" ".join(words[1:]), "no face 99 for %s" % ME)
self.assertEqual(s.next("applied")[0][1], "1")
s.next("frame") # the camera goes on
s.send("snap")
s.next("snap")
s.send("apply ")
self.assertEqual(s.next("applied")[0][1], "0")
self.assertEqual(s.finish(), 0)
self.assertEqual(len(self.vectors()[0]["vectors"]), 2)
def test_apply_refuses_bad_data(self):
for bad in (b"[]", b"{\"add\": [{\"vectors\": [[1, 2]]}]}",
b"{\"add\": [{\"vectors\": [[1e999, 0, 0, 0]]}]}", b"{\"remove\": [7]}", b"nonsense"):
buf = io.StringIO()
with redirect_stdout(buf):
cfg = cf.Config(self.env.conf)
with self.assertRaises(cf.Fail, msg=bad):
cf.cmd_apply(cfg, ME, cf.Out(True), bad)
self.assertEqual(self.vectors(), [])
@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)