Compare commits

...
34 Commits
Author SHA1 Message Date
Gina Häußge 87f4a4e8c9 🔖 Preparing release of 1.8.2 2022-08-09 13:54:24 +02:00
Gina Häußge 91ef0c0d99 📌 Pin Flask to 2.1
Flask 2.2 requires werkzeug 2.2 which we can't
upgrade to due to flask-login, and the current
version pins might be causing issues in the
field.

TODO for 1.9.0: upgrade werkzeug & flask if
possible with flask-login.
2022-08-09 13:03:42 +02:00
Gina Häußge dabdd40806 🔒️ Fix another open redirect issue
The redirect parameter to the login dialog now gets restricted to local URLs (as detected by unset scheme & netloc) that match a short list of allowed endpoints routes.
2022-08-04 10:33:31 +02:00
Gina Häußge 4a9b18582d Merge branch 'master' into staging/bugfix 2022-08-02 12:27:20 +02:00
Christian Clauss 5753ee3cfa ✏ Highlight branch names in PR template (#4573) 2022-08-01 11:41:55 +02:00
Christian Clauss c18a5046d5 ✏️ timelapse.rst: Fix typos (#4569) 2022-07-12 18:48:39 +01:00
Gina Häußge 2e1ec42c5b 👷‍♂️ Needs to run against pull_request_target 2022-06-23 10:50:06 +02:00
Gina Häußge 6bddada8c2 👷‍♂️ Add task labeling 2022-06-21 10:12:53 +02:00
Gina Häußge 008292ce60 Use org wide secret 2022-06-20 15:56:07 +02:00
Gina Häußge 01f24e6cea 👷‍♂️ Add issues/PRs to backlog automatically 2022-06-20 15:49:00 +02:00
Gina Häußge 53b9b61857 👷 Only trigger release jobs on main repo 2022-05-30 14:51:54 +02:00
Gina Häußge e2349b4565 👷 Ignore errors on Discord hook & e2e
e2e are too flaky, discord hook might be unconfigured in a fork.
2022-05-30 14:45:16 +02:00
Gina Häußge 422e3d2b66 🔖 staging/bugfix is now 1.8.2.dev 2022-05-24 12:25:17 +02:00
Gina Häußge 260a1aef11 🔖 Preparing release of 1.8.1 2022-05-24 10:55:31 +02:00
Gina Häußge 866c9a20d7 🐛 Fix a redirect loop on login
If guest/anonymous users where configured with read-only rights,
the login dialog would enter a redirect loop due to require_login_with
not recognizing anonymous use with permissions as valid.

Fixes #4516
2022-05-24 10:26:57 +02:00
Gina Häußge 77904a71b4 🔒️ Fix an XSS issue in the user/group delete confirmation
Requires admin rights to exploit in any way.
With OctoPrint 1.8.0 all cookies with credentials
are http-only and thus not targetable (to my
knowledge) by this.

CVSS:3.1/AV:L/AC:H/PR:N/UI:R/S:U/C:L/I:N/A:N, Severity Low
2022-05-19 13:08:16 +02:00
Gina Häußge 89fbcfd214 🐛 Gracefully handle errors scanning /dev
Solves an issue with Octo4a on some Android devices.
2022-05-19 09:38:00 +02:00
Gina Häußge 26aac1701f 🔖 staging/bugfix is 1.8.1.dev 2022-05-19 09:25:03 +02:00
Gina Häußge f430257d70 Merge branch 'rc/maintenance' 2022-05-16 14:58:38 +02:00
Gina Häußge d2a9aaceda 🔖 Preparing release of 1.8.0 2022-05-16 14:55:05 +02:00
Gina Häußge 8ca327669c 🔒️ XSS in webcam stream URL test in Chrome
Apparently Chrome will happily create URL objects from
what is actually HTML tags. So now we will also
URI encode the stream URL prior to embedding in the page.
2022-05-12 18:58:16 +02:00
Gina Häußge d1fca86636 🥅 Better error handling 2022-05-12 10:58:08 +02:00
Gina Häußge 4d9e86ca0f 🐛 We also recognize webrtcs: for webcam streams
Thanks for the heads-up, @cp2004
2022-05-12 10:57:39 +02:00
Gina Häußge 6d259d7e6f 🔒️ Fix XSS in webcam stream test 2022-05-11 16:40:07 +02:00
Gina Häußge 5ef16773c8 🔒️ Escape requested user id
Fixes an XSS issue.
2022-05-11 13:03:40 +02:00
Gina Häußge 8087528e4a 🔒️ Sanitize and validate login redirect
Fixes an XSS and an open redirect issue.
2022-05-11 13:02:52 +02:00
Gina Häußge 700034d028 🔒️ Set remember_me cookie http only 2022-05-10 20:56:48 +02:00
Gina Häußge 885ca31168 👷‍♂️ Fix nightly merge
The action needed an upgrade due to a behaviour change in latest git.
2022-05-04 11:28:25 +02:00
Billy Richardson 64c21ba8f0 ✏️ Documentation spelling fixes (#4497) 2022-04-24 17:21:13 +01:00
Gina Häußge 53dbde2ef9 🔖 staging/maintenance is now 1.8.0rc6.dev 2022-04-12 16:21:41 +02:00
Gina Häußge 45598764e6 🔖 Preparing release of 1.8.0rc5 2022-04-12 15:30:56 +02:00
Gina Häußge 2ecc1c944f 🥅 Only use the first value pair for a temp sensor
This protects against lines from the printer like

  T:210.04 /210.00 B:52.00 /52.00 @:85 B:1234.0 /1234.0

We've seen *so* much weird stuff out there in firmware, let's better
be safe rather than sorry and rule out latter values from overwriting
former values just in case.
2022-04-12 14:26:55 +02:00
Gina Häußge d81504c12e 🐛 Fix folder saving & config migration
Settings._config has been turned into a read-only view by the
recent refactoring of the settings hierarchy. Refactored our use
as needed to still function and added deprecated decorator to
getter and setter property to communicate this change in behaviour.

_config wasn't documented, so it is not part of the official API and
thus this doesn't qualify as a breaking change, however there might
be plugins there that went beyond the documented API and use it in
some way (possibly even stuff I have written in the past), so
best give them a heads-up.

Closes #4486
2022-04-11 16:51:22 +02:00
Gina Häußge 302ccc087b 🔖 staging/maintenance is now 1.8.0rc5.dev 2022-04-05 14:49:48 +02:00
37 changed files with 1914 additions and 1740 deletions

No files matched your search

+10 -10
View File
@@ -1,10 +1,10 @@
<!--
Thank you for your interest into contributing to OctoPrint, it's
Thank you for your interest in contributing to OctoPrint, it's
highly appreciated!
Please make sure you have read the "guidelines for contributing" as
linked just above this form, there's a section on Pull Requests in there
as well that contains important information.
as well which contains important information.
As a summary, please make sure you have ticked all points on this
checklist:
@@ -16,25 +16,25 @@ checklist:
made sure your changes don't interfere with current development by
talking it through with the maintainers, e.g. through a
Brainstorming ticket
* [ ] Your PR targets OctoPrint's devel branch if it's a completely
new feature, or maintenance if it's a bug fix or improvement of
* [ ] Your PR targets OctoPrint's `devel` branch if it's a completely
new feature, or `maintenance` if it's a bug fix or improvement of
existing functionality for the current stable version (no PRs
against master or anything else please)
against `master` or anything else please)
* [ ] Your PR was opened from a custom branch on your repository
(no PRs from your version of master, maintenance or devel please),
e.g. dev/my_new_feature or fix/my_bugfix
(no PRs from your version of `master`, `maintenance`, or `devel`
please), e.g. `dev/my_new_feature` or `fix/my_bugfix`
* [ ] Your PR only contains relevant changes: no unrelated files,
no dead code, ideally only one commit - rebase and squash your PR
if necessary!
* [ ] Your changes follow the existing coding style
* [ ] If your changes include style sheets: You have modified the
.less source files, not the .css files (those are generated with
lessc)
`.less` source files, not the `.css` files (those are generated
with `lessc`)
* [ ] You have tested your changes (please state how!) - ideally you
have added unit tests
* [ ] You have run the existing unit tests against your changes and
nothing broke
* [ ] You have added yourself to the AUTHORS.md file :)
* [ ] You have added yourself to the `AUTHORS.md` file :)
<!--
Describe your PR further using the template provided below. The more
+20
View File
@@ -0,0 +1,20 @@
name: Add issues/PRs to backlog automatically
on:
issues:
types:
- opened
- transferred
pull_request_target:
types:
- opened
jobs:
add-to-project:
name: Add issue or PR to OctoPrint Backlog project
runs-on: ubuntu-latest
steps:
- uses: actions/add-to-project@main
with:
project-url: https://github.com/orgs/OctoPrint/projects/6
github-token: ${{ secrets.BACKLOG_PROJECT_ACCESS }}
+4 -3
View File
@@ -96,6 +96,7 @@ jobs:
name: 🧪 E2E tests
needs: build
runs-on: ubuntu-latest
continue-on-error: true
steps:
- name: ⬇ Checkout code
uses: actions/checkout@v2
@@ -141,7 +142,7 @@ jobs:
publish-on-testpypi:
name: 📦 Publish on TestPyPI
if: github.event_name == 'release'
if: github.event_name == 'release' && github.repository == 'OctoPrint/OctoPrint'
needs:
- pre-commit
- test-unit
@@ -163,7 +164,7 @@ jobs:
publish-on-pypi:
name: 📦 Publish tagged releases to PyPI
if: github.event_name == 'release'
if: github.event_name == 'release' && github.repository == 'OctoPrint/OctoPrint'
needs: publish-on-testpypi
runs-on: ubuntu-latest
steps:
@@ -179,7 +180,7 @@ jobs:
notify-custopizer-build:
name: 📧 Notify OctoPi-UpToDate
if: github.event_name == 'release'
if: github.event_name == 'release' && github.repository == 'OctoPrint/OctoPrint'
needs: publish-on-pypi
runs-on: ubuntu-latest
steps:
+6 -1
View File
@@ -28,6 +28,11 @@ jobs:
labels = labels.filter(label => label !== 'triage');
setLabels = true;
}
if (context.payload.issue.title.match(/\[task\]/i)) {
labels.push('task');
labels = labels.filter(label => label !== 'triage');
setLabels = true;
}
if (labels.length === 0) {
labels.push('triage');
@@ -37,7 +42,7 @@ jobs:
}
case 'closed': {
if (labels.includes('bug') || labels.includes('request') || labels.includes('improvement')) {
if (labels.includes('bug') || labels.includes('request') || labels.includes('improvement') || labels.includes('task')) {
labels.push('done');
setLabels = true;
}
+2 -2
View File
@@ -15,7 +15,7 @@ jobs:
fetch-depth: 0
- name: 🔀 Merge master into maintenance
uses: robotology/gh-action-nightly-merge@v1.3.2
uses: robotology/gh-action-nightly-merge@v1.3.3
with:
stable_branch: "master"
development_branch: "maintenance"
@@ -24,7 +24,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: 🔀 Merge maintenance into devel
uses: robotology/gh-action-nightly-merge@v1.3.2
uses: robotology/gh-action-nightly-merge@v1.3.3
with:
stable_branch: "maintenance"
development_branch: "devel"
+4
View File
@@ -31,12 +31,14 @@ jobs:
run: |
pip install .
- name: 📧 Discord success notification
continue-on-error: true
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` was successful"
- name: 📧 Discord failure notification
continue-on-error: true
if: failure()
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
@@ -65,12 +67,14 @@ jobs:
run: |
pip install https://github.com/OctoPrint/OctoPrint/archive/${{ steps.latest.outputs.release }}.zip
- name: 📧 Discord success notification
continue-on-error: true
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
uses: Ilshidur/action-discord@master
with:
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful"
- name: 📧 Discord failure notification
continue-on-error: true
if: failure()
env:
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
+6 -6
View File
@@ -24,15 +24,15 @@ maintenance 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
fix/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
improve/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
# staging/bugfix is the branch for preparation of the 1.7.4 bugfix release
# staging/bugfix is the branch for preparation of the 1.8.1 bugfix release
# so are any bug/... branches
staging/bugfix 1.7.4 59cbfadf8922d85b9df40f8d0173e8c21724c3b8 pep440-dev
bug/.* 1.7.4 59cbfadf8922d85b9df40f8d0173e8c21724c3b8 pep440-dev
staging/bugfix 1.8.2 260a1aef11432c421246019e25b6b744abbaed60 pep440-dev
bug/.* 1.8.2 260a1aef11432c421246019e25b6b744abbaed60 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.8.0rc4
# staging/maintenance is currently the branch for preparation of 1.8.0rc6
# so is regressionfix/...
staging/maintenance 1.8.0rc4 3c478036ae9edde3dd294af28bf1d8c78a2555d5 pep440-dev
regressionfix/.* 1.8.0rc4 3c478036ae9edde3dd294af28bf1d8c78a2555d5 pep440-dev
staging/maintenance 1.8.0rc6 45598764e6c7f6257de87a98d15964209ddc9e09 pep440-dev
regressionfix/.* 1.8.0rc6 45598764e6c7f6257de87a98d15964209ddc9e09 pep440-dev
# staging/devel is currently inactive (but has the 1.4.1rc4 namespace)
staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f pep440-dev
+8 -13
View File
@@ -8,37 +8,31 @@ thanks to everyone who contributed!
* 3D-TECH
* 3DPrinterOS
* Al Mucci
* Arnljot Arntsen
* Artillery 3D
* Ash King
* BigTreeTech
* Boris Hussein
* Brad Jackson
* BuildBee
* Calvin Vette
* Christian Petropolis
* Christian Wolf
* Christian Würthner
* Christoph Sigrist
* Craig Parker
* Creality3D
* David Bounds
* DeltaMaker 3D Printers
* Dennis Breining
* Douglas Floyd
* Dr. Frank Wester
* Eric Betts
* Ernesto Martinez
* Franziska Kunsmann
* George Robles
* Greg Holloway
* Hog Duske
* Itay Shem-tov
* James Mackay
* Jeff Green
* Jeff Moe
* jeffiel
* Jeremy Cole
* Joshua Wills
* Julian Melo
* Justin Kaufman
* Kaile Riser
@@ -50,13 +44,15 @@ thanks to everyone who contributed!
* Lefteris Lertas
* LulzBot
* Makespace Madrid
* Mark Greenwald
* Mark Walker
* Matt Van Itallie
* Michael Aumock
* Mike Kershaw
* Miles Flavel
* Mosaic Manufacturing
* Norman Jaffe
* Obico
* Ory Weaver
* Peopoly
* Pete Barnwell
* Raise3D
@@ -66,16 +62,15 @@ thanks to everyone who contributed!
* Richard Michaud
* Richard Stocks
* Robert Gusek
* Ronald Griehsler
* Sean Jensen-Grey
* Sebastien Andrivet
* SimplyPrint
* Stefan Krister
* Steve Dougherty
* Steve Thompson
* TH3D
* The Spaghetti Detective
* TJ Horner
* Trent Shumay
* Ulrich Kempken
* Yehuda Katz
and 2307 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
and 2209 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
+2 -2
View File
@@ -2,11 +2,11 @@
[jinja2: src/octoprint/templates/**.jinja2]
silent=false
extensions=jinja2.ext.autoescape, jinja2.ext.with_, webassets.ext.jinja2.AssetsExtension, jinja2.ext.do, octoprint.util.jinja.trycatch
extensions=webassets.ext.jinja2.AssetsExtension, jinja2.ext.do, octoprint.util.jinja.trycatch
[jinja2: src/octoprint/plugins/**.jinja2]
silent=false
extensions=jinja2.ext.autoescape, jinja2.ext.with_, webassets.ext.jinja2.AssetsExtension, jinja2.ext.do, octoprint.util.jinja.trycatch
extensions=webassets.ext.jinja2.AssetsExtension, jinja2.ext.do, octoprint.util.jinja.trycatch
[javascript: src/octoprint/static/js/app/**.js]
extract_messages = gettext, ngettext
+1 -1
View File
@@ -649,7 +649,7 @@ Permission record
* - ``dangerous``
- 1
- boolean
- Whether the permission should be considered dangerous due to a high reponsibility (true) or not (false).
- Whether the permission should be considered dangerous due to a high responsibility (true) or not (false).
* - ``default_groups``
- 1
- List of string
+2 -2
View File
@@ -76,7 +76,7 @@ Change current timelapse config
.. http:post:: /api/timelapse
Save a new :ref:`timelapse configuration <sec-api-timelapse-datamodel-config>` to use for the next print. Set the optional ``save`` flag in the
configuration to ``true`` in order to make the new configuration persist accross restarts.
configuration to ``true`` in order to make the new configuration persist across restarts.
The configuration is expected as the request body.
@@ -220,7 +220,7 @@ Timelapse configuration
* - ``save``
- 1
- bool
- Optional flag to be included when when saving a configuration to make the configuration persist accross restarts
- Optional flag to be included when when saving a configuration to make the configuration persist across restarts
Further fields are timelapse type specific, see below for details.
+1 -1
View File
@@ -452,7 +452,7 @@ Use the following settings to enable or disable OctoPrint features:
# whether G90/G91 also influence absolute/relative mode of extruders
g90InfluencesExtruder: false
# Replace all special characters and spaces with text equivalent to make them univerally compatible.
# Replace all special characters and spaces with text equivalent to make them universally compatible.
# Most OS filesystems work fine with unicode characters, but just in case you can revert to the
# older behaviour by setting this to true.
enforceReallyUniversalFilenames: false
+1 -1
View File
@@ -216,7 +216,7 @@ There many configuration options via ``config.yaml`` for the virtual printer tha
# Enable virtual EEPROM
# If enabled, a file `eeprom.json` will be created in the plugin data folder
# to enable settings persistence across connections. Enables M500/1/2/4 commmands
# to enable settings persistence across connections. Enables M500/1/2/4 commands
# And a selection of other settings commands. Responses modeled on Marlin 2.0
enable_eeprom: true
+1 -1
View File
@@ -133,7 +133,7 @@ Example: Your PC has an IP address of ``192.168.23.42`` and a subnet mask of
The easy way: Using the OctoPrint-AutoLoginConfig plugin
........................................................
The easist way to configure AutoLogin is to install the
The easiest way to configure AutoLogin is to install the
`OctoPrint-AutoLoginConfig plugin <https://plugins.octoprint.org/plugins/autologin_config/>`_
via the plugin manager.
+1 -1
View File
@@ -1938,7 +1938,7 @@ octoprint.timelapse.capture.post
Perform specific actions after capturing a timelapse frame.
``filename`` will be the path of the frame that should have been saved.
``sucesss`` indicates whether the capture was successful or not.
``success`` indicates whether the capture was successful or not.
:param str filename: The path of the frame that should have been saved.
:param boolean success: Indicates whether the capture was successful or not.
+1 -1
View File
@@ -336,7 +336,7 @@ As a summary, follow this checklist to migrate your plugin to be compatible to b
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
* Thorougly test your plugin under Python 3. Pay special attention to any kind of string handling issues, integer
* Thoroughly test your plugin under Python 3. Pay special attention to any kind of string handling issues, integer
division, relative imports from your plugin package and how the results of ``map``, ``filter`` and ``zip`` are
used in your code, as those have proven to be the biggest issues during past migrations.
* Once everything works under both Python versions and you've prepared a new release of your plugin (don't forget to
+1 -1
View File
@@ -43,7 +43,7 @@ core_deps = [
"Flask-Assets>=2.0,<3",
"Flask-Babel>=2.0,<3",
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
"flask>=2,<3",
"flask>=2.1,<2.2", # flask 2.2 requires werkzeug 2.2+
"frozendict>=2.0,<3",
"future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins
"markdown>=3.2.2,<4",
@@ -18,10 +18,10 @@ from octoprint.util.version import (
)
SENTRY_URL_SERVER = (
"https://b39cd0dcaea5404798ec3eb193b291db@o118517.ingest.sentry.io/1373987"
"https://32fedab787cf4ef0abb9f4fb9060f7c5@o118517.ingest.sentry.io/1373987"
)
SENTRY_URL_COREUI = (
"https://ab48b21452fe424eaf79468aa6c94bd7@o118517.ingest.sentry.io/1374096"
"https://09c57ca82d4047b5a37bb0655ce14187@o118517.ingest.sentry.io/1374096"
)
SETTINGS_DEFAULTS = {
+1
View File
@@ -1352,6 +1352,7 @@ class Server:
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
app.config["REMEMBER_COOKIE_HTTPONLY"] = True
# we must not set this before TEMPLATES_AUTO_RELOAD is set to True or that won't take
app.debug = self._debug
+1
View File
@@ -490,6 +490,7 @@ def _saveSettings(data):
s.setBaseFolder(folder, future[folder])
except Exception:
logger.exception("Something went wrong while saving a folder path")
abort(400, description="At least one of the configured folders is invalid")
if "api" in data:
+20 -3
View File
@@ -378,9 +378,6 @@ def require_login_with(permissions=None, user_id=None):
):
requires_login = False
if current_user.is_anonymous:
requires_login = True
if permissions is not None and not has_permissions(*permissions):
requires_login = True
login_kwargs["permissions"] = ",".join([x.key for x in permissions])
@@ -424,3 +421,23 @@ def require_login(*permissions):
)
return None
def validate_local_redirect(url, allowed_paths):
"""Validates the given local redirect URL against the given allowed paths.
An `url` is valid for a local redirect if it has neither scheme nor netloc defined,
and its path is one of the given allowed paths.
Args:
url (str): URL to validate
allowed_paths (List[str]): List of allowed paths, only paths contained
will be considered valid.
Returns:
bool: Whether the `url` passed validation or not.
"""
from urllib.parse import urlparse
parsed = urlparse(url)
return parsed.scheme == "" and parsed.netloc == "" and parsed.path in allowed_paths
+15 -2
View File
@@ -38,7 +38,11 @@ from octoprint.server import ( # noqa: F401
preemptiveCache,
userManager,
)
from octoprint.server.util import has_permissions, require_login_with
from octoprint.server.util import (
has_permissions,
require_login_with,
validate_local_redirect,
)
from octoprint.settings import settings
from octoprint.util import sv, to_bytes, to_unicode
from octoprint.util.version import get_python_version_string
@@ -170,7 +174,16 @@ def _add_additional_assets(hook):
def login():
from flask_login import current_user
redirect_url = request.args.get("redirect", request.script_root + url_for("index"))
default_redirect_url = request.script_root + url_for("index")
redirect_url = request.args.get("redirect", default_redirect_url)
allowed_paths = [url_for("index"), url_for("recovery")]
if not validate_local_redirect(redirect_url, allowed_paths):
_logger.warning(
f"Got an invalid redirect URL with the login attempt, misconfiguration or attack attempt: {redirect_url}"
)
redirect_url = default_redirect_url
permissions = sorted(
filter(
lambda x: x is not None and isinstance(x, OctoPrintPermission),
+40 -27
View File
@@ -34,6 +34,7 @@ from yaml import YAMLError
from octoprint.util import (
CaseInsensitiveSet,
atomic_write,
deprecated,
dict_merge,
fast_deepcopy,
generate_api_key,
@@ -862,7 +863,6 @@ class Settings:
self._map = HierarchicalChainMap({}, default_settings)
self.load_overlays(overlays)
self._config = None
self._dirty = False
self._dirty_time = 0
self._last_config_hash = None
@@ -1125,7 +1125,7 @@ class Settings:
@property
def config_yaml(self):
return yaml.dump(self._config)
return yaml.dump(self.config)
@property
def config_hash(self):
@@ -1140,10 +1140,28 @@ class Settings:
return self._last_config_hash
@property
def _config(self):
def config(self):
"""
A view of the local config as stored in config.yaml
Does not support modifications, they will be thrown away silently. If you need to
modify anything in the settings, utilize the provided set and remove methods.
"""
return self._map.top_map
@property
@deprecated(
"Settings._config has been deprecated and is a read-only view. Please use Settings.config or the set & remove methods instead.",
since="1.8.0",
)
def _config(self):
return self.config
@_config.setter
@deprecated(
"Setting of Settings._config has been deprecated. Please use the set & remove methods instead and get in touch if you have a usecase they don't cover.",
since="1.8.0",
)
def _config(self, value):
self._map.top_map = value
@@ -1174,11 +1192,14 @@ class Settings:
# ~~ load and save
def load(self, migrate=False):
config = None
mtime = None
if os.path.exists(self._configfile) and os.path.isfile(self._configfile):
with open(self._configfile, encoding="utf-8", errors="replace") as f:
try:
self._config = yaml.load_from_file(file=f)
self._mtime = self.last_modified
config = yaml.load_from_file(file=f)
mtime = self.last_modified
except YAMLError as e:
details = str(e)
@@ -1198,8 +1219,11 @@ class Settings:
)
# changed from else to handle cases where the file exists, but is empty / 0 bytes
if not self._config or not isinstance(self._config, dict):
self._config = {}
if not config or not isinstance(config, dict):
config = {}
self._map.top_map = config
self._mtime = mtime
if migrate:
self._migrate_config()
@@ -1293,7 +1317,7 @@ class Settings:
def _migrate_config(self, config=None, persist=False):
if config is None:
config = self._config
config = self._map.top_map
persist = True
dirty = False
@@ -1315,6 +1339,9 @@ class Settings:
dirty = migrate(config) or dirty
if dirty and persist:
self._map.top_map = (
config # we need to write it back here or the changes will be lost
)
self.save(force=True)
def _migrate_gcode_scripts(self, config):
@@ -1833,7 +1860,7 @@ class Settings:
permissions=0o600,
max_permissions=0o666,
) as configFile:
yaml.save_to_file(self._config, file=configFile)
yaml.save_to_file(self._map.top_map, file=configFile)
self._dirty = False
except Exception:
self._logger.exception("Error while saving config.yaml!")
@@ -2072,10 +2099,7 @@ class Settings:
folder = default_folder
try:
del self._config["folder"][type]
if not len(self._config["folder"]):
del self._config["folder"]
self._mark_dirty()
self.remove(["folder", type])
self.save()
except KeyError:
pass
@@ -2270,23 +2294,12 @@ class Settings:
currentPath = self.getBaseFolder(type)
defaultPath = self._get_default_folder(type)
if (
(path is None or path == defaultPath)
and "folder" in self._config
and type in self._config["folder"]
):
del self._config["folder"][type]
if not self._config["folder"]:
del self._config["folder"]
self._mark_dirty()
if path is None or path == defaultPath:
self.remove(["folder", type])
elif (path != currentPath and path != defaultPath) or force:
if validate:
_validate_folder(path, check_writable=True, deep_check_writable=True)
if "folder" not in self._config:
self._config["folder"] = {}
self._config["folder"][type] = path
self._mark_dirty()
self.set(["folder", type], path, force=force)
def saveScript(self, script_type, name, script):
script_folder = self.getBaseFolder("scripts")
+64 -30
View File
@@ -1542,41 +1542,75 @@ var copyToClipboard = function (text) {
temp.remove();
};
var determineWebcamStreamType = function (streamUrl) {
if (streamUrl) {
if (streamUrl.startsWith("webrtc")) {
return "webrtc";
}
var getExternalHostUrl = function () {
var loc = window.location;
var port = "";
if (
(loc.protocol === "http:" && loc.port !== "80") ||
(loc.protocol === "https:" && loc.port !== "443")
) {
port = ":" + loc.port;
}
return loc.protocol + "//" + loc.hostname + port;
};
var lastDotPosition = streamUrl.lastIndexOf(".");
var firstQuotationSignPosition = streamUrl.indexOf("?");
if (
lastDotPosition != -1 &&
firstQuotationSignPosition != -1 &&
lastDotPosition >= firstQuotationSignPosition
) {
throw "Malformed URL. Cannot determine stream type.";
}
var validateWebcamUrl = function (streamUrl) {
if (!streamUrl) {
return false;
}
// If we have found a dot, try to extract the extension.
if (lastDotPosition > -1) {
if (firstQuotationSignPosition > -1) {
var extension = streamUrl.slice(
lastDotPosition + 1,
firstQuotationSignPosition - 1
);
} else {
var extension = streamUrl.slice(lastDotPosition + 1);
}
if (extension.toLowerCase() == "m3u8") {
return "hls";
}
}
// By default, 'mjpg' is the stream type.
return "mjpg";
var lower = streamUrl.toLowerCase();
var toParse = streamUrl;
if (lower.startsWith("//")) {
// protocol relative
toParse = window.location.protocol + streamUrl;
} else if (lower.startsWith("/")) {
// host relative
toParse = getExternalHostUrl() + streamUrl;
} else if (
lower.startsWith("http:") ||
lower.startsWith("https:") ||
lower.startsWith("webrtc:") ||
lower.startsWith("webrtcs:")
) {
// absolute & supported protocol
toParse = streamUrl;
} else {
return false;
}
try {
return new URL(toParse);
} catch (e) {
return false;
}
};
var determineWebcamStreamType = function (streamUrl) {
if (!streamUrl) {
throw "Empty streamUrl. Cannot determine stream type.";
}
var parsed = validateWebcamUrl(streamUrl);
if (!parsed) {
throw "Invalid streamUrl. Cannot determine stream type.";
}
if (parsed.protocol === "webrtc:" || parsed.protocol === "webrtcs:") {
return "webrtc";
}
var lastDotPosition = parsed.pathname.lastIndexOf(".");
if (lastDotPosition !== -1) {
var extension = parsed.pathname.substring(lastDotPosition + 1);
if (extension.toLowerCase() === "m3u8") {
return "hls";
}
}
// By default, 'mjpg' is the stream type.
return "mjpg";
};
var saveToLocalStorage = function (key, data) {
@@ -324,7 +324,7 @@ $(function () {
title: gettext("Are you sure?"),
message: _.sprintf(
gettext('You are about to delete the user "%(name)s".'),
{name: user.name}
{name: _.escape(user.name)}
),
proceed: gettext("Delete"),
onproceed: function () {
@@ -656,7 +656,7 @@ $(function () {
title: gettext("Are you sure?"),
message: _.sprintf(
gettext('You are about to delete the group "%(name)s".'),
{name: group.name}
{name: _.escape(group.name)}
),
proceed: gettext("Delete"),
onproceed: function () {
@@ -573,7 +573,7 @@ $(function () {
}
// Determine stream type and switch to corresponding webcam.
var streamType = determineWebcamStreamType(self.settings.webcam_streamUrl());
var streamType = self.settings.webcam_streamType();
if (streamType == "mjpg") {
self._switchToMjpgWebcam();
} else if (streamType == "hls") {
@@ -760,7 +760,7 @@ $(function () {
return;
}
var newSrc = self.settings.webcam_streamUrl();
var newSrc = self.settings.webcam_streamUrlEscaped();
if (currentSrc != newSrc) {
if (self.settings.webcam_cacheBuster()) {
if (newSrc.lastIndexOf("?") > -1) {
@@ -797,10 +797,10 @@ $(function () {
typeof video.canPlayType != undefined &&
video.canPlayType("application/vnd.apple.mpegurl") == "probably"
) {
video.src = self.settings.webcam_streamUrl();
video.src = self.settings.webcam_streamUrlEscaped();
} else if (Hls.isSupported()) {
self.hls = new Hls();
self.hls.loadSource(self.settings.webcam_streamUrl());
self.hls.loadSource(self.settings.webcam_streamUrlEscaped());
self.hls.attachMedia(video);
}
@@ -836,7 +836,7 @@ $(function () {
if (self.webRTCPeerConnection == null) {
self.webRTCPeerConnection = startWebRTC(
video,
self.settings.webcam_streamUrl(),
self.settings.webcam_streamUrlEscaped(),
self.settings.webcam_streamWebrtcIceServers()
);
}
@@ -312,13 +312,20 @@ $(function () {
self.webcam_ffmpegPathOk(false);
self.webcam_ffmpegPathBroken(false);
};
self.webcam_streamUrlEscaped = ko.pureComputed(function () {
return encodeURI(self.webcam_streamUrl());
});
self.webcam_streamType = ko.pureComputed(function () {
try {
return determineWebcamStreamType(self.webcam_streamUrl());
return determineWebcamStreamType(self.webcam_streamUrlEscaped());
} catch (e) {
return "";
}
});
self.webcam_streamValid = ko.pureComputed(function () {
var url = self.webcam_streamUrlEscaped();
return !url || validateWebcamUrl(url);
});
self.server_onlineCheckText = ko.observable();
self.server_onlineCheckOk = ko.observable(false);
@@ -439,7 +446,8 @@ $(function () {
self.testWebcamStreamUrlBusy = ko.observable(false);
self.testWebcamStreamUrl = function () {
if (!self.webcam_streamUrl()) {
var url = self.webcam_streamUrlEscaped();
if (!url) {
return;
}
@@ -450,24 +458,31 @@ $(function () {
var text = gettext(
"If you see your webcam stream below, the entered stream URL is ok."
);
var streamType = self.webcam_streamType();
var streamType;
try {
streamType = self.webcam_streamType();
} catch (e) {
streamType = "";
}
var webcam_element;
var webrtc_peer_connection;
if (streamType == "mjpg") {
webcam_element = $('<img src="' + self.webcam_streamUrl() + '">');
} else if (streamType == "hls") {
if (streamType === "mjpg") {
webcam_element = $('<img src="' + url + '">');
} else if (streamType === "hls") {
webcam_element = $(
'<video id="webcam_hls" muted autoplay style="width: 100%"/>'
);
video_element = webcam_element[0];
if (video_element.canPlayType("application/vnd.apple.mpegurl")) {
video_element.src = self.webcam_streamUrl();
video_element.src = url;
} else if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource(self.webcam_streamUrl());
hls.loadSource(url);
hls.attachMedia(video_element);
}
} else if (isWebRTCAvailable() && streamType == "webrtc") {
} else if (isWebRTCAvailable() && streamType === "webrtc") {
webcam_element = $(
'<video id="webcam_webrtc" muted autoplay playsinline controls style="width: 100%"/>'
);
@@ -475,7 +490,7 @@ $(function () {
webrtc_peer_connection = startWebRTC(
video_element,
self.webcam_streamUrl(),
url,
self.webcam_streamWebrtcIceServers()
);
} else {
+2 -2
View File
@@ -69,12 +69,12 @@
<div id="login-offline" class="alert alert-error">{{ _('Server is currently offline.') }} <a id="login-reconnect" href="javascript:void(0)">{{ _('Reconnect...') }}</a></div>
{% if user_id %}<p>
{{ _('The following account is required:') }} {{ user_id }}
{{ _('The following account is required:') }} {{ user_id|e }}
</p>{% elif logged_in %}<p>
{{ _('An account with the following permissions is required:') }} {{ permission_names|join(", ") }}
</p>{% endif %}
<input type="text" id="login-user" data-test-id="login-username" class="input-block-level" placeholder="{{ _('Username')|edq }}" {% if user_id %}value="{{ user_id }}" disabled{% endif %} autofocus autocapitalize="none">
<input type="text" id="login-user" data-test-id="login-username" class="input-block-level" placeholder="{{ _('Username')|edq }}" {% if user_id %}value="{{ user_id|edq }}" disabled{% endif %} autofocus autocapitalize="none">
<input type="password" id="login-password" data-test-id="login-password" class="input-block-level" placeholder="{{ _('Password')|edq }}">
<span class="pull-right"><small><a href="https://faq.octoprint.org/forgotten-password" id="login-forgotpassword" target="_blank" tabindex="-1">{{ _('Forgot password?') }}</a></small></span>
<label class="checkbox">
@@ -1,9 +1,9 @@
<div class="control-group" title="{{ _('URL to embed into the UI for live viewing of the webcam stream')|edq }}">
<div class="control-group" title="{{ _('URL to embed into the UI for live viewing of the webcam stream')|edq }}" data-bind="css: { error: !webcam_streamValid() }">
<label class="control-label" for="settings-webcamStreamUrl">{{ _('Stream URL') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level" data-bind="value: webcam_streamUrl, valueUpdate: 'afterkeydown'" id="settings-webcamStreamUrl">
<button class="btn" type="button" data-bind="click: testWebcamStreamUrl, enable: webcam_streamUrl() && !testWebcamStreamUrlBusy(), css: {disabled: !webcam_streamUrl() || testWebcamStreamUrlBusy()}"><i class="fas fa-spinner fa-spin" data-bind="visible: testWebcamStreamUrlBusy"></i> {{ _('Test') }}</button>
<button class="btn" type="button" data-bind="click: testWebcamStreamUrl, enable: !testWebcamStreamUrlBusy() && webcam_streamValid(), css: {disabled: testWebcamStreamUrlBusy() || !webcam_streamValid()}"><i class="fas fa-spinner fa-spin" data-bind="visible: testWebcamStreamUrlBusy"></i> {{ _('Test') }}</button>
</div>
<span class="help-block">
<p>{% trans %}Needs to be reachable from the browser displaying the OctoPrint UI, used to embed the webcam stream into the page.{% endtrans %}</p>
File diff suppressed because it is too large. Load diff
+13 -4
View File
@@ -198,10 +198,15 @@ def serialList():
else:
candidates = []
with os.scandir("/dev") as it:
for entry in it:
if regex_serial_devices.match(entry.name):
candidates.append(entry.path)
try:
with os.scandir("/dev") as it:
for entry in it:
if regex_serial_devices.match(entry.name):
candidates.append(entry.path)
except Exception:
logging.getLogger(__name__).exception(
"Could not scan /dev for serial ports on the system"
)
# additional ports
additionalPorts = settings().get(["serial", "additionalPorts"])
@@ -6268,6 +6273,10 @@ def parse_temperature_line(line, current):
for match in re.finditer(regex_temp, line):
values = match.groupdict()
sensor = values["sensor"]
if sensor in result:
# sensor already seen, let's not overwrite stuff
continue
toolnum = values.get("toolnum", None)
tool_number = int(toolnum) if toolnum is not None and len(toolnum) else None
if tool_number and tool_number > max_tool_num:
+36
View File
@@ -0,0 +1,36 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
import pytest
@pytest.mark.parametrize(
"url,paths,expected",
[
# various default UI URLs
("/", ["/", "/recovery/"], True),
("/?", ["/", "/recovery/"], True),
("/?l10n=de", ["/", "/recovery/"], True),
("/?l10n=de&", ["/", "/recovery/"], True),
("/octoprint/", ["/octoprint/", "/octoprint/recovery/"], True),
# various recovery URLs
("/recovery/", ["/", "/recovery/"], True),
("/recovery/?", ["/", "/recovery/"], True),
("/recovery/?l10n=de", ["/", "/recovery/"], True),
("/octoprint/recovery/?l10n=de", ["/octoprint/", "/octoprint/recovery/"], True),
# various external URLs
("http://example.com", ["/", "/recovery/"], False),
("https://example.com", ["/", "/recovery/"], False),
("//example.com", ["/", "/recovery/"], False),
("/\\/\\example.com", ["/", "/recovery/"], False),
(" /\\/\\example.com", ["/", "/recovery/"], False),
("\\/\\/example.com", ["/", "/recovery/"], False),
(" \\/\\/example.com", ["/", "/recovery/"], False),
# other stuff
("javascript:alert(document.cookie)", ["/", "/recovery/"], False),
],
)
def test_validate_local_redirect(url, paths, expected):
from octoprint.server.util import validate_local_redirect
assert validate_local_redirect(url, paths) == expected
+10
View File
@@ -330,6 +330,16 @@ class TestCommHelpers(unittest.TestCase):
},
0,
),
(
# Only first occurrence of a sensor should be used, second B gets ignored
"T:210.04 /210.00 B:52.00 /52.00 @:85 B:1234.0 /1234.0",
0,
{
"T0": (210.04, 210.0),
"B": (52.00, 52.0),
},
0,
),
)
@unpack
def test_process_temperature_line(self, line, current, expected_result, expected_max):
Binary file not shown.
File diff suppressed because it is too large. Load diff
+541 -541
View File
File diff suppressed because it is too large. Load diff