Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(server): recheck token links across the scan and warn only for authenticated repeats (#760)
Krisztian Gajdar81922aaeb668
diff --git a/COMPATIBILITY.md b/COMPATIBILITY.mdindex 68f02f3dd..648fb8e7c 100644--- a/COMPATIBILITY.md+++ b/COMPATIBILITY.md@@ -230,8 +230,10 @@ The changes:passes today still passes, including one where a proxy in front of thegateway adds an `x-api-key` of its own. Repeated `x-api-key` values thatcarry different tokens get `401`.- - A repeated `Authorization` header still uses its first value. When the- values carry different tokens, the gateway logs a warning once.+ - A repeated `Authorization` header still uses its first value. The gateway+ logs a warning, once per process, the first time a request that passes+ authentication repeats `Authorization` with values that carry different+ tokens or with a value it cannot read. A refused request never logs it.- `SIE_WORKER_AUTH_TOKEN` is the token the gateway presents to workers.- Logs a warning when `SIE_AUTH_MODE` is unset on a non-loopback bind.- Telemetry: `SIE_TELEMETRY_ENABLED=1` opts in explicitly. The default stays on,diff --git a/packages/sie_gateway/src/middleware/auth.rs b/packages/sie_gateway/src/middleware/auth.rsindex 321151fb3..94fdd4986 100644--- a/packages/sie_gateway/src/middleware/auth.rs+++ b/packages/sie_gateway/src/middleware/auth.rs@@ -149,17 +149,7 @@ where}let token = match extract_request_credential(req.headers()) {- RequestCredential::Token(t) => {- if authorization_values_disagree(req.headers())- && !repeated_authorization_warned.swap(true, Ordering::Relaxed)- {- tracing::warn!(- audit = "auth",- "A request repeated the Authorization header with different values. The gateway used the first value; from 0.13.0 it refuses such requests with 401. Send one Authorization header."- );- }- t- }+ RequestCredential::Token(t) => t,RequestCredential::Missing => {record_admission_rejection(&req, AdmissionOutcome::Unauthenticated);return Ok(error_response(@@ -207,6 +197,7 @@ where));}+ warn_on_repeated_authorization(&req, &repeated_authorization_warned);return inner.call(req).await;}@@ -224,11 +215,25 @@ where));}+ warn_on_repeated_authorization(&req, &repeated_authorization_warned);inner.call(req).await})}}+/// Log, once per gateway, that an authenticated request repeated+/// `Authorization` with values that 0.13.0 refuses. Only requests that pass+/// authentication count, so an unauthenticated client cannot spend the+/// warning.+fn warn_on_repeated_authorization(req: &Request<Body>, warned: &AtomicBool) {+ if authorization_values_disagree(req.headers()) && !warned.swap(true, Ordering::Relaxed) {+ tracing::warn!(+ audit = "auth",+ "A request repeated the Authorization header with different values. The gateway used the first value; from 0.13.0 it refuses such requests with 401. Send one Authorization header."+ );+ }+}+fn record_admission_rejection(req: &Request<Body>, outcome: AdmissionOutcome) {if let Some(slot) = req.extensions().get::<AdmissionOutcomeSlot>() {slot.set(outcome);@@ -1290,6 +1295,60 @@ mod tests {assert_eq!(log.count("from 0.13.0 it refuses such requests"), 1);}+ fn repeated_authorization(path: &str, first: &str, second: &str) -> Request<Body> {+ HttpRequest::builder()+ .method(Method::POST)+ .uri(path)+ .header("authorization", format!("Bearer {first}"))+ .header("authorization", format!("Bearer {second}"))+ .body(Body::empty())+ .unwrap()+ }++ #[tokio::test]+ async fn middleware_warns_only_for_a_repeat_that_passes_authentication() {+ use tracing::instrument::WithSubscriber;++ for (refused, passing) in [+ (+ repeated_authorization("/v1/encode/any", "bogus", "user"),+ repeated_authorization("/v1/encode/any", "user", "bogus"),+ ),+ (+ repeated_authorization("/v1/pools", "user", "admin"),+ repeated_authorization("/v1/pools", "admin", "user"),+ ),+ ] {+ let log = CapturedLog::default();+ let dispatch = tracing::Dispatch::new(+ tracing_subscriber::fmt()+ .with_writer(log.clone())+ .with_ansi(false)+ .finish(),+ );+ let router = test_router(cfg_for_middleware("token", vec!["user"], "admin", false));++ let status = router+ .clone()+ .oneshot(refused)+ .with_subscriber(dispatch.clone())+ .await+ .unwrap()+ .status();+ assert!(status.is_client_error(), "{status}");+ assert_eq!(log.count("repeated the Authorization header"), 0);++ let status = router+ .oneshot(passing)+ .with_subscriber(dispatch)+ .await+ .unwrap()+ .status();+ assert_eq!(status, StatusCode::OK);+ assert_eq!(log.count("repeated the Authorization header"), 1);+ }+ }+#[tokio::test]async fn middleware_refuses_repeated_x_api_key_that_disagrees() {let cfg = cfg_for_middleware("token", vec!["user", "other"], "admin", false);diff --git a/packages/sie_server/README.md b/packages/sie_server/README.mdindex 9c878b864..e72c81090 100644--- a/packages/sie_server/README.md+++ b/packages/sie_server/README.md@@ -1047,7 +1047,10 @@ as a profile an operator chooses.Clients send the token as `Authorization: Bearer <token>` or `x-api-key: <token>`;when both are sent, `Authorization` is used and `x-api-key` is ignored, as on thegateway. The SDKs send `SIE_API_KEY`-as a Bearer token.+as a Bearer token. Repeated headers differ from the gateway until 0.13.0: the+server reads every value of a repeated header, skips empty ones, and refuses+values that carry different tokens, while the gateway uses only the first+`Authorization` value.Token auth covers the HTTP port. The other listeners are local: the IPC socketthat a worker sidecar uses (`SIE_IPC_SOCKET_PATH`, mode `0600`) and thediff --git a/packages/sie_server/src/sie_server/core/server_auth.py b/packages/sie_server/src/sie_server/core/server_auth.pyindex a00f0334d..35d04d27b 100644--- a/packages/sie_server/src/sie_server/core/server_auth.py+++ b/packages/sie_server/src/sie_server/core/server_auth.py@@ -3,7 +3,10 @@One vocabulary with the gateway: ``SIE_AUTH_MODE`` selects the mode,``SIE_AUTH_TOKENS`` (or ``SIE_AUTH_TOKEN``) holds comma-separated tokens, and arequest presents one in ``Authorization: Bearer`` or ``x-api-key``, with-``Authorization`` taking precedence when both are sent.+``Authorization`` taking precedence when both are sent. Repeated headers are+read differently until 0.13.0: the gateway uses only the first+``Authorization`` value, while this server reads every value, skips empty ones+and refuses values that carry different tokens."""from __future__ import annotations@@ -49,6 +52,7 @@ _READ_ONLY_ERRNOS = frozenset({errno.EACCES, errno.EROFS})_HOST_CHECK_RELEASE = "0.13.0"_MAX_WARNED_HOSTS = 64_MAX_LOGGED_HOST_CHARS = 100+_LINK_SCAN_ATTEMPTS = 3class AuthConfigError(ValueError):@@ -266,26 +270,37 @@ def _drop_temporary_links(path: Path, fd: int, token: os.stat_result) -> bool:True when every extra hard link of the token is such a file, even if aread-only directory keeps them in place; any other link is left alone and- the token is refused. The link count is read again after the scan, so a- concurrent start that removes its own link meanwhile is not mistaken for a- foreign link.+ the token is refused. The token's link count is read before and after each+ scan: one link after the scan means the temporary links are gone, and an+ unchanged count equal to the temporary links found plus one means they are+ the only extra links. A count that changes during the scan means a+ concurrent start is still adding or removing its link, so the scan is+ repeated a few times before the token is refused."""- try:- linked = [- entry- for entry, info in owned_files(path.parent, _TEMP_NAME)- if (info.st_dev, info.st_ino) == (token.st_dev, token.st_ino)- ]- except OSError:- return False- if os.fstat(fd).st_nlink not in (1, len(linked) + 1):- return False- for entry in linked:+ before = token.st_nlink+ for _ in range(_LINK_SCAN_ATTEMPTS):try:- entry.unlink(missing_ok=True)+ linked = [+ entry+ for entry, info in owned_files(path.parent, _TEMP_NAME)+ if (info.st_dev, info.st_ino) == (token.st_dev, token.st_ino)+ ]except OSError:- continue- return True+ return False+ after = os.fstat(fd).st_nlink+ if after == 1:+ return True+ if after == before == len(linked) + 1:+ for entry in linked:+ try:+ entry.unlink(missing_ok=True)+ except OSError:+ continue+ return True+ if after == before:+ return False+ before = after+ return Falsedef server_tokens(env: Mapping[str, str]) -> tuple[str, ...]:@@ -300,12 +315,15 @@ def server_tokens(env: Mapping[str, str]) -> tuple[str, ...]:def request_credentials(headers: Iterable[tuple[bytes, bytes]]) -> set[bytes]:- """The distinct tokens a request presents, as the gateway reads them.+ """The distinct tokens a request presents.``Authorization`` (``Bearer <token>`` in any case, or the bare token) takes- precedence: when it carries a token, ``x-api-key`` is ignored. Otherwise the- ``x-api-key`` values count. Empty values are ignored. More than one distinct- token means repeated headers that disagree.+ precedence, as on the gateway: when it carries a token, ``x-api-key`` is+ ignored. Otherwise the ``x-api-key`` values count. Every value of a+ repeated header is read and empty values are ignored, so an empty+ ``Authorization`` followed by a valid one is accepted here, while the+ gateway reads only the first ``Authorization`` value until 0.13.0. More+ than one distinct token means repeated headers that disagree."""authorization: set[bytes] = set()api_key: set[bytes] = set()diff --git a/packages/sie_server/tests/core/test_server_auth.py b/packages/sie_server/tests/core/test_server_auth.pyindex 3458507d0..af244db47 100644--- a/packages/sie_server/tests/core/test_server_auth.py+++ b/packages/sie_server/tests/core/test_server_auth.py@@ -21,7 +21,8 @@ from fastapi import FastAPI, WebSocketfrom fastapi.testclient import TestClientfrom sie_server.app.app_factory import AppFactoryfrom sie_server.app.app_state_config import AppStateConfig-from sie_server.core.data_dir import resolve_data_dir+from sie_server.core import server_auth+from sie_server.core.data_dir import owned_files, resolve_data_dirfrom sie_server.core.server_auth import (AuthConfigError,LoopbackHostMiddleware,@@ -238,6 +239,62 @@ class TestPersistedToken:assert read_stored_token(tmp_path) == stored.tokenassert seen == [2]+ @pytest.mark.parametrize("foreign", [False, True], ids=["temporary-only", "with-foreign-link"])+ def test_a_temporary_link_removed_after_the_scan(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, foreign: bool+ ) -> None:+ stored = load_or_create_token(tmp_path)+ if foreign:+ os.link(stored.path, tmp_path / "copy")+ staged = tmp_path / ".auth-token.sie-server-0123456789abcdef"+ os.link(stored.path, staged)+ scans: list[int] = []++ def scan_then_the_other_start_unlinks(directory: Path, name: re.Pattern[str]) -> Iterator[Any]:+ yield from owned_files(directory, name)+ scans.append(1)+ staged.unlink(missing_ok=True)++ monkeypatch.setattr(server_auth, "owned_files", scan_then_the_other_start_unlinks)++ if foreign:+ with pytest.raises(TokenFileError, match="hard links"):+ read_stored_token(tmp_path)+ assert (tmp_path / "copy").exists()+ else:+ assert read_stored_token(tmp_path) == stored.token+ assert len(scans) == 1+ assert not staged.exists()++ def test_a_link_count_that_keeps_changing_is_refused_after_a_few_scans(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ stored = load_or_create_token(tmp_path)+ os.link(stored.path, tmp_path / ".auth-token.sie-server-0000000000000000")+ scans: list[int] = []++ def scan_then_another_link_appears(directory: Path, name: re.Pattern[str]) -> Iterator[Any]:+ yield from owned_files(directory, name)+ scans.append(1)+ os.link(stored.path, tmp_path / f".auth-token.sie-server-{len(scans):016x}")++ monkeypatch.setattr(server_auth, "owned_files", scan_then_another_link_appears)++ with pytest.raises(TokenFileError, match="hard links"):+ read_stored_token(tmp_path)+ assert 1 < len(scans) <= 5++ def test_a_symbolic_link_named_like_a_temporary_file_does_not_hide_a_foreign_link(self, tmp_path: Path) -> None:+ stored = load_or_create_token(tmp_path)+ os.link(stored.path, tmp_path / "copy")+ decoy = tmp_path / ".auth-token.sie-server-0123456789abcdef"+ decoy.symlink_to(stored.path)++ with pytest.raises(TokenFileError, match="hard links"):+ read_stored_token(tmp_path)+ assert decoy.is_symlink()+ assert (tmp_path / "copy").exists()+def test_a_temporary_link_in_a_directory_without_write_permission_is_tolerated(self, tmp_path: Path) -> None:directory = tmp_path / "sie"stored = load_or_create_token(directory)diff --git a/packages/sie_server/tests/observability/test_telemetry.py b/packages/sie_server/tests/observability/test_telemetry.pyindex 148447c04..478c7b350 100644--- a/packages/sie_server/tests/observability/test_telemetry.py+++ b/packages/sie_server/tests/observability/test_telemetry.py@@ -206,6 +206,29 @@ class TestGetOrCreateWorkerId:assert in_flight.exists()assert users.exists()+ def test_a_write_interrupted_before_the_rename_is_swept_later(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ class Interrupted(BaseException):+ pass++ def interrupted(self: Path, target: object) -> Path:+ raise Interrupted++ with monkeypatch.context() as patched:+ patched.setattr(Path, "replace", interrupted)+ with pytest.raises(Interrupted):+ _get_or_create_worker_id(str(tmp_path))+ (leftover,) = tmp_path.iterdir()+ old = time.time() - 600+ os.utime(leftover, (old, old))++ worker_id = _get_or_create_worker_id(str(tmp_path))++ assert not leftover.exists()+ assert [entry.name for entry in tmp_path.iterdir()] == ["worker-id"]+ assert (tmp_path / "worker-id").read_text() == worker_id+def test_temporary_files_of_another_user_are_kept(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:old = time.time() - 600orphan = tmp_path / ".worker-id.sie-server-00000000000000aa"