Skip to content
Draft
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
8 changes: 5 additions & 3 deletions backend/ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from anthropic import Anthropic
from dotenv import load_dotenv

from database import db_get
from database import db_get, escape_filter_value

load_dotenv()

Expand All @@ -28,14 +28,16 @@ def _get_client() -> Anthropic:


def _fetch_ticket(ticket_id: str) -> dict[str, Any]:
result = db_get("tickets", f"id=eq.{ticket_id}")
result = db_get("tickets", f"id=eq.{escape_filter_value(ticket_id)}")
if not isinstance(result, list) or not result:
raise ValueError(f"Ticket {ticket_id} not found")
return result[0]


def _fetch_notes(ticket_id: str) -> list[dict[str, Any]]:
notes = db_get("ticket_notes", f"ticket_id=eq.{ticket_id}&order=created_at.asc")
notes = db_get(
"ticket_notes", f"ticket_id=eq.{escape_filter_value(ticket_id)}&order=created_at.asc"
)
return notes if isinstance(notes, list) else []


Expand Down
27 changes: 27 additions & 0 deletions backend/test_ai.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Unit tests for ai.py -- PostgREST filter injection guard on ticket_id."""

import pytest

import ai


@pytest.mark.parametrize(
"fetch",
[ai._fetch_ticket, ai._fetch_notes],
ids=["_fetch_ticket", "_fetch_notes"],
)
def test_fetch_helpers_escape_injected_ticket_id(monkeypatch, fetch):
captured = {}

def fake_db_get(table, params=""):
captured["params"] = params
return [{"id": "t1"}]

monkeypatch.setattr(ai, "db_get", fake_db_get)

malicious_id = "t1&status=eq.Closed"
fetch(malicious_id)

params = captured["params"]
assert "&status=eq.Closed" not in params
assert "status=eq.Closed" not in params