Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(server): add operator-defined upstreams with credential and egress controls (#431)

Krisztian Gajdarfe22241111ea
diff --git a/packages/sie_server/src/sie_server/app/app_factory.py b/packages/sie_server/src/sie_server/app/app_factory.py
index a1d0ef0b8..4a8891965 100644
--- a/packages/sie_server/src/sie_server/app/app_factory.py
+++ b/packages/sie_server/src/sie_server/app/app_factory.py
@@ -25,6 +25,7 @@ from sie_server.api.ws import init_server_start_time
from sie_server.api.ws import router as ws_router
from sie_server.app.app_state_config import AppStateConfig
from sie_server.config.engine import EngineConfig
+from sie_server.config.upstreams import load_upstreams
from sie_server.core.memory import MemoryConfig
from sie_server.core.readiness import mark_not_ready, mark_ready, register_liveness_probe
from sie_server.core.registry import ModelRegistry
@@ -85,6 +86,8 @@ class AppFactory:
# Add graceful shutdown middleware (for spot instance preemption)
app.add_middleware(ShutdownMiddleware, shutdown_state=shutdown_state)
+ app.state.upstreams = load_upstreams(config.upstreams_file) if config.upstreams_file else {}
+
# Setup OpenTelemetry tracing (no-op unless the flag and endpoint are set)
setup_tracing(app)
setup_worker_telemetry()
diff --git a/packages/sie_server/src/sie_server/app/app_state_config.py b/packages/sie_server/src/sie_server/app/app_state_config.py
index 52deaf472..c0859ae9d 100644
--- a/packages/sie_server/src/sie_server/app/app_state_config.py
+++ b/packages/sie_server/src/sie_server/app/app_state_config.py
@@ -4,6 +4,8 @@ import os
from dataclasses import dataclass
from pathlib import Path
+from sie_server.config.upstreams import UPSTREAMS_FILE_ENV
+
# Environment variable names for configuration
ENV_DEVICE = "SIE_DEVICE"
ENV_DEVICES = "SIE_DEVICES"
@@ -12,6 +14,7 @@ ENV_MODEL_FILTER = "SIE_MODEL_FILTER"
ENV_PRELOAD_MODELS = "SIE_PRELOAD_MODELS"
ENV_PINNED_MODELS = "SIE_PINNED_MODELS"
ENV_POOL = "SIE_POOL"
+ENV_UPSTREAMS_FILE = UPSTREAMS_FILE_ENV
@dataclass
@@ -43,6 +46,9 @@ class AppStateConfig:
pool_name: str | None = None
"""Optional worker pool identity used by ModelRegistry pool-isolation checks."""
+ upstreams_file: str | None = None
+ """Optional YAML file of operator-defined upstreams for remote profiles."""
+
def __post_init__(self) -> None:
"""Keep scalar and concrete device settings in the same device family."""
if not self.devices:
@@ -107,6 +113,11 @@ class AppStateConfig:
elif ENV_POOL in os.environ:
del os.environ[ENV_POOL]
+ if self.upstreams_file:
+ os.environ[ENV_UPSTREAMS_FILE] = self.upstreams_file
+ elif ENV_UPSTREAMS_FILE in os.environ:
+ del os.environ[ENV_UPSTREAMS_FILE]
+
@classmethod
def from_env_vars(cls) -> AppStateConfig:
"""Deserialize configuration from environment variables."""
@@ -124,6 +135,7 @@ class AppStateConfig:
pinned_str = os.environ.get(ENV_PINNED_MODELS)
pinned_models = [m.strip() for m in pinned_str.split(",") if m.strip()] if pinned_str else None
pool_name = os.environ.get(ENV_POOL) or None
+ upstreams_file = os.environ.get(ENV_UPSTREAMS_FILE) or None
return cls(
models_dir=models_dir,
@@ -133,4 +145,5 @@ class AppStateConfig:
preload_models=preload_models,
pinned_models=pinned_models,
pool_name=pool_name,
+ upstreams_file=upstreams_file,
)
diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.py
index f452b7303..f23100839 100644
--- a/packages/sie_server/src/sie_server/cli.py
+++ b/packages/sie_server/src/sie_server/cli.py
@@ -51,6 +51,7 @@ from sie_server.app.app_state_config import (
AppStateConfig,
)
from sie_server.config.model import ModelConfig
+from sie_server.config.upstreams import UPSTREAMS_FILE_ENV, UpstreamConfigError, load_upstreams
from sie_server.core.deps import collect_bundle_deps
from sie_server.core.loader import load_model_configs
from sie_server.core.logging import configure_logging, is_valid_log_level, valid_log_levels
@@ -350,6 +351,14 @@ def serve(
] = "info",
preload: str | None = typer.Option(None, "--preload", help="Comma-separated model names to preload at startup"),
json_logs: bool = typer.Option(False, "--json-logs", help="Enable structured JSON logging (for Loki)"),
+ upstreams_file: Annotated[
+ str | None,
+ typer.Option(
+ "--upstreams-file",
+ envvar=UPSTREAMS_FILE_ENV,
+ help="YAML file of upstreams for remote profiles. Credentials are named environment variables.",
+ ),
+ ] = None,
) -> None:
"""Start the SIE inference server."""
from sie_sdk.storage import is_cloud_path
@@ -646,6 +655,21 @@ def serve(
raise typer.Exit(1)
typer.echo(f"Pinned (from env): {len(pinned_models)} models will be kept resident")
+ if upstreams_file:
+ # Same split as --log-level: a typed flag fails fast, a value from the
+ # environment (Helm) warns and loads no upstream rather than crash-loop.
+ # With no upstream loaded, nothing is sent outside this deployment.
+ try:
+ upstreams = load_upstreams(upstreams_file)
+ except UpstreamConfigError as exc:
+ if _came_from_command_line("upstreams_file"):
+ typer.echo(f"Error: {exc}", err=True)
+ raise typer.Exit(1) from None
+ typer.echo(f"Warning: {exc}. No upstream is loaded.", err=True)
+ upstreams_file = None
+ else:
+ typer.echo(f"Upstreams: {', '.join(sorted(upstreams)) or 'none defined'}")
+
config = AppStateConfig(
models_dir=models_dir_resolved,
device=resolved_device,
@@ -654,6 +678,7 @@ def serve(
preload_models=preload_models,
pinned_models=pinned_models,
pool_name=pool_name,
+ upstreams_file=upstreams_file,
)
uvicorn_log = "debug" if verbose else log_level.strip().lower()
diff --git a/packages/sie_server/src/sie_server/config/upstreams.py b/packages/sie_server/src/sie_server/config/upstreams.py
new file mode 100644
index 000000000..f7eaea383
--- /dev/null
+++ b/packages/sie_server/src/sie_server/config/upstreams.py
@@ -0,0 +1,221 @@
+"""Operator-defined upstreams for remote profiles.
+
+An upstream is a named endpoint outside this deployment. It is defined only in
+the server's startup configuration (``--upstreams-file`` or
+``SIE_UPSTREAMS_FILE``), never through the model configuration API. Its
+credential is the name of an environment variable. The value is read when a
+request is sent and is never stored on the parsed configuration.
+
+Validation messages never repeat the offending value, because a rejected URL or
+a literal credential is exactly what must not reach a log.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import os
+import re
+from enum import StrEnum
+from pathlib import Path
+from urllib.parse import urlsplit
+
+import httpx
+import yaml
+from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
+from yaml.constructor import ConstructorError
+
+UPSTREAMS_FILE_ENV = "SIE_UPSTREAMS_FILE"
+
+_UPSTREAM_NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")
+_ENV_VAR_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,127}$")
+_VISIBLE_ASCII = re.compile(r"^[\x21-\x7e]+$")
+_DEFAULT_PORTS = {"http": 80, "https": 443}
+
+
+class UpstreamConfigError(ValueError):
+ """An upstreams file or an upstream definition is invalid."""
+
+
+class _DuplicateKeyError(yaml.YAMLError):
+ def __init__(self, line: int) -> None:
+ super().__init__(f"duplicate key on line {line}")
+ self.line = line
+
+
+class _UniqueKeyLoader(yaml.SafeLoader):
+ """A safe loader that refuses a repeated mapping key instead of keeping the last one."""
+
+ def construct_mapping(self, node: yaml.MappingNode, deep: bool = False) -> dict[object, object]:
+ seen: set[object] = set()
+ for key_node, _ in node.value:
+ key = self.construct_object(key_node, deep=deep)
+ try:
+ hash(key)
+ except TypeError:
+ raise ConstructorError(problem="found an unhashable mapping key") from None
+ if key in seen:
+ raise _DuplicateKeyError(key_node.start_mark.line + 1)
+ seen.add(key)
+ return super().construct_mapping(node, deep=deep)
+
+
+class UpstreamCredentialError(RuntimeError):
+ """The environment variable holding an upstream's credential is not set."""
+
+
+def _is_loopback(host: str) -> bool:
+ if host.lower() == "localhost":
+ return True
+ try:
+ return ipaddress.ip_address(host).is_loopback
+ except ValueError:
+ return False
+
+
+def validate_upstream_url(url: str, *, field: str = "base_url", require_tls: bool = True) -> str:
+ """Return ``url`` without a trailing slash, or raise :class:`UpstreamConfigError`.
+
+ A URL that carries credentials, a query or a fragment is rejected. With
+ ``require_tls``, plain HTTP is accepted only for a loopback host.
+ """
+ if not _VISIBLE_ASCII.fullmatch(url):
+ raise UpstreamConfigError(f"{field} must be printable ASCII without spaces; use punycode for IDN hosts")
+ if "?" in url or "#" in url:
+ raise UpstreamConfigError(f"{field} must not carry a query or a fragment")
+ try:
+ parts = urlsplit(url)
+ port = parts.port
+ sent = httpx.URL(url)
+ except (ValueError, httpx.InvalidURL):
+ raise UpstreamConfigError(f"{field} is not a valid URL") from None
+ if parts.scheme not in {"http", "https"}:
+ raise UpstreamConfigError(f"{field} must be an http or https URL")
+ if "@" in parts.netloc:
+ raise UpstreamConfigError(f"{field} must not carry credentials")
+ if "%" in parts.netloc:
+ raise UpstreamConfigError(f"{field} must not percent-encode the host")
+ if not parts.hostname:
+ raise UpstreamConfigError(f"{field} must name a host")
+ # The URL is checked with one parser and sent with another; both must agree
+ # on where it goes.
+ default_port = _DEFAULT_PORTS.get(parts.scheme)
+ sent_host = sent.raw_host.decode("ascii").lower()
+ if (sent.scheme, sent_host, sent.port or default_port) != (parts.scheme, parts.hostname, port or default_port):
+ raise UpstreamConfigError(f"{field} is parsed inconsistently")
+ if require_tls and parts.scheme == "http" and not _is_loopback(parts.hostname):
+ raise UpstreamConfigError(f"{field} must use https outside loopback")
+ return url.rstrip("/")
+
+
+class UpstreamKind(StrEnum):
+ OPENAI = "openai"
+ SIE = "sie"
+
+
+class RateCap(BaseModel):
+ """Per-replica limits on calls to one upstream."""
+
+ model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True)
+
+ requests_per_minute: int = Field(gt=0)
+ max_concurrency: int = Field(gt=0)
+
+
+class Upstream(BaseModel):
+ """One named upstream from the startup configuration."""
+
+ model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True)
+
+ kind: UpstreamKind
+ base_url: str
+ api_key_secret: str | None = None
+ """Name of the environment variable that holds the credential."""
+ rate_cap: RateCap
+ proxy_url: str | None = None
+ """The only egress proxy used for this upstream. Ambient proxy variables are ignored."""
+
+ @field_validator("base_url")
+ @classmethod
+ def _base_url(cls, value: str) -> str:
+ return validate_upstream_url(value)
+
+ @field_validator("proxy_url")
+ @classmethod
+ def _proxy_url(cls, value: str | None) -> str | None:
+ if value is None:
+ return None
+ return validate_upstream_url(value, field="proxy_url", require_tls=False)
+
+ @field_validator("api_key_secret")
+ @classmethod
+ def _api_key_secret(cls, value: str | None) -> str | None:
+ if value is not None and not _ENV_VAR_NAME.fullmatch(value):
+ raise UpstreamConfigError("api_key_secret must name an environment variable, not hold a credential")
+ return value
+
+ @model_validator(mode="after")
+ def _proxy_only_over_tls(self) -> Upstream:
+ # A plain-HTTP request through a proxy reaches the proxy in cleartext,
+ # bearer token included. Over TLS the proxy only sees a CONNECT tunnel.
+ if self.proxy_url is not None and not self.base_url.startswith("https://"):
+ raise UpstreamConfigError("proxy_url requires an https base_url")
+ return self
+
+ def api_key(self) -> str | None:
+ """Read the credential now. ``None`` when the upstream declares none.
+
+ Surrounding whitespace, such as the newline a secret file often ends
+ with, is removed. Any other non-printable character is refused without
+ repeating the value, because an HTTP library would quote it in its error.
+ """
+ if self.api_key_secret is None:
+ return None
+ value = os.environ.get(self.api_key_secret, "").strip()
+ if not value:
+ raise UpstreamCredentialError(f"environment variable {self.api_key_secret} is not set")
+ if not _VISIBLE_ASCII.fullmatch(value):
+ raise UpstreamCredentialError(
+ f"environment variable {self.api_key_secret} holds characters a credential cannot contain"
+ )
+ return value
+
+
+class UpstreamsFile(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True)
+
+ upstreams: dict[str, Upstream] = Field(default_factory=dict)
+
+ @field_validator("upstreams")
+ @classmethod
+ def _names(cls, value: dict[str, Upstream]) -> dict[str, Upstream]:
+ for name in value:
+ if not _UPSTREAM_NAME.fullmatch(name):
+ raise UpstreamConfigError(
+ "upstream names are lowercase letters, digits and hyphens, at most 63 characters"
+ )
+ return value
+
+
+def load_upstreams(path: str | Path) -> dict[str, Upstream]:
+ """Parse and validate an upstreams file. Raises :class:`UpstreamConfigError`."""
+ try:
+ text = Path(path).read_text(encoding="utf-8")
+ except OSError as exc:
+ raise UpstreamConfigError(f"upstreams file {path} could not be read: {exc.strerror}") from None
+ try:
+ raw = yaml.load(text, Loader=_UniqueKeyLoader) # noqa: S506 - a SafeLoader subclass
+ except _DuplicateKeyError as exc:
+ raise UpstreamConfigError(f"upstreams file {path} repeats a key on line {exc.line}") from None
+ except yaml.YAMLError:
+ raise UpstreamConfigError(f"upstreams file {path} is not valid YAML") from None
+ if raw is None:
+ return {}
+ try:
+ parsed = UpstreamsFile.model_validate(raw)
+ except ValidationError as exc:
+ problems = "; ".join(
+ f"{'.'.join(str(part) for part in error['loc']) or 'file'}: {error['msg']}"
+ for error in exc.errors(include_url=False, include_input=False)
+ )
+ raise UpstreamConfigError(f"upstreams file {path} is invalid: {problems}") from None
+ return dict(parsed.upstreams)
diff --git a/packages/sie_server/src/sie_server/core/upstream_client.py b/packages/sie_server/src/sie_server/core/upstream_client.py
new file mode 100644
index 000000000..de3039dad
--- /dev/null
+++ b/packages/sie_server/src/sie_server/core/upstream_client.py
@@ -0,0 +1,57 @@
+"""Outbound HTTP client for an operator-defined upstream.
+
+The client never follows a redirect, ignores ambient proxy variables, verifies
+TLS, and reads the credential from its environment variable for each request,
+so no long-lived object holds the value.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Generator
+
+import httpx
+
+from sie_server.config.upstreams import Upstream
+
+DEFAULT_TIMEOUT = httpx.Timeout(30.0, connect=5.0)
+
+
+class UpstreamRedirectRefusedError(httpx.HTTPError):
+ """The upstream answered with a redirect. Credentials never follow one."""
+
+
+class _EnvBearerAuth(httpx.Auth):
+ def __init__(self, upstream: Upstream) -> None:
+ self._upstream = upstream
+
+ def auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]:
+ api_key = self._upstream.api_key()
+ if api_key is not None:
+ request.headers["Authorization"] = f"Bearer {api_key}"
+ yield request
+
+
+async def _refuse_redirect(response: httpx.Response) -> None:
+ if 300 <= response.status_code < 400:
+ await response.aclose()
+ raise UpstreamRedirectRefusedError("upstream answered with a redirect, which is refused")
+
+
+def upstream_client(
+ upstream: Upstream,
+ *,
+ timeout: httpx.Timeout = DEFAULT_TIMEOUT,
+ transport: httpx.AsyncBaseTransport | None = None,
+) -> httpx.AsyncClient:
+ """Build the only client that may call ``upstream``."""
+ return httpx.AsyncClient(
+ base_url=upstream.base_url,
+ auth=_EnvBearerAuth(upstream),
+ follow_redirects=False,
+ trust_env=False,
+ proxy=upstream.proxy_url,
+ verify=True,
+ timeout=timeout,
+ transport=transport,
+ event_hooks={"response": [_refuse_redirect]},
+ )
diff --git a/packages/sie_server/tests/config/test_upstreams.py b/packages/sie_server/tests/config/test_upstreams.py
new file mode 100644
index 000000000..f5b8f2197
--- /dev/null
+++ b/packages/sie_server/tests/config/test_upstreams.py
@@ -0,0 +1,211 @@
+"""Operator-defined upstreams: URL rules and credentials by reference."""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+
+import pytest
+from pydantic import ValidationError
+from sie_server.config.upstreams import (
+ Upstream,
+ UpstreamConfigError,
+ UpstreamCredentialError,
+ UpstreamKind,
+ load_upstreams,
+ validate_upstream_url,
+)
+
+CANARY = "sk-canary-6f1d0c9a2b7e4f5a"
+RATE_CAP = " rate_cap: {requests_per_minute: 600, max_concurrency: 32}\n"
+
+
+def write(tmp_path: Path, text: str) -> Path:
+ path = tmp_path / "upstreams.yaml"
+ path.write_text(text, encoding="utf-8")
+ return path
+
+
+def test_a_valid_file_defines_both_kinds(tmp_path: Path) -> None:
+ path = write(
+ tmp_path,
+ "upstreams:\n"
+ " team-sie:\n"
+ " kind: sie\n"
+ " base_url: https://sie.example.internal/\n"
+ " api_key_secret: TEAM_SIE_KEY\n"
+ " proxy_url: http://proxy.example.internal:3128\n" + RATE_CAP + " local-openai:\n"
+ " kind: openai\n"
+ " base_url: http://127.0.0.1:8000/v1\n" + RATE_CAP,
+ )
+
+ upstreams = load_upstreams(path)
+
+ assert set(upstreams) == {"team-sie", "local-openai"}
+ assert upstreams["team-sie"].kind is UpstreamKind.SIE
+ assert upstreams["team-sie"].base_url == "https://sie.example.internal"
+ assert upstreams["team-sie"].rate_cap.max_concurrency == 32
+ assert upstreams["local-openai"].api_key_secret is None
+ assert upstreams["team-sie"].proxy_url == "http://proxy.example.internal:3128"
+
+
+def test_an_empty_file_defines_no_upstream(tmp_path: Path) -> None:
+ assert load_upstreams(write(tmp_path, "")) == {}
+
+
+ "url",
+ [
+ "https://sie.example.internal",
+ "https://host.example.com/v1",
+ "http://localhost:8080",
+ "http://127.0.0.1:9000",
+ "http://127.8.0.1:9000",
+ "http://[::1]:8080",
+ ],
+)
+def test_tls_or_loopback_urls_are_accepted(url: str) -> None:
+ assert validate_upstream_url(url) == url
+
+
+ ("url", "reason"),
+ [
+ ("http://sie.example.internal", "https outside loopback"),
+ ("http://10.0.0.5:8080", "https outside loopback"),
+ ("https://user:[email protected]", "credentials"),
+ ("https://[email protected]", "credentials"),
+ ("https://sie.example.internal/v1?key=abc", "query or a fragment"),
+ ("https://sie.example.internal/?", "query or a fragment"),
+ ("https://sie.example.internal/#top", "query or a fragment"),
+ ("ftp://sie.example.internal", "http or https"),
+ ("https:///v1", "name a host"),
+ ("https://sie.example.internal:99999", "not a valid URL"),
+ ("https://sie.example.internal /v1", "printable ASCII"),
+ ("https://sie.example.internal/v1\t", "printable ASCII"),
+ ("https://h\u00e9.example", "punycode"),
+ ("http://[::1%25eth0]:8080", "percent-encode the host"),
+ ("https://sie%2eexample.internal", "percent-encode the host"),
+ ],
+)
+def test_unsafe_urls_are_rejected(url: str, reason: str) -> None:
+ with pytest.raises(UpstreamConfigError, match=reason):
+ validate_upstream_url(url)
+
+
+def test_a_proxy_is_refused_for_a_plain_http_upstream() -> None:
+ with pytest.raises(ValidationError, match="proxy_url requires an https base_url"):
+ Upstream.model_validate(
+ {
+ "kind": "sie",
+ "base_url": "http://localhost:8080",
+ "proxy_url": "http://proxy.example:3128",
+ "rate_cap": {"requests_per_minute": 60, "max_concurrency": 4},
+ }
+ )
+
+
+def test_a_proxy_may_be_plain_http_but_never_carries_credentials() -> None:
+ assert validate_upstream_url("http://proxy.example:3128", field="proxy_url", require_tls=False)
+ with pytest.raises(UpstreamConfigError, match="proxy_url must not carry credentials"):
+ validate_upstream_url("http://user:[email protected]:3128", field="proxy_url", require_tls=False)
+
+
+ "body",
+ [
+ "upstreams:\n Team_SIE:\n kind: sie\n base_url: https://h.example\n" + RATE_CAP,
+ "upstreams:\n team:\n kind: grpc\n base_url: https://h.example\n" + RATE_CAP,
+ "upstreams:\n team:\n kind: sie\n base_url: https://h.example\n",
+ "upstreams:\n team:\n kind: sie\n base_url: https://h.example\n extra: 1\n" + RATE_CAP,
+ "upstreams:\n team:\n kind: sie\n base_url: https://h.example\n"
+ " rate_cap: {requests_per_minute: 0, max_concurrency: 1}\n",
+ "models: {}\n",
+ ],
+ ids=["bad-name", "unknown-kind", "no-rate-cap", "unknown-field", "zero-rate", "unknown-top-level-key"],
+)
+def test_invalid_definitions_are_rejected(tmp_path: Path, body: str) -> None:
+ with pytest.raises(UpstreamConfigError, match="is invalid"):
+ load_upstreams(write(tmp_path, body))
+
+
+ "body",
+ [
+ "upstreams:\n team:\n kind: sie\n base_url: https://a.example\n"
+ + RATE_CAP
+ + " team:\n kind: sie\n base_url: https://b.example\n"
+ + RATE_CAP,
+ "upstreams:\n team:\n kind: sie\n base_url: https://a.example\n"
+ " base_url: https://b.example\n" + RATE_CAP,
+ ],
+ ids=["repeated-upstream", "repeated-field"],
+)
+def test_a_repeated_key_is_rejected_rather_than_silently_replaced(tmp_path: Path, body: str) -> None:
+ with pytest.raises(UpstreamConfigError, match="repeats a key on line"):
+ load_upstreams(write(tmp_path, body))
+
+
[email protected]("body", ["upstreams: {[]: {}}\n", "upstreams: {{a: 1}: {}}\n", "? [a]\n: 1\n"])
+def test_an_unhashable_key_is_invalid_yaml_not_a_crash(tmp_path: Path, body: str) -> None:
+ with pytest.raises(UpstreamConfigError, match="not valid YAML"):
+ load_upstreams(write(tmp_path, body))
+
+
+def test_unreadable_or_malformed_files_are_rejected(tmp_path: Path) -> None:
+ with pytest.raises(UpstreamConfigError, match="could not be read"):
+ load_upstreams(tmp_path / "missing.yaml")
+ with pytest.raises(UpstreamConfigError, match="not valid YAML"):
+ load_upstreams(write(tmp_path, "upstreams: [unclosed\n"))
+
+
+ "field",
+ [
+ f" api_key_secret: {CANARY}\n",
+ f" api_key_secret: Bearer {CANARY}\n",
+ f" base_url: https://{CANARY}@sie.example.internal\n",
+ f" base_url: https://sie.example.internal/v1?api_key={CANARY}\n",
+ ],
+ ids=["literal-key", "literal-bearer", "url-userinfo", "url-query"],
+)
+def test_a_rejected_credential_is_never_repeated(tmp_path: Path, field: str, caplog: pytest.LogCaptureFixture) -> None:
+ base_url = "" if "base_url" in field else " base_url: https://sie.example.internal\n"
+ path = write(tmp_path, "upstreams:\n team:\n kind: sie\n" + base_url + field + RATE_CAP)
+
+ caplog.set_level(logging.DEBUG)
+ with pytest.raises(UpstreamConfigError) as raised:
+ load_upstreams(path)
+
+ assert CANARY not in str(raised.value)
+ assert raised.value.__cause__ is None
+ assert raised.value.__context__ is None or CANARY not in str(raised.value.__context__)
+ assert CANARY not in caplog.text
+
+
+def test_the_credential_is_read_by_reference_when_needed(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("TEAM_SIE_KEY", raising=False)
+ upstream = Upstream.model_validate(
+ {
+ "kind": "sie",
+ "base_url": "https://sie.example.internal",
+ "api_key_secret": "TEAM_SIE_KEY",
+ "rate_cap": {"requests_per_minute": 60, "max_concurrency": 4},
+ }
+ )
+
+ with pytest.raises(UpstreamCredentialError, match="TEAM_SIE_KEY is not set"):
+ upstream.api_key()
+
+ monkeypatch.setenv("TEAM_SIE_KEY", f"{CANARY}\n")
+ assert upstream.api_key() == CANARY, "the newline a secret file ends with is not part of the credential"
+
+ monkeypatch.setenv("TEAM_SIE_KEY", f"{CANARY}\r\ninjected: header")
+ with pytest.raises(UpstreamCredentialError, match="holds characters a credential cannot contain") as raised:
+ upstream.api_key()
+ assert CANARY not in str(raised.value)
+
+ monkeypatch.setenv("TEAM_SIE_KEY", CANARY)
+ assert upstream.api_key() == CANARY
+ for rendering in (repr(upstream), str(upstream), upstream.model_dump_json(), str(upstream.model_dump())):
+ assert CANARY not in rendering
diff --git a/packages/sie_server/tests/core/test_upstream_client.py b/packages/sie_server/tests/core/test_upstream_client.py
new file mode 100644
index 000000000..5199323bc
--- /dev/null
+++ b/packages/sie_server/tests/core/test_upstream_client.py
@@ -0,0 +1,135 @@
+"""The upstream egress client: no redirects, no ambient proxy, credential per request."""
+
+from __future__ import annotations
+
+import logging
+
+import httpx
+import pytest
+from sie_server.config.upstreams import Upstream, UpstreamCredentialError
+from sie_server.core.upstream_client import UpstreamRedirectRefusedError, upstream_client
+
+CANARY = "sk-canary-0b8e5d7c3a91f246"
+
+
+def make_upstream(**overrides: object) -> Upstream:
+ spec: dict[str, object] = {
+ "kind": "sie",
+ "base_url": "https://sie.example.internal",
+ "api_key_secret": "TEAM_SIE_KEY",
+ "rate_cap": {"requests_per_minute": 60, "max_concurrency": 4},
+ }
+ spec.update(overrides)
+ return Upstream.model_validate(spec)
+
+
+class Recorder:
+ def __init__(self, respond: httpx.Response) -> None:
+ self.requests: list[httpx.Request] = []
+ self._respond = respond
+
+ def __call__(self, request: httpx.Request) -> httpx.Response:
+ self.requests.append(request)
+ return self._respond
+
+
+async def test_the_credential_is_sent_only_as_a_header_and_never_rendered(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ monkeypatch.setenv("TEAM_SIE_KEY", CANARY)
+ recorder = Recorder(httpx.Response(500, json={"error": "boom"}))
+ caplog.set_level(logging.DEBUG)
+
+ async with upstream_client(make_upstream(), transport=httpx.MockTransport(recorder)) as client:
+ response = await client.post("/v1/encode/BAAI/bge-m3", json={"items": [{"text": "hi"}]})
+ with pytest.raises(httpx.HTTPStatusError) as raised:
+ response.raise_for_status()
+ client_repr = repr(client)
+
+ assert recorder.requests[0].headers["authorization"] == f"Bearer {CANARY}"
+ assert str(recorder.requests[0].url) == "https://sie.example.internal/v1/encode/BAAI/bge-m3"
+ assert CANARY not in str(raised.value)
+ assert CANARY not in repr(raised.value.request.headers)
+ assert CANARY not in client_repr
+ assert CANARY not in caplog.text
+
+
+async def test_the_credential_is_read_for_each_request(monkeypatch: pytest.MonkeyPatch) -> None:
+ recorder = Recorder(httpx.Response(200, json={}))
+ async with upstream_client(make_upstream(), transport=httpx.MockTransport(recorder)) as client:
+ monkeypatch.setenv("TEAM_SIE_KEY", "first")
+ await client.get("/v1/models")
+ monkeypatch.setenv("TEAM_SIE_KEY", "rotated")
+ await client.get("/v1/models")
+
+ assert [request.headers["authorization"] for request in recorder.requests] == [
+ "Bearer first",
+ "Bearer rotated",
+ ]
+
+
+async def test_a_missing_credential_stops_the_request_before_it_is_sent(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("TEAM_SIE_KEY", raising=False)
+ recorder = Recorder(httpx.Response(200, json={}))
+
+ async with upstream_client(make_upstream(), transport=httpx.MockTransport(recorder)) as client:
+ with pytest.raises(UpstreamCredentialError, match="TEAM_SIE_KEY is not set"):
+ await client.get("/v1/models")
+
+ assert recorder.requests == []
+
+
+async def test_a_malformed_credential_is_refused_before_anything_is_sent(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ monkeypatch.setenv("TEAM_SIE_KEY", f"{CANARY} extra")
+ recorder = Recorder(httpx.Response(200, json={}))
+ caplog.set_level(logging.DEBUG)
+
+ async with upstream_client(make_upstream(), transport=httpx.MockTransport(recorder)) as client:
+ with pytest.raises(UpstreamCredentialError) as raised:
+ await client.get("/v1/models")
+
+ assert recorder.requests == []
+ assert CANARY not in str(raised.value)
+ assert CANARY not in caplog.text
+
+
+async def test_an_upstream_without_a_credential_sends_no_authorization() -> None:
+ recorder = Recorder(httpx.Response(200, json={}))
+ upstream = make_upstream(api_key_secret=None, base_url="http://127.0.0.1:8080")
+
+ async with upstream_client(upstream, transport=httpx.MockTransport(recorder)) as client:
+ await client.get("/v1/models")
+
+ assert "authorization" not in recorder.requests[0].headers
+
+
[email protected]("status", [301, 302, 303, 307, 308])
+async def test_redirects_are_refused_and_never_followed(monkeypatch: pytest.MonkeyPatch, status: int) -> None:
+ monkeypatch.setenv("TEAM_SIE_KEY", CANARY)
+ recorder = Recorder(httpx.Response(status, headers={"location": "https://collector.example/steal"}))
+
+ async with upstream_client(make_upstream(), transport=httpx.MockTransport(recorder)) as client:
+ with pytest.raises(UpstreamRedirectRefusedError) as raised:
+ await client.get("/v1/models")
+
+ assert [request.url.host for request in recorder.requests] == ["sie.example.internal"]
+ assert "collector.example" not in str(raised.value)
+
+
+def test_ambient_proxy_variables_are_ignored(monkeypatch: pytest.MonkeyPatch) -> None:
+ for name in ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "all_proxy"):
+ monkeypatch.setenv(name, "http://ambient-proxy.example:3128")
+
+ client = upstream_client(make_upstream())
+
+ assert client.trust_env is False
+ assert client._mounts == {}
+
+
+def test_only_the_declared_proxy_is_used() -> None:
+ client = upstream_client(make_upstream(proxy_url="http://proxy.example.internal:3128"))
+
+ proxies = [transport._pool._proxy_url for transport in client._mounts.values()]
+ assert [(url.host, url.port) for url in proxies] == [(b"proxy.example.internal", 3128)]
diff --git a/packages/sie_server/tests/test_cli_upstreams.py b/packages/sie_server/tests/test_cli_upstreams.py
new file mode 100644
index 000000000..3afb09ab3
--- /dev/null
+++ b/packages/sie_server/tests/test_cli_upstreams.py
@@ -0,0 +1,87 @@
+"""`sie-server serve --upstreams-file`: startup-only upstream definitions.
+
+A typed flag with an invalid file stops startup. The same file from
+`SIE_UPSTREAMS_FILE` (a Helm value) warns and loads no upstream, so nothing is
+sent outside the deployment and the pod does not crash-loop.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+from sie_server import cli
+from sie_server.app.app_state_config import AppStateConfig
+from typer.testing import CliRunner
+
+VALID = (
+ "upstreams:\n"
+ " team-sie:\n"
+ " kind: sie\n"
+ " base_url: https://sie.example.internal\n"
+ " api_key_secret: TEAM_SIE_KEY\n"
+ " rate_cap: {requests_per_minute: 600, max_concurrency: 32}\n"
+)
+INVALID = VALID.replace("https://", "http://")
+
+
+def no_server(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
+ started: dict[str, Any] = {}
+
+ def fake_run_server(**kwargs: Any) -> None:
+ started["kwargs"] = kwargs
+
+ monkeypatch.setattr(cli, "run_server", fake_run_server)
+ for name in ("SIE_UPSTREAMS_FILE", "SIE_LOG_LEVEL", "SIE_PRELOAD_MODELS", "SIE_PINNED_MODELS", "SIE_EXTRA_MODELS"):
+ monkeypatch.delenv(name, raising=False)
+ return started
+
+
+def upstreams_file(tmp_path: Path, text: str) -> str:
+ path = tmp_path / "upstreams.yaml"
+ path.write_text(text, encoding="utf-8")
+ return str(path)
+
+
+def test_a_valid_file_reaches_the_server_process(no_server: dict[str, Any], tmp_path: Path) -> None:
+ path = upstreams_file(tmp_path, VALID)
+
+ result = CliRunner().invoke(cli.app, ["serve", "--upstreams-file", path])
+
+ assert result.exit_code == 0, result.output
+ assert "Upstreams: team-sie" in result.output
+ config: AppStateConfig = no_server["kwargs"]["config"]
+ assert config.upstreams_file == path
+
+
+def test_an_invalid_typed_file_stops_startup(no_server: dict[str, Any], tmp_path: Path) -> None:
+ result = CliRunner().invoke(cli.app, ["serve", "--upstreams-file", upstreams_file(tmp_path, INVALID)])
+
+ assert result.exit_code == 1
+ assert "must use https outside loopback" in result.output
+ assert "kwargs" not in no_server
+
+
+def test_an_invalid_environment_file_loads_no_upstream(
+ no_server: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("SIE_UPSTREAMS_FILE", upstreams_file(tmp_path, INVALID))
+
+ result = CliRunner().invoke(cli.app, ["serve"])
+
+ assert result.exit_code == 0, result.output
+ assert "No upstream is loaded" in result.output
+ assert no_server["kwargs"]["config"].upstreams_file is None
+
+
+def test_the_file_survives_the_uvicorn_handoff(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("SIE_UPSTREAMS_FILE", raising=False)
+ path = upstreams_file(tmp_path, VALID)
+
+ AppStateConfig(upstreams_file=path).save_to_env_vars()
+ assert AppStateConfig.from_env_vars().upstreams_file == path
+
+ AppStateConfig().save_to_env_vars()
+ assert AppStateConfig.from_env_vars().upstreams_file is None