#!/usr/bin/env python3 import json import os import shutil import stat import subprocess import sys import tempfile import threading from pathlib import Path sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common")) from werkzeug.serving import make_server from werkzeug.wrappers import Request, Response PASS = [] FAIL = [] def check(name, cond, detail=""): if cond: PASS.append(name) else: FAIL.append((name, detail)) print(f"FAIL: {name} {detail}") class FakeServer: """Serves /history, //download, and a fake /login that accepts exactly one email+password pair and sets a session cookie -- mirrors real HedgeDoc's local-auth /login: always 302s, whether accepted or rejected, and the caller must probe /history to find out which.""" VALID_EMAIL = "joakim@example.com" VALID_PASSWORD = "correct horse battery staple" def __init__(self, port, notes): self.notes = notes self.port = port self.valid_sessions = {"session=abc123"} def app(environ, start_response): request = Request(environ) if request.path == "/login" and request.method == "POST": from urllib.parse import parse_qs body = request.get_data(as_text=True) fields = parse_qs(body) email = (fields.get("email") or [""])[0] password = (fields.get("password") or [""])[0] resp = Response(status=302, headers={"Location": "/"}) if email == self.VALID_EMAIL and password == self.VALID_PASSWORD: resp.set_cookie("connect.sid", "loggedinsession") self.valid_sessions.add("connect.sid=loggedinsession") return resp(environ, start_response) if request.path == "/history": cookie = request.headers.get("Cookie", "") if not any(v in cookie for v in self.valid_sessions): resp = Response("forbidden", status=403) else: history = [{"id": nid, "text": n["title"], "tags": n["tags"], "time": 0} for nid, n in self.notes.items()] resp = Response(json.dumps({"history": history}), mimetype="application/json") elif request.path.endswith("/download"): nid = request.path.split("/")[1] resp = Response(self.notes[nid]["content"], mimetype="text/markdown") else: resp = Response("not found", status=404) return resp(environ, start_response) self.srv = make_server("127.0.0.1", port, app, threaded=True) self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True) def start(self): self.thread.start() def stop(self): self.srv.shutdown() def free_port(): import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("127.0.0.1", 0)) p = s.getsockname()[1] s.close() return p def run_hd(*args, cwd, input_text=None): return subprocess.run( [sys.executable, str(Path(__file__).parent / "hdc"), *args], cwd=cwd, capture_output=True, text=True, timeout=15, input=input_text, ) def main(): port = free_port() notes = { "n1": {"title": "Fox Hunt Notes", "tags": ["radio"], "content": "# Fox Hunt\nfrequencies here"}, } server = FakeServer(port, notes) server.start() tmpdir = Path(tempfile.mkdtemp(prefix="hd-cli-test-")) target = tmpdir / "notes" try: # --- init with --cookie, wrong value: files saved, but sync fails --- r = run_hd("init", f"http://127.0.0.1:{port}", "--cookie", "session=wrong", "--dir", str(target), cwd=tmpdir) check("init with bad cookie exits nonzero (sync fails)", r.returncode != 0, r.stderr) check("init with bad cookie still saved cookies.json", (target / ".hd" / "cookies.json").exists()) shutil.rmtree(target) # --- init with --cookie, correct value --- r = run_hd("init", f"http://127.0.0.1:{port}", "--cookie", "session=abc123", "--dir", str(target), cwd=tmpdir) check("init with good cookie exits 0", r.returncode == 0, r.stderr) check("config.json created", (target / ".hd" / "config.json").exists()) check("cookies.json created", (target / ".hd" / "cookies.json").exists()) for fname in ("config.json", "cookies.json"): mode = stat.S_IMODE((target / ".hd" / fname).stat().st_mode) check(f"{fname} is mode 0600", mode == 0o600, oct(mode)) check("cookie not leaked into config.json", "cookie" not in json.loads((target / ".hd" / "config.json").read_text())) check("cookie present in cookies.json", json.loads((target / ".hd" / "cookies.json").read_text())["cookie"] == "session=abc123") check("state.json created", (target / ".hd" / "state.json").exists()) check("radio/ created with symlink", (target / "radio" / "Fox Hunt Notes").is_symlink()) check("symlinked content matches", (target / "radio" / "Fox Hunt Notes").read_text() == "# Fox Hunt\nfrequencies here") # --- --dir auto-detection: standing anywhere inside the hd-managed # tree, 'hdc sync' with no --dir at all should still find it --- r_auto1 = run_hd("sync", cwd=target) # at the root itself check("sync with no --dir, standing AT the hd root, auto-detects it", r_auto1.returncode == 0, r_auto1.stdout + r_auto1.stderr) r_auto2 = run_hd("sync", cwd=target / "radio") # a subdirectory check("sync with no --dir, standing in a SUBDIRECTORY, still auto-detects the root above it", r_auto2.returncode == 0, r_auto2.stdout + r_auto2.stderr) # From somewhere with no .hd/ above it at all, and a controlled, # guaranteed-empty $HOME so the ~/notes fallback can't accidentally # succeed against whatever the real test machine happens to have -- # this must fail cleanly, not silently do nothing or pick up an # unrelated real folder. fake_home = tmpdir / "fake-home-no-notes-here" fake_home.mkdir() r_nowhere = subprocess.run( [sys.executable, str(Path(__file__).parent / "hdc"), "sync"], cwd=tmpdir, capture_output=True, text=True, timeout=15, env={**os.environ, "HOME": str(fake_home)}, ) check("sync with no --dir and nothing discoverable anywhere fails cleanly, not silently", r_nowhere.returncode != 0, r_nowhere.stdout + r_nowhere.stderr) # --- re-init refuses to clobber --- r2 = run_hd("init", f"http://127.0.0.1:{port}", "--cookie", "session=abc123", "--dir", str(target), cwd=tmpdir) check("re-init refuses (nonzero exit)", r2.returncode != 0) check("re-init leaves existing cookie untouched", json.loads((target / ".hd" / "cookies.json").read_text())["cookie"] == "session=abc123") # --- sync after a server-side change --- notes["n1"]["tags"] = ["radio", "reference"] r3 = run_hd("sync", "--dir", str(target), cwd=tmpdir) check("sync exits 0", r3.returncode == 0, r3.stderr) check("sync picked up new tag", (target / "reference" / "Fox Hunt Notes").is_symlink()) # --- sync with no changes reports up to date --- r4 = run_hd("sync", "--dir", str(target), cwd=tmpdir) check("second sync exits 0", r4.returncode == 0) check("second sync says up to date", "Up to date" in r4.stdout, r4.stdout) # --- sync against a nonexistent dir fails cleanly --- r5 = run_hd("sync", "--dir", str(tmpdir / "nope"), cwd=tmpdir) check("sync on uninitialized dir fails", r5.returncode != 0) shutil.rmtree(target) # --- login dialog: email prompted via --email, password via stdin --- r6 = run_hd("init", f"http://127.0.0.1:{port}", "--email", FakeServer.VALID_EMAIL, "--dir", str(target), cwd=tmpdir, input_text=FakeServer.VALID_PASSWORD + "\n") check("login-flow init exits 0", r6.returncode == 0, r6.stderr) check("login-flow saved email in config.json (no password)", json.loads((target / ".hd" / "config.json").read_text()).get("email") == FakeServer.VALID_EMAIL) check("login-flow config.json has no password field", "password" not in json.loads((target / ".hd" / "config.json").read_text())) check("login-flow captured the session cookie HedgeDoc actually set", "connect.sid=loggedinsession" in json.loads((target / ".hd" / "cookies.json").read_text())["cookie"]) check("login-flow ran first sync successfully", (target / "radio" / "Fox Hunt Notes").is_symlink()) shutil.rmtree(target) # --- login dialog with wrong password: clean failure, nothing written --- r7 = run_hd("init", f"http://127.0.0.1:{port}", "--email", FakeServer.VALID_EMAIL, "--dir", str(target), cwd=tmpdir, input_text="wrong password\n") check("wrong-password init exits nonzero", r7.returncode != 0) check("wrong-password init did not create .hd", not (target / ".hd").exists()) check("wrong-password init explains the failure", "Login failed" in r7.stderr, r7.stderr) finally: server.stop() shutil.rmtree(tmpdir, ignore_errors=True) print(f"\n{len(PASS)} passed, {len(FAIL)} failed") return 0 if not FAIL else 1 if __name__ == "__main__": raise SystemExit(main())