Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(marketplace): an https-only download stays https-only past the redirect
Harald3416c3d5892c
diff --git a/jarvis/core/http_guard.py b/jarvis/core/http_guard.pynew file mode 100644index 0000000000..bb49250004--- /dev/null+++ b/jarvis/core/http_guard.py@@ -0,0 +1,70 @@+"""Keep an https-only download https-only, redirect after redirect.++Several places fetch a URL that came from the community registry: the index+itself, a skill's ``SKILL.md``, a wallpaper's bytes, a plugin's files. Each of+them checks the URL is ``https://`` before fetching, and each says why in a+comment — the fetch runs on the user's machine, so a plaintext or internal+address would let a published entry aim the backend at the loopback API, the+router's admin page, or a cloud metadata endpoint.++That check covers the FIRST url only. With ``follow_redirects=True`` the+server on the other end picks the next one, and a publisher who controls+``https://their-host/skill.md`` controls its ``Location`` header too. So the+guard has to travel with the request rather than stand in front of it.++Usage — one keyword argument on the client::++ async with httpx.AsyncClient(follow_redirects=True, **https_only_async()) as c:+ resp = await c.get(url)++ with httpx.Client(follow_redirects=True, **https_only()) as c:+ resp = c.get(url)++A redirect to anything but https raises :class:`InsecureRedirect`, which is an+``httpx.HTTPError`` — the exception every one of these call sites already+handles as "the download failed".+"""++from __future__ import annotations++from typing import Any++import httpx++__all__ = ["InsecureRedirect", "https_only", "https_only_async"]+++class InsecureRedirect(httpx.HTTPError):+ """A redirect tried to leave https.++ Subclasses ``httpx.HTTPError`` on purpose: every download this guards is+ already wrapped in ``except httpx.HTTPError``, so a refused redirect+ surfaces as the ordinary "could not fetch" the caller knows how to report.+ """+++def _check(response: httpx.Response) -> None:+ if not response.has_redirect_location:+ return+ location = response.headers.get("location")+ if not location:+ return+ # Resolved against the current URL: a relative Location keeps the scheme it+ # already had, and only an absolute one can change it.+ target = response.url.join(location)+ if target.scheme != "https":+ raise InsecureRedirect(f"refusing a non-https redirect from {response.url} to {target}")+++async def _check_async(response: httpx.Response) -> None:+ _check(response)+++def https_only() -> dict[str, Any]:+ """Client kwargs that refuse any redirect leaving https (sync client)."""+ return {"event_hooks": {"response": [_check]}}+++def https_only_async() -> dict[str, Any]:+ """The same, for ``httpx.AsyncClient`` — its hooks must be awaitable."""+ return {"event_hooks": {"response": [_check_async]}}diff --git a/jarvis/marketplace/community_source.py b/jarvis/marketplace/community_source.pyindex 713923baf1..1e8167d003 100644--- a/jarvis/marketplace/community_source.py+++ b/jarvis/marketplace/community_source.py@@ -24,6 +24,8 @@ from typing import Anyimport httpxfrom pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator+from jarvis.core.http_guard import https_only_async+logger = logging.getLogger(__name__)# Repo-root data/ — same resolution as jarvis/marketplace/catalog_data.py.@@ -316,8 +318,13 @@ async def get_index(return hit[1], "fresh"try:+ # The index URL is configuration, but its redirects are not: the+ # host on the other end picks them, so the chain stays on https.async with httpx.AsyncClient(- timeout=_FETCH_TIMEOUT, follow_redirects=True, transport=transport+ timeout=_FETCH_TIMEOUT,+ follow_redirects=True,+ transport=transport,+ **https_only_async(),) as client:response = await client.get(url)response.raise_for_status()diff --git a/jarvis/skills/finder.py b/jarvis/skills/finder.pyindex 8581817234..dc651461fa 100644--- a/jarvis/skills/finder.py+++ b/jarvis/skills/finder.py@@ -439,9 +439,16 @@ class SkillFinder:# httpx is in the runtime deps (mcp_routes etc.)import httpx+ from jarvis.core.http_guard import https_only_async++ # The https check above covers the URL the index gave us. The guard+ # covers every url after it: a publisher who controls the host also+ # controls its Location header, and one 302 would otherwise put this+ # download back on the loopback API or a metadata endpoint.async with httpx.AsyncClient(follow_redirects=True,timeout=httpx.Timeout(15.0),+ **https_only_async(),) as client:try:resp = await client.get(candidate.raw_url)diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.pyindex badd4956d3..b8db99f70c 100644--- a/jarvis/ui/web/marketplace_routes.py+++ b/jarvis/ui/web/marketplace_routes.py@@ -42,6 +42,7 @@ from fastapi.responses import HTMLResponsefrom pydantic import BaseModel, Fieldfrom jarvis.core.events import MarketplaceItemInstalled+from jarvis.core.http_guard import InsecureRedirect, https_only_asyncfrom jarvis.core.process_utils import resolve_executablefrom jarvis.core.uploads import UploadRejected, stage_uploadfrom jarvis.marketplace.auth import (@@ -946,6 +947,7 @@ async def _download_text(raw_url: str, *, transport: Any = None) -> tuple[str, bfollow_redirects=True,timeout=httpx.Timeout(connect=5.0, read=20.0, write=20.0, pool=20.0),transport=transport,+ **https_only_async(),) as client:try:async with client.stream("GET", raw_url) as resp:@@ -1221,7 +1223,9 @@ async def _download_image(Streamed rather than read whole so an oversized (or endless) body is cutoff mid-flight instead of being absorbed first. The redirect chain isre-checked: the index validator only sees the URL it was given, and a- 302 to plain http would put the server back on an SSRF path.+ 302 to plain http would put the server back on an SSRF path. The guard+ refuses that hop BEFORE it is made; the scheme check below stays as the+ second pair of eyes on where the chain actually ended up.``transport`` is the injection point tests use (same shape as``community_source.get_index``); production passes nothing.@@ -1230,6 +1234,7 @@ async def _download_image(follow_redirects=True,timeout=httpx.Timeout(connect=5.0, read=20.0, write=20.0, pool=20.0),transport=transport,+ **https_only_async(),) as client:try:async with client.stream("GET", raw_url) as resp:@@ -1252,6 +1257,11 @@ async def _download_image(),)chunks.append(chunk)+ except InsecureRedirect as exc:+ # Not a 502: the registry entry itself is what is wrong, and+ # saying "the other end failed" would send the reader looking for+ # a network problem that does not exist.+ raise HTTPException(status_code=400, detail=str(exc)) from excexcept httpx.HTTPError as exc:raise HTTPException(status_code=502, detail=f"download from {raw_url} failed: {exc}"diff --git a/tests/unit/core/test_http_guard.py b/tests/unit/core/test_http_guard.pynew file mode 100644index 0000000000..2672c3df54--- /dev/null+++ b/tests/unit/core/test_http_guard.py@@ -0,0 +1,77 @@+"""The https-only redirect guard.++The registry is auto-merged, so a published entry's URL is attacker-chosen and+so is the ``Location`` header of the host it points at. Checking the first URL+is https — which every one of these call sites does — proves nothing about the+second one.+"""++from __future__ import annotations++import httpx+import pytest++from jarvis.core.http_guard import InsecureRedirect, https_only, https_only_async+++def _redirecting(target: str) -> httpx.MockTransport:+ """https://start.example redirects once, to ``target``."""++ def handler(request: httpx.Request) -> httpx.Response:+ if str(request.url) == "https://start.example/skill.md":+ return httpx.Response(302, headers={"location": target})+ return httpx.Response(200, text="landed")++ return httpx.MockTransport(handler)+++ "target",+ [+ "http://127.0.0.1:8765/api/anything", # the user's own Jarvis+ "http://169.254.169.254/latest/meta-data/", # cloud metadata+ "http://192.168.1.1/admin", # the router on the LAN+ ],+)+async def test_redirect_off_https_is_refused(target: str) -> None:+ async with httpx.AsyncClient(+ transport=_redirecting(target), follow_redirects=True, **https_only_async()+ ) as client:+ with pytest.raises(InsecureRedirect):+ await client.get("https://start.example/skill.md")+++async def test_refusal_is_an_http_error() -> None:+ """Every caller already handles httpx.HTTPError as "the download failed"."""+ async with httpx.AsyncClient(+ transport=_redirecting("http://127.0.0.1:8765/"),+ follow_redirects=True,+ **https_only_async(),+ ) as client:+ with pytest.raises(httpx.HTTPError):+ await client.get("https://start.example/skill.md")+++async def test_https_redirect_still_follows() -> None:+ """A CDN moving a file is the normal case and must keep working."""+ async with httpx.AsyncClient(+ transport=_redirecting("https://cdn.example/skill.md"),+ follow_redirects=True,+ **https_only_async(),+ ) as client:+ resp = await client.get("https://start.example/skill.md")+ assert resp.status_code == 200+ assert resp.text == "landed"+++def test_sync_client_guard_refuses_too() -> None:+ with httpx.Client(+ transport=_redirecting("http://127.0.0.1:8765/"),+ follow_redirects=True,+ **https_only(),+ ) as client:+ with pytest.raises(InsecureRedirect):+ client.get("https://start.example/skill.md")