diff --git a/src/stac_auth_proxy/middleware/ProcessLinksMiddleware.py b/src/stac_auth_proxy/middleware/ProcessLinksMiddleware.py index 9712b045..ac385bd0 100644 --- a/src/stac_auth_proxy/middleware/ProcessLinksMiddleware.py +++ b/src/stac_auth_proxy/middleware/ProcessLinksMiddleware.py @@ -53,9 +53,12 @@ def transform_json(self, data: dict[str, Any], request: Request) -> dict[str, An continue # Remove the upstream_url path from the link if it exists - if urlparse(self.upstream_url).path != "/": + parsed_upstream_url = urlparse(self.upstream_url) + if parsed_upstream_url.path != "/" and parsed_link.path.startswith( + parsed_upstream_url.path + ): parsed_link = parsed_link._replace( - path=parsed_link.path[len(urlparse(self.upstream_url).path) :] + path=parsed_link.path[len(parsed_upstream_url.path) :] ) # Add the root_path to the link if it exists diff --git a/tests/test_process_links.py b/tests/test_process_links.py index ff382093..43752b4d 100644 --- a/tests/test_process_links.py +++ b/tests/test_process_links.py @@ -186,3 +186,19 @@ def test_transform_json_nested_links(middleware, request_scope): transformed["collections"][0]["links"][1]["href"] == "http://proxy.example.com/proxy/collections/test-collection/items" ) + + +def test_transform_without_prefix(request_scope): + """Sometimes the upstream url will have a path, but the links won't.""" + middleware = ProcessLinksMiddleware( + app=None, upstream_url="http://upstream.example.com/prod/", root_path="" + ) + request = Request(request_scope) + + data = { + "links": [ + {"rel": "data", "href": "http://proxy.example.com/collections"}, + ] + } + transformed = middleware.transform_json(data, request) + assert transformed["links"][0]["href"] == "http://proxy.example.com/collections"