Fix SQLite LIKE wildcard escaping in IP filter queries

- Add escape_like() helper to escape % and _ wildcards in LIKE queries
- Update fail2ban_db_repo.get_history_page() to use escaping
- Update history_archive_repo.get_archived_history() to use escaping
- Add ESCAPE clause to all LIKE queries
- Add comprehensive unit tests for escape_like function
- Add integration tests for LIKE wildcard handling
- Document LIKE escaping best practices in Backend-Development.md

Fixes TASK-017: Prevent unintended LIKE matches when IP filter contains
special characters like underscore or percent sign.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-04-26 14:07:49 +02:00
parent 94bdabe622
commit 667ab674ca
7 changed files with 234 additions and 4 deletions

View File

@@ -6,6 +6,21 @@ import json
from datetime import UTC, datetime
def escape_like(s: str) -> str:
"""Escape SQLite LIKE wildcard characters in a string.
SQLite's LIKE operator treats % (any sequence) and _ (any single char) as
wildcards. This function escapes them to prevent unintended matches.
Args:
s: The string to escape.
Returns:
The escaped string where backslashes, %, and _ are escaped.
"""
return s.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
def ts_to_iso(unix_ts: int) -> str:
"""Convert a Unix timestamp to an ISO 8601 UTC string."""
return datetime.fromtimestamp(unix_ts, tz=UTC).isoformat()