3 Commits
Author SHA1 Message Date
LeoVasanko 7633ee0d84 onlyoffice: bind temp file server to bridge IP, silence handler tracebacks, self-limit lifetime
The temporary HTTP server that OnlyOffice downloads the source document
from was bound to 0.0.0.0, so internet scanners could (and did) connect,
and socketserver dumped a full traceback to stderr for every dropped
connection. It also stayed up for the whole conversion attempt, leaving
the port exposed when conversions hang.

- Bind only to the callback host (oonet gateway by default) so the port
  is unreachable from the internet.
- Override handle_error to log at debug level instead of printing
  tracebacks.
- Watchdog shuts the server down ~2s after the file is fetched, or at
  max_lifetime (request_timeout + 30s), and the socket is closed with
  server_close() in the normal path.
2026-09-10 20:22:41 +00:00
LeoVasanko d4dfc57994 onlyoffice: hardcode oonet gateway as callback host, drop docker detection
The cista service account has no docker CLI access, so detecting the
gateway via docker network inspect silently fell back to docker0/legacy
behavior. With the pinned subnet the gateway is always 172.30.0.1;
ONLYOFFICE_CALLBACK_HOST remains as an env override.
2026-08-13 07:38:52 +00:00
LeoVasanko 65e2fddf1a onlyoffice: drop legacy localhost:8988 URL fallback
The container always lives on the isolated oonet network at the fixed
IP; falling back to a published localhost port silently masked broken
setups with confusing 'not reachable at localhost:8988' diagnostics.
2026-08-13 07:26:57 +00:00
+63 -70
View File
@@ -50,9 +50,11 @@ logger = logging.getLogger(__name__)
# Isolated docker network for the OnlyOffice container: internal-only (no
# outbound internet), the container can only reach the host on this bridge.
# Docker discards published ports on internal networks, so the container is
# reached at its fixed IP instead of a published localhost port.
# reached at its fixed IP instead of a published localhost port. The host is
# always the first address of the pinned subnet (the bridge gateway).
OO_NETWORK = "oonet"
OO_SUBNET = "172.30.0.0/24"
OO_GATEWAY = "172.30.0.1"
OO_CONTAINER_IP = "172.30.0.2"
# ---------------------------------------------------------------------------
@@ -65,73 +67,28 @@ _httpx_client_loop: asyncio.AbstractEventLoop | None = None
def _get_onlyoffice_url() -> str:
if url := os.environ.get(
"ONLYOFFICE_URL", os.environ.get("ONLYOFFICE_CISTA_URL")
):
return url
# When the isolated network exists, the container is at its fixed IP and
# no localhost port is published (Docker discards ports on internal
# networks). Otherwise assume a legacy setup with a published port.
if _docker_network_gateway(OO_NETWORK):
return f"http://{OO_CONTAINER_IP}"
return "http://localhost:8988"
# The container runs on the isolated oonet network at a fixed IP; the
# host is the bridge gateway and reaches it directly, no published port.
return os.environ.get(
"ONLYOFFICE_URL",
os.environ.get("ONLYOFFICE_CISTA_URL", f"http://{OO_CONTAINER_IP}"),
)
def _get_jwt_secret() -> str:
return os.environ.get("ONLYOFFICE_JWT_SECRET", "")
def _docker_network_gateway(network: str) -> str | None:
"""Return the host-side gateway IP of a docker network, or None."""
try:
result = subprocess.run(
[
"docker",
"network",
"inspect",
network,
"--format",
"{{range .IPAM.Config}}{{.Gateway}}{{end}}",
],
capture_output=True,
text=True,
timeout=2,
check=False,
)
gateway = result.stdout.strip()
if result.returncode == 0 and gateway:
return gateway
except Exception:
logger.debug("Failed to inspect docker network %s", network)
return None
@lru_cache(maxsize=1)
def _get_callback_host() -> str:
"""Return the host IP that OnlyOffice (in Docker) can use to reach us."""
"""Return the host IP that OnlyOffice (in Docker) can use to reach us.
The host is always the gateway of the pinned oonet subnet; no detection
is needed (the cista service account may not have docker CLI access).
"""
if host := os.environ.get("ONLYOFFICE_CALLBACK_HOST"):
return host
# Prefer the gateway of the isolated network setup_docker() creates —
# this is the network the container is actually attached to.
if gateway := _docker_network_gateway(OO_NETWORK):
return gateway
# Fall back to the default docker bridge IP
try:
result = subprocess.run(
["/sbin/ip", "-4", "addr", "show", "docker0"],
capture_output=True,
text=True,
timeout=2,
check=False,
)
for line in result.stdout.splitlines():
if "inet " in line:
parts = line.strip().split()
addr_part = parts[1] # e.g. 172.17.0.1/16
return addr_part.split("/")[0]
except Exception:
logger.debug("Failed to auto-detect docker bridge IP")
return "127.0.0.1"
return OO_GATEWAY
# ---------------------------------------------------------------------------
@@ -271,9 +228,7 @@ def setup_docker(name: str = "onlyoffice-mediapreview") -> str:
# Docker discards published ports on internal networks, so the container
# is reached at its fixed IP; no localhost port is exposed.
logger.info("OnlyOffice is running on http://%s", OO_CONTAINER_IP)
logger.info(
"Callback host for file downloads: %s", _docker_network_gateway(OO_NETWORK)
)
logger.info("Callback host for file downloads: %s", OO_GATEWAY)
return secret
@@ -328,32 +283,65 @@ async def is_available_cached() -> bool:
# ---------------------------------------------------------------------------
class _TempServer(socketserver.TCPServer):
"""TCPServer that logs handler errors instead of dumping tracebacks to stderr."""
daemon_threads = True
oo_fetched: bool
def handle_error(self, request, client_address) -> None: # noqa: ARG002
# Dropped connections (client disconnects mid-request, port scanners)
# are routine noise; socketserver's default prints a full traceback.
logger.debug("Temp file server: error from %s", client_address)
class _QuietHandler(SimpleHTTPRequestHandler):
server: _TempServer
def log_message(self, fmt, *args) -> None:
# Any request logged here means a client (OnlyOffice) connected to
# fetch the file; record it for timeout diagnostics.
self.server.oo_fetched = True
def _get_free_port() -> int:
def _get_free_port(host: str) -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("0.0.0.0", 0)) # noqa: S104
s.bind((host, 0))
return s.getsockname()[1]
def _serve_file_temporarily(file_path: Path):
"""Start a temporary HTTP server for *file_path* and return (url, server)."""
def _serve_file_temporarily(file_path: Path, max_lifetime: float = 60.0):
"""Start a temporary HTTP server for *file_path* and return (url, server).
The server binds only to the callback host address (the docker bridge
gateway by default), not 0.0.0.0, so it is unreachable from the internet.
It shuts itself down shortly after the file has been fetched, or when
*max_lifetime* elapses, so a hung OnlyOffice request cannot leave the
port open indefinitely.
"""
directory = str(file_path.parent)
filename = file_path.name
port = _get_free_port()
host = _get_callback_host()
port = _get_free_port(host)
handler = partial(_QuietHandler, directory=directory)
httpd = socketserver.TCPServer(("0.0.0.0", port), handler) # noqa: S104
httpd = _TempServer((host, port), handler)
httpd.oo_fetched = False
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
thread.start()
host = _get_callback_host()
def _watchdog() -> None:
deadline = perf_counter() + max_lifetime
while perf_counter() < deadline and not httpd.oo_fetched:
threading.Event().wait(0.1)
if httpd.oo_fetched:
# Brief grace so the in-flight response finishes transferring.
threading.Event().wait(2.0)
httpd.shutdown()
httpd.server_close()
threading.Thread(target=_watchdog, daemon=True).start()
url = f"http://{host}:{port}/{quote(filename)}"
return url, httpd
@@ -388,8 +376,12 @@ async def convert_to_png_async(
convert_url = f"{oo_url}/ConvertService.ashx"
client = get_httpx_client()
# Start temporary HTTP server so OnlyOffice can fetch the file
doc_url, httpd = await asyncio.to_thread(_serve_file_temporarily, file_path)
# Start temporary HTTP server so OnlyOffice can fetch the file. The
# watchdog lifetime covers the full conversion plus slack so a hung
# conversion cannot leave the port open forever.
doc_url, httpd = await asyncio.to_thread(
_serve_file_temporarily, file_path, request_timeout + 30.0
)
try:
suffix = file_path.suffix.lstrip(".").lower()
payload = {
@@ -460,6 +452,7 @@ async def convert_to_png_async(
return png_response.content
finally:
await asyncio.to_thread(httpd.shutdown)
await asyncio.to_thread(httpd.server_close)
# ---------------------------------------------------------------------------