Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/4553.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
omnivoice-dub with an https --api endpoint now sends the job over TLS instead of plaintext HTTP (#4553)
49 changes: 35 additions & 14 deletions omnivoice/cli/dub.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
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
--------
Expand All @@ -23,23 +24,47 @@
from __future__ import annotations

import argparse
import http.client
import json
import os
import sys
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)


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)}"
Expand All @@ -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()
Expand All @@ -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:
Expand All @@ -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}")
Expand Down
104 changes: 104 additions & 0 deletions tests/test_omnivoice_dub_cli.py
Original file line number Diff line number Diff line change
@@ -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 == []
Loading