feat(server): auth au 1er demarrage (lien setup usage unique dans les logs) + src_lang + logs OCR
- server: si aucun compte (SCALPER_AUTH_FILE, defaut data/auth.json), init_auth affiche dans les logs un lien /setup?token=... a usage unique ; le compte cree, le lien est invalide. POST /login -> Bearer token (session 8h) exige sur tous les endpoints sauf /, /healthz, /login, /setup. Mot de passe hash PBKDF2. - front: formulaire de connexion (token en localStorage), header Authorization sur tous les fetch, champ 'langue d'entree' (src_lang) envoye a /run, et affichage de meta.language dans le panneau chapitre. - pipeline: run_pipeline(..., src_lang=...) -> meta['language'] persiste dans meta.json (utilise comme langue source de l'OCR) ; _run_ocr_typeset loggue skipped/erreur sur stderr au lieu d'avaler silencieusement. - cli: scalper run --src-lang. Docs README + deploy-coolify mises a jour. - tests: test_server adapte a l'auth (setup puis Bearer) + nouveaux tests 401/403/login ; test src_lang persiste ; test erreur OCR remontee. Co-authored-by: Orionis312050 <Orionis312050@users.noreply.github.com>
This commit is contained in:
1 parent
0f9889a264
commit
a5234e5869
8 files changed
+257
-24
No files matched your search
@@ -69,6 +69,15 @@ class TestPaddleOCRMapping(unittest.TestCase):
|
||||
PaddleOCR().recognize(Path("p.png"))
|
||||
self.assertIn("ocr-paddle", str(cm.exception))
|
||||
|
||||
def test_pipeline_ocr_error_is_surfaced_not_raised(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
d = Path(tmp)
|
||||
(d / "images").mkdir()
|
||||
with mock.patch("scalper.ocr.default_ocr_client", side_effect=RuntimeError("boom")):
|
||||
out = pipeline._run_ocr_typeset(d, {"language": "en"}, "fr", FakeLLM(), {})
|
||||
self.assertTrue(out.startswith("erreur"), out)
|
||||
self.assertIn("boom", out)
|
||||
|
||||
|
||||
class TestTesseractBoxFormat(unittest.TestCase):
|
||||
def test_box_is_xywh_not_corners(self):
|
||||
|
||||
@@ -40,6 +40,12 @@ class TestPipeline(unittest.TestCase):
|
||||
raw1 = Path(tmp) / "raw" / "demo" / "demo-1" / "demo-1-ch1"
|
||||
self.assertFalse((raw1 / "export").exists())
|
||||
|
||||
def test_src_lang_persisted_in_meta_json(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
pipeline.run_pipeline("demo", "demo-1", "fr", out_root=tmp, mock_llm=True, max_chapters=1, src_lang="ja")
|
||||
meta = json.loads((Path(tmp) / "raw" / "demo" / "demo-1" / "demo-1-ch1" / "meta.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(meta["language"], "ja")
|
||||
|
||||
def test_on_progress_callback(self):
|
||||
calls = []
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
|
||||
+64
-11
@@ -10,31 +10,60 @@ from http.server import ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from scalper import server as server_mod
|
||||
from scalper.server import Handler
|
||||
|
||||
|
||||
class TestServer(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmpdir = tempfile.TemporaryDirectory()
|
||||
cls._old_auth_file = server_mod.AUTH_FILE
|
||||
server_mod.AUTH_FILE = Path(cls.tmpdir.name) / "auth.json"
|
||||
server_mod.SETUP_TOKEN = None
|
||||
server_mod.SESSIONS.clear()
|
||||
cls.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
cls.port = cls.server.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
# simulate first start: setup link (logged) -> create the single account
|
||||
server_mod.init_auth("127.0.0.1", cls.port)
|
||||
req = urllib.request.Request(
|
||||
f"http://127.0.0.1:{cls.port}/setup",
|
||||
data=json.dumps({"token": server_mod.SETUP_TOKEN, "username": "admin", "password": "supersecret"}).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(req) as r:
|
||||
cls.token = json.loads(r.read())["token"]
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.server.shutdown()
|
||||
cls.server.server_close()
|
||||
server_mod.AUTH_FILE = cls._old_auth_file
|
||||
server_mod.SETUP_TOKEN = None
|
||||
server_mod.SESSIONS.clear()
|
||||
cls.tmpdir.cleanup()
|
||||
|
||||
def _get(self, path: str):
|
||||
with urllib.request.urlopen(f"http://127.0.0.1:{self.port}{path}") as r:
|
||||
return r.status, json.loads(r.read())
|
||||
def _get(self, path: str, auth: bool = True):
|
||||
req = urllib.request.Request(f"http://127.0.0.1:{self.port}{path}")
|
||||
if auth:
|
||||
req.add_header("Authorization", f"Bearer {self.token}")
|
||||
try:
|
||||
with urllib.request.urlopen(req) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read())
|
||||
|
||||
def _post(self, path: str, payload: dict):
|
||||
def _post(self, path: str, payload: dict, auth: bool = True):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if auth:
|
||||
headers["Authorization"] = f"Bearer {self.token}"
|
||||
req = urllib.request.Request(
|
||||
f"http://127.0.0.1:{self.port}{path}",
|
||||
data=json.dumps(payload).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
headers=headers,
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
@@ -43,11 +72,28 @@ class TestServer(unittest.TestCase):
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read())
|
||||
|
||||
def test_healthz(self):
|
||||
status, body = self._get("/healthz")
|
||||
def test_healthz_public(self):
|
||||
status, body = self._get("/healthz", auth=False)
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(body["status"], "ok")
|
||||
|
||||
def test_run_requires_auth(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
status, _ = self._post("/run", {"source": "demo", "series": "demo-1", "lang": "fr", "mock_llm": True, "out": tmp}, auth=False)
|
||||
self.assertEqual(status, 401)
|
||||
|
||||
def test_setup_token_single_use_and_login(self):
|
||||
# setup token already consumed in setUpClass -> /setup is now locked
|
||||
status, _ = self._post("/setup", {"token": "bidon", "username": "x", "password": "12345678"}, auth=False)
|
||||
self.assertEqual(status, 403)
|
||||
status, _ = self._get("/setup?token=x", auth=False)
|
||||
self.assertEqual(status, 403)
|
||||
status, _ = self._post("/login", {"username": "admin", "password": "wrongpass"}, auth=False)
|
||||
self.assertEqual(status, 401)
|
||||
status, body = self._post("/login", {"username": "admin", "password": "supersecret"}, auth=False)
|
||||
self.assertEqual(status, 200)
|
||||
self.assertIn("token", body)
|
||||
|
||||
def test_web_ui_served(self):
|
||||
with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/") as r:
|
||||
body = r.read().decode("utf-8")
|
||||
@@ -97,13 +143,20 @@ class TestServer(unittest.TestCase):
|
||||
self.assertEqual(Path(data["dir"]).as_posix(), "raw/demo/demo-1/demo-1-ch1")
|
||||
md = next((Path(tmp) / "raw" / "demo" / "demo-1" / "demo-1-ch1" / "export").glob("*.md"))
|
||||
rel = md.relative_to(tmp).as_posix()
|
||||
with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/file?out={urllib.parse.quote(tmp)}&path={urllib.parse.quote(rel)}") as r:
|
||||
req = urllib.request.Request(f"http://127.0.0.1:{self.port}/file?out={urllib.parse.quote(tmp)}&path={urllib.parse.quote(rel)}")
|
||||
req.add_header("Authorization", f"Bearer {self.token}")
|
||||
with urllib.request.urlopen(req) as r:
|
||||
self.assertEqual(r.status, 200)
|
||||
self.assertIn("markdown", r.headers.get("Content-Type", ""))
|
||||
self.assertTrue(r.read())
|
||||
with self.assertRaises(urllib.error.HTTPError) as cm:
|
||||
self._get(f"/file?out={urllib.parse.quote(tmp)}&path=../pyproject.toml")
|
||||
self.assertEqual(cm.exception.code, 404)
|
||||
status, _ = self._get(f"/file?out={urllib.parse.quote(tmp)}&path=../pyproject.toml")
|
||||
self.assertEqual(status, 404)
|
||||
|
||||
def test_api_chapter_requires_auth(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
q = urllib.parse.urlencode({"out": tmp, "source": "demo", "series": "demo-1", "chapter": "demo-1-ch1", "lang": "fr"})
|
||||
status, _ = self._get(f"/api/chapter?{q}", auth=False)
|
||||
self.assertEqual(status, 401)
|
||||
|
||||
def test_run_force_bypasses_qa_gate(self):
|
||||
fake = {"score": 10, "pass": False, "issues": [{"type": "x", "critical": True}]}
|
||||
|
||||
Reference in new issue
Block a user