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
3 changes: 3 additions & 0 deletions embodichain/gen_sim/services/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ budget and adapter options. Fields can use `{"env": "NAME"}`; `api_key_env` is
shorthand for an API-key reference. Only references are resolved: process values
win over the selected dotenv (`EMBODICHAIN_ENV_FILE` or the default GenSim `.env`).
Unrelated `OPENAI_*` values never fill missing fields in an explicit profile.
HTTP profile API keys are sent only to the configured origin (scheme, host and
port). External mesh URLs and redirects to another origin receive no profile
Authorization header.
Unused roles require no credentials, connection or health check. The example's
optional job-control profile is only needed when using Gradio's remote panel.
An OpenAI-compatible profile may omit its API key for a trusted local endpoint.
Expand Down
56 changes: 56 additions & 0 deletions embodichain/gen_sim/services/adapters/_http.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# ----------------------------------------------------------------------------
# Copyright (c) 2021-2026 DexForce Technology Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------

"""Keep profile credentials on their configured HTTP origin."""

from __future__ import annotations

from urllib.parse import urlsplit
import requests

__all__: list[str] = []


def _origin(url: str) -> tuple[str, str | None, int | None]:
parts = urlsplit(url)
port = parts.port
if port is None:
port = {"https": 443, "http": 80}.get(parts.scheme)
return parts.scheme, parts.hostname, port


class _OriginBoundSession(requests.Session):
def __init__(self, base_url: str, api_key: str) -> None:
super().__init__()
self._service_origin = _origin(base_url)
self._authorization = f"Bearer {api_key}"

def prepare_request(self, request: requests.Request) -> requests.PreparedRequest:
prepared = super().prepare_request(request)
if _origin(prepared.url) == self._service_origin:
prepared.headers["Authorization"] = self._authorization
else:
prepared.headers.pop("Authorization", None)
return prepared

def rebuild_auth(
self, prepared_request: requests.PreparedRequest, response: requests.Response
) -> None:
super().rebuild_auth(prepared_request, response)
# Requests permits HTTP-to-HTTPS auth forwarding on the same host;
# profile credentials remain restricted to the exact configured origin.
if _origin(prepared_request.url) != self._service_origin:
prepared_request.headers.pop("Authorization", None)
5 changes: 2 additions & 3 deletions embodichain/gen_sim/services/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,9 @@ def _http_adapter(role: str, profile: Mapping[str, Any]) -> Any:
kwargs.update(options)
api_key = profile.get("api_key")
if api_key:
import requests
from .adapters._http import _OriginBoundSession

session = requests.Session()
session.headers["Authorization"] = f"Bearer {api_key}"
session = _OriginBoundSession(profile["base_url"], api_key)
kwargs["session"] = session
try:
return cls(**kwargs)
Expand Down
60 changes: 60 additions & 0 deletions tests/gen_sim/services/test_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -1024,3 +1024,63 @@ def test_invalid_default_user_file_is_not_ignored(tmp_path, monkeypatch):
p.write_text("{}")
with pytest.raises(ServiceConfigurationError):
load_services_config()


@pytest.mark.parametrize(
"mesh_url,redirect,authorized",
[
("/mesh.glb", None, [True]),
("http://service.test:80/mesh.glb", None, [True]),
("http://files.test/mesh.glb", None, [False]),
("http://service.test:8080/mesh.glb", None, [False]),
("/mesh.glb", "http://files.test/mesh.glb", [True, False]),
("/mesh.glb", "https://service.test/mesh.glb", [True, False]),
("/mesh.glb", "/download.glb", [True, True]),
],
)
def test_geometry_download_keeps_profile_key_on_service_origin(
tmp_path, mesh_url, redirect, authorized
):
import io
import requests
from embodichain.gen_sim.services.runtime import _http_adapter

observed = []

class Transport(requests.adapters.BaseAdapter):
def send(self, request, **kwargs):
observed.append(request.headers.get("Authorization"))
response = requests.Response()
response.status_code = 302 if redirect and len(observed) == 1 else 200
if response.status_code == 302:
response.headers["Location"] = redirect
response._content = b"glTFtest"
response.raw = io.BytesIO(response._content)
response.url, response.request = request.url, request
return response

def close(self):
pass

client = _http_adapter(
"geometry_reconstruction",
{
"base_url": "http://service.test",
"api_key": "test-service-token",
"timeout_s": 1,
"max_attempts": 1,
"options": {"health_path": "/health", "generate_objects_path": "/objects"},
},
)
client._session.trust_env = False
transport = Transport()
client._session.mount("http://", transport)
client._session.mount("https://", transport)
try:
client._download_glb(mesh_url, tmp_path / "mesh.glb")
assert observed == [
"Bearer test-service-token" if value else None for value in authorized
]
assert (tmp_path / "mesh.glb").read_bytes() == b"glTFtest"
finally:
client.close()
Loading