mirror of
https://github.com/cottongin/cardputerzero-sync.git
synced 2026-11-20 14:44:47 -06:00
fix(mac-receiver): escape osascript args and expand server tests
This commit is contained in:
@@ -55,12 +55,15 @@ def is_allowed_client_ip(ip_str: str, tailscale_only: bool) -> bool:
|
|||||||
def _default_osascript_notifier(count: int, dest_root: Path) -> None:
|
def _default_osascript_notifier(count: int, dest_root: Path) -> None:
|
||||||
"""Display a native macOS Notification Center banner via osascript."""
|
"""Display a native macOS Notification Center banner via osascript."""
|
||||||
noun = "photo" if count == 1 else "photos"
|
noun = "photo" if count == 1 else "photos"
|
||||||
folder = dest_root.name.replace('"', '\\"')
|
message = f"Synced {count} {noun} to {dest_root.name}"
|
||||||
message = f"Synced {count} {noun} to {folder}"
|
script = (
|
||||||
script = f'display notification "{message}" with title "CardputerZero Sync"'
|
"on run argv\n"
|
||||||
|
' display notification (item 1 of argv) with title "CardputerZero Sync"\n'
|
||||||
|
"end run"
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["osascript", "-e", script],
|
["osascript", "-e", script, message],
|
||||||
check=False,
|
check=False,
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True,
|
text=True,
|
||||||
|
|||||||
@@ -5,13 +5,20 @@ import tempfile
|
|||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
import unittest
|
import unittest
|
||||||
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from subprocess import CompletedProcess
|
||||||
|
from unittest.mock import patch
|
||||||
from urllib.error import HTTPError
|
from urllib.error import HTTPError
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
from urllib.request import Request, urlopen
|
from urllib.request import Request, urlopen
|
||||||
|
|
||||||
from cp0_mac_receiver.config import MacConfig, load_mac_config, save_mac_config
|
from cp0_mac_receiver.config import MacConfig, load_mac_config, save_mac_config
|
||||||
from cp0_mac_receiver.server import MacReceiverServer, is_allowed_client_ip
|
from cp0_mac_receiver.server import (
|
||||||
|
MacReceiverServer,
|
||||||
|
_default_osascript_notifier,
|
||||||
|
is_allowed_client_ip,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class TestMacConfigAndFilter(unittest.TestCase):
|
class TestMacConfigAndFilter(unittest.TestCase):
|
||||||
@@ -44,6 +51,22 @@ class TestMacConfigAndFilter(unittest.TestCase):
|
|||||||
loaded = load_mac_config(cfg_path)
|
loaded = load_mac_config(cfg_path)
|
||||||
self.assertEqual(loaded, custom)
|
self.assertEqual(loaded, custom)
|
||||||
|
|
||||||
|
def test_env_override_cp0_mac_config(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
env_cfg_path = Path(tmp) / "env-dir" / "config.json"
|
||||||
|
custom = MacConfig(
|
||||||
|
dest_root=str(Path(tmp) / "EnvPhotos"),
|
||||||
|
listen_host="127.0.0.1",
|
||||||
|
listen_port=9001,
|
||||||
|
notify_on_batch=False,
|
||||||
|
tailscale_only=True,
|
||||||
|
)
|
||||||
|
with patch.dict(os.environ, {"CP0_MAC_CONFIG": str(env_cfg_path)}):
|
||||||
|
save_mac_config(custom)
|
||||||
|
self.assertTrue(env_cfg_path.is_file())
|
||||||
|
loaded = load_mac_config()
|
||||||
|
self.assertEqual(loaded, custom)
|
||||||
|
|
||||||
def test_tailscale_ip_filter(self):
|
def test_tailscale_ip_filter(self):
|
||||||
self.assertTrue(is_allowed_client_ip("100.101.102.103", True))
|
self.assertTrue(is_allowed_client_ip("100.101.102.103", True))
|
||||||
self.assertTrue(is_allowed_client_ip("fd7a:115c:a1e0::1", True))
|
self.assertTrue(is_allowed_client_ip("fd7a:115c:a1e0::1", True))
|
||||||
@@ -56,6 +79,23 @@ class TestMacConfigAndFilter(unittest.TestCase):
|
|||||||
self.assertFalse(is_allowed_client_ip("not-an-ip", True))
|
self.assertFalse(is_allowed_client_ip("not-an-ip", True))
|
||||||
self.assertTrue(is_allowed_client_ip("192.168.1.50", False))
|
self.assertTrue(is_allowed_client_ip("192.168.1.50", False))
|
||||||
|
|
||||||
|
def test_default_osascript_notifier_passes_message_via_argv(self):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_run(cmd, **kwargs):
|
||||||
|
calls.append(cmd)
|
||||||
|
return CompletedProcess(cmd, 0, stdout="", stderr="")
|
||||||
|
|
||||||
|
with patch("cp0_mac_receiver.server.subprocess.run", side_effect=fake_run):
|
||||||
|
_default_osascript_notifier(2, Path('/tmp/bad\\"folder'))
|
||||||
|
|
||||||
|
self.assertEqual(len(calls), 1)
|
||||||
|
cmd = calls[0]
|
||||||
|
self.assertEqual(cmd[0], "osascript")
|
||||||
|
self.assertEqual(cmd[1], "-e")
|
||||||
|
self.assertIn("on run argv", cmd[2])
|
||||||
|
self.assertEqual(cmd[3], 'Synced 2 photos to bad\\"folder')
|
||||||
|
|
||||||
|
|
||||||
class TestMacReceiverServer(unittest.TestCase):
|
class TestMacReceiverServer(unittest.TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
@@ -84,17 +124,23 @@ class TestMacReceiverServer(unittest.TestCase):
|
|||||||
notifier=_notifier,
|
notifier=_notifier,
|
||||||
debounce_sec=0.05,
|
debounce_sec=0.05,
|
||||||
)
|
)
|
||||||
self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True)
|
self.srv.start()
|
||||||
self.thread.start()
|
self.srv.start() # idempotent second call
|
||||||
self.base_url = f"http://127.0.0.1:{self.srv.server_port}"
|
self.base_url = f"http://127.0.0.1:{self.srv.server_address[1]}"
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
self.srv.shutdown()
|
self.srv.shutdown()
|
||||||
self.srv.server_close()
|
self.srv.server_close()
|
||||||
self.thread.join(timeout=2.0)
|
|
||||||
self.tmp.cleanup()
|
self.tmp.cleanup()
|
||||||
|
|
||||||
def _upload(self, label: str, rel_path: str, data: bytes, mtime: float = 1700000000.0):
|
def _upload(
|
||||||
|
self,
|
||||||
|
label: str,
|
||||||
|
rel_path: str,
|
||||||
|
data: bytes,
|
||||||
|
mtime: float = 1700000000.0,
|
||||||
|
encode: bool = True,
|
||||||
|
):
|
||||||
sha = hashlib.sha256(data).hexdigest()
|
sha = hashlib.sha256(data).hexdigest()
|
||||||
req = Request(
|
req = Request(
|
||||||
f"{self.base_url}/upload",
|
f"{self.base_url}/upload",
|
||||||
@@ -102,8 +148,8 @@ class TestMacReceiverServer(unittest.TestCase):
|
|||||||
method="POST",
|
method="POST",
|
||||||
headers={
|
headers={
|
||||||
"Content-Length": str(len(data)),
|
"Content-Length": str(len(data)),
|
||||||
"X-CP0-Folder-Label": quote(label, safe=""),
|
"X-CP0-Folder-Label": quote(label, safe="") if encode else label,
|
||||||
"X-CP0-Rel-Path": quote(rel_path, safe="/"),
|
"X-CP0-Rel-Path": quote(rel_path, safe="/") if encode else rel_path,
|
||||||
"X-CP0-SHA256": sha,
|
"X-CP0-SHA256": sha,
|
||||||
"X-CP0-Mtime": str(mtime),
|
"X-CP0-Mtime": str(mtime),
|
||||||
},
|
},
|
||||||
@@ -119,6 +165,23 @@ class TestMacReceiverServer(unittest.TestCase):
|
|||||||
self.assertIn("version", body)
|
self.assertIn("version", body)
|
||||||
self.assertIn("hostname", body)
|
self.assertIn("hostname", body)
|
||||||
|
|
||||||
|
def test_rejects_disallowed_client_ip_with_403(self):
|
||||||
|
with (
|
||||||
|
patch("cp0_mac_receiver.server.is_allowed_client_ip", return_value=False),
|
||||||
|
self.assertLogs("cp0_mac_receiver.server", level="WARNING"),
|
||||||
|
):
|
||||||
|
with self.assertRaises(HTTPError) as ctx_health:
|
||||||
|
urlopen(f"{self.base_url}/health")
|
||||||
|
self.assertEqual(ctx_health.exception.code, 403)
|
||||||
|
self.assertEqual(json.loads(ctx_health.exception.read())["error"], "forbidden")
|
||||||
|
ctx_health.exception.close()
|
||||||
|
|
||||||
|
with self.assertRaises(HTTPError) as ctx_upload:
|
||||||
|
self._upload("Camera", "a.jpg", b"abc")
|
||||||
|
self.assertEqual(ctx_upload.exception.code, 403)
|
||||||
|
self.assertEqual(json.loads(ctx_upload.exception.read())["error"], "forbidden")
|
||||||
|
ctx_upload.exception.close()
|
||||||
|
|
||||||
def test_upload_dedup_collision_and_utf8_headers(self):
|
def test_upload_dedup_collision_and_utf8_headers(self):
|
||||||
payload = b"jpeg-bytes-1"
|
payload = b"jpeg-bytes-1"
|
||||||
with self._upload("Trip Photos", "2026/café 1.jpg", payload, 1700000123.0) as resp1:
|
with self._upload("Trip Photos", "2026/café 1.jpg", payload, 1700000123.0) as resp1:
|
||||||
@@ -132,24 +195,40 @@ class TestMacReceiverServer(unittest.TestCase):
|
|||||||
r2 = json.loads(resp2.read())
|
r2 = json.loads(resp2.read())
|
||||||
self.assertEqual(r2["status"], "already_exists")
|
self.assertEqual(r2["status"], "already_exists")
|
||||||
|
|
||||||
with self._upload("Trip Photos", "2026/café 1.jpg", b"jpeg-bytes-different", 1700000456.0) as resp3:
|
diff_payload = b"jpeg-bytes-different"
|
||||||
|
collision_mtime = 1700000456.0
|
||||||
|
stamp = datetime.fromtimestamp(collision_mtime, tz=timezone.utc).strftime("%Y%m%d_%H%M%S")
|
||||||
|
sha8 = hashlib.sha256(diff_payload).hexdigest()[:8]
|
||||||
|
expected_collision_name = f"café 1_{stamp}_{sha8}.jpg"
|
||||||
|
|
||||||
|
with self._upload("Trip Photos", "2026/café 1.jpg", diff_payload, collision_mtime) as resp3:
|
||||||
r3 = json.loads(resp3.read())
|
r3 = json.loads(resp3.read())
|
||||||
self.assertEqual(r3["status"], "saved")
|
self.assertEqual(r3["status"], "saved")
|
||||||
saved_path = Path(r3["saved_path"])
|
saved_path = Path(r3["saved_path"])
|
||||||
self.assertNotEqual(saved_path, target)
|
self.assertNotEqual(saved_path, target)
|
||||||
self.assertEqual(saved_path.read_bytes(), b"jpeg-bytes-different")
|
self.assertEqual(saved_path.name, expected_collision_name)
|
||||||
|
self.assertEqual(saved_path.read_bytes(), diff_payload)
|
||||||
self.assertEqual(target.read_bytes(), payload)
|
self.assertEqual(target.read_bytes(), payload)
|
||||||
|
|
||||||
def test_rejects_path_traversal_and_bad_sha256(self):
|
# Retry of the colliding payload at the same path/mtime must deduplicate cleanly.
|
||||||
with self.assertRaises(HTTPError) as ctx:
|
with self._upload("Trip Photos", "2026/café 1.jpg", diff_payload, collision_mtime) as resp4:
|
||||||
self._upload("../etc", "passwd", b"bad")
|
r4 = json.loads(resp4.read())
|
||||||
self.assertEqual(ctx.exception.code, 400)
|
self.assertEqual(r4["status"], "already_exists")
|
||||||
ctx.exception.close()
|
self.assertEqual(list(target.parent.glob("*.part")), [])
|
||||||
|
|
||||||
with self.assertRaises(HTTPError) as ctx_abs:
|
def test_rejects_path_traversal_percent_encoded_and_bad_sha256(self):
|
||||||
self._upload("Camera", "/etc/passwd", b"bad")
|
bad_paths = [
|
||||||
self.assertEqual(ctx_abs.exception.code, 400)
|
("../etc", "passwd", True),
|
||||||
ctx_abs.exception.close()
|
("Camera", "/etc/passwd", True),
|
||||||
|
("a%2Fb", "img.jpg", False),
|
||||||
|
("Camera", "2026/..%2f..%2fetc/passwd", False),
|
||||||
|
("Camera", "%FF%FE.jpg", False),
|
||||||
|
]
|
||||||
|
for label, rel_path, encode in bad_paths:
|
||||||
|
with self.assertRaises(HTTPError) as ctx:
|
||||||
|
self._upload(label, rel_path, b"bad", encode=encode)
|
||||||
|
self.assertEqual(ctx.exception.code, 400)
|
||||||
|
ctx.exception.close()
|
||||||
|
|
||||||
req = Request(
|
req = Request(
|
||||||
f"{self.base_url}/upload",
|
f"{self.base_url}/upload",
|
||||||
@@ -168,6 +247,11 @@ class TestMacReceiverServer(unittest.TestCase):
|
|||||||
self.assertEqual(ctx2.exception.code, 400)
|
self.assertEqual(ctx2.exception.code, 400)
|
||||||
ctx2.exception.close()
|
ctx2.exception.close()
|
||||||
|
|
||||||
|
camera_dir = self.dest_root / "Camera"
|
||||||
|
if camera_dir.exists():
|
||||||
|
self.assertEqual(list(camera_dir.rglob("*.part")), [])
|
||||||
|
self.assertFalse((camera_dir / "a.jpg").exists())
|
||||||
|
|
||||||
def test_debounced_batch_notification_fires_once_after_burst(self):
|
def test_debounced_batch_notification_fires_once_after_burst(self):
|
||||||
with self._upload("Camera", "img1.jpg", b"photo-1", 1700000001.0) as r1:
|
with self._upload("Camera", "img1.jpg", b"photo-1", 1700000001.0) as r1:
|
||||||
self.assertEqual(r1.status, 200)
|
self.assertEqual(r1.status, 200)
|
||||||
|
|||||||
Reference in New Issue
Block a user