fix(cli): honour the --api scheme in omnivoice-dub

The CLI's three request helpers parsed \--api\ and then always opened
\http.client.HTTPConnection(host, port or 80)\, so an https endpoint got the
multipart video, the transcript, the translation request and the progress
stream over plaintext HTTP port 80, and a TLS-only backend could not be
reached at all. One \_connection()\ helper now picks HTTPConnection or
HTTPSConnection from the scheme, defaults the port to 80/443, keeps an
explicit port, and refuses a non-http(s) scheme instead of downgrading it.
Plain http LAN and Tailscale backends behave exactly as before, and
tests/test_omnivoice_dub_cli.py pins each case.

The test resolves \omnivoice.cli.dub\ per test with
\importlib.import_module\, so it uses the current entry in sys.modules
rather than a package attribute that another test may have replaced.
This commit is contained in:
DeryFerd committed 2026-11-30 13:32:31 +07:00
1 parent 6ad98a4acc
commit e82c210d9e
3 files changed
+140 -14

No files matched your search

+1
View File
@@ -0,0 +1 @@
omnivoice-dub with an https --api endpoint now sends the job over TLS instead of plaintext HTTP (#4553)
+35 -14
View File
@@ -6,7 +6,8 @@ translate → generate → export. Uses the HTTP API under the hood so the same
orchestration logic that powers the UI runs here.
Requires the backend to be running (`uv run uvicorn main:app --app-dir backend`).
Auto-starts against `http://localhost:8000` unless `--api` is given.
Auto-starts against `http://localhost:8000` unless `--api` is given. `--api`
follows the URL's scheme, so an `https://` backend is reached over TLS.
Examples
--------
@@ -23,6 +24,7 @@ Examples
from __future__ import annotations
import argparse
import http.client
import json
import os
import sys
@@ -30,6 +32,31 @@ import time
import urllib.parse
import urllib.request
API_TIMEOUT_S = 3600
def _connection(api: str, path: str):
"""Open a connection to *api* for *path*, following the URL's scheme.
``--api`` accepts a full URL, but the request used to be sent over a plain
``HTTPConnection`` whatever the scheme said: an ``https://`` backend got the
video, the transcript and the translation in cleartext on port 80 (and a
TLS-only endpoint could not be reached at all). The scheme now picks the
connection class, and anything that is not http(s) is refused instead of
being silently downgraded.
"""
url = urllib.parse.urlparse(api + path)
if url.scheme not in ("http", "https"):
raise ValueError(
f"unsupported --api scheme {url.scheme or '(none)'!r}: use http:// or https://"
)
if not url.hostname:
raise ValueError(f"--api needs a host: {api!r}")
target = url.path + (f"?{url.query}" if url.query else "")
if url.scheme == "https":
return http.client.HTTPSConnection(url.hostname, url.port or 443, timeout=API_TIMEOUT_S), target
return http.client.HTTPConnection(url.hostname, url.port or 80, timeout=API_TIMEOUT_S), target
def _log(msg: str):
print(msg, file=sys.stderr, flush=True)
@@ -37,9 +64,7 @@ def _log(msg: str):
def _post(api: str, path: str, body=None, files=None):
"""Minimal JSON/multipart POST. Avoids adding requests as a CLI dep."""
import http.client
url = urllib.parse.urlparse(api + path)
conn = http.client.HTTPConnection(url.hostname, url.port or 80, timeout=3600)
conn, target = _connection(api, path)
if files:
# Simple multipart encode.
boundary = f"----ovbound{int(time.time()*1000)}"
@@ -53,12 +78,12 @@ def _post(api: str, path: str, body=None, files=None):
)
parts.append(f"--{boundary}--\r\n".encode())
payload = b"".join(parts)
conn.request("POST", url.path + (f"?{url.query}" if url.query else ""), payload, {
conn.request("POST", target, payload, {
"Content-Type": f"multipart/form-data; boundary={boundary}",
})
else:
payload = json.dumps(body or {}).encode()
conn.request("POST", url.path + (f"?{url.query}" if url.query else ""), payload, {
conn.request("POST", target, payload, {
"Content-Type": "application/json",
})
r = conn.getresponse()
@@ -71,10 +96,8 @@ def _post(api: str, path: str, body=None, files=None):
def _get(api: str, path: str):
import http.client
url = urllib.parse.urlparse(api + path)
conn = http.client.HTTPConnection(url.hostname, url.port or 80, timeout=3600)
conn.request("GET", url.path + (f"?{url.query}" if url.query else ""))
conn, target = _connection(api, path)
conn.request("GET", target)
r = conn.getresponse()
data = r.read()
if r.status >= 400:
@@ -84,10 +107,8 @@ def _get(api: str, path: str):
def _stream_task(api: str, task_id: str):
"""Tail `/tasks/stream/{task_id}` as SSE lines. Yields decoded event dicts."""
import http.client
url = urllib.parse.urlparse(api + f"/tasks/stream/{task_id}")
conn = http.client.HTTPConnection(url.hostname, url.port or 80, timeout=3600)
conn.request("GET", url.path)
conn, target = _connection(api, f"/tasks/stream/{task_id}")
conn.request("GET", target)
r = conn.getresponse()
if r.status >= 400:
raise RuntimeError(f"stream {task_id} → {r.status}")
+104
View File
@@ -0,0 +1,104 @@
"""`omnivoice-dub --api` must honour the URL scheme instead of always using plain http.
The CLI drives the whole dubbing job over HTTP: the multipart video upload, the
transcript, the translation request and the progress stream. Pointing it at an
``https://`` backend used to open a plain ``HTTPConnection`` to port 80, which
silently sends all of that in cleartext (and cannot reach a TLS-only server).
"""
from __future__ import annotations
import http.client
import importlib
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
@pytest.fixture
def dub():
"""Resolve the module at run time.
A module-level import goes stale when another test replaces the entry in
``sys.modules``. ``importlib.import_module`` resolves the fully qualified
name on every call, so each test sees the current module rather than a
cached package attribute.
"""
return importlib.import_module("omnivoice.cli.dub")
class _FakeConnection:
"""Records construction and refuses to open a socket."""
scheme = "http"
built: list["_FakeConnection"] = []
def __init__(self, host, port=None, timeout=None):
self.host = host
self.port = port
self.timeout = timeout
_FakeConnection.built.append(self)
def request(self, *args, **kwargs): # pragma: no cover - never reached
raise RuntimeError("connection opened")
class _FakeHTTPSConnection(_FakeConnection):
scheme = "https"
@pytest.fixture(autouse=True)
def _no_real_sockets(monkeypatch):
_FakeConnection.built = []
monkeypatch.setattr(http.client, "HTTPConnection", _FakeConnection)
monkeypatch.setattr(http.client, "HTTPSConnection", _FakeHTTPSConnection)
def test_an_https_api_opens_a_tls_connection(dub):
with pytest.raises(RuntimeError, match="connection opened"):
dub._post("https://studio.example", "/tasks/1/confirm", {"ok": True})
assert len(_FakeConnection.built) == 1
conn = _FakeConnection.built[0]
assert isinstance(conn, _FakeHTTPSConnection)
assert conn.host == "studio.example"
assert conn.port == 443 # the scheme's default, not 80
def test_an_https_api_with_an_explicit_port_keeps_it(dub):
with pytest.raises(RuntimeError, match="connection opened"):
dub._get("https://studio.example:8443", "/tasks/stream/1")
conn = _FakeConnection.built[0]
assert isinstance(conn, _FakeHTTPSConnection)
assert conn.port == 8443
def test_a_plain_http_api_still_uses_http_and_its_port(dub):
# A LAN or Tailscale backend over http:// is a documented deployment and
# must keep working exactly as before.
with pytest.raises(RuntimeError, match="connection opened"):
dub._get("http://10.0.0.5:3900", "/tasks/1")
conn = _FakeConnection.built[0]
assert not isinstance(conn, _FakeHTTPSConnection)
assert (conn.host, conn.port) == ("10.0.0.5", 3900)
def test_the_default_api_stays_loopback_http(dub):
with pytest.raises(RuntimeError, match="connection opened"):
dub._get("http://localhost:8000", "/tasks/1")
conn = _FakeConnection.built[0]
assert not isinstance(conn, _FakeHTTPSConnection)
assert (conn.host, conn.port) == ("localhost", 8000)
def test_a_non_http_api_scheme_is_refused(dub):
with pytest.raises(ValueError, match="http"):
dub._get("ftp://studio.example", "/tasks/1")
assert _FakeConnection.built == []