diff --git a/agentic_security/core/app.py b/agentic_security/core/app.py index e4000180..6bdac23c 100644 --- a/agentic_security/core/app.py +++ b/agentic_security/core/app.py @@ -65,4 +65,4 @@ def expand_secrets(secrets: dict[str, str]) -> None: if env_value is not None: secrets[key] = env_value else: - secrets[key] = None + secrets[key] = "" diff --git a/agentic_security/core/test_app.py b/agentic_security/core/test_app.py index 1f032392..ee63906a 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) @@ -20,10 +21,23 @@ 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(): secrets = {"secret_key": "plain_value"} expand_secrets(secrets) assert secrets["secret_key"] == "plain_value" + + +def test_set_secrets_repeated_calls_with_unset_env_vars(monkeypatch): + monkeypatch.setattr(app_module, "_secrets", {}) + monkeypatch.delenv("NON_EXISTENT_VAR", raising=False) + + set_secrets({"missing": "$NON_EXISTENT_VAR"}) + set_secrets({"present": "$TEST_ENV_VAR"}) + + assert get_secrets() == { + "missing": "", + "present": "test_value", + } diff --git a/agentic_security/http_spec.py b/agentic_security/http_spec.py index 36bcb1e6..34778292 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], +) -> 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)