Sanity check for configured folders

* On startup: Check they are writable, if not revert to defaults
  * On settings save: Check they are writable, if not return an HTTP 400
  * In the settings dialog: Allow quick check of writability via Test
    buttons

Should hopefully prevent users from nuking their instance by configuring
some custom folder that isn't writable.

TODO:
Currently simply doesn't close the settings dialog, needs some message
or something (or client side folder validation on clicking the button).
This commit is contained in:
Gina Häußge committed 2018-04-27 17:44:07 +02:00
1 parent 9e32439f44
commit 4bbe49ac6d
6 files changed
+228 -44

No files matched your search

+25 -13
View File
@@ -30,6 +30,14 @@ Test paths or URLs
existence but also whether it is of the specified type. Optional.
* ``check_access``: A list of any of ``r``, ``w`` and ``x``. If present it will also
be checked if OctoPrint has read, write, execute permissions on the specified path.
* ``allow_create_dir``: If ``check_type`` is provided and set to ``dir``, this will allow
OctoPrint to create the target ``path`` as a directory if it doesn't yet exist to allow
for further tests.
* ``check_writable_dir``: If ``check_type`` is provided and set to ``dir``, this will
check that the provided ``path`` is a writable directory. OctoPrint not only check if the
permissions on the directory allow for writing but also attempt to write (and delete) a
small test file ``.testballoon.txt`` to the directory to test if writing is actually
possible.
The ``path`` command returns a :http:statuscode:`200` with a :ref:`path test result <sec-api-util-datamodel-pathtestresult>`
when the test could be performed. The status code of the response does NOT reflect the
@@ -278,19 +286,23 @@ Test paths or URLs
"result": true
}
:json command: The command to execute, currently either ``path`` or ``url``
:json path: ``path`` command only: the path to test
:json check_type: ``path`` command only: the type of path to test for, either ``file`` or ``dir``
:json check_access: ``path`` command only: a list of access permissions to check for
:json url: ``url`` command only: the URL to test
:json status: ``url`` command only: one or more expected status codes
:json method: ``url`` command only: the HTTP method to use for the check
:json timeout: ``url`` and ``server`` commands only: the timeout for the test request
:json response: ``url`` command only: whether to include response data and if so in what form
:json host: ``server`` command only: the server to test
:json port: ``server`` command only: the port to test
:json protocol: ``server`` command only: the protocol to test
:statuscode 200: No error occurred
:json command: The command to execute, currently either ``path`` or ``url``
:json path: ``path`` command only: the path to test
:json check_type: ``path`` command only: the type of path to test for, either ``file`` or ``dir``
:json check_access: ``path`` command only: a list of access permissions to check for
:json allow_create_dir: ``path`` command and ``checktype`` of ``dir`` only: whether to allow creation of the
directory if it doesn't yet exist (``true``) or not (``false``, default)
:json check_writable_dir: ``path`` command and ``checktype`` of ``dir`` only: whether to test if the directory
is writable by also trying to create a test file in it (``true``) or not (``false``, default)
:json url: ``url`` command only: the URL to test
:json status: ``url`` command only: one or more expected status codes
:json method: ``url`` command only: the HTTP method to use for the check
:json timeout: ``url`` and ``server`` commands only: the timeout for the test request
:json response: ``url`` command only: whether to include response data and if so in what form
:json host: ``server`` command only: the server to test
:json port: ``server`` command only: the port to test
:json protocol: ``server`` command only: the protocol to test
:statuscode 200: No error occurred
.. _sec-api-util-datamodel:
+29 -2
View File
@@ -278,9 +278,23 @@ def utilTestPath():
check_access = [check for check in request_check_access if check in ("r", "w", "x")]
exists = os.path.exists(path)
allow_create_dir = data.get("allow_create_dir", False) and check_type == "dir"
check_writable_dir = data.get("check_writable_dir", False) and check_type == "dir"
if check_writable_dir and "w" not in check_access:
check_access.append("w")
# check if path exists
exists = os.path.exists(path)
if not exists and check_type == "dir" and allow_create_dir:
try:
os.makedirs(path)
except:
logging.getLogger(__name__).exception("Error while trying to create {}".format(path))
return jsonify(path=path, exists=False, typeok=False, access=False, result=False)
else:
exists = True
# check path type
type_mapping = dict(file=os.path.isfile, dir=os.path.isdir)
if check_type:
typeok = type_mapping[check_type](path)
@@ -290,10 +304,23 @@ def utilTestPath():
# check if path allows requested access
access_mapping = dict(r=os.R_OK, w=os.W_OK, x=os.X_OK)
if check_access:
access = os.access(path, reduce(lambda x, y: x | y, map(lambda a: access_mapping[a], check_access)))
mode = 0
for a in map(lambda x: access_mapping[x], check_access):
mode |= a
access = os.access(path, mode)
else:
access = exists
if check_writable_dir and check_type == "dir":
try:
test_path = os.path.join(path, ".testballoon.txt")
with open(test_path, "wb") as f:
f.write("Test")
os.remove(test_path)
except:
logging.getLogger(__name__).exception("Error while testing if {} is really writable".format(path))
return jsonify(path=path, exists=exists, typeok=typeok, access=False, result=False)
return jsonify(path=path, exists=exists, typeok=typeok, access=access, result=exists and typeok and access)
elif command == "url":
+13 -8
View File
@@ -290,7 +290,9 @@ def setSettings():
return make_response("Malformed request, need settings dictionary, "
"got a {} instead: {!r}".format(type(data).__name__, data), 400)
_saveSettings(data)
response = _saveSettings(data)
if response:
return response
return getSettings()
@@ -318,6 +320,16 @@ def _saveSettings(data):
# NOTE: Remember to adjust the docs of the data model on the Settings API if anything
# is changed, added or removed here
if "folder" in data.keys():
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)
if "api" in data.keys():
if "enabled" in data["api"]: s.setBoolean(["api", "enabled"], data["api"]["enabled"])
if "allowCrossOrigin" in data["api"]: s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
@@ -418,13 +430,6 @@ def _saveSettings(data):
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
if "folder" in data.keys():
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"])
if "temperature" in data.keys():
if "profiles" in data["temperature"]:
result = []
+77 -11
View File
@@ -621,6 +621,8 @@ class Settings(object):
self._script_env = self._init_script_templating()
self._sanity_check_folders()
def _init_basedir(self, basedir):
if basedir is not None:
self._basedir = basedir
@@ -628,7 +630,16 @@ class Settings(object):
self._basedir = _default_basedir(_APPNAME)
if not os.path.isdir(self._basedir):
os.makedirs(self._basedir)
try:
os.makedirs(self._basedir)
except:
self._logger.fatal("Could not create basefolder at {}. This is a fatal error, OctoPrint "
"can't run without a writable base folder.".format(self._basedir), exc_info=1)
raise
def _sanity_check_folders(self):
for folder in default_settings["folder"].keys():
self.getBaseFolder(folder, log_error=True)
def _get_default_folder(self, type):
folder = default_settings["folder"][type]
@@ -1477,7 +1488,7 @@ class Settings(object):
return value.lower() in valid_boolean_trues
return value is not None
def getBaseFolder(self, type, create=True):
def getBaseFolder(self, type, create=True, allow_fallback=True, log_error=False):
if type not in default_settings["folder"].keys() + ["base"]:
return None
@@ -1485,17 +1496,33 @@ class Settings(object):
return self._basedir
folder = self.get(["folder", type])
default_folder = self._get_default_folder(type)
if folder is None:
folder = self._get_default_folder(type)
folder = default_folder
if not os.path.exists(folder):
if create:
os.makedirs(folder)
try:
_validate_folder(folder, create=create, writable=True, log_error=log_error)
except:
if folder != default_folder and allow_fallback:
if log_error:
self._logger.error("Invalid configured {} folder at {}, attempting to "
"fall back on default folder at {}".format(type,
folder,
default_folder))
_validate_folder(default_folder, create=create, writable=True, log_error=log_error)
folder = default_folder
try:
del self._config["folder"][type]
if not len(self._config["folder"]):
del self._config["folder"]
self._dirty = True
self._dirty_time = time.time()
self.save()
except KeyError:
pass
else:
raise IOError("No such folder: {}".format(folder))
elif os.path.isfile(folder):
# hardening against misconfiguration, see #1953
raise IOError("Expected a folder at {} but found a file instead".format(folder))
raise
return folder
@@ -1661,7 +1688,7 @@ class Settings(object):
else:
self.set(path, False, **kwargs)
def setBaseFolder(self, type, path, force=False):
def setBaseFolder(self, type, path, force=False, validate=True):
if type not in default_settings["folder"].keys():
return None
@@ -1674,6 +1701,9 @@ class Settings(object):
self._dirty = True
self._dirty_time = time.time()
elif (path != currentPath and path != defaultPath) or force:
if validate:
_validate_folder(path)
if not "folder" in self._config.keys():
self._config["folder"] = {}
self._config["folder"][type] = path
@@ -1713,3 +1743,39 @@ def _default_basedir(applicationName):
return os.path.join(os.environ["APPDATA"], applicationName)
else:
return os.path.expanduser(os.path.join("~", "." + applicationName.lower()))
def _validate_folder(folder, create=True, writable=True, log_error=False):
logger = logging.getLogger(__name__)
if not os.path.exists(folder):
if create:
try:
os.makedirs(folder)
except:
if log_error:
logger.exception("Could not create {}".format(folder))
raise IOError("Folder for type {} at {} does not exist and creation failed".format(type, folder))
else:
raise IOError("No such folder: {}".format(folder))
elif os.path.isfile(folder):
# hardening against misconfiguration, see #1953
raise IOError("Expected a folder at {} but found a file instead".format(folder))
elif writable:
# make sure we can also write into the folder
error = "Folder at {} doesn't appear to be writable, please fix its permissions".format(folder)
if not os.access(folder, os.W_OK):
raise IOError(error)
else:
# try to write a file to the folder - on network shares that might be the only reliable way
# to determine whether things are *actually* writable
testfile = os.path.join(folder, ".testballoon.txt")
try:
with open(testfile, "wb") as f:
f.write("test")
os.remove(testfile)
except:
if log_error:
logger.exception("Could not write test file to {}".format(folder))
raise IOError(error)
@@ -252,6 +252,23 @@ $(function() {
self.server_onlineCheckBroken(false);
};
var folderTypes = ["uploads", "timelapse", "timelapseTmp", "logs", "watched"];
self.testFolderConfigText = {};
self.testFolderConfigOk = {};
self.testFolderConfigBroken = {};
_.each(folderTypes, function(folderType) {
self.testFolderConfigText[folderType] = ko.observable("");
self.testFolderConfigOk[folderType] = ko.observable(false);
self.testFolderConfigBroken[folderType] = ko.observable(false);
});
self.testFolderConfigReset = function() {
_.each(folderTypes, function(folderType) {
self.testFolderConfigText[folderType]("");
self.testFolderConfigOk[folderType](false);
self.testFolderConfigBroken[folderType](false);
});
};
self.observableCopies = {
"feature_waitForStart": "serial_waitForStart",
"feature_sendChecksum": "serial_sendChecksum",
@@ -437,9 +454,46 @@ $(function() {
});
};
self.testFolderConfigBusy = ko.observable(false);
self.testFolderConfig = function(folder) {
var observable = "folder_" + folder;
if (!self.hasOwnProperty(observable)) return;
if (self.testFolderConfigBusy()) return;
self.testFolderConfigBusy(true);
var opts = {
check_type: "dir",
check_access: "w",
allow_create_dir: true,
check_writable_dir: true
};
var path = self[observable]();
OctoPrint.util.testPath(path, opts)
.done(function(response) {
if (!response.result) {
if (!response.exists) {
self.testFolderConfigText[folder](gettext("The path does not exist and cannot be created."));
} else if (!response.typeok) {
self.testFolderConfigText[folder](gettext("The path is not a folder."));
} else if (!response.access) {
self.testFolderConfigText[folder](gettext("The path is not writable."));
}
} else {
self.testFolderConfigText[folder](gettext("The path is valid"));
}
self.testFolderConfigOk[folder](response.result);
self.testFolderConfigBroken[folder](!response.result);
})
.always(function() {
self.testFolderConfigBusy(false);
});
};
self.onSettingsHidden = function() {
self.webcam_ffmpegPathReset();
self.server_onlineCheckReset();
self.testFolderConfigReset();
};
self.isDialogActive = function() {
@@ -1,34 +1,54 @@
<form class="form-horizontal">
<h3>{{ _('Folders') }}</h3>
<div class="control-group">
<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="controls">
<input type="text" class="input-block-level" data-bind="value: folder_uploads" id="settings-folderUploads">
<div class="input-append input-block-level">
<input type="text" data-bind="value: folder_uploads" 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">
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.timelapse, success: testFolderConfigOk.timelapse}">
<label class="control-label" for="settings-folderTimelapse">{{ _('Timelapse Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_timelapse" id="settings-folderTimelapse">
<div class="input-append input-block-level">
<input type="text" class="input-block-level" data-bind="value: folder_timelapse" 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">
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.timelapseTmp, success: testFolderConfigOk.timelapseTmp}">
<label class="control-label" for="settings-folderTimelapseTemp">{{ _('Timelapse Temp Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_timelapseTmp" id="settings-folderTimelapseTemp">
<div class="input-append input-block-level">
<input type="text" data-bind="value: folder_timelapseTmp" 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">
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.logs, success: testFolderConfigOk.logs}">
<label class="control-label" for="settings-folderLogs">{{ _('Logs Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_logs" id="settings-folderLogs">
<div class="input-append input-block-level">
<input type="text" data-bind="value: folder_logs" 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">
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.watched, success: testFolderConfigOk.watched}">
<label class="control-label" for="settings-folderWatched">{{ _('Watched Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_watched" id="settings-folderWatched">
<div class="input-append input-block-level">
<input type="text" data-bind="value: folder_watched" 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>
</div>
</div>
<div class="control-group">