Open-source personal finance manager. Self-hosted, privacy-first.
fix: reject blank rule condition values that match every transaction (#488)
Tássio Noronhab70692894b3e
diff --git a/backend/app/schemas/rule.py b/backend/app/schemas/rule.pyindex 4781a1fd..6714aa49 100644--- a/backend/app/schemas/rule.py+++ b/backend/app/schemas/rule.py@@ -2,7 +2,7 @@import uuidfrom typing import Any, Optional-from pydantic import BaseModel, ConfigDict+from pydantic import BaseModel, ConfigDict, field_validatorclass RuleCondition(BaseModel):@@ -10,6 +10,19 @@ class RuleCondition(BaseModel):op: str # contains, not_contains, equals, not_equals, starts_with, ends_with, regex, gt, gte, lt, ltevalue: Any # str or number depending on field+ @field_validator("value")+ @classmethod+ def value_must_not_be_blank(cls, v: Any) -> Any:+ """Reject blank values — they silently match every transaction.++ A blank value turns `contains`/`starts_with`/`ends_with`/`regex` into a+ tautology, and numeric comparisons fall back to 0, so the rule applies+ its actions to the whole ledger. Explicit `0` and `False` stay valid.+ """+ if v is None or (isinstance(v, str) and not v.strip()):+ raise ValueError("Condition value cannot be blank")+ return v+class RuleAction(BaseModel):op: str # set_category, set_payee, append_notes, ignorediff --git a/backend/app/services/rule_engine.py b/backend/app/services/rule_engine.pyindex 2cd56611..8062a748 100644--- a/backend/app/services/rule_engine.py+++ b/backend/app/services/rule_engine.py@@ -48,6 +48,15 @@ def _match_condition(condition: dict, tx: "Transaction") -> bool:tx_val = getattr(tx, field, None)+ # A blank value matches everything: "" is a substring of any string, every+ # string starts/ends with it, an empty regex always matches, and numeric+ # comparisons fall back to 0. Creation now rejects these, but rules saved+ # before that validation existed are still in users' databases — refuse to+ # match rather than recategorizing their whole ledger. Explicit 0/False+ # are real values and pass through.+ if value is None or (isinstance(value, str) and not value.strip()):+ return False+# String operatorsif op in ("contains", "not_contains", "starts_with", "ends_with", "equals", "not_equals", "regex"):tx_str = _normalize(str(tx_val or ""))diff --git a/backend/tests/test_new_rules_api.py b/backend/tests/test_new_rules_api.pyindex a3da4285..2570ebba 100644--- a/backend/tests/test_new_rules_api.py+++ b/backend/tests/test_new_rules_api.py@@ -751,3 +751,63 @@ async def test_import_rules_with_overwrite_preserves_existing_when_every_rule_isassert response.json() == {"imported": 0, "skipped": 1, "overwritten": 0}after_response = await client.get("/api/rules", headers=auth_headers)assert [rule["name"] for rule in after_response.json()] == before_names++[email protected]("blank", ["", " ", None])+async def test_create_rule_rejects_blank_condition_value(+ client: AsyncClient, auth_headers, test_categories, blank+):+ """A blank condition value matches every transaction, so it must be rejected+ rather than silently recategorising the whole ledger (issue #438)."""+ payload = {+ "name": "Blank condition",+ "conditions_op": "and",+ "conditions": [{"field": "description", "op": "contains", "value": blank}],+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],+ }+ response = await client.post("/api/rules", json=payload, headers=auth_headers)+ assert response.status_code == 422++ # And nothing was persisted.+ listed = await client.get("/api/rules", headers=auth_headers)+ assert all(r["name"] != "Blank condition" for r in listed.json())+++async def test_update_rule_rejects_blank_condition_value(+ client: AsyncClient, auth_headers, test_categories+):+ created = await client.post(+ "/api/rules",+ json={+ "name": "Ifood",+ "conditions_op": "and",+ "conditions": [{"field": "description", "op": "contains", "value": "IFOOD"}],+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],+ },+ headers=auth_headers,+ )+ assert created.status_code == 201++ response = await client.patch(+ f"/api/rules/{created.json()['id']}",+ json={"conditions": [{"field": "description", "op": "contains", "value": ""}]},+ headers=auth_headers,+ )+ assert response.status_code == 422+++async def test_create_rule_allows_zero_value(+ client: AsyncClient, auth_headers, test_categories+):+ """0 is a real value, not a blank one."""+ payload = {+ "name": "Positive amounts",+ "conditions_op": "and",+ "conditions": [{"field": "amount", "op": "gt", "value": 0}],+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],+ }+ response = await client.post("/api/rules", json=payload, headers=auth_headers)+ assert response.status_code == 201diff --git a/backend/tests/test_rule_engine.py b/backend/tests/test_rule_engine.pyindex 2e30d1e9..a201ed23 100644--- a/backend/tests/test_rule_engine.py+++ b/backend/tests/test_rule_engine.py@@ -459,3 +459,34 @@ def test_set_payee_combined_with_category():apply_rule_actions(actions, tx, category_already_set=False)assert tx.category_id == cat_idassert tx.payee_id == payee_id+++# --- blank condition values (issue #438) ---++def test_blank_value_never_matches():+ """A blank value must not turn a condition into a match-everything rule."""+ tx = make_tx(description="UBER TRIP")+ for op in ("contains", "starts_with", "ends_with", "regex", "equals", "not_equals"):+ conditions = [{"field": "description", "op": op, "value": ""}]+ assert evaluate_conditions("and", conditions, tx) is False, op+++def test_whitespace_and_none_values_never_match():+ tx = make_tx(description="UBER TRIP")+ for value in (" ", None):+ conditions = [{"field": "description", "op": "contains", "value": value}]+ assert evaluate_conditions("and", conditions, tx) is False+++def test_blank_numeric_value_never_matches():+ """Blank numeric values used to fall back to 0, matching every amount."""+ tx = make_tx(amount=Decimal("25.50"))+ conditions = [{"field": "amount", "op": "gt", "value": ""}]+ assert evaluate_conditions("and", conditions, tx) is False+++def test_zero_value_still_matches():+ """0 is a real value, not a blank one — it must keep working."""+ tx = make_tx(amount=Decimal("25.50"))+ conditions = [{"field": "amount", "op": "gt", "value": 0}]+ assert evaluate_conditions("and", conditions, tx) is Truediff --git a/frontend/src/components/rule-dialog.tsx b/frontend/src/components/rule-dialog.tsxindex c2bf51dd..126161d8 100644--- a/frontend/src/components/rule-dialog.tsx+++ b/frontend/src/components/rule-dialog.tsx@@ -136,8 +136,13 @@ export function RuleDialog({setActions(prev => [...prev, { op: 'set_category', value: '' }])}+ // A blank condition value matches every transaction, so the rule would apply+ // its actions to the whole ledger. The API rejects these too.+ const hasBlankCondition = conditions.some(c => String(c.value ?? '').trim() === '')+function handleSubmit(e: React.FormEvent) {e.preventDefault()+ if (hasBlankCondition) returnonSave({name,conditions_op: conditionsOp,@@ -262,6 +267,9 @@ export function RuleDialog({</button></div>))}+ {hasBlankCondition && (+ <p className="text-xs text-rose-500">{t('rules.blankConditionValue')}</p>+ )}<buttontype="button"className="text-xs text-primary hover:text-primary/80 font-medium flex items-center gap-1"@@ -381,7 +389,7 @@ export function RuleDialog({<DialogFooter><Button type="button" variant="outline" onClick={onClose}>{t('common.cancel')}</Button>- <Button type="submit" disabled={loading}>+ <Button type="submit" disabled={loading || hasBlankCondition}>{loading ? t('common.loading') : t('common.save')}</Button></DialogFooter>diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex ab57a824..cc4b6701 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -836,6 +836,7 @@"andOp": "UND","orOp": "ODER","addCondition": "Bedingung hinzufügen",+ "blankConditionValue": "Jede Bedingung benötigt einen Wert. Eine leere Bedingung würde auf alle Transaktionen zutreffen.","addAction": "Aktion hinzufügen","setCategory": "Kategorie festlegen","setPayee": "Zahlungsempfänger festlegen",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex c3bb0546..a04794e6 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -836,6 +836,7 @@"andOp": "AND","orOp": "OR","addCondition": "Add condition",+ "blankConditionValue": "Every condition needs a value. A blank one would match every transaction.","addAction": "Add action","setCategory": "Set category","setPayee": "Set payee",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 0f72e36b..1a75e789 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -836,6 +836,7 @@"andOp": "Y","orOp": "O","addCondition": "Agregar condición",+ "blankConditionValue": "Cada condición necesita un valor. Una condición en blanco coincidiría con todas las transacciones.","addAction": "Agregar acción","setCategory": "Establecer categoría","setPayee": "Establecer beneficiario",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex 886d391d..28f99caf 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -836,6 +836,7 @@"andOp": "ET","orOp": "OU","addCondition": "Ajouter une condition",+ "blankConditionValue": "Chaque condition nécessite une valeur. Une condition vide correspondrait à toutes les transactions.","addAction": "Ajouter une action","setCategory": "Définir la catégorie","setPayee": "Définir le bénéficiaire",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 260f5c5d..e21b2642 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -836,6 +836,7 @@"andOp": "E","orOp": "O","addCondition": "Aggiungi condizione",+ "blankConditionValue": "Ogni condizione richiede un valore. Una condizione vuota corrisponderebbe a tutte le transazioni.","addAction": "Aggiungi azione","setCategory": "Imposta categoria","setPayee": "Imposta beneficiario",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 24d05c43..02447a84 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -890,6 +890,7 @@"andOp": "ORAZ","orOp": "LUB","addCondition": "Dodaj warunek",+ "blankConditionValue": "Każdy warunek wymaga wartości. Pusty warunek pasowałby do wszystkich transakcji.","addAction": "Dodaj akcję","setCategory": "Ustaw kategorię","setPayee": "Ustaw odbiorcę",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 5e9fe6d8..19532c98 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -836,6 +836,7 @@"andOp": "E (AND)","orOp": "OU (OR)","addCondition": "Adicionar condição",+ "blankConditionValue": "Toda condição precisa de um valor. Uma condição em branco corresponderia a todas as transações.","addAction": "Adicionar ação","setCategory": "Definir categoria","setPayee": "Definir beneficiário",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 29a579d0..69deb952 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -836,6 +836,7 @@"andOp": "E (AND)","orOp": "OU (OR)","addCondition": "Adicionar condição",+ "blankConditionValue": "Todas as condições precisam de um valor. Uma condição em branco corresponderia a todas as transações.","addAction": "Adicionar ação","setCategory": "Definir categoria","setPayee": "Definir beneficiário",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex b47e2e75..3e9cc4e9 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -836,6 +836,7 @@"andOp": "И","orOp": "ИЛИ","addCondition": "Добавить условие",+ "blankConditionValue": "Каждому условию нужно значение. Пустое условие совпадёт со всеми транзакциями.","addAction": "Добавить действие","setCategory": "Установить категорию","setPayee": "Установить получателя",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex 91420632..c7e0ff73 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -836,6 +836,7 @@"andOp": "І","orOp": "АБО","addCondition": "Додати умову",+ "blankConditionValue": "Кожна умова потребує значення. Порожня умова збігатиметься з усіма транзакціями.","addAction": "Додати дію","setCategory": "Установити категорію","setPayee": "Установити отримувача",