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
9 changes: 6 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,17 @@ 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
49 changes: 49 additions & 0 deletions backend/test_ai.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""Unit tests for backend/ai.py -- PostgREST filter injection guards.

Mirrors the id-escaping coverage in test_database.py / test_main.py: ticket
ids that flow into ai.py's Supabase lookups must be escaped the same way
main.py's routes escape them.
"""

import pytest

import ai


def test_fetch_ticket_escapes_injected_id(monkeypatch):
captured = {}

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

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

ai._fetch_ticket("t1&status=eq.Closed")

assert captured["table"] == "tickets"
assert captured["params"] == "id=eq.t1%26status%3Deq.Closed"


def test_fetch_ticket_raises_when_not_found(monkeypatch):
monkeypatch.setattr(ai, "db_get", lambda table, params="": [])

with pytest.raises(ValueError):
ai._fetch_ticket("missing")


def test_fetch_notes_escapes_injected_id(monkeypatch):
captured = {}

def fake_get(table, params=""):
captured["table"] = table
captured["params"] = params
return []

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

ai._fetch_notes("t1&status=eq.Closed")

assert captured["table"] == "ticket_notes"
assert captured["params"] == "ticket_id=eq.t1%26status%3Deq.Closed&order=created_at.asc"