Skip to content

fix: prevent path traversal for message_id in file_session_manager #728

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
1 change: 1 addition & 0 deletions src/strands/_identifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class Identifier(enum.Enum):

AGENT = "agent"
SESSION = "session"
MESSAGE = "message"


def validate(id_: str, type_: Identifier) -> str:
Expand Down
9 changes: 8 additions & 1 deletion src/strands/session/file_session_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,16 @@ def _get_message_path(self, session_id: str, agent_id: str, message_id: int) ->
message_id: Index of the message
Returns:
The filename for the message

Raises:
ValueError: If message id contains path separators.
"""
# Validate message_id to prevent path traversal
message_id_str = str(message_id)
message_id_str = _identifier.validate(message_id_str, _identifier.Identifier.MESSAGE)

agent_path = self._get_agent_path(session_id, agent_id)
return os.path.join(agent_path, "messages", f"{MESSAGE_PREFIX}{message_id}.json")
return os.path.join(agent_path, "messages", f"{MESSAGE_PREFIX}{message_id_str}.json")

def _read_file(self, path: str) -> dict[str, Any]:
"""Read JSON file."""
Expand Down
15 changes: 15 additions & 0 deletions tests/strands/session/test_file_session_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,3 +390,18 @@ def test__get_session_path_invalid_session_id(session_id, file_manager):
def test__get_agent_path_invalid_agent_id(agent_id, file_manager):
with pytest.raises(ValueError, match=f"agent_id={agent_id} | id cannot contain path separators"):
file_manager._get_agent_path("session1", agent_id)


@pytest.mark.parametrize(
"message_id",
[
"../../../secret",
"../../attack",
"../escape",
"path/traversal",
],
)
def test__get_message_path_invalid_message_id(message_id, file_manager):
"""Test that message_id with path traversal sequences raises ValueError."""
with pytest.raises(ValueError, match=f"message_id={message_id} | id cannot contain path separators"):
file_manager._get_message_path("session1", "agent1", message_id)
Loading