fix(security): whitelist-validate metric column in get_top_factors (B608)

The metric parameter was passed directly into an f-string SQL query.
Add explicit validation against _ALLOWED_METRICS before use, raising
ValueError on unknown values. Raises ValueError on injection attempt
instead of silently accepting arbitrary column names.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
TPTBusiness
2026-04-30 07:25:14 +02:00
parent 31a75eeb07
commit a910d70d40
+9 -7
View File
@@ -190,16 +190,18 @@ class ResultsDatabase:
pd.DataFrame
DataFrame with factor names and metrics
"""
# Map shorthand to full column name
_ALLOWED_METRICS = frozenset({
'sharpe', 'ic', 'annual_return', 'max_drawdown',
'win_rate', 'information_ratio', 'volatility',
})
metric_map = {
'sharpe': 'sharpe',
'ic': 'ic',
'return': 'annual_return',
'drawdown': 'max_drawdown',
'win_rate': 'win_rate',
'sharpe': 'sharpe', 'ic': 'ic', 'return': 'annual_return',
'drawdown': 'max_drawdown', 'win_rate': 'win_rate',
'information_ratio': 'information_ratio',
}
col = metric_map.get(metric, metric)
if col not in _ALLOWED_METRICS:
raise ValueError(f"Unknown metric: {metric!r}")
return pd.read_sql_query(
f"""SELECT factor_name, ic, sharpe, annual_return, max_drawdown,
@@ -208,7 +210,7 @@ class ResultsDatabase:
JOIN factors ON factor_id = factors.id
WHERE {col} IS NOT NULL
ORDER BY {col} DESC
LIMIT ?""",
LIMIT ?""", # nosec B608 — col is validated against _ALLOWED_METRICS above
self.conn,
params=[limit]
)