From 0795b2d1c9640e1e43163348e7186a7154deab84 Mon Sep 17 00:00:00 2001 From: kmoy007 Date: Sat, 14 Nov 2026 21:11:41 -0800 Subject: [PATCH 1/2] bug-report-py 3.1.0: the proxy's core is bug_report.proxy.forward(), a plain function for apps that are not Flask; the blueprint wraps it Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 12 ++ packages/backend-python/README.md | 20 ++ .../backend-python/bug_report/__init__.py | 4 +- packages/backend-python/bug_report/proxy.py | 170 ++++++++++------ packages/backend-python/pyproject.toml | 2 +- .../tests/test_proxy_forward.py | 192 ++++++++++++++++++ 6 files changed, 331 insertions(+), 69 deletions(-) create mode 100644 packages/backend-python/tests/test_proxy_forward.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 84562d2..b2844c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ All notable changes to this monorepo. +## backends v3.1.0 - 2026-11-15 (`bug-report-py` 3.1.0) + +The proxy's core is a plain function. No contract change. + +- **`bug_report.proxy.forward(method, rest, query, body, browser_headers, *, central_url, app, token_provider, person_provider, timeout=30)`** + returns `(status, body_bytes, headers_dict)` and uses no web framework, so an app on the standard-library `http.server` + (the daily report) can proxy to the central store. It carries every rule `create_proxy_blueprint` had: `..` and `\` are 400; + a list defaults to `app=`; only `Content-Type` and `Accept` come from the browser; the bearer token and `X-Leap-*` headers + are added; a marked trust refusal and a short body are 502; `http.client` with no `Connection: close`; generic 502 bodies; only + the contract's response headers come back. +- `create_proxy_blueprint` is now a thin Flask wrapper over `forward` (Flask is imported inside it). Its behaviour and tests are unchanged. + ## backends v3.0.2 — 2026-11-15 (`bug-report-py` 3.0.2) One fix to `create_proxy_blueprint`, found on the seal viewer's first live day. No contract change. diff --git a/packages/backend-python/README.md b/packages/backend-python/README.md index 2663e36..b1335cb 100644 --- a/packages/backend-python/README.md +++ b/packages/backend-python/README.md @@ -118,6 +118,26 @@ and 401 (sign in to vote) pass through. A list with no `app` query is asked for passes through. A `..` path segment is refused (400). A service that cannot be reached is a 502, and a token or identity that cannot be produced is a 502 with nothing sent; the 502 bodies are generic (the reason goes to the log, not the browser). Standard library only (`http.client`; it never sends `Connection: close`, which Azure Container Apps' internal ingress answers by cutting large responses short). +### Without Flask: `bug_report.proxy.forward` (3.1.0) + +An app that is not Flask (a standard-library `http.server`, say) calls the proxy's core directly. The blueprint above is a +thin wrapper over it, so every rule is the same: + +```python +from bug_report.proxy import forward + +status, body, headers = forward( + method, rest, query, body, browser_headers, # rest: "" | "" | "/vote" | "/screenshot"; query: no "?" + central_url="http://leaphq-reports/api/bugs", app="report", + token_provider=lambda: credential.get_token(SCOPE).token, + person_provider=lambda: {"email": "ann@example.com", "name": "Ann"}, +) +# write `status`, `headers` and `body` back to the browser +``` + +It returns `(status, body_bytes, headers_dict)` and never raises for a service or network problem (those are 502s). The +package still installs Flask as a dependency; `forward` itself imports none of it. + ## The service side: who is calling (3.0.0) ```python diff --git a/packages/backend-python/bug_report/__init__.py b/packages/backend-python/bug_report/__init__.py index 7da6433..f9b631d 100644 --- a/packages/backend-python/bug_report/__init__.py +++ b/packages/backend-python/bug_report/__init__.py @@ -21,7 +21,7 @@ from .blueprint import create_blueprint from .importer import ImportMismatch, import_reports -from .proxy import create_proxy_blueprint +from .proxy import create_proxy_blueprint, forward from .trust import Caller, TrustedCallers, trusted_caller from . import identity from .email import AcsNotifier, Notice, render @@ -44,7 +44,7 @@ valid_bug_id, ) -__version__ = "3.0.1" +__version__ = "3.1.0" from . import contract from .contract import ( diff --git a/packages/backend-python/bug_report/proxy.py b/packages/backend-python/bug_report/proxy.py index 031a46b..3a190b2 100644 --- a/packages/backend-python/bug_report/proxy.py +++ b/packages/backend-python/bug_report/proxy.py @@ -10,6 +10,10 @@ person_provider=person_provider(trust_easyauth=True), ), url_prefix="/api") +The core is ``forward()`` (3.1.0), a plain function with no web framework in it, for an app that +is not Flask - the daily report's standard-library ``http.server`` calls it directly. The blueprint +below is a thin Flask wrapper over it, so the rules live once. + Every route (POST, list, detail, PATCH, vote, screenshot) is forwarded with its method, query, body and content type, and the service's status code, body and content type come back unchanged. Each forwarded request carries @@ -33,11 +37,9 @@ import http.client import json import logging -from typing import Callable +from typing import Callable, Mapping from urllib.parse import quote, urlsplit -from flask import Blueprint, Response, request - from .trust import TRUST_REFUSAL_HEADER log = logging.getLogger(__name__) @@ -47,6 +49,93 @@ _FORWARD = ("Content-Type", "Accept") #: response headers passed back: the contract's, plus the redirect target _BACK = ("Content-Type", "Location", "Cache-Control", "X-Leap-App-Used", "X-Leap-App-Ignored") +#: methods that carry a body to the service +_WITH_BODY = ("POST", "PATCH", "DELETE") + + +def _target(central_url: str): + base = central_url.rstrip("/") + target = urlsplit(base) + if target.scheme not in ("http", "https") or not target.hostname: + raise ValueError(f"central_url must be an http(s) URL: {central_url!r}") + return target + + +def _ascii(v: str) -> str: + return quote(v or "", safe=" @.+-_'") + + +def _err(status: int, message: str) -> tuple[int, bytes, dict]: + return status, json.dumps({"error": message}).encode(), {"Content-Type": "application/json"} + + +def forward( + method: str, + rest: str, + query: str, + body: bytes | None, + browser_headers: Mapping[str, str], + *, + central_url: str, + app: str, + token_provider: Callable[[], str], + person_provider: Callable[[], dict | None], + timeout: float = 30, +) -> tuple[int, bytes, dict]: + """Forward one ``/bugs`` request to the central service; return ``(status, body, headers)``. + + ``rest`` is the path after ``/bugs`` ("" for the collection, "", "/vote", ...), ``query`` + the raw query string without the "?", ``body`` the request body (sent for POST, PATCH and DELETE + only), ``browser_headers`` the browser's request headers (only Content-Type and Accept are taken, + any case). Never raises for a service or network problem: those are 502s. + """ + target = _target(central_url) + method = method.upper() + if any(seg in ("..", ".") or "\\" in seg for seg in rest.split("/")): + return _err(400, "invalid path") + path = target.path.rstrip("/") + ("/" + rest if rest else "") + # The list is this app's own reports unless the caller says otherwise (3.0.1): the open count and + # the queue must not show every app's, which is what the service gives a trusted app with no filter. + if method == "GET" and not rest and "app" not in {p.split("=", 1)[0] for p in query.split("&") if p}: + query = (query + "&" if query else "") + "app=" + quote(app, safe="") + if query: + path += "?" + query + try: + person = person_provider() or {} + lowered = {k.lower(): v for k, v in browser_headers.items()} + headers = {h: lowered[h.lower()] for h in _FORWARD if h.lower() in lowered} + headers.update({ + "Authorization": f"Bearer {token_provider()}", + "X-Leap-Actor-Email": _ascii(person.get("email", "")), + "X-Leap-Actor-Name": _ascii(person.get("name", "")), + "X-Leap-App": app, + }) + except Exception as e: # noqa: BLE001 - no token / identity: say so, do not guess + log.warning("reports proxy (%s): could not get a token or identity: %s", app, e) + return _err(502, "could not authenticate to the reports service") + data = body if method in _WITH_BODY else None + connection = http.client.HTTPSConnection if target.scheme == "https" else http.client.HTTPConnection + conn = connection(target.hostname, target.port, timeout=timeout) + try: + # Any status - 3xx (a signed screenshot URL goes back as it is), 4xx, 5xx - is the service's answer. + conn.request(method, path, body=data, headers=headers) + r = conn.getresponse() + status, payload, upstream = r.status, r.read(), r.headers + except http.client.IncompleteRead as e: + log.warning("reports proxy (%s): %s came back short: %d bytes, %s more expected", + app, path, len(e.partial), e.expected) + return _err(502, "the reports service's answer came back incomplete") + except (http.client.HTTPException, OSError, TimeoutError) as e: + log.warning("reports proxy (%s): %s unreachable: %s", app, path, e) + return _err(502, "the reports service is not reachable") + finally: + conn.close() + if status in (401, 403) and upstream.get(TRUST_REFUSAL_HEADER): + # The service refused THIS APP (a setup mistake), not the person. A 401 here would read, to a + # client that treats 401 as "your sign-in failed" (a seal laptop's outbox), as the person's. + log.warning("reports proxy (%s): the service refused this app: %s %s", app, status, payload[:300]) + return _err(502, "the reports service refused this app") + return status, payload, {h: upstream[h] for h in _BACK if upstream.get(h) is not None} def create_proxy_blueprint( @@ -57,73 +146,22 @@ def create_proxy_blueprint( *, url_prefix: str = "/bugs", timeout: float = 30, -) -> Blueprint: - bp = Blueprint(f"bug_report_proxy_{app}", __name__) - base = central_url.rstrip("/") - target = urlsplit(base) - if target.scheme not in ("http", "https") or not target.hostname: - raise ValueError(f"central_url must be an http(s) URL: {central_url!r}") - connection = http.client.HTTPSConnection if target.scheme == "https" else http.client.HTTPConnection +): + from flask import Blueprint, Response, request - def _ascii(v: str) -> str: - return quote(v or "", safe=" @.+-_'") + _target(central_url) # a bad URL fails at start-up, not on the first report + bp = Blueprint(f"bug_report_proxy_{app}", __name__) @bp.route(url_prefix, defaults={"rest": ""}, methods=["GET", "POST", "PATCH", "DELETE"]) @bp.route(f"{url_prefix}/", methods=["GET", "POST", "PATCH", "DELETE"]) - def forward(rest: str): - if any(seg in ("..", ".") or "\\" in seg for seg in rest.split("/")): - return _err(400, "invalid path") - path = target.path + ("/" + rest if rest else "") - query = request.query_string.decode("latin-1") - # The list is this app's own reports unless the caller says otherwise (3.0.1): the open count and - # the queue must not show every app's, which is what the service gives a trusted app with no filter. - if request.method == "GET" and not rest and "app" not in request.args: - query = (query + "&" if query else "") + "app=" + quote(app, safe="") - if query: - path += "?" + query - try: - person = person_provider() or {} - headers = {h: request.headers[h] for h in _FORWARD if h in request.headers} - headers.update({ - "Authorization": f"Bearer {token_provider()}", - "X-Leap-Actor-Email": _ascii(person.get("email", "")), - "X-Leap-Actor-Name": _ascii(person.get("name", "")), - "X-Leap-App": app, - }) - except Exception as e: # noqa: BLE001 — no token / identity: say so, do not guess - log.warning("reports proxy (%s): could not get a token or identity: %s", app, e) - return _err(502, "could not authenticate to the reports service") - data = request.get_data() if request.method in ("POST", "PATCH", "DELETE") else None - conn = connection(target.hostname, target.port, timeout=timeout) - try: - # Any status - 3xx (a signed screenshot URL goes back as it is), 4xx, 5xx - is the service's answer. - conn.request(request.method, path, body=data, headers=headers) - r = conn.getresponse() - return _relay(r.status, r.read(), r.headers) - except http.client.IncompleteRead as e: - log.warning("reports proxy (%s): %s came back short: %d bytes, %s more expected", - app, path, len(e.partial), e.expected) - return _err(502, "the reports service's answer came back incomplete") - except (http.client.HTTPException, OSError, TimeoutError) as e: - log.warning("reports proxy (%s): %s unreachable: %s", app, path, e) - return _err(502, "the reports service is not reachable") - finally: - conn.close() - - def _relay(status, body, upstream_headers): - if status in (401, 403) and upstream_headers.get(TRUST_REFUSAL_HEADER): - # The service refused THIS APP (a setup mistake), not the person. A 401 here would read, to a - # client that treats 401 as "your sign-in failed" (a seal laptop's outbox), as the person's. - log.warning("reports proxy (%s): the service refused this app: %s %s", app, status, body[:300]) - return _err(502, "the reports service refused this app") - resp = Response(body, status=status) - for h in _BACK: - v = upstream_headers.get(h) - if v is not None: - resp.headers[h] = v + def _forward(rest: str): + status, payload, headers = forward( + request.method, rest, request.query_string.decode("latin-1"), request.get_data(), + request.headers, central_url=central_url, app=app, token_provider=token_provider, + person_provider=person_provider, timeout=timeout) + resp = Response(payload, status=status) + for k, v in headers.items(): + resp.headers[k] = v return resp - def _err(status, message): - return Response(json.dumps({"error": message}), status=status, mimetype="application/json") - return bp diff --git a/packages/backend-python/pyproject.toml b/packages/backend-python/pyproject.toml index 796dc58..7862339 100644 --- a/packages/backend-python/pyproject.toml +++ b/packages/backend-python/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "bug-report-py" -version = "3.0.2" +version = "3.1.0" description = "Flask blueprint + storage interface implementing the bug-report-widget API spec." readme = "README.md" license = { text = "MIT" } diff --git a/packages/backend-python/tests/test_proxy_forward.py b/packages/backend-python/tests/test_proxy_forward.py new file mode 100644 index 0000000..9ce5524 --- /dev/null +++ b/packages/backend-python/tests/test_proxy_forward.py @@ -0,0 +1,192 @@ +"""bug_report.proxy.forward(): the framework-free core (3.1.0), called directly against a real central +blueprint served over HTTP. No Flask on the calling side: this is how a standard-library app uses it.""" +from __future__ import annotations + +import base64 +import json +import socket +import threading + +from bug_report.proxy import forward + +from test_proxy import JPEG, Serving, central # noqa: F401 (central is a fixture) + + +class Caller: + def __init__(self, central_url, app="placements"): + self.url = central_url + "/bugs" + self.app = app + self.token = "ok:client-placements" + self.person = {"email": "admin@example.com", "name": "Ann Admin"} + + def __call__(self, method, rest="", query="", body=None, headers=None): + return forward(method, rest, query, body, headers or {}, central_url=self.url, app=self.app, + token_provider=lambda: self.token, person_provider=lambda: self.person) + + def file(self, **kw): + status, body, _ = self("POST", body=json.dumps({"details": "it broke", **kw}).encode(), + headers={"content-type": "application/json"}) + assert status == 201, body + return json.loads(body)["id"] + + +def test_every_route_returns_status_body_and_headers(central): + c = Caller(central[0].url) + bid = c.file(screenshot=base64.b64encode(JPEG).decode(), tags=["feature"]) + status, body, h = c("GET", query="days=1&kind=feature&app=placements") + assert status == 200 and h["Content-Type"] == "application/json" + assert [b["id"] for b in json.loads(body)["bugs"]] == [bid] + assert json.loads(c("GET", bid)[1])["app"] == "placements" + status, body, _ = c("PATCH", bid, body=b'{"status": "triaged", "area": "Belt"}', + headers={"Content-Type": "application/json"}) + assert status == 200 and json.loads(body)["area"] == "Belt" + assert json.loads(c("POST", f"{bid}/vote")[1]) == {"votes": 1, "voted": True} + assert json.loads(c("DELETE", f"{bid}/vote")[1]) == {"votes": 0, "voted": False} + status, body, h = c("GET", f"{bid}/screenshot") + assert (status, h["Content-Type"], body) == (200, "image/jpeg", JPEG) + assert c("GET", "bug-20200101-000000-aaaaaa")[0] == 404 + assert c("GET", "junk")[0] == 400 + + +def test_the_service_sees_the_token_the_actor_and_the_app_and_only_two_browser_headers(central): + _, store, seen = central + c = Caller(central[0].url) + status, body, _ = c("POST", body=b'{"details": "x", "app": "leaphq"}', + headers={"content-type": "application/json", "ACCEPT": "application/json", + "Authorization": "Bearer browser-claim", "X-Leap-Actor-Email": "liar@example.com", + "X-Leap-App": "leaphq", "Cookie": "session=1"}) + assert status == 201 + h = seen[-1] + assert h["Authorization"] == "Bearer ok:client-placements" + assert (h["X-Leap-Actor-Email"], h["X-Leap-Actor-Name"], h["X-Leap-App"]) == ("admin@example.com", "Ann Admin", "placements") + assert "Cookie" not in h and h["Accept"] == "application/json" + rec = store.get_bug(json.loads(body)["id"]) + assert (rec.app, rec.actor_email) == ("placements", "admin@example.com") + + +def test_an_accented_name_is_percent_encoded_and_survives(central): + _, store, _ = central + c = Caller(central[0].url) + c.person = {"email": "sean@example.com", "name": "Seán Ó Briain"} + assert store.get_bug(c.file()).actor_name == "Seán Ó Briain" + + +def test_a_list_is_this_apps_own_unless_it_names_an_app(central): + s, _, _ = central + mine = Caller(s.url, "sealviewer") + mine.token = "ok:client-seal" + theirs = Caller(s.url) + a, b = mine.file(), theirs.file() + ids = lambda r: [x["id"] for x in json.loads(r[1])["bugs"]] # noqa: E731 + assert ids(mine("GET", query="status=open&days=365")) == [a] + assert ids(mine("GET")) == [a] + assert ids(mine("GET", query="app=placements")) == [b] + + +def test_dot_dot_dot_and_backslash_are_400_and_never_sent(central): + _, _, seen = central + c = Caller(central[0].url) + n = len(seen) + for rest in ("../admin", "x/../../y", "./x", "x\\y", "a/..\\b"): + assert c("GET", rest)[0] == 400, rest + assert c("GET", "..")[1] == b'{"error": "invalid path"}' + assert len(seen) == n + + +def test_a_refusal_of_the_app_is_a_502_with_a_generic_body_and_the_real_one_is_logged(central, caplog): + c = Caller(central[0].url) + c.token = "ok:client-stranger" + with caplog.at_level("WARNING"): + status, body, _ = c("GET") + assert status == 502 and json.loads(body) == {"error": "the reports service refused this app"} + assert "caller is not a trusted app" in caplog.text and "caller is not a trusted app" not in body.decode() + c.token = "forged" + assert c("POST", body=b'{"details": "x"}')[0] == 502 + + +def test_a_persons_403_and_401_pass_through(central): + c = Caller(central[0].url) + bid = c.file() + c.person = {"email": "someone@example.com", "name": ""} + assert c("GET")[0] == 403 + c.person = {"email": "", "name": ""} + assert c("POST", f"{bid}/vote")[0] == 401 + + +def test_a_token_or_identity_that_fails_is_a_502_and_nothing_is_sent(central): + _, _, seen = central + def boom(): + raise RuntimeError("no managed identity here") + for kw in ({"token_provider": boom, "person_provider": lambda: {}}, + {"token_provider": lambda: "ok:client-placements", "person_provider": boom}): + status, body, _ = forward("POST", "", "", b"{}", {}, central_url=central[0].url + "/bugs", app="placements", **kw) + assert status == 502 and json.loads(body) == {"error": "could not authenticate to the reports service"} + assert b"managed identity" not in body + assert seen == [] + + +def test_a_service_that_is_down_is_a_502_with_no_host_in_it(): + status, body, _ = forward("GET", "", "", None, {}, central_url="http://127.0.0.1:9/bugs", app="a", + token_provider=lambda: "t", person_provider=lambda: {}) + assert status == 502 and json.loads(body) == {"error": "the reports service is not reachable"} + + +def test_the_request_never_says_connection_close(central): + _, _, seen = central + c = Caller(central[0].url) + c.file() + c("GET") + assert seen and all(h.get("Connection", "").lower() != "close" for h in seen) + + +def test_a_short_body_is_a_502(): + lsock = socket.socket() + lsock.bind(("127.0.0.1", 0)) + lsock.listen(1) + + def serve_short(): + conn, _ = lsock.accept() + conn.recv(65536) + conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: 100000\r\n\r\n" + b"x" * 1000) + conn.close() + + t = threading.Thread(target=serve_short, daemon=True) + t.start() + status, body, _ = forward("GET", "x/screenshot", "", None, {}, central_url=f"http://127.0.0.1:{lsock.getsockname()[1]}/bugs", + app="a", token_provider=lambda: "t", person_provider=lambda: {}) + t.join(3) + lsock.close() + assert status == 502 and "incomplete" in json.loads(body)["error"] + + +def test_only_the_back_headers_come_back_and_a_redirect_is_not_followed(): + from flask import Flask, redirect + other = Flask(__name__) + + @other.route("/bugs//screenshot") + def shot(i): + r = redirect("https://blob.example/signed?sig=1", 302) + r.headers["Set-Cookie"] = "s=1" + r.headers["X-Secret"] = "no" + return r + + s = Serving(other) + try: + status, _, h = forward("GET", "bug-20261101-100000-aaaaaa/screenshot", "", None, {}, central_url=s.url + "/bugs", + app="a", token_provider=lambda: "t", person_provider=lambda: {}) + assert status == 302 and h["Location"] == "https://blob.example/signed?sig=1" + assert set(h) <= {"Content-Type", "Location", "Cache-Control", "X-Leap-App-Used", "X-Leap-App-Ignored"} + finally: + s.stop() + + +def test_the_app_the_service_used_comes_back_in_the_headers(central): + c = Caller(central[0].url, "leaphq") # claims leaphq with the placements token + status, _, h = c("POST", body=b'{"details": "x"}', headers={"Content-Type": "application/json"}) + assert status == 201 and h["X-Leap-App-Used"] == "placements" and h["X-Leap-App-Ignored"] == "leaphq" + + +def test_a_bad_central_url_raises(): + import pytest + with pytest.raises(ValueError): + forward("GET", "", "", None, {}, central_url="ftp://x", app="a", token_provider=lambda: "t", person_provider=lambda: {}) From 8369a4b4675ae891464bd7cc1e6edceb4b404933 Mon Sep 17 00:00:00 2001 From: kmoy007 Date: Sat, 14 Nov 2026 21:32:50 -0800 Subject: [PATCH 2/2] bug-report-py 3.1.0: forward() decodes rest before refusing .. and \ (%2e%2e, %5c), re-quotes outgoing segments; docs say which forms rest takes Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 1 + docs/CENTRAL-STORE.md | 1 + packages/backend-python/README.md | 2 +- packages/backend-python/bug_report/proxy.py | 14 ++++++--- .../tests/test_proxy_forward.py | 31 +++++++++++++++++++ 5 files changed, 44 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2844c9..7564103 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ The proxy's core is a plain function. No contract change. a list defaults to `app=`; only `Content-Type` and `Accept` come from the browser; the bearer token and `X-Leap-*` headers are added; a marked trust refusal and a short body are 502; `http.client` with no `Connection: close`; generic 502 bodies; only the contract's response headers come back. +- `forward()` takes `rest` raw or decoded: it decodes once before refusing `..` and `\`, so `%2e%2e` and `%5c` are 400 whatever the caller passes, and re-quotes each outgoing segment. - `create_proxy_blueprint` is now a thin Flask wrapper over `forward` (Flask is imported inside it). Its behaviour and tests are unchanged. ## backends v3.0.2 — 2026-11-15 (`bug-report-py` 3.0.2) diff --git a/docs/CENTRAL-STORE.md b/docs/CENTRAL-STORE.md index ea5474e..e50d7e7 100644 --- a/docs/CENTRAL-STORE.md +++ b/docs/CENTRAL-STORE.md @@ -35,6 +35,7 @@ LeapHQ Review ──(LeapHQ's own identity, a token)──► leaphq-reports (on - It is the only place reports are stored, emails are sent and triage rights are checked: one `BUG_ADMINS`, and one sending identity (`leaphq-bug-notify`). - **The apps keep their URL.** Each app's `/api/bugs` becomes `create_proxy_blueprint(central_url, app="placements")` from the library. - It forwards every route (POST, list, detail, PATCH and screenshot) with its body unchanged. + - An app that is not Flask (the daily report's `http.server`) calls the framework-free core, `bug_report.proxy.forward()`, which the blueprint wraps. - The widget, BugQueue and every page that links to a report keep working, with no front-end change. - The app stamps `app`; the caller cannot set it. - **Who is asking.** Every request carries a token: the calling app's **own managed identity** (an Entra token). There is no person path on the service, so a request with no token is 401 and the service never reads `X-Ms-Client-Principal` or Tailscale headers. diff --git a/packages/backend-python/README.md b/packages/backend-python/README.md index b1335cb..d8bda58 100644 --- a/packages/backend-python/README.md +++ b/packages/backend-python/README.md @@ -136,7 +136,7 @@ status, body, headers = forward( ``` It returns `(status, body_bytes, headers_dict)` and never raises for a service or network problem (those are 502s). The -package still installs Flask as a dependency; `forward` itself imports none of it. +package still depends on Flask and `import bug_report` imports it; `forward()` itself uses no Flask. `rest` may be raw from the request line (`a%20b`, `%2e%2e`) or already decoded; it is decoded once and `..`, `.` and `\` segments are refused (400, nothing sent) either way. ## The service side: who is calling (3.0.0) diff --git a/packages/backend-python/bug_report/proxy.py b/packages/backend-python/bug_report/proxy.py index 3a190b2..2608940 100644 --- a/packages/backend-python/bug_report/proxy.py +++ b/packages/backend-python/bug_report/proxy.py @@ -38,7 +38,7 @@ import json import logging from typing import Callable, Mapping -from urllib.parse import quote, urlsplit +from urllib.parse import quote, unquote, urlsplit from .trust import TRUST_REFUSAL_HEADER @@ -84,16 +84,22 @@ def forward( ) -> tuple[int, bytes, dict]: """Forward one ``/bugs`` request to the central service; return ``(status, body, headers)``. - ``rest`` is the path after ``/bugs`` ("" for the collection, "", "/vote", ...), ``query`` + ``rest`` is the path after ``/bugs`` ("" for the collection, "", "/vote", ...), in either form: + raw from the request line (``a%20b``, ``%2e%2e``) or already decoded (Flask's). It is percent-decoded once, + checked for ``..``, ``.`` and ``\\`` segments (400, nothing sent), and each segment re-quoted going out. ``query`` the raw query string without the "?", ``body`` the request body (sent for POST, PATCH and DELETE only), ``browser_headers`` the browser's request headers (only Content-Type and Accept are taken, any case). Never raises for a service or network problem: those are 502s. """ target = _target(central_url) method = method.upper() - if any(seg in ("..", ".") or "\\" in seg for seg in rest.split("/")): + # `rest` may be percent-encoded or already decoded (Flask hands over a decoded one): it is decoded here, once, + # BEFORE the dot-dot and backslash refusal, so `%2e%2e` and `%5c` are refused whichever way the caller got + # it, and each segment is re-quoted for the outgoing path. + segments = unquote(rest).split("/") if rest else [] + if any(seg in ("..", ".") or "\\" in seg for seg in segments): return _err(400, "invalid path") - path = target.path.rstrip("/") + ("/" + rest if rest else "") + path = target.path.rstrip("/") + "".join("/" + quote(seg, safe="") for seg in segments) # The list is this app's own reports unless the caller says otherwise (3.0.1): the open count and # the queue must not show every app's, which is what the service gives a trusted app with no filter. if method == "GET" and not rest and "app" not in {p.split("=", 1)[0] for p in query.split("&") if p}: diff --git a/packages/backend-python/tests/test_proxy_forward.py b/packages/backend-python/tests/test_proxy_forward.py index 9ce5524..df3d86f 100644 --- a/packages/backend-python/tests/test_proxy_forward.py +++ b/packages/backend-python/tests/test_proxy_forward.py @@ -190,3 +190,34 @@ def test_a_bad_central_url_raises(): import pytest with pytest.raises(ValueError): forward("GET", "", "", None, {}, central_url="ftp://x", app="a", token_provider=lambda: "t", person_provider=lambda: {}) + + +def test_percent_encoded_dot_dot_and_backslash_are_400_and_never_sent(central): + _, _, seen = central + c = Caller(central[0].url) + n = len(seen) + for rest in ("%2e%2e", "%2E%2E/x", "x/%2e%2E/y", "%5c", "a%5Cb", "%2e", "a/%2E"): + status, body, _ = c("GET", rest) + assert (status, json.loads(body)) == (400, {"error": "invalid path"}), rest + assert len(seen) == n + + +def test_an_id_with_escapes_round_trips_whether_the_caller_passes_it_raw_or_decoded(): + from flask import Flask, request + other = Flask(__name__) + got = [] + + @other.route("/bugs/") + def echo(rest): + got.append(request.environ["RAW_URI"] if "RAW_URI" in request.environ else request.full_path) + return rest + + s = Serving(other) + try: + for passed in ("a%20b/c", "a b/c"): + status, body, _ = forward("GET", passed, "", None, {}, central_url=s.url + "/bugs", app="a", + token_provider=lambda: "t", person_provider=lambda: {}) + assert (status, body) == (200, b"a b/c"), passed + assert all("a%20b/c" in g for g in got), got + finally: + s.stop()