Skip to content
Open
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
2 changes: 1 addition & 1 deletion agentic_security/core/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] = ""
18 changes: 16 additions & 2 deletions agentic_security/core/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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",
}
45 changes: 37 additions & 8 deletions agentic_security/http_spec.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import base64
import json
import re
from collections.abc import Callable
from enum import Enum
from urllib.parse import urlparse

Expand Down Expand Up @@ -167,6 +169,35 @@ def modality(self) -> Modality:
return Modality.TEXT


def _build_secret_replacer(

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding this _build_secret_replacer!

However, I would leave get_secrets and set_secrets as they are and use an empty string instead of None.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call — reverted get_secrets and set_secrets to their original signatures/behavior and updated expand_secrets to fall back to "" instead of None.

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.

Expand All @@ -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()
Expand All @@ -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
Expand Down Expand Up @@ -231,11 +263,8 @@ def parse_http_spec(http_spec: str) -> LLMSpec:
has_image = "<<BASE64_IMAGE>>" in body
has_audio = "<<BASE64_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,
Expand Down
69 changes: 69 additions & 0 deletions tests/unit/test_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 "<<PROMPT>>" 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": "<<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": "<<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)
Loading