🥅 Detect and deny duplicate folder path config

Closes #3754
This commit is contained in:
Gina Häußge committed 2020-10-09 13:53:00 +02:00
1 parent de81591b26
commit b96f7657e6
5 files changed
+153 -37

No files matched your search

+1 -6
View File
@@ -228,12 +228,7 @@ def init_settings(basedir, configfile):
try:
return settings(init=True, basedir=basedir, configfile=configfile)
except InvalidSettings as e:
message = "Error parsing the configuration file, it appears to be invalid YAML."
if e.line is not None and e.column is not None:
message += " The parser reported an error on line {}, column {}.".format(
e.line, e.column
)
raise FatalStartupError(message)
raise FatalStartupError(str(e))
def preinit_logging(
+30 -12
View File
@@ -21,6 +21,9 @@ from octoprint.settings import settings, valid_boolean_trues
# ~~ settings
FOLDER_TYPES = ("uploads", "timelapse", "timelapse_tmp", "logs", "watched")
FOLDER_MAPPING = {"timelapseTmp": "timelapse_tmp"}
def _lastmodified():
return settings().last_modified
@@ -444,18 +447,33 @@ def _saveSettings(data):
if "folder" in data:
try:
if "uploads" in data["folder"]:
s.setBaseFolder("uploads", data["folder"]["uploads"])
if "timelapse" in data["folder"]:
s.setBaseFolder("timelapse", data["folder"]["timelapse"])
if "timelapseTmp" in data["folder"]:
s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
if "logs" in data["folder"]:
s.setBaseFolder("logs", data["folder"]["logs"])
if "watched" in data["folder"]:
s.setBaseFolder("watched", data["folder"]["watched"])
except IOError:
return make_response("One of the configured folders is invalid", 400)
folders = dict(
(FOLDER_MAPPING.get(folder, folder), path)
for folder, path in data["folder"].items()
)
future = {}
for folder in FOLDER_TYPES:
future[folder] = s.getBaseFolder(folder)
if folder in folders:
future[folder] = data["folder"][folder]
for folder in data["folder"]:
if folder not in FOLDER_TYPES:
continue
for other_folder in FOLDER_TYPES:
if folder == other_folder:
continue
if future[folder] == future[other_folder]:
# duplicate detected, raise
raise ValueError(
"Duplicate folder path for {} and {}".format(
folder, other_folder
)
)
s.setBaseFolder(folder, future[folder])
except Exception:
return make_response("At least one of the configured folders is invalid", 400)
if "api" in data:
if "allowCrossOrigin" in data["api"]:
+54 -4
View File
@@ -455,12 +455,52 @@ class NoSuchSettingsPath(Exception):
class InvalidSettings(Exception):
def __init__(self, message, line=None, column=None, details=None):
self.message = message
pass
class InvalidYaml(InvalidSettings):
def __init__(self, file, line=None, column=None, details=None):
self.file = file
self.line = line
self.column = column
self.details = details
def __str__(self):
message = (
"Error parsing the configuration file {}, "
"it is invalid YAML.".format(self.file)
)
if self.line and self.column:
message += " The parser reported an error on line {}, column {}.".format(
self.line, self.column
)
return message
class DuplicateFolderPaths(InvalidSettings):
def __init__(self, folders):
self.folders = folders
self.duplicates = {}
for folder, path in folders.items():
duplicates = []
for other_folder, other_path in folders.items():
if other_folder == folder:
continue
if other_path == path:
duplicates.append(other_folder)
if len(duplicates):
self.duplicates[folder] = duplicates
def __str__(self):
duplicates = [
"{} (duplicates: {})".format(folder, ", ".join(dupes))
for folder, dupes in self.duplicates.items()
]
return "There are duplicate folder paths configured: {}".format(
", ".join(duplicates)
)
class HierarchicalChainMap(ChainMap):
def deep_dict(self, root=None):
@@ -951,8 +991,8 @@ class Settings(object):
line = None
column = None
raise InvalidSettings(
"Invalid YAML file: {}".format(self._configfile),
raise InvalidYaml(
self._configfile,
details=details,
line=line,
column=column,
@@ -964,6 +1004,7 @@ class Settings(object):
if migrate:
self._migrate_config()
self._validate_config()
self._forget_hashes()
@@ -1533,6 +1574,15 @@ class Settings(object):
return True
return False
def _validate_config(self):
# validate uniqueness of folder paths
folder_keys = self.get(["folder"], merged=True).keys()
folders = dict(
(folder_key, self.getBaseFolder(folder_key)) for folder_key in folder_keys
)
if len(folders.values()) != len(set(folders.values())):
raise DuplicateFolderPaths(folders)
def backup(self, suffix=None, path=None, ext=None, hidden=False):
import shutil
@@ -312,13 +312,45 @@ $(function () {
};
var folderTypes = ["uploads", "timelapse", "timelapseTmp", "logs", "watched"];
var checkForDuplicateFolders = function () {
_.each(folderTypes, function (folderType) {
var path = self["folder_" + folderType]();
var duplicate = false;
_.each(folderTypes, function (otherFolderType) {
if (folderType !== otherFolderType) {
duplicate =
duplicate || path === self["folder_" + otherFolderType]();
}
});
self.testFolderConfigDuplicate[folderType](duplicate);
});
};
self.testFolderConfigText = {};
self.testFolderConfigOk = {};
self.testFolderConfigBroken = {};
self.testFolderConfigDuplicate = {};
self.testFolderConfigError = {};
self.testFolderConfigSuccess = {};
_.each(folderTypes, function (folderType) {
self.testFolderConfigText[folderType] = ko.observable("");
self.testFolderConfigOk[folderType] = ko.observable(false);
self.testFolderConfigBroken[folderType] = ko.observable(false);
self.testFolderConfigDuplicate[folderType] = ko.observable(false);
self.testFolderConfigError[folderType] = ko.pureComputed(function () {
return (
self.testFolderConfigBroken[folderType]() ||
self.testFolderConfigDuplicate[folderType]()
);
});
self.testFolderConfigSuccess[folderType] = ko.pureComputed(function () {
return (
self.testFolderConfigOk[folderType]() &&
!self.testFolderConfigDuplicate[folderType]()
);
});
self["folder_" + folderType].subscribe(checkForDuplicateFolders);
});
self.testFolderConfigReset = function () {
_.each(folderTypes, function (folderType) {
@@ -327,6 +359,13 @@ $(function () {
self.testFolderConfigBroken[folderType](false);
});
};
self.testFoldersDuplicate = ko.pureComputed(function () {
var foundDupe = false;
_.each(folderTypes, function (folderType) {
foundDupe = foundDupe || self.testFolderConfigDuplicate[folderType]();
});
return foundDupe;
});
self.observableCopies = {
feature_waitForStart: "serial_waitForStart",
@@ -1311,18 +1350,26 @@ $(function () {
} else {
options = {
success: successCallback,
sending: setAsSending == true
sending: setAsSending === true
};
}
self.settingsDialog.trigger("beforeSave");
self.sawUpdateEventWhileSending = false;
self.sending(data == undefined || options.sending || false);
self.sending(data === undefined || options.sending || false);
if (data == undefined) {
if (data === undefined) {
// we also only send data that actually changed when no data is specified
data = getOnlyChangedData(self.getLocalData(), self.lastReceivedSettings);
var localData = self.getLocalData();
data = getOnlyChangedData(localData, self.lastReceivedSettings);
}
// final validation
if (self.testFoldersDuplicate()) {
// duplicate folders configured, we refuse to send any folder config
// to the server
delete data.folder;
}
self.active = true;
@@ -1,51 +1,50 @@
<form class="form-horizontal" onsubmit="return false;">
<h3>{{ _('Folders') }}</h3>
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.uploads, success: testFolderConfigOk.uploads}">
<label class="control-label" for="settings-folderUploads">{{ _('Upload Folder') }}</label>
<div class="control-group" data-bind="css: {error: testFolderConfigError.uploads, success: testFolderConfigSuccess.uploads}"> <label class="control-label" for="settings-folderUploads">{{ _('Upload Folder') }}</label>
<div class="controls">
<div class="input-append input-block-level">
<input type="text" data-bind="value: folder_uploads" id="settings-folderUploads">
<input type="text" data-bind="value: folder_uploads, valueUpdate: 'input'" id="settings-folderUploads">
<a class="btn add-on" data-bind="click: function() { testFolderConfig('uploads'); }, enable: folder_uploads() && !testFolderConfigBusy(), css: {disabled: !folder_uploads() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
</div>
<span class="help-block" data-bind="visible: testFolderConfigBroken.uploads() || testFolderConfigOk.uploads(), text: testFolderConfigText.uploads"></span>
</div>
</div>
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.timelapse, success: testFolderConfigOk.timelapse}">
<div class="control-group" data-bind="css: {error: testFolderConfigError.timelapse, success: testFolderConfigSuccess.timelapse}">
<label class="control-label" for="settings-folderTimelapse">{{ _('Timelapse Folder') }}</label>
<div class="controls">
<div class="input-append input-block-level">
<input type="text" class="input-block-level" data-bind="value: folder_timelapse" id="settings-folderTimelapse">
<input type="text" class="input-block-level" data-bind="value: folder_timelapse, valueUpdate: 'input'" id="settings-folderTimelapse">
<a class="btn add-on" data-bind="click: function() { testFolderConfig('timelapse'); }, enable: folder_timelapse() && !testFolderConfigBusy(), css: {disabled: !folder_timelapse() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
</div>
<span class="help-block" data-bind="visible: testFolderConfigBroken.timelapse() || testFolderConfigOk.timelapse(), text: testFolderConfigText.timelapse"></span>
</div>
</div>
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.timelapseTmp, success: testFolderConfigOk.timelapseTmp}">
<div class="control-group" data-bind="css: {error: testFolderConfigError.timelapseTmp, success: testFolderConfigSuccess.timelapseTmp}">
<label class="control-label" for="settings-folderTimelapseTemp">{{ _('Timelapse Temp Folder') }}</label>
<div class="controls">
<div class="input-append input-block-level">
<input type="text" data-bind="value: folder_timelapseTmp" id="settings-folderTimelapseTemp">
<input type="text" data-bind="value: folder_timelapseTmp, valueUpdate: 'input'" id="settings-folderTimelapseTemp">
<a class="btn add-on" data-bind="click: function() { testFolderConfig('timelapseTmp'); }, enable: folder_timelapseTmp() && !testFolderConfigBusy(), css: {disabled: !folder_timelapseTmp() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
</div>
<span class="help-block" data-bind="visible: testFolderConfigBroken.timelapseTmp() || testFolderConfigOk.timelapseTmp(), text: testFolderConfigText.timelapseTmp"></span>
</div>
</div>
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.logs, success: testFolderConfigOk.logs}">
<div class="control-group" data-bind="css: {error: testFolderConfigError.logs, success: testFolderConfigSuccess.logs}">
<label class="control-label" for="settings-folderLogs">{{ _('Logs Folder') }}</label>
<div class="controls">
<div class="input-append input-block-level">
<input type="text" data-bind="value: folder_logs" id="settings-folderLogs">
<input type="text" data-bind="value: folder_logs, valueUpdate: 'input'" id="settings-folderLogs">
<a class="btn add-on" data-bind="click: function() { testFolderConfig('logs'); }, enable: folder_logs() && !testFolderConfigBusy(), css: {disabled: !folder_logs() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
</div>
<span class="help-block" data-bind="visible: testFolderConfigBroken.logs() || testFolderConfigOk.logs(), text: testFolderConfigText.logs"></span>
</div>
</div>
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.watched, success: testFolderConfigOk.watched}">
<div class="control-group" data-bind="css: {error: testFolderConfigError.watched, success: testFolderConfigSuccess.watched}">
<label class="control-label" for="settings-folderWatched">{{ _('Watched Folder') }}</label>
<div class="controls">
<div class="input-append input-block-level">
<input type="text" data-bind="value: folder_watched" id="settings-folderWatched">
<input type="text" data-bind="value: folder_watched, valueUpdate: 'input'" id="settings-folderWatched">
<a class="btn add-on" data-bind="click: function() { testFolderConfig('watched'); }, enable: folder_watched() && !testFolderConfigBusy(), css: {disabled: !folder_watched() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
</div>
<span class="help-block" data-bind="visible: testFolderConfigBroken.watched() || testFolderConfigOk.watched(), text: testFolderConfigText.watched"></span>
@@ -58,6 +57,13 @@
</label>
</div>
</div>
<div class="alert alert-error" data-bind="visible: testFoldersDuplicate">
{% trans %}
Two or more of the folders configured share a location. This is not
supported. You need to fix this, until then no changes to your folder
configuration will be persisted when saving the settings.
{% endtrans %}
</div>
<h3>{{ _('Disk space thresholds') }}</h3>