diff --git a/.gitignore b/.gitignore index 4acf482..a970613 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,6 @@ data/ certs/*.pem certs/*.crt certs/*.key + +# Test caches +.pytest_cache/ diff --git a/local_backend/requirements-dev.txt b/local_backend/requirements-dev.txt new file mode 100644 index 0000000..044082d --- /dev/null +++ b/local_backend/requirements-dev.txt @@ -0,0 +1,3 @@ +# Test-only dependencies (python -m pytest tests -q) +-r requirements.txt +pytest==8.3.3 diff --git a/local_backend/tests/conftest.py b/local_backend/tests/conftest.py new file mode 100644 index 0000000..093e953 --- /dev/null +++ b/local_backend/tests/conftest.py @@ -0,0 +1,10 @@ +"""Fast unit tests for local_backend — no server, no database, no network. + +Run from local_backend/: + pip install -r requirements-dev.txt + python -m pytest tests -q +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) diff --git a/local_backend/tests/test_lan_ip.py b/local_backend/tests/test_lan_ip.py new file mode 100644 index 0000000..c6d020c --- /dev/null +++ b/local_backend/tests/test_lan_ip.py @@ -0,0 +1,103 @@ +"""Which LAN IP phones get: netinfo detection (fake sysfs) + resolver priority (services/lan_ip.py).""" +import json +import os +from datetime import datetime, timedelta, timezone + +import pytest + +from services.lan_ip import read_detected, resolve_lan_ip, validate_lan_ip +from services.netinfo_helper import detect + +ADDRS = {"eth0": "10.98.20.70", "wlan0": "192.168.1.44", "wg0": "10.9.9.2", "docker0": "172.17.0.1", + "tailscale0": "100.101.1.2", "enp3s0": "169.254.10.1"} + + +def fake_host(tmp_path, physical, default_if): + """sysfs where only `physical` interfaces have a device/ entry, and a route table.""" + sysnet = tmp_path / "net" + for name in ["lo", "docker0", "wg0", "tailscale0"]: + (sysnet / name).mkdir(parents=True) + for name in physical: + (sysnet / name / "device").mkdir(parents=True) + route = tmp_path / "route" + lines = ["Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask"] + if default_if: + lines.append(f"{default_if}\t00000000\t0114620A\t0003\t0\t0\t100\t00000000") + route.write_text("\n".join(lines) + "\n") + return str(sysnet), str(route) + + +# ── netinfo detection: physical NIC only, never a VPN ──────────────────────── + +@pytest.mark.parametrize("physical,default_if,want", [ + (["eth0"], "eth0", "10.98.20.70"), # wg-quick full tunnel: main default via eth0 + (["eth0"], "wg0", "10.98.20.70"), # tunnel owns the default route + (["eth0"], "tailscale0", "10.98.20.70"), + (["eth0"], None, "10.98.20.70"), # offline LAN-only box + (["wlan0"], "wlan0", "192.168.1.44"), # WiFi-only server + (["eth0", "wlan0"], "wlan0", "192.168.1.44"), # two NICs: the default-route one wins + (["enp3s0", "wlan0"], None, "192.168.1.44"), # link-local address ignored + ([], "wg0", None), # no physical NIC → nothing (never the VPN) +]) +def test_detect_physical_nic(tmp_path, physical, default_if, want): + sysnet, route = fake_host(tmp_path, physical, default_if) + assert detect(sysnet, route, ipv4=ADDRS.get)["ip"] == want + + +# ── resolver priority + mismatch ───────────────────────────────────────────── + +FRESH = {"ip": "10.98.20.70", "candidates": [{"iface": "eth0", "ip": "10.98.20.70"}], "stale": False} + + +def test_detected_beats_stale_host_ip(): + r = resolve_lan_ip(override=None, detected=FRESH, env="10.98.20.99") + assert (r["effective"], r["source"]) == ("10.98.20.70", "detected") + + +def test_override_wins_and_flags_mismatch(): + r = resolve_lan_ip(override="192.168.1.50", detected=FRESH, env=None) + assert (r["effective"], r["source"], r["mismatch"]) == ("192.168.1.50", "override", True) + + +def test_override_matching_nic_no_mismatch(): + assert resolve_lan_ip(override="10.98.20.70", detected=FRESH, env=None)["mismatch"] is False + + +def test_docker_desktop_falls_back_to_host_ip(): + r = resolve_lan_ip(override=None, detected={"ip": None, "unsupported": "docker-desktop", "candidates": [], "stale": False}, + env="10.98.20.70") + assert (r["effective"], r["source"], r["detection"]) == ("10.98.20.70", "env", "unsupported") + + +def test_stale_detection_ignored(): + r = resolve_lan_ip(override=None, detected={**FRESH, "stale": True}, env="10.98.20.70") + assert (r["source"], r["detection"]) == ("env", "stale") + + +def test_nothing_known(): + r = resolve_lan_ip(override=None, detected=None, env=None) + assert (r["effective"], r["source"], r["detection"]) == (None, None, "unavailable") + + +def test_read_detected_staleness(tmp_path): + f = tmp_path / "host_ip.json" + now = datetime.now(timezone.utc) + f.write_text(json.dumps({"ip": "10.98.20.70", "candidates": [], "detected_at": (now - timedelta(seconds=30)).isoformat()})) + assert read_detected(str(f), now)["stale"] is False + f.write_text(json.dumps({"ip": "10.98.20.70", "candidates": [], "detected_at": (now - timedelta(minutes=10)).isoformat()})) + assert read_detected(str(f), now)["stale"] is True + assert read_detected(os.path.join(tmp_path, "missing.json"), now) is None + + +# ── override validation ────────────────────────────────────────────────────── + +@pytest.mark.parametrize("ip,ok", [ + ("192.168.1.50", True), (" 10.0.0.5 ", True), ("172.16.4.4", True), + ("8.8.8.8", False), ("127.0.0.1", False), ("169.254.1.1", False), ("fd00::1", False), ("abc", False), +]) +def test_validate_lan_ip(ip, ok): + if ok: + validate_lan_ip(ip) + else: + with pytest.raises(ValueError): + validate_lan_ip(ip) diff --git a/local_backend/tests/test_license.py b/local_backend/tests/test_license.py new file mode 100644 index 0000000..bcfbe52 --- /dev/null +++ b/local_backend/tests/test_license.py @@ -0,0 +1,130 @@ +"""Offline-capable licensing rules (services/license.py, KI-006). + +Tokens are signed with a throwaway key here — the production signing key is +never needed; verify_token() takes the public key as a parameter. +""" +import base64 +import json +from datetime import datetime, timedelta + +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +from services.license import LICENSE_PUBLIC_KEY, evaluate, verify_token + +KEY = Ed25519PrivateKey.generate() +PUB = base64.b64encode(KEY.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)).decode() +ISSUED = datetime.fromisoformat("2026-09-28T12:00:00+00:00") +EXPIRES = datetime.fromisoformat("2027-09-28T00:00:00+00:00") + + +def b64(data: bytes) -> str: + return base64.urlsafe_b64encode(data).rstrip(b"=").decode() + + +def make_token(signer=KEY, **overrides) -> str: + payload = {"v": 1, "site_id": "site-A", "active": True, "locked": False, "lock_reason": None, + "expires_at": EXPIRES.isoformat(), "issued_at": ISSUED.isoformat(), **overrides} + body = b64(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode()) + return f"{body}.{b64(signer.sign(body.encode()))}" + + +@pytest.fixture +def payload(): + return verify_token(make_token(), "site-A", PUB) + + +# ── verify_token ───────────────────────────────────────────────────────────── + +def test_genuine_token_accepted(payload): + assert payload is not None and payload["expires_at"] == EXPIRES.isoformat() + + +def test_edited_expiry_rejected(payload): + _, sig = make_token().split(".") + forged = b64(json.dumps({**payload, "expires_at": "2099-01-01T00:00:00+00:00"}, + separators=(",", ":"), sort_keys=True).encode()) + assert verify_token(f"{forged}.{sig}", "site-A", PUB) is None + + +def test_token_for_another_site_rejected(): + assert verify_token(make_token(site_id="site-B"), "site-A", PUB) is None + + +def test_token_signed_by_another_key_rejected(): + assert verify_token(make_token(signer=Ed25519PrivateKey.generate()), "site-A", PUB) is None + + +@pytest.mark.parametrize("junk", [None, "", "not.a.token", "abc"]) +def test_garbage_rejected(junk): + assert verify_token(junk, "site-A", PUB) is None + + +def test_production_public_key_is_ed25519(): + assert len(base64.b64decode(LICENSE_PUBLIC_KEY)) == 32 + + +# ── evaluate: offline ──────────────────────────────────────────────────────── + +def test_364_days_offline_still_licensed(payload): + r = evaluate(payload, ISSUED + timedelta(days=364), ISSUED, workday_open=False) + assert (r["licensed"], r["license_problem"]) == (True, None) + + +# ── evaluate: expiry + grace, never mid-service ────────────────────────────── + +def test_two_days_after_expiry_is_grace(payload): + r = evaluate(payload, EXPIRES + timedelta(days=2), ISSUED, workday_open=False) + assert (r["licensed"], r["grace_over"], r["grace_days_remaining"]) == (True, False, 3) + + +def test_grace_over_without_workday_blocks(payload): + r = evaluate(payload, EXPIRES + timedelta(days=6), ISSUED, workday_open=False) + assert (r["licensed"], r["license_problem"], r["grace_over"]) == (False, "expired", True) + + +def test_grace_over_with_open_workday_keeps_running(payload): + r = evaluate(payload, EXPIRES + timedelta(days=6), ISSUED, workday_open=True) + assert (r["licensed"], r["grace_over"]) == (True, True) + + +def test_deactivated_site_blocks(): + p = verify_token(make_token(active=False), "site-A", PUB) + r = evaluate(p, ISSUED + timedelta(days=1), ISSUED, workday_open=False) + assert (r["licensed"], r["license_problem"]) == (False, "inactive") + + +# ── evaluate: clock set back ───────────────────────────────────────────────── + +def test_clock_before_newest_activity_blocks(payload): + floor = ISSUED + timedelta(days=100) + r = evaluate(payload, floor - timedelta(days=30), floor, workday_open=False) + assert (r["licensed"], r["license_problem"]) == (False, "clock") + + +def test_small_clock_skew_tolerated(payload): + floor = ISSUED + timedelta(days=100) + assert evaluate(payload, floor - timedelta(hours=12), floor, workday_open=False)["licensed"] + + +def test_clock_before_signed_issue_time_blocks(payload): + r = evaluate(payload, ISSUED - timedelta(days=5), ISSUED, workday_open=False) + assert r["license_problem"] == "clock" + + +# ── evaluate: no genuine token ─────────────────────────────────────────────── + +def test_transition_old_cloud_recent_ok(): + r = evaluate(None, ISSUED, None, False, legacy_ok_at=ISSUED - timedelta(hours=10)) + assert (r["licensed"], r["license_problem"]) == (True, None) + + +def test_transition_old_cloud_stale(): + r = evaluate(None, ISSUED, None, False, legacy_ok_at=ISSUED - timedelta(hours=80)) + assert (r["licensed"], r["license_problem"]) == (False, "unverified") + + +def test_never_licensed_blocks(): + r = evaluate(None, ISSUED, None, False) + assert (r["licensed"], r["license_problem"]) == (False, "unverified") diff --git a/local_backend/tests/test_tls_identity.py b/local_backend/tests/test_tls_identity.py new file mode 100644 index 0000000..3c6f184 --- /dev/null +++ b/local_backend/tests/test_tls_identity.py @@ -0,0 +1,61 @@ +"""The server's self-managed TLS identity (services/tls_identity.py, plan step 7).""" +import shutil +import subprocess +from datetime import datetime, timedelta, timezone + +import pytest +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec + +from services.tls_identity import _issue_cert, ensure_tls_identity, spki_sha256 + +NOW = datetime.now(timezone.utc) + + +@pytest.fixture(autouse=True) +def host_ip(monkeypatch): + monkeypatch.setenv("HOST_IP", "192.168.1.50") + + +def cert_of(d): + return x509.load_pem_x509_certificate((d / "cert.pem").read_bytes()) + + +def test_first_run_creates_ec_key_and_10y_cert(tmp_path): + r = ensure_tls_identity(tmp_path, NOW) + assert r["created"] + assert isinstance(serialization.load_pem_private_key((tmp_path / "key.pem").read_bytes(), None), ec.EllipticCurvePrivateKey) + assert round((cert_of(tmp_path).not_valid_after_utc - NOW).days / 365) == 10 + sans = [str(n.value) for n in cert_of(tmp_path).extensions.get_extension_for_class(x509.SubjectAlternativeName).value] + assert "192.168.1.50" in sans + + +@pytest.mark.skipif(not shutil.which("openssl"), reason="openssl CLI not available") +def test_pin_matches_openssl_spki(tmp_path): + pin = ensure_tls_identity(tmp_path, NOW)["spki_sha256"] + cmd = ("openssl x509 -in cert.pem -pubkey -noout | openssl pkey -pubin -outform der" + " | openssl dgst -sha256 -binary | openssl base64 -A") + assert subprocess.run(cmd, shell=True, cwd=tmp_path, capture_output=True, text=True).stdout.strip() == pin + + +def test_restart_changes_nothing(tmp_path): + first = ensure_tls_identity(tmp_path, NOW) + again = ensure_tls_identity(tmp_path, NOW) + assert (again["created"], again["renewed"], again["spki_sha256"]) == (False, False, first["spki_sha256"]) + + +def test_renewal_keeps_the_key(tmp_path): + first = ensure_tls_identity(tmp_path, NOW) + serial = cert_of(tmp_path).serial_number + later = ensure_tls_identity(tmp_path, NOW + timedelta(days=365 * 8 + 30)) # < 2 years left + assert later["renewed"] and later["spki_sha256"] == first["spki_sha256"] + assert cert_of(tmp_path).serial_number != serial + + +def test_foreign_cert_replaced(tmp_path): + first = ensure_tls_identity(tmp_path, NOW) + other = ec.generate_private_key(ec.SECP256R1()) + (tmp_path / "cert.pem").write_bytes(_issue_cert(other, None, NOW).public_bytes(serialization.Encoding.PEM)) + again = ensure_tls_identity(tmp_path, NOW) + assert spki_sha256(cert_of(tmp_path).public_key()) == first["spki_sha256"] == again["spki_sha256"] diff --git a/waiter_pwa/package.json b/waiter_pwa/package.json index 0fafa8e..a542173 100644 --- a/waiter_pwa/package.json +++ b/waiter_pwa/package.json @@ -10,7 +10,8 @@ "preview": "vite preview", "build:native": "vite build --mode native && cap sync android", "apk:debug": "npm run build:native && node scripts/build-apk.mjs debug", - "apk:release": "npm run build:native && node scripts/build-apk.mjs release" + "apk:release": "npm run build:native && node scripts/build-apk.mjs release", + "test": "node --test \"tests/*.test.mjs\"" }, "dependencies": { "@capacitor/android": "^8.5.2", diff --git a/waiter_pwa/tests/rediscovery.test.mjs b/waiter_pwa/tests/rediscovery.test.mjs new file mode 100644 index 0000000..bd196e0 --- /dev/null +++ b/waiter_pwa/tests/rediscovery.test.mjs @@ -0,0 +1,56 @@ +// Server rediscovery scan (src/native/rediscovery.js, plan step 5) — pure logic, fake network. +// Run: npm test +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { scanForVenue, subnetCandidates } from '../src/native/rediscovery.js' + +test('same-/24 candidates, nearest first, old host excluded', () => { + const c = subnetCandidates('http://192.168.1.50') + assert.equal(c.length, 253) + assert.deepEqual(c.slice(0, 4), ['http://192.168.1.49', 'http://192.168.1.51', 'http://192.168.1.48', 'http://192.168.1.52']) + assert.ok(!c.includes('http://192.168.1.50')) +}) + +test('scheme and port are kept (plain HTTP and the TLS entry)', () => { + assert.equal(subnetCandidates('http://10.0.0.7:8080')[0], 'http://10.0.0.6:8080') + assert.equal(subnetCandidates('https://10.0.0.7:8443')[0], 'https://10.0.0.6:8443') +}) + +test('hostnames and garbage are never scanned', () => { + assert.deepEqual(subnetCandidates('http://waiter.example.gr'), []) + assert.deepEqual(subnetCandidates('not a url'), []) +}) + +const network = { + 'http://192.168.1.12': { app: 'xenia-pos', site_id: 'OTHER-venue', api_version: 1 }, + 'http://192.168.1.77': { app: 'xenia-pos', site_id: 'MY-venue', api_version: 1 }, +} +function fakeProbe() { + const calls = { n: 0 } + const probe = async origin => { calls.n++; await new Promise(r => setTimeout(r, 1)); return network[origin] ?? null } + return { probe, calls } +} + +test('finds this venue at its new address and stops early', async () => { + const { probe, calls } = fakeProbe() + assert.equal(await scanForVenue('http://192.168.1.50', 'MY-venue', { probe, concurrency: 8 }), 'http://192.168.1.77') + assert.ok(calls.n < 253) +}) + +test('another venue\'s server is never chosen', async () => { + const { probe } = fakeProbe() + assert.equal(await scanForVenue('http://192.168.1.50', 'NOBODY', { probe, concurrency: 8 }), null) +}) + +test('no site id → no scan', async () => { + const { probe, calls } = fakeProbe() + assert.equal(await scanForVenue('http://192.168.1.50', null, { probe }), null) + assert.equal(calls.n, 0) +}) + +test('progress is reported for every probe', async () => { + const { probe } = fakeProbe() + let progress = 0 + await scanForVenue('http://192.168.1.50', 'NOBODY', { probe, concurrency: 16, onProgress: () => progress++ }) + assert.equal(progress, 253) +})