ui: restrict allowed characters in the rule name

Since the name of the rule is used for the file name on the disk,
certain characters caused issues when saving the rule, like '/'.

Now if the user types or pastes '/' in the name field, a warning is
displayed, indicating that some characters are not allowed.

Closes #1166
This commit is contained in:
Gustavo Iñiguez Goia 2024-09-03 12:26:43 +02:00
parent 1984fb9954
commit 2e90f3832d
2 changed files with 48 additions and 1 deletions

View file

@ -16,7 +16,13 @@ from opensnitch.nodes import Nodes
from opensnitch.database import Database
from opensnitch.database.enums import RuleFields, ConnFields
from opensnitch.version import version
from opensnitch.utils import Message, FileDialog, Icons, NetworkInterfaces
from opensnitch.utils import (
Message,
FileDialog,
Icons,
NetworkInterfaces,
qvalidator
)
from opensnitch.rules import Rule, Rules
DIALOG_UI_PATH = "%s/../res/ruleseditor.ui" % os.path.dirname(sys.modules[__name__].__file__)
@ -33,6 +39,8 @@ class RulesEditorDialog(QtWidgets.QDialog, uic.loadUiType(DIALOG_UI_PATH)[0]):
LAN_LABEL = "LAN"
MULTICAST_LABEL = "MULTICAST"
INVALID_RULE_NAME_CHARS = '/'
ADD_RULE = 0
EDIT_RULE = 1
WORK_MODE = ADD_RULE
@ -55,6 +63,10 @@ class RulesEditorDialog(QtWidgets.QDialog, uic.loadUiType(DIALOG_UI_PATH)[0]):
self.setupUi(self)
self.setWindowIcon(appicon)
self.ruleNameValidator = qvalidator.RestrictChars(RulesEditorDialog.INVALID_RULE_NAME_CHARS)
self.ruleNameValidator.result.connect(self._cb_rule_name_validator_result)
self.ruleNameEdit.setValidator(self.ruleNameValidator)
self.buttonBox.setStandardButtons(
QtWidgets.QDialogButtonBox.Help |
QtWidgets.QDialogButtonBox.Reset |
@ -139,6 +151,16 @@ class RulesEditorDialog(QtWidgets.QDialog, uic.loadUiType(DIALOG_UI_PATH)[0]):
def _bool(self, s):
return s == 'True'
def _cb_rule_name_validator_result(self, result):
if result == QtGui.QValidator.Invalid:
self._set_status_error(
QC.translate("rules",
"Invalid rule name (not allowed characters: '{0}' )".format(RulesEditorDialog.INVALID_RULE_NAME_CHARS)
)
)
else:
self._set_status_message("")
def _cb_accept_clicked(self):
pass

View file

@ -0,0 +1,25 @@
from PyQt5 import QtCore, QtGui
class RestrictChars(QtGui.QValidator):
result = QtCore.pyqtSignal(object)
def __init__(self, restricted_chars, *args, **kwargs):
QtGui.QValidator.__init__(self, *args, **kwargs)
self._restricted_chars = restricted_chars
def validate(self, value, pos):
# allow to delete all characters
if len(value) == 0:
return QtGui.QValidator.Intermediate, value, pos
# user can type characters or paste them.
# pos value when pasting can be any number, depending on where did the
# user paste the characters.
for char in self._restricted_chars:
if char in value:
self.result.emit(QtGui.QValidator.Invalid)
return QtGui.QValidator.Invalid, value, pos
self.result.emit(QtGui.QValidator.Acceptable)
return QtGui.QValidator.Acceptable, value, pos