From a40e3bbd0b7baf4dee59221bd5f10f4c98245e42 Mon Sep 17 00:00:00 2001 From: Brixton Pham <117471232+brixtonpham@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:10:45 +0700 Subject: [PATCH 1/2] fix(http_spec): expand secrets in headers and URL and guard None values --- agentic_security/core/app.py | 25 +++++------ agentic_security/core/test_app.py | 25 ++++++++++- agentic_security/http_spec.py | 45 ++++++++++++++++---- tests/unit/test_spec.py | 69 +++++++++++++++++++++++++++++++ 4 files changed, 141 insertions(+), 23 deletions(-) diff --git a/agentic_security/core/app.py b/agentic_security/core/app.py index e4000180..77c106dd 100644 --- a/agentic_security/core/app.py +++ b/agentic_security/core/app.py @@ -16,7 +16,7 @@ class CurrentRun(TypedDict): tools_inbox: Queue = Queue() stop_event: Event = Event() current_run: CurrentRun = {"spec": None, "id": None} -_secrets: dict[str, str] = {} +_secrets: dict[str, str | None] = {} def create_app() -> FastAPI: @@ -47,22 +47,19 @@ def set_current_run(spec: LLMSpec) -> CurrentRun: return current_run -def get_secrets() -> dict[str, str]: +def get_secrets() -> dict[str, str | None]: return _secrets -def set_secrets(secrets: dict[str, str]) -> dict[str, str]: - _secrets.update(secrets) - expand_secrets(_secrets) +def set_secrets(secrets: dict[str, str | None]) -> dict[str, str | None]: + expanded = dict(secrets) + expand_secrets(expanded) + _secrets.update(expanded) return _secrets -def expand_secrets(secrets: dict[str, str]) -> None: - for key in secrets: - val = secrets[key] - if val.startswith("$"): - env_value = os.getenv(val.strip("$")) - if env_value is not None: - secrets[key] = env_value - else: - secrets[key] = None +def expand_secrets(secrets: dict[str, str | None]) -> None: + for key, val in secrets.items(): + if isinstance(val, str) and val.startswith("$"): + env_name = val.strip("$") + secrets[key] = os.getenv(env_name) if env_name else None diff --git a/agentic_security/core/test_app.py b/agentic_security/core/test_app.py index 1f032392..70fe4d37 100644 --- a/agentic_security/core/test_app.py +++ b/agentic_security/core/test_app.py @@ -2,7 +2,8 @@ import pytest -from agentic_security.core.app import expand_secrets +from agentic_security.core import app as app_module +from agentic_security.core.app import expand_secrets, get_secrets, set_secrets @pytest.fixture(autouse=True) @@ -27,3 +28,25 @@ def test_expand_secrets_without_dollar_sign(): secrets = {"secret_key": "plain_value"} expand_secrets(secrets) assert secrets["secret_key"] == "plain_value" + + +def test_expand_secrets_skips_none_and_non_string_values(): + secrets = {"missing": None, "count": 42, "env": "$TEST_ENV_VAR"} + expand_secrets(secrets) + assert secrets == {"missing": None, "count": 42, "env": "test_value"} + + +def test_set_secrets_repeated_calls_with_unset_and_dollar_values(monkeypatch): + monkeypatch.setattr(app_module, "_secrets", {}) + monkeypatch.delenv("NON_EXISTENT_VAR", raising=False) + monkeypatch.setenv("DOLLAR_SECRET", "$literal_token_value") + monkeypatch.delenv("literal_token_value", raising=False) + + set_secrets({"missing": "$NON_EXISTENT_VAR", "token": "$DOLLAR_SECRET"}) + set_secrets({"present": "$TEST_ENV_VAR"}) + + assert get_secrets() == { + "missing": None, + "token": "$literal_token_value", + "present": "test_value", + } diff --git a/agentic_security/http_spec.py b/agentic_security/http_spec.py index 36bcb1e6..21099a5a 100644 --- a/agentic_security/http_spec.py +++ b/agentic_security/http_spec.py @@ -1,5 +1,7 @@ import base64 import json +import re +from collections.abc import Callable from enum import Enum from urllib.parse import urlparse @@ -167,6 +169,35 @@ def modality(self) -> Modality: return Modality.TEXT +def _build_secret_replacer( + secrets: dict[str, str | None], +) -> Callable[[str], str]: + """Return a single-pass replacer for ``$SECRET`` placeholders.""" + replacements: dict[str, str] = {} + for key, value in secrets.items(): + if not isinstance(key, str) or not isinstance(value, str) or not value: + continue + name = key.strip("$") + if not name: + continue + replacements[f"${name}"] = value + + if not replacements: + return lambda text: text + + ordered_tokens = sorted(replacements, key=len, reverse=True) + pattern = re.compile( + "(?:" + + "|".join(re.escape(token) for token in ordered_tokens) + + r")(?![A-Za-z0-9_])" + ) + + def replace(text: str) -> str: + return pattern.sub(lambda match: replacements[match.group(0)], text) + + return replace + + def parse_http_spec(http_spec: str) -> LLMSpec: """Parses an HTTP specification string into a LLMSpec object. @@ -178,7 +209,7 @@ def parse_http_spec(http_spec: str) -> LLMSpec: """ from agentic_security.core.app import get_secrets - secrets = get_secrets() + replace_secrets = _build_secret_replacer(get_secrets()) # Split the spec by lines lines = http_spec.strip("\n").splitlines() @@ -191,14 +222,15 @@ def parse_http_spec(http_spec: str) -> LLMSpec: raise InvalidHTTPSpecError( "First line of HTTP spec must include the method and URL." ) - method, url = request_line_parts[0], request_line_parts[1] + method, raw_url = request_line_parts[0], request_line_parts[1] + url = replace_secrets(raw_url) # Check url validity valid_url = urlparse(url) # if missing the correct formatting ://, urlparse.netloc will be empty if valid_url.scheme not in ("http", "https") or not valid_url.netloc: raise InvalidHTTPSpecError( - f"Invalid URL: {url}. Ensure it starts with 'http://' or 'https://'" + f"Invalid URL: {raw_url}. Ensure it starts with 'http://' or 'https://'" ) # Initialize headers and body @@ -231,11 +263,8 @@ def parse_http_spec(http_spec: str) -> LLMSpec: has_image = "<>" in body has_audio = "<>" in body - for key, value in secrets.items(): - if not value: - continue - key = key.strip("$") - body = body.replace(f"${key}", value) + headers = {key: replace_secrets(value) for key, value in headers.items()} + body = replace_secrets(body) return LLMSpec( method=method, diff --git a/tests/unit/test_spec.py b/tests/unit/test_spec.py index 75cec543..7fefdd04 100644 --- a/tests/unit/test_spec.py +++ b/tests/unit/test_spec.py @@ -2,12 +2,14 @@ import pytest +from agentic_security.core import app as app_module from agentic_security.http_spec import ( InvalidHTTPSpecError, LLMSpec, escape_special_chars_for_json, parse_http_spec, ) +from agentic_security.routes._specs import LLM_SPECS class TestParseHttpSpec: @@ -111,3 +113,70 @@ def test_escaped_prompt_round_trips_through_json(self, prompt): def test_keeps_non_ascii_text_unescaped(self): assert escape_special_chars_for_json("café") == "café" + + +class TestParseHttpSpecSecretExpansion: + @pytest.fixture(autouse=True) + def isolated_secrets(self, monkeypatch): + monkeypatch.setattr(app_module, "_secrets", {}) + + def test_expands_openai_preset_url_headers_and_body(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "sk-test-FAKEOPENAI999") + app_module.set_secrets( + {"OPENAI_API_KEY": "$OPENAI_API_KEY", "API_KEY": "user:p@ss=1;2"} + ) + entry = next(item for item in LLM_SPECS if item["name"] == "Open AI") + preset = LLMSpec.from_string(entry["spec"]) + assert preset.headers["Authorization"] == "Bearer sk-test-FAKEOPENAI999" + assert "<>" in preset.body + + spec = parse_http_spec( + "POST https://api.example.com/v1?key=$API_KEY\n" + "$API_KEY: $API_KEY\n\n" + '{"token": "$API_KEY", "prompt": "<>"}' + ) + assert spec.url == "https://api.example.com/v1?key=user:p@ss=1;2" + assert spec.headers == {"$API_KEY": "user:p@ss=1;2"} + assert spec.body == '{"token": "user:p@ss=1;2", "prompt": "<>"}' + + def test_longest_key_boundary_and_single_pass_substitution(self): + app_module.set_secrets( + {"API_KEY": "sk-test-V1", "API_KEY_V2": r"tok_$API_KEY\1"} + ) + spec = parse_http_spec( + "POST https://api.example.com/v1/chat\n" + "X-V1: $API_KEY\nX-V2: $API_KEY_V2\nX-Unset: $API_KEY_UNSET\n\n{}" + ) + assert spec.headers == { + "X-V1": "sk-test-V1", + "X-V2": r"tok_$API_KEY\1", + "X-Unset": "$API_KEY_UNSET", + } + + def test_skips_non_string_secrets_and_redacts_invalid_url_errors(self, monkeypatch): + monkeypatch.setattr( + app_module, + "_secrets", + { + "MISSING": None, + "EMPTY": "", + "PORT": 8080, + "$": "x", + "KEY": "sk-test-FAKEOK", + }, + ) + spec = parse_http_spec( + "POST https://api.example.com/v1/chat\n" + "X-Missing: $MISSING\nX-Port: $PORT\nAuthorization: Bearer $KEY\n\n" + '{"missing": "$MISSING", "empty": "$EMPTY"}' + ) + assert spec.headers == { + "X-Missing": "$MISSING", + "X-Port": "$PORT", + "Authorization": "Bearer sk-test-FAKEOK", + } + assert spec.body == '{"missing": "$MISSING", "empty": "$EMPTY"}' + + with pytest.raises(InvalidHTTPSpecError) as exc_info: + parse_http_spec("POST ftp://api.example.com/v1?key=$KEY\n\n{}") + assert "sk-test-FAKEOK" not in str(exc_info.value) From edab6fd896149f278a1f638cde92a38c6a63735a Mon Sep 17 00:00:00 2001 From: Brixton Pham <117471232+brixtonpham@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:54:07 +0700 Subject: [PATCH 2/2] refactor(secrets): keep get_secrets/set_secrets unchanged and use empty string fallback --- agentic_security/core/app.py | 25 ++++++++++++++----------- agentic_security/core/test_app.py | 17 ++++------------- agentic_security/http_spec.py | 2 +- 3 files changed, 19 insertions(+), 25 deletions(-) diff --git a/agentic_security/core/app.py b/agentic_security/core/app.py index 77c106dd..6bdac23c 100644 --- a/agentic_security/core/app.py +++ b/agentic_security/core/app.py @@ -16,7 +16,7 @@ class CurrentRun(TypedDict): tools_inbox: Queue = Queue() stop_event: Event = Event() current_run: CurrentRun = {"spec": None, "id": None} -_secrets: dict[str, str | None] = {} +_secrets: dict[str, str] = {} def create_app() -> FastAPI: @@ -47,19 +47,22 @@ def set_current_run(spec: LLMSpec) -> CurrentRun: return current_run -def get_secrets() -> dict[str, str | None]: +def get_secrets() -> dict[str, str]: return _secrets -def set_secrets(secrets: dict[str, str | None]) -> dict[str, str | None]: - expanded = dict(secrets) - expand_secrets(expanded) - _secrets.update(expanded) +def set_secrets(secrets: dict[str, str]) -> dict[str, str]: + _secrets.update(secrets) + expand_secrets(_secrets) return _secrets -def expand_secrets(secrets: dict[str, str | None]) -> None: - for key, val in secrets.items(): - if isinstance(val, str) and val.startswith("$"): - env_name = val.strip("$") - secrets[key] = os.getenv(env_name) if env_name else None +def expand_secrets(secrets: dict[str, str]) -> None: + for key in secrets: + val = secrets[key] + if val.startswith("$"): + env_value = os.getenv(val.strip("$")) + if env_value is not None: + secrets[key] = env_value + else: + secrets[key] = "" diff --git a/agentic_security/core/test_app.py b/agentic_security/core/test_app.py index 70fe4d37..ee63906a 100644 --- a/agentic_security/core/test_app.py +++ b/agentic_security/core/test_app.py @@ -21,7 +21,7 @@ def test_expand_secrets_with_env_var(): def test_expand_secrets_without_env_var(): secrets = {"secret_key": "$NON_EXISTENT_VAR"} expand_secrets(secrets) - assert secrets["secret_key"] is None + assert secrets["secret_key"] == "" def test_expand_secrets_without_dollar_sign(): @@ -30,23 +30,14 @@ def test_expand_secrets_without_dollar_sign(): assert secrets["secret_key"] == "plain_value" -def test_expand_secrets_skips_none_and_non_string_values(): - secrets = {"missing": None, "count": 42, "env": "$TEST_ENV_VAR"} - expand_secrets(secrets) - assert secrets == {"missing": None, "count": 42, "env": "test_value"} - - -def test_set_secrets_repeated_calls_with_unset_and_dollar_values(monkeypatch): +def test_set_secrets_repeated_calls_with_unset_env_vars(monkeypatch): monkeypatch.setattr(app_module, "_secrets", {}) monkeypatch.delenv("NON_EXISTENT_VAR", raising=False) - monkeypatch.setenv("DOLLAR_SECRET", "$literal_token_value") - monkeypatch.delenv("literal_token_value", raising=False) - set_secrets({"missing": "$NON_EXISTENT_VAR", "token": "$DOLLAR_SECRET"}) + set_secrets({"missing": "$NON_EXISTENT_VAR"}) set_secrets({"present": "$TEST_ENV_VAR"}) assert get_secrets() == { - "missing": None, - "token": "$literal_token_value", + "missing": "", "present": "test_value", } diff --git a/agentic_security/http_spec.py b/agentic_security/http_spec.py index 21099a5a..34778292 100644 --- a/agentic_security/http_spec.py +++ b/agentic_security/http_spec.py @@ -170,7 +170,7 @@ def modality(self) -> Modality: def _build_secret_replacer( - secrets: dict[str, str | None], + secrets: dict[str, str], ) -> Callable[[str], str]: """Return a single-pass replacer for ``$SECRET`` placeholders.""" replacements: dict[str, str] = {}