Files
chandra/face/test_face.py
T
nandi 40c5d6722c
CI / test (push) Failing after 51s
Face unlock: screen fill-light for low light; fix Quad-Bayer AE ramp
- Boost the backlight to 90% while enrolling with the light on or while sign-in is scanning, then restore the previous level when that ends or the window closes.
- Add a Light: On/Off toggle (L key) to the Face window; the backdrop turns soft white while the light is on.
- Quad-Bayer AE: compute the low-light gain once and cap it by the highlight limit, so ramp-up and highlight back-off agree.
- Tests: backlight round-trip through the Face window, Quad-Bayer debayer color/low-light/dark-frame cases, and the AE ramp, back-off and restore order.
2026-11-28 18:32:15 -08:00

639 lines
26 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")
out = self.env.run("status")[1]
self.assertTrue(any(l.startswith("problem no camera at /dev/no-such-camera (not there") for l in out), out)
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_a_missing_camera_says_why_and_lists_the_cameras(self):
self.env.camera([], device="/dev/v4l/by-id/usb-No-Such-Camera-video-index0", backend="fake")
s = Session(self.env)
words, _ = s.next("error")
text = " ".join(words[1:])
self.assertTrue(text.startswith("no camera at /dev/v4l/by-id/usb-No-Such-Camera-video-index0 (not there"), text)
self.assertIn("chandra-face set-camera PATH", text)
self.assertEqual(s.finish(), 2)
rc, out = self.env.run("status")
self.assertTrue(any(l.startswith("problem no camera at /dev/v4l/by-id/usb-No-Such") for l in out), out)
def test_set_camera_refuses_what_is_not_a_camera(self):
for bad in ("/dev/null", "/dev/v4l/by-id/nothing", "/etc/passwd"):
rc, out = self.env.run("set-camera", bad)
self.assertNotEqual(rc, 0, bad)
self.assertTrue(out[-1].startswith("error"), out)
self.assertNotIn("/dev/null", slurp(self.env.conf))
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()
try:
import cv2 as _cv2 # noqa
import numpy as _np # noqa
HAS_CV2_NUMPY = True
except ImportError:
HAS_CV2_NUMPY = False
def _make_quad_raw(w, h, p8_func):
"""Build an unpacked->CSI2P Quad-Bayer raw buffer from per-block pixel helper `p8_func(x, y, phase)`."""
stride = (w // 4) * 5
arr = _np.zeros((h, stride), dtype=_np.uint8)
for y in range(h):
for xb in range(w // 4):
c0, c1 = p8_func(xb, y)
base = xb * 5
arr[y, base + 0] = c0
arr[y, base + 1] = c0
arr[y, base + 2] = c1
arr[y, base + 3] = c1
return arr.tobytes(), stride
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
class QuadDebayerTests(unittest.TestCase):
def test_quad_debayer_color_lowlight_and_covered_dark(self):
# 1. Normal color response: red top half, blue bottom half
def rb(xb, y):
if (y % 4) < 2:
return (200, 24) if y < 4 else (24, 24)
return (24, 24) if y < 4 else (24, 200)
raw, stride = _make_quad_raw(8, 8, rb)
out = cf.debayer_quad_csi2p(raw, 8, 8, stride, rot=0, target_size=None, cv2_mod=_cv2, np_mod=_np)
self.assertEqual(out.shape, (4, 4, 3))
self.assertGreater(float(out[0, :, 2].mean()), float(out[0, :, 0].mean()) + 30.0)
self.assertGreater(float(out[3, :, 0].mean()), float(out[3, :, 2].mean()) + 30.0)
# 2. Low-light scene: optical black=15 (sum=60), signal +2..+3 per p8 (8..12 above black in 2x2 sum)
w, h = 80, 80
raw_dim, stride_dim = _make_quad_raw(w, h, lambda xb, y: (17 if xb < w // 8 else 18, 17 if y < h // 2 else 18))
out_dim, stats_dim = cf.debayer_quad_csi2p(
raw_dim, w, h, stride_dim, rot=0, target_size=(80, 80), return_stats=True, cv2_mod=_cv2, np_mod=_np
)
self.assertEqual(len(stats_dim), 2)
self.assertGreater(float(out_dim.mean()), 65.0)
# 3. Covered lens dark frame: constant black=15 (zero signal above black 60) -> must stay dark
raw_dark, stride_dark = _make_quad_raw(w, h, lambda xb, y: (15, 15))
out_dark, stats_dark = cf.debayer_quad_csi2p(
raw_dark, w, h, stride_dark, rot=0, target_size=(80, 80), return_stats=True, cv2_mod=_cv2, np_mod=_np
)
self.assertLess(float(out_dark.mean()), 12.0)
self.assertLess(stats_dark[1], 0.8)
class _MockSubdevIO:
def __init__(self):
self.meta = {
cf.V4L2_CID_VBLANK: (56, 62029, 1, 56),
cf.V4L2_CID_EXPOSURE: (4, 3542, 1, 1000),
cf.V4L2_CID_ANALOGUE_GAIN: (0, 480, 1, 0),
cf.V4L2_CID_DIGITAL_GAIN: (0, 4096, 1, 1024),
}
self.vals = {
cf.V4L2_CID_VBLANK: 56,
cf.V4L2_CID_EXPOSURE: 1000,
cf.V4L2_CID_ANALOGUE_GAIN: 0,
cf.V4L2_CID_DIGITAL_GAIN: 1024,
}
self.log = []
self.closed = False
def query(self, cid):
if cid == cf.V4L2_CID_EXPOSURE:
extra = max(0, self.vals[cf.V4L2_CID_VBLANK] - 56)
return (4, 3542 + extra, 1, 1000)
return self.meta[cid]
def get(self, cid):
return self.vals[cid]
def set(self, cid, val):
if cid == cf.V4L2_CID_EXPOSURE:
max_exp = 3542 + max(0, self.vals[cf.V4L2_CID_VBLANK] - 56)
if val > max_exp:
raise AssertionError("EXPOSURE %d set before VBLANK raised (max %d)" % (val, max_exp))
elif cid == cf.V4L2_CID_VBLANK:
max_exp_after = 3542 + max(0, val - 56)
if self.vals[cf.V4L2_CID_EXPOSURE] > max_exp_after:
raise AssertionError("VBLANK %d lowered while EXPOSURE still %d" % (val, self.vals[cf.V4L2_CID_EXPOSURE]))
self.vals[cid] = val
self.log.append((cid, val))
return val
def close(self):
self.closed = True
class QuadSensorAETests(unittest.TestCase):
def test_lowlight_ramp_cooldown_and_restore(self):
io = _MockSubdevIO()
ae = cf.QuadSensorAE("/dev/null", io=io)
ae.apply_initial()
self.assertEqual(ae.cooldown, 2)
# Cooldown skips 2 frames
self.assertFalse(ae.update(4.0, 8.0))
self.assertEqual(ae.cooldown, 1)
self.assertFalse(ae.update(4.0, 8.0))
self.assertEqual(ae.cooldown, 0)
# Ramp in pitch dimness through vblank/exposure, analogue gain, then digital gain
for _ in range(10):
ae.cooldown = 0
ae.update(3.0, 6.0)
self.assertGreater(io.vals[cf.V4L2_CID_VBLANK], 56)
self.assertGreater(io.vals[cf.V4L2_CID_EXPOSURE], 3542)
self.assertEqual(io.vals[cf.V4L2_CID_ANALOGUE_GAIN], 480)
self.assertGreater(io.vals[cf.V4L2_CID_DIGITAL_GAIN], 1024)
# Bright highlight overload backs off exposure safely before reducing vblank
io.log.clear()
for _ in range(12):
ae.cooldown = 0
ae.update(210.0, 250.0)
self.assertEqual(io.vals[cf.V4L2_CID_VBLANK], 56)
self.assertLess(io.vals[cf.V4L2_CID_EXPOSURE], 3542)
self.assertEqual(io.vals[cf.V4L2_CID_DIGITAL_GAIN], 1024)
# Raise again then close() to test clean restore order
ae.cooldown = 0
for _ in range(8):
ae.cooldown = 0
ae.update(3.0, 6.0)
ae.close()
self.assertTrue(io.closed)
self.assertEqual(io.vals[cf.V4L2_CID_VBLANK], 56)
self.assertEqual(io.vals[cf.V4L2_CID_EXPOSURE], 1000)
self.assertEqual(io.vals[cf.V4L2_CID_ANALOGUE_GAIN], 0)
self.assertEqual(io.vals[cf.V4L2_CID_DIGITAL_GAIN], 1024)
@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)