Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e4c1f5246 | ||
|
|
d813a0cc86 | ||
|
|
7489b3c398 | ||
|
|
6e009d2544 | ||
|
|
59054cc1e5 | ||
|
|
fcb9eaebda | ||
|
|
b151152c00 | ||
|
|
a1d95dd44b | ||
|
|
c01216cfab | ||
|
|
a47b5187bb | ||
|
|
40d71f1242 | ||
|
|
3088c3be0b | ||
|
|
135249c554 | ||
|
|
814c3a1519 | ||
|
|
68191cfbf4 | ||
|
|
c5b56ae11b | ||
|
|
cc47b41bae | ||
|
|
397de4e3a7 | ||
|
|
9179545c33 | ||
|
|
7659c811f5 | ||
|
|
7d336bd098 | ||
|
|
a68916f05a | ||
|
|
dfced1118a | ||
|
|
588a1c4cc8 | ||
|
|
ab3ebf101f | ||
|
|
1875623f05 | ||
|
|
ac6240a3a3 | ||
|
|
ae407492bc | ||
|
|
de3a12999e | ||
|
|
395354212c | ||
|
|
b38785a25a | ||
|
|
f28a53f3e6 | ||
|
|
d94e13e9dc | ||
|
|
eb9e144746 | ||
|
|
b4d0ed30ab | ||
|
|
8e9c09a818 | ||
|
|
5091487719 | ||
|
|
2f62feaaec | ||
|
|
27a576e352 | ||
|
|
2703d528a3 | ||
|
|
be0d452ab9 | ||
|
|
0093d96da4 | ||
|
|
73c199c98c | ||
|
|
f334decb33 | ||
|
|
daa5dbc4d6 | ||
|
|
147d982c87 | ||
|
|
b87b965fc5 | ||
|
|
9bc2d54196 | ||
|
|
d0d226f3e0 | ||
|
|
59a0c8e8d7 | ||
|
|
0db80dc0c9 | ||
|
|
3c8f8c84f4 | ||
|
|
b447779e33 | ||
|
|
14aec95898 | ||
|
|
dc201416b6 | ||
|
|
e550c94068 | ||
|
|
0d89198464 | ||
|
|
3092734c62 | ||
|
|
452dcdfbcc | ||
|
|
92e8a2a138 | ||
|
|
40e6217ac1 | ||
|
|
b83b57406e | ||
|
|
3cca3a43f3 | ||
|
|
ef95ef1c10 | ||
|
|
2cbeb27140 | ||
|
|
c87a7b6851 | ||
|
|
6af0ce48dc | ||
|
|
3e3c11811e | ||
|
|
a33622e0b7 | ||
|
|
ae1cba8d91 | ||
|
|
9f1ffde4c0 | ||
|
|
fd2db95508 |
No files matched your search
@@ -76,10 +76,10 @@ body:
|
|||||||
Issues caused by a third party plugin are a major cause of bugs reported here, so we really need to
|
Issues caused by a third party plugin are a major cause of bugs reported here, so we really need to
|
||||||
rule out that a plugin is at fault here. [Safe mode](https://docs.octoprint.org/en/master/features/safemode.html) is an easy way to do that. Only skip safe mode
|
rule out that a plugin is at fault here. [Safe mode](https://docs.octoprint.org/en/master/features/safemode.html) is an easy way to do that. Only skip safe mode
|
||||||
if your particular problem *absolutely requires* third party plugins to be enabled. "It would take
|
if your particular problem *absolutely requires* third party plugins to be enabled. "It would take
|
||||||
too long" is **not** a reason to skip testing in safe mode, neither is "I do not know how to
|
too long" or "I have a long print running right now" are **not** a reason to skip testing in safe mode, neither is "I do not know how to
|
||||||
enable it" as you can find info on that [here](https://docs.octoprint.org/en/master/features/safemode.html).
|
enable it" as you can find info on that [here](https://docs.octoprint.org/en/master/features/safemode.html).
|
||||||
|
|
||||||
If you really *cannot* test in safe mode, leave a short explanation as to why.
|
If you really *cannot* test in safe mode at all, leave a short explanation as to why. If you,can but just not right now, then wait with reporting until you can.
|
||||||
- type: markdown
|
- type: markdown
|
||||||
attributes:
|
attributes:
|
||||||
value: |
|
value: |
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
# Check for updates to GitHub Actions every week
|
||||||
|
- package-ecosystem: "github-actions"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
accessControl:
|
accessControl:
|
||||||
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
|
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
|
||||||
|
devel:
|
||||||
|
enableRateLimiter: false
|
||||||
|
enableCsrfProtection: false
|
||||||
plugins:
|
plugins:
|
||||||
virtual_printer:
|
virtual_printer:
|
||||||
enabled: true
|
enabled: true
|
||||||
|
|||||||
@@ -15,7 +15,10 @@ meta:
|
|||||||
ci/cd:
|
ci/cd:
|
||||||
- ".github/fixtures/**/*"
|
- ".github/fixtures/**/*"
|
||||||
- ".github/workflows/*"
|
- ".github/workflows/*"
|
||||||
|
- ".github/dependabot.yml"
|
||||||
|
- ".github/issue-validation.yml"
|
||||||
- ".github/labeler.yml"
|
- ".github/labeler.yml"
|
||||||
|
- ".github/pr-validation.yml"
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
- ".github/workflows/trigger_docker.yml"
|
- ".github/workflows/trigger_docker.yml"
|
||||||
|
|||||||
+32
-17
@@ -11,11 +11,11 @@ jobs:
|
|||||||
name: 🔨 Build distribution
|
name: 🔨 Build distribution
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- name: 🏗 Set up Python 3.7
|
- name: 🏗 Set up Python 3.7
|
||||||
uses: actions/setup-python@v1
|
uses: actions/setup-python@v4
|
||||||
with:
|
with:
|
||||||
python-version: 3.7
|
python-version: 3.7
|
||||||
- name: 🏗 Install build dependencies
|
- name: 🏗 Install build dependencies
|
||||||
@@ -25,7 +25,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
python setup.py sdist bdist_wheel
|
python setup.py sdist bdist_wheel
|
||||||
- name: ⬆ Upload build result
|
- name: ⬆ Upload build result
|
||||||
uses: actions/upload-artifact@v1
|
uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: dist
|
name: dist
|
||||||
path: dist
|
path: dist
|
||||||
@@ -34,9 +34,9 @@ jobs:
|
|||||||
name: 🧹 Pre-commit
|
name: 🧹 Pre-commit
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
- name: 🏗 Set up Python 3.7
|
- name: 🏗 Set up Python 3.7
|
||||||
uses: actions/setup-python@v1
|
uses: actions/setup-python@v4
|
||||||
with:
|
with:
|
||||||
python-version: 3.7
|
python-version: 3.7
|
||||||
- name: 🏗 Set up dev dependencies
|
- name: 🏗 Set up dev dependencies
|
||||||
@@ -53,9 +53,9 @@ jobs:
|
|||||||
python: ["3.7", "3.8", "3.9", "3.10"]
|
python: ["3.7", "3.8", "3.9", "3.10"]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
- name: 🏗 Set up Python ${{ matrix.python }}
|
- name: 🏗 Set up Python ${{ matrix.python }}
|
||||||
uses: actions/setup-python@v1
|
uses: actions/setup-python@v4
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python }}
|
python-version: ${{ matrix.python }}
|
||||||
- name: 🏗 Set up test dependencies
|
- name: 🏗 Set up test dependencies
|
||||||
@@ -65,6 +65,20 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
pytest
|
pytest
|
||||||
|
|
||||||
|
test-js-unit:
|
||||||
|
name: 🧪 JavaScript unit tests
|
||||||
|
needs: build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- name: 🏗 Set up test dependencies
|
||||||
|
run: |
|
||||||
|
npm -g install node-qunit-puppeteer@2.1.0
|
||||||
|
- name: 🚀 Run helpers.js test suite
|
||||||
|
run: |
|
||||||
|
node-qunit-puppeteer tests/static/js/test-helpers.html
|
||||||
|
node-qunit-puppeteer tests/static/js/test-client-base.html
|
||||||
|
|
||||||
test-install:
|
test-install:
|
||||||
name: 🧪 Installation tests
|
name: 🧪 Installation tests
|
||||||
needs: build
|
needs: build
|
||||||
@@ -75,12 +89,12 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: ⬇ Download build result
|
- name: ⬇ Download build result
|
||||||
uses: actions/download-artifact@v1
|
uses: actions/download-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: dist
|
name: dist
|
||||||
path: dist
|
path: dist
|
||||||
- name: 🏗 Set up Python ${{ matrix.python }}
|
- name: 🏗 Set up Python ${{ matrix.python }}
|
||||||
uses: actions/setup-python@v1
|
uses: actions/setup-python@v4
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python }}
|
python-version: ${{ matrix.python }}
|
||||||
- name: 🚀 Install wheel
|
- name: 🚀 Install wheel
|
||||||
@@ -99,15 +113,15 @@ jobs:
|
|||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
steps:
|
steps:
|
||||||
- name: ⬇ Checkout code
|
- name: ⬇ Checkout code
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
- name: ⬇ Download build result
|
- name: ⬇ Download build result
|
||||||
uses: actions/download-artifact@v1
|
uses: actions/download-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: dist
|
name: dist
|
||||||
path: dist
|
path: dist
|
||||||
- name: 🏗 Set up Python 3.7
|
- name: 🏗 Set up Python 3.7
|
||||||
uses: actions/setup-python@v1
|
uses: actions/setup-python@v4
|
||||||
with:
|
with:
|
||||||
python-version: 3.7
|
python-version: 3.7
|
||||||
- name: 🚀 Install wheel
|
- name: 🚀 Install wheel
|
||||||
@@ -120,7 +134,7 @@ jobs:
|
|||||||
cp -r .github/fixtures/with_acl/* e2econfig
|
cp -r .github/fixtures/with_acl/* e2econfig
|
||||||
|
|
||||||
- name: 🚀 Run Cypress
|
- name: 🚀 Run Cypress
|
||||||
uses: cypress-io/github-action@v2
|
uses: cypress-io/github-action@v4.2.0
|
||||||
with:
|
with:
|
||||||
working-directory: tests/cypress
|
working-directory: tests/cypress
|
||||||
browser: chrome
|
browser: chrome
|
||||||
@@ -128,7 +142,7 @@ jobs:
|
|||||||
wait-on: "http://127.0.0.1:5000/online.txt"
|
wait-on: "http://127.0.0.1:5000/online.txt"
|
||||||
|
|
||||||
- name: ⬆ Upload screenshots
|
- name: ⬆ Upload screenshots
|
||||||
uses: actions/upload-artifact@v1
|
uses: actions/upload-artifact@v3
|
||||||
if: failure()
|
if: failure()
|
||||||
with:
|
with:
|
||||||
name: cypress-screenshots
|
name: cypress-screenshots
|
||||||
@@ -146,12 +160,13 @@ jobs:
|
|||||||
needs:
|
needs:
|
||||||
- pre-commit
|
- pre-commit
|
||||||
- test-unit
|
- test-unit
|
||||||
|
- test-js-unit
|
||||||
- test-install
|
- test-install
|
||||||
- test-e2e
|
- test-e2e
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: ⬇ Download build result
|
- name: ⬇ Download build result
|
||||||
uses: actions/download-artifact@v1
|
uses: actions/download-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: dist
|
name: dist
|
||||||
path: dist
|
path: dist
|
||||||
@@ -169,7 +184,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: ⬇ Download build result
|
- name: ⬇ Download build result
|
||||||
uses: actions/download-artifact@v1
|
uses: actions/download-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: dist
|
name: dist
|
||||||
path: dist
|
path: dist
|
||||||
@@ -189,7 +204,7 @@ jobs:
|
|||||||
OCTOPRINT_VERSION=$(echo $GITHUB_REF | cut -d/ -f3)
|
OCTOPRINT_VERSION=$(echo $GITHUB_REF | cut -d/ -f3)
|
||||||
echo "OCTOPRINT_VERSION=$OCTOPRINT_VERSION" >> $GITHUB_ENV
|
echo "OCTOPRINT_VERSION=$OCTOPRINT_VERSION" >> $GITHUB_ENV
|
||||||
- name: 🚀 Repository Dispatch
|
- name: 🚀 Repository Dispatch
|
||||||
uses: peter-evans/repository-dispatch@v1
|
uses: peter-evans/repository-dispatch@v2
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.REPODISPATCH_TOKEN }}
|
token: ${{ secrets.REPODISPATCH_TOKEN }}
|
||||||
repository: OctoPrint/OctoPi-UpToDate
|
repository: OctoPrint/OctoPi-UpToDate
|
||||||
|
|||||||
@@ -10,11 +10,11 @@ jobs:
|
|||||||
name: 🔒 Lock issues & PRs closed over a year
|
name: 🔒 Lock issues & PRs closed over a year
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: dessant/lock-threads@v2
|
- uses: dessant/lock-threads@v4
|
||||||
with:
|
with:
|
||||||
github-token: ${{ github.token }}
|
github-token: ${{ github.token }}
|
||||||
issue-lock-comment: ""
|
issue-comment: ""
|
||||||
pr-lock-comment: ""
|
pr-comment: ""
|
||||||
|
|
||||||
cleanup:
|
cleanup:
|
||||||
name: 🧹 Close issues marked as incomplete & older than 14 days
|
name: 🧹 Close issues marked as incomplete & older than 14 days
|
||||||
@@ -22,7 +22,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- id: date
|
- id: date
|
||||||
run: |
|
run: |
|
||||||
echo "::set-output name=CUTOFF::`date --date='14 days ago' +'%Y-%m-%d'`"
|
echo "CUTOFF=`date --date='14 days ago' +'%Y-%m-%d'`" >> $GITHUB_OUTPUT
|
||||||
- uses: OctoPrint/actions/close-by-query@main
|
- uses: OctoPrint/actions/close-by-query@main
|
||||||
with:
|
with:
|
||||||
repo-token: "${{ secrets.GITHUB_TOKEN }}"
|
repo-token: "${{ secrets.GITHUB_TOKEN }}"
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ jobs:
|
|||||||
issue-automation:
|
issue-automation:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/github-script@v5
|
- uses: actions/github-script@v6
|
||||||
with:
|
with:
|
||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
script: |
|
script: |
|
||||||
@@ -72,7 +72,7 @@ jobs:
|
|||||||
# with:
|
# with:
|
||||||
# repo-token: ${{ secrets.GITHUB_TOKEN }}
|
# repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
- uses: actions/github-script@v5
|
- uses: actions/github-script@v6
|
||||||
env:
|
env:
|
||||||
REMINDER: >
|
REMINDER: >
|
||||||
Hi @${{ github.event.issue.user.login }}!
|
Hi @${{ github.event.issue.user.login }}!
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ jobs:
|
|||||||
linkifyBundles:
|
linkifyBundles:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/github-script@v2
|
- uses: actions/github-script@v6
|
||||||
with:
|
with:
|
||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
script: |
|
script: |
|
||||||
@@ -38,14 +38,14 @@ jobs:
|
|||||||
});
|
});
|
||||||
text += "\n*edited by @github-actions to add bundle viewer links*\n";
|
text += "\n*edited by @github-actions to add bundle viewer links*\n";
|
||||||
|
|
||||||
github.issues.updateComment({
|
github.rest.issues.updateComment({
|
||||||
owner: context.repo.owner,
|
owner: context.repo.owner,
|
||||||
repo: context.repo.repo,
|
repo: context.repo.repo,
|
||||||
comment_id: context.payload.comment.id,
|
comment_id: context.payload.comment.id,
|
||||||
body: text
|
body: text
|
||||||
});
|
});
|
||||||
} else if (botWasHere !== -1) {
|
} else if (botWasHere !== -1) {
|
||||||
github.issues.updateComment({
|
github.rest.issues.updateComment({
|
||||||
owner: context.repo.owner,
|
owner: context.repo.owner,
|
||||||
repo: context.repo.repo,
|
repo: context.repo.repo,
|
||||||
comment_id: context.payload.comment.id,
|
comment_id: context.payload.comment.id,
|
||||||
|
|||||||
@@ -10,12 +10,12 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: ⬇ Checkout
|
- name: ⬇ Checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: 🔀 Merge master into maintenance
|
- name: 🔀 Merge master into maintenance
|
||||||
uses: robotology/gh-action-nightly-merge@v1.3.3
|
uses: robotology/gh-action-nightly-merge@v1.4.0
|
||||||
with:
|
with:
|
||||||
stable_branch: "master"
|
stable_branch: "master"
|
||||||
development_branch: "maintenance"
|
development_branch: "maintenance"
|
||||||
@@ -23,8 +23,26 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: 🔀 Merge staging/bugfix into maintenance
|
||||||
|
uses: robotology/gh-action-nightly-merge@v1.4.0
|
||||||
|
with:
|
||||||
|
stable_branch: "staging/bugfix"
|
||||||
|
development_branch: "maintenance"
|
||||||
|
allow_ff: false
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: 🔀 Merge staging/maintenance into maintenance
|
||||||
|
uses: robotology/gh-action-nightly-merge@v1.4.0
|
||||||
|
with:
|
||||||
|
stable_branch: "staging/bugfix"
|
||||||
|
development_branch: "maintenance"
|
||||||
|
allow_ff: false
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
- name: 🔀 Merge maintenance into devel
|
- name: 🔀 Merge maintenance into devel
|
||||||
uses: robotology/gh-action-nightly-merge@v1.3.3
|
uses: robotology/gh-action-nightly-merge@v1.4.0
|
||||||
with:
|
with:
|
||||||
stable_branch: "maintenance"
|
stable_branch: "maintenance"
|
||||||
development_branch: "devel"
|
development_branch: "devel"
|
||||||
|
|||||||
@@ -8,11 +8,11 @@ jobs:
|
|||||||
pr-automation:
|
pr-automation:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/labeler@v3
|
- uses: actions/labeler@v4
|
||||||
with:
|
with:
|
||||||
repo-token: "${{ secrets.GITHUB_TOKEN }}"
|
repo-token: "${{ secrets.GITHUB_TOKEN }}"
|
||||||
|
|
||||||
- uses: actions/github-script@v5
|
- uses: actions/github-script@v6
|
||||||
with:
|
with:
|
||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
script: |
|
script: |
|
||||||
|
|||||||
@@ -19,11 +19,11 @@ jobs:
|
|||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
steps:
|
steps:
|
||||||
- name: 🐍 Set up Python ${{ matrix.python }}
|
- name: 🐍 Set up Python ${{ matrix.python }}
|
||||||
uses: actions/setup-python@v2
|
uses: actions/setup-python@v4
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python }}
|
python-version: ${{ matrix.python }}
|
||||||
- name: ⬇ Checkout code
|
- name: ⬇ Checkout code
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
with:
|
with:
|
||||||
ref: ${{ matrix.branch }}
|
ref: ${{ matrix.branch }}
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
@@ -55,24 +55,23 @@ jobs:
|
|||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
steps:
|
steps:
|
||||||
- name: 👀 Determine latest release
|
- name: 👀 Determine latest release
|
||||||
id: latest
|
run: |
|
||||||
uses: foosel/github-action-get-latest-release@master
|
OCTOPRINT_VERSION=$(curl -i https://github.com/OctoPrint/OctoPrint/releases/latest | grep -i location: | head -n1 | awk -F/ '{print $NF}' | tr -d '\r')
|
||||||
with:
|
echo "OCTOPRINT_VERSION=$OCTOPRINT_VERSION" >> $GITHUB_ENV
|
||||||
repository: "OctoPrint/OctoPrint"
|
|
||||||
- name: 🐍 Set up Python ${{ matrix.python }}
|
- name: 🐍 Set up Python ${{ matrix.python }}
|
||||||
uses: actions/setup-python@v2
|
uses: actions/setup-python@v4
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python }}
|
python-version: ${{ matrix.python }}
|
||||||
- name: 👷 Build and install latest release
|
- name: 👷 Build and install latest release
|
||||||
run: |
|
run: |
|
||||||
pip install https://github.com/OctoPrint/OctoPrint/archive/${{ steps.latest.outputs.release }}.zip
|
pip install https://github.com/OctoPrint/OctoPrint/archive/${{ env.OCTOPRINT_VERSION }}.zip
|
||||||
- name: 📧 Discord success notification
|
- name: 📧 Discord success notification
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
env:
|
env:
|
||||||
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
||||||
uses: Ilshidur/action-discord@master
|
uses: Ilshidur/action-discord@master
|
||||||
with:
|
with:
|
||||||
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful"
|
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ env.OCTOPRINT_VERSION }}` was successful"
|
||||||
- name: 📧 Discord failure notification
|
- name: 📧 Discord failure notification
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
if: failure()
|
if: failure()
|
||||||
@@ -80,4 +79,4 @@ jobs:
|
|||||||
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
||||||
uses: Ilshidur/action-discord@master
|
uses: Ilshidur/action-discord@master
|
||||||
with:
|
with:
|
||||||
args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed"
|
args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ env.OCTOPRINT_VERSION }}` failed"
|
||||||
@@ -15,7 +15,7 @@ jobs:
|
|||||||
if: github.repository == 'OctoPrint/OctoPrint' && github.event_name != 'push'
|
if: github.repository == 'OctoPrint/OctoPrint' && github.event_name != 'push'
|
||||||
steps:
|
steps:
|
||||||
- name: 🚀 Repository Dispatch
|
- name: 🚀 Repository Dispatch
|
||||||
uses: peter-evans/repository-dispatch@v1
|
uses: peter-evans/repository-dispatch@v2
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
|
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
|
||||||
repository: ${{ github.repository_owner }}/octoprint-docker
|
repository: ${{ github.repository_owner }}/octoprint-docker
|
||||||
@@ -27,7 +27,7 @@ jobs:
|
|||||||
if: github.repository == 'OctoPrint/OctoPrint' && github.event_name == 'push' && github.ref == 'refs/heads/maintenance'
|
if: github.repository == 'OctoPrint/OctoPrint' && github.event_name == 'push' && github.ref == 'refs/heads/maintenance'
|
||||||
steps:
|
steps:
|
||||||
- name: 🚀 Repository Dispatch
|
- name: 🚀 Repository Dispatch
|
||||||
uses: peter-evans/repository-dispatch@v1
|
uses: peter-evans/repository-dispatch@v2
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
|
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
|
||||||
repository: ${{ github.repository_owner }}/octoprint-docker
|
repository: ${{ github.repository_owner }}/octoprint-docker
|
||||||
@@ -39,7 +39,7 @@ jobs:
|
|||||||
if: github.repository == 'OctoPrint/OctoPrint' && github.event_name == 'push' && github.ref == 'refs/heads/devel'
|
if: github.repository == 'OctoPrint/OctoPrint' && github.event_name == 'push' && github.ref == 'refs/heads/devel'
|
||||||
steps:
|
steps:
|
||||||
- name: 🚀 Repository Dispatch
|
- name: 🚀 Repository Dispatch
|
||||||
uses: peter-evans/repository-dispatch@v1
|
uses: peter-evans/repository-dispatch@v2
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
|
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
|
||||||
repository: ${{ github.repository_owner }}/octoprint-docker
|
repository: ${{ github.repository_owner }}/octoprint-docker
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
name: Trigger doc build
|
name: Trigger doc build
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
- maintenance
|
||||||
|
- devel
|
||||||
release:
|
release:
|
||||||
types:
|
types:
|
||||||
- released
|
- released
|
||||||
@@ -12,7 +16,7 @@ jobs:
|
|||||||
if: github.repository == 'OctoPrint/OctoPrint'
|
if: github.repository == 'OctoPrint/OctoPrint'
|
||||||
steps:
|
steps:
|
||||||
- name: 🚀 Repository Dispatch
|
- name: 🚀 Repository Dispatch
|
||||||
uses: peter-evans/repository-dispatch@v1
|
uses: peter-evans/repository-dispatch@v2
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.REPODISPATCH_TOKEN }}
|
token: ${{ secrets.REPODISPATCH_TOKEN }}
|
||||||
repository: OctoPrint/docs.octoprint.org
|
repository: OctoPrint/docs.octoprint.org
|
||||||
|
|||||||
@@ -49,12 +49,13 @@ repos:
|
|||||||
args: ["--config", "black.toml"]
|
args: ["--config", "black.toml"]
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- click==8.0.4
|
- click==8.0.4
|
||||||
- repo: https://gitlab.com/pycqa/flake8
|
- repo: https://github.com/pycqa/flake8
|
||||||
rev: 3.9.2
|
rev: 3.9.2
|
||||||
hooks:
|
hooks:
|
||||||
- id: flake8
|
- id: flake8
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- flake8-bugbear==22.1.11
|
- flake8-bugbear==22.1.11
|
||||||
|
- importlib-metadata<5.0
|
||||||
- repo: https://github.com/pre-commit/mirrors-prettier
|
- repo: https://github.com/pre-commit/mirrors-prettier
|
||||||
rev: v2.5.1
|
rev: v2.5.1
|
||||||
hooks:
|
hooks:
|
||||||
|
|||||||
+3
-3
@@ -24,10 +24,10 @@ maintenance 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
|||||||
fix/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
fix/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
||||||
improve/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
improve/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
||||||
|
|
||||||
# staging/bugfix is the branch for preparation of the 1.8.1 bugfix release
|
# staging/bugfix is the branch for preparation of the 1.8.7 bugfix release
|
||||||
# so are any bug/... branches
|
# so are any bug/... branches
|
||||||
staging/bugfix 1.8.2 260a1aef11432c421246019e25b6b744abbaed60 pep440-dev
|
staging/bugfix 1.8.7 1875623f05e14c3a197c6ff324f02dce55cec7d2 pep440-dev
|
||||||
bug/.* 1.8.2 260a1aef11432c421246019e25b6b744abbaed60 pep440-dev
|
bug/.* 1.8.7 1875623f05e14c3a197c6ff324f02dce55cec7d2 pep440-dev
|
||||||
|
|
||||||
# staging/maintenance is currently the branch for preparation of 1.8.0rc6
|
# staging/maintenance is currently the branch for preparation of 1.8.0rc6
|
||||||
# so is regressionfix/...
|
# so is regressionfix/...
|
||||||
|
|||||||
@@ -5,10 +5,9 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="https://img.shields.io/github/v/release/OctoPrint/OctoPrint?logo=github&logoColor=white" alt="GitHub release"/>
|
<img src="https://img.shields.io/github/v/release/OctoPrint/OctoPrint?logo=github&logoColor=white" alt="GitHub release"/>
|
||||||
<img src="https://img.shields.io/pypi/v/OctoPrint?logo=python&logoColor=white" alt="PyPI"/>
|
<img src="https://img.shields.io/pypi/v/OctoPrint?logo=python&logoColor=white" alt="PyPI"/>
|
||||||
<img src="https://img.shields.io/github/workflow/status/OctoPrint/OctoPrint/Build" alt="Build status"/>
|
<img src="https://img.shields.io/github/actions/workflow/status/OctoPrint/OctoPrint/build.yml?branch=master" alt="Build status"/>
|
||||||
<a href="https://community.octoprint.org"><img src="https://img.shields.io/discourse/users?logo=discourse&logoColor=white&server=https%3A%2F%2Fcommunity.octoprint.org" alt="Community Forum"/></a>
|
<a href="https://community.octoprint.org"><img src="https://img.shields.io/discourse/users?label=forum&logo=discourse&logoColor=white&server=https%3A%2F%2Fcommunity.octoprint.org" alt="Community Forum"/></a>
|
||||||
<a href="https://discord.octoprint.org"><img src="https://img.shields.io/discord/704958479194128507?label=discord&logo=discord&logoColor=white" alt="Discord"/></a>
|
<a href="https://discord.octoprint.org"><img src="https://img.shields.io/discord/704958479194128507?label=discord&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||||
<a href="https://twitter.com/OctoPrint3d"><img src="https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow" alt="Twitter Follow"/></a>
|
|
||||||
<a href="https://octoprint.org/conduct/"><img src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg" alt="Contributor Covenant"/></a>
|
<a href="https://octoprint.org/conduct/"><img src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg" alt="Contributor Covenant"/></a>
|
||||||
<a href="https://github.com/psf/black"><img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Code style: black"/></a>
|
<a href="https://github.com/psf/black"><img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Code style: black"/></a>
|
||||||
<a href="https://github.com/prettier/prettier"><img src="https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square" alt="Code style: prettier"/></a>
|
<a href="https://github.com/prettier/prettier"><img src="https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square" alt="Code style: prettier"/></a>
|
||||||
@@ -21,7 +20,7 @@ and released under the [GNU Affero General Public License V3](https://www.gnu.or
|
|||||||
|
|
||||||
Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme).
|
Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme).
|
||||||
|
|
||||||
The community forum is available at [community.octoprint.org](https://community.octoprint.org/?utm_source=github&utm_medium=readme). It also serves as central knowledge base.
|
The community forum is available at [community.octoprint.org](https://community.octoprint.org/?utm_source=github&utm_medium=readme). It also serves as a central knowledge base.
|
||||||
|
|
||||||
An invite to the Discord server can be found at [discord.octoprint.org](https://discord.octoprint.org).
|
An invite to the Discord server can be found at [discord.octoprint.org](https://discord.octoprint.org).
|
||||||
|
|
||||||
|
|||||||
+1
-9
@@ -1,11 +1,3 @@
|
|||||||
# Security Policy
|
# Security Policy
|
||||||
|
|
||||||
## Supported Versions
|
OctoPrint's security policy can be found [here](https://octoprint.org/security/).
|
||||||
|
|
||||||
Always update to the latest version of OctoPrint to keep up with security patches.
|
|
||||||
|
|
||||||
## Reporting a Vulnerability
|
|
||||||
|
|
||||||
Email to security@octoprint.org.
|
|
||||||
|
|
||||||
For the sake of the userbase of OctoPrint please always disclose responsibly and with a 90+ day window.
|
|
||||||
+6
-9
@@ -11,42 +11,42 @@ thanks to everyone who contributed!
|
|||||||
* Al Mucci
|
* Al Mucci
|
||||||
* Arnljot Arntsen
|
* Arnljot Arntsen
|
||||||
* Ash King
|
* Ash King
|
||||||
|
* Ben Fritsch
|
||||||
* BigTreeTech
|
* BigTreeTech
|
||||||
* Boris Hussein
|
* Boris Hussein
|
||||||
* Brad Jackson
|
* Brad Jackson
|
||||||
* Calvin Vette
|
|
||||||
* Christian Petropolis
|
* Christian Petropolis
|
||||||
* Christian Wolf
|
* Christian Wolf
|
||||||
* Christian Würthner
|
* Christian Würthner
|
||||||
* Christoph Sigrist
|
* Christoph Sigrist
|
||||||
|
* CooperSpartan
|
||||||
* Creality3D
|
* Creality3D
|
||||||
* DeltaMaker 3D Printers
|
* DeltaMaker 3D Printers
|
||||||
* Dennis Breining
|
* Dennis Breining
|
||||||
* Douglas Floyd
|
* Douglas Floyd
|
||||||
* Dr. Frank Wester
|
* Ed Crump
|
||||||
* Ernesto Martinez
|
* Ernesto Martinez
|
||||||
* Franziska Kunsmann
|
* Franziska Kunsmann
|
||||||
* Greg Holloway
|
|
||||||
* Hog Duske
|
* Hog Duske
|
||||||
|
* Jacob Renstrom
|
||||||
* James Mackay
|
* James Mackay
|
||||||
* Jeff Green
|
* Jeff Green
|
||||||
* Jeff Moe
|
* Jeff Moe
|
||||||
* jeffiel
|
* jeffiel
|
||||||
* Jeremy Cole
|
* Jeremy Cole
|
||||||
|
* John Cassel
|
||||||
* Julian Melo
|
* Julian Melo
|
||||||
* Justin Kaufman
|
* Justin Kaufman
|
||||||
* Kaile Riser
|
* Kaile Riser
|
||||||
* Kazuhiro Ogura
|
* Kazuhiro Ogura
|
||||||
* Kenneth Jiang
|
* Kenneth Jiang
|
||||||
* Kurt Wubbels
|
* Kurt Wubbels
|
||||||
* Kyle Menigoz
|
|
||||||
* Lachlan Bell
|
* Lachlan Bell
|
||||||
* Lefteris Lertas
|
* Lefteris Lertas
|
||||||
* LulzBot
|
* LulzBot
|
||||||
* Makespace Madrid
|
* Makespace Madrid
|
||||||
* Mark Greenwald
|
* Mark Greenwald
|
||||||
* Mark Walker
|
* Mark Walker
|
||||||
* Matt Van Itallie
|
|
||||||
* Michael Aumock
|
* Michael Aumock
|
||||||
* Mike Kershaw
|
* Mike Kershaw
|
||||||
* Mosaic Manufacturing
|
* Mosaic Manufacturing
|
||||||
@@ -68,9 +68,6 @@ thanks to everyone who contributed!
|
|||||||
* Stefan Krister
|
* Stefan Krister
|
||||||
* Steve Dougherty
|
* Steve Dougherty
|
||||||
* Steve Thompson
|
* Steve Thompson
|
||||||
* TJ Horner
|
|
||||||
* Trent Shumay
|
|
||||||
* Ulrich Kempken
|
* Ulrich Kempken
|
||||||
* Yehuda Katz
|
|
||||||
|
|
||||||
and 2209 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
|
and 2036 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||||
+10
-4
@@ -238,16 +238,22 @@ Change a user's password
|
|||||||
|
|
||||||
Changes the password of a user.
|
Changes the password of a user.
|
||||||
|
|
||||||
Expects a JSON object with a single property ``password`` as request body.
|
Expects a JSON object with a property ``password`` containing the new password as
|
||||||
|
request body. Without the ``SETTINGS`` permission, an additional property ``current``
|
||||||
|
is also required to be set on the request body, containing the user's current password.
|
||||||
|
|
||||||
Requires the ``SETTINGS`` permission or to be logged in as the user.
|
Requires the ``SETTINGS`` permission or to be logged in as the user. Note that ``current``
|
||||||
|
will be evaluated even in presence of the ``SETTINGS`` permission, if set.
|
||||||
|
|
||||||
:param username: Name of the user to change the password for
|
:param username: Name of the user to change the password for
|
||||||
:json password: The new password to set
|
:json password: The new password to set
|
||||||
|
:json current: The current password
|
||||||
:status 200: No error
|
:status 200: No error
|
||||||
:status 400: If the request doesn't contain a ``password`` property or the request
|
:status 400: If the request doesn't contain a ``password`` property, doesn't
|
||||||
|
contain a ``current`` property even though required, or the request
|
||||||
is otherwise invalid
|
is otherwise invalid
|
||||||
:status 403: No admin rights and not logged in as the user
|
:status 403: No admin rights, not logged in as the user or a current password
|
||||||
|
mismatch
|
||||||
:status 404: The user is unknown
|
:status 404: The user is unknown
|
||||||
|
|
||||||
.. _sec-api-access-users-settings-get:
|
.. _sec-api-access-users-settings-get:
|
||||||
|
|||||||
+24
-1
@@ -135,7 +135,7 @@ check the corresponding checkbox in the API settings dialog.
|
|||||||
|
|
||||||
.. warning::
|
.. warning::
|
||||||
|
|
||||||
This means any browser page can send requests to the OctoPrint API. Authorization is still required however.
|
This means any browser page can send requests to the OctoPrint API. Authorization via an API-Key is still required however.
|
||||||
|
|
||||||
If CORS is not enabled you will get errors like the following::
|
If CORS is not enabled you will get errors like the following::
|
||||||
|
|
||||||
@@ -151,6 +151,29 @@ If CORS is not enabled you will get errors like the following::
|
|||||||
the login mechanism (or reusing an existing login session). When accessing OctoPrint
|
the login mechanism (or reusing an existing login session). When accessing OctoPrint
|
||||||
via CORS, you'll therefore always need to use an API key.
|
via CORS, you'll therefore always need to use an API key.
|
||||||
|
|
||||||
|
.. _sec-api-general-csrf:
|
||||||
|
|
||||||
|
CSRF Protection
|
||||||
|
===============
|
||||||
|
|
||||||
|
.. versionadded:: 1.8.3
|
||||||
|
|
||||||
|
To protect OctoPrint against `CSRF attacks <https://owasp.org/www-community/attacks/csrf>`_ against the non CORS affected upload endpoints, in case of browser session based authorization the API
|
||||||
|
is protected using the `Double Submit Cookie mitigation strategy <https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie>`_.
|
||||||
|
On first page load of the UI, the login page or the recovery page, a ``csrf_token_P<port>`` or ``csrf_token_P<port>_R<root>`` cookie is set
|
||||||
|
that can be read via client-side JavaScript. All requests towards the API that are not ``GET``, ``HEAD`` or ``OPTIONS``
|
||||||
|
and rely on cookie based authorization (so not on an API key but rather an active login session) are required
|
||||||
|
to send both the ``csrf_token`` cookie as well as an ``X-CSRF-Token`` header containing its value.
|
||||||
|
|
||||||
|
.. note::
|
||||||
|
|
||||||
|
If you use the :ref:`JS Client library <sec-jsclientlib>`, this will take care of doing the needful for you. Any code in the *Core UI* calling
|
||||||
|
API functions through ``$.ajax`` or ``$.get`` or ``$.post`` will also take care of this for you. If you use another library for
|
||||||
|
accessing OctoPrint's API in a browser context, you'll need to make sure to send the ``X-CSRF-Token`` header yourself. Examples for
|
||||||
|
several JS frameworks can be found in the `OWASP cheatsheet on CSRF attacks <https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#javascript-guidance-for-auto-inclusion-of-csrf-tokens-as-an-ajax-request-header>`_.
|
||||||
|
Take a look at the implementations of ``OctoPrintClient.getCookie`` and ``OctoPrintClient.getHeaders`` in ``src/octoprint/static/js/client/base.js``
|
||||||
|
for details on how to retrieve the cookie value and how to construct the header.
|
||||||
|
|
||||||
.. _sec-api-general-login:
|
.. _sec-api-general-login:
|
||||||
|
|
||||||
Login
|
Login
|
||||||
|
|||||||
+1
-1
@@ -30,7 +30,7 @@ following message types are currently available for usage by 3rd party clients:
|
|||||||
* ``connected``: Initial connection information, sent only right after establishing the socket connection. See
|
* ``connected``: Initial connection information, sent only right after establishing the socket connection. See
|
||||||
:ref:`the payload data model <sec-api-push-datamodel-connected>`.
|
:ref:`the payload data model <sec-api-push-datamodel-connected>`.
|
||||||
* ``reauthRequired``: A reauthentication of the current login session is required. The ``reason`` parameter in the
|
* ``reauthRequired``: A reauthentication of the current login session is required. The ``reason`` parameter in the
|
||||||
payload defines whether a full active login is necessary (values ``logout`` and ``removed``) or a simple passive
|
payload defines whether a full active login is necessary (values ``logout``, ``stale``, ``removed``) or a simple passive
|
||||||
login will suffice (all other values).
|
login will suffice (all other values).
|
||||||
* ``current``: Rate limited general state update, payload contains information about the printer's state, job progress,
|
* ``current``: Rate limited general state update, payload contains information about the printer's state, job progress,
|
||||||
accumulated temperature points and log lines since last update. OctoPrint will send these updates when new information
|
accumulated temperature points and log lines since last update. OctoPrint will send these updates when new information
|
||||||
|
|||||||
@@ -72,10 +72,6 @@ Use the following settings to enable access control:
|
|||||||
# If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint.
|
# If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint.
|
||||||
addRemoteUsers: false
|
addRemoteUsers: false
|
||||||
|
|
||||||
# Secret salt used for password hashing, DO NOT TOUCH. If changed you will no longer be able to log in with your
|
|
||||||
# existing accounts.
|
|
||||||
salt: someSecretSalt
|
|
||||||
|
|
||||||
.. _sec-configuration-config_yaml-api:
|
.. _sec-configuration-config_yaml-api:
|
||||||
|
|
||||||
API
|
API
|
||||||
|
|||||||
@@ -165,7 +165,7 @@ further down there's also a dedicated list of steps for OctoPi specifically.
|
|||||||
|
|
||||||
1. Shutdown OctoPrint
|
1. Shutdown OctoPrint
|
||||||
2. Make a backup of your config.yaml
|
2. Make a backup of your config.yaml
|
||||||
3. Open it in a text editor (e.g. nano). Right at the very top it'll say something like
|
3. Open it in a text editor (e.g. nano). Look if right at the very top it says something like
|
||||||
this:
|
this:
|
||||||
|
|
||||||
.. code-block:: yaml
|
.. code-block:: yaml
|
||||||
@@ -173,7 +173,7 @@ further down there's also a dedicated list of steps for OctoPi specifically.
|
|||||||
accessControl:
|
accessControl:
|
||||||
salt: aabbccddee1234523452345
|
salt: aabbccddee1234523452345
|
||||||
|
|
||||||
Edit this, adding lines so it looks like this (making absolutely sure not to touch the
|
If so, edit this, adding lines so it looks like this (making absolutely sure not to touch the
|
||||||
salt line):
|
salt line):
|
||||||
|
|
||||||
.. code-block:: yaml
|
.. code-block:: yaml
|
||||||
@@ -187,6 +187,19 @@ further down there's also a dedicated list of steps for OctoPi specifically.
|
|||||||
- "::1/128"
|
- "::1/128"
|
||||||
- "<yourAddressRange>"
|
- "<yourAddressRange>"
|
||||||
|
|
||||||
|
Otherwise, add the following lines to the very top of the file, making sure to keep the
|
||||||
|
indentation:
|
||||||
|
|
||||||
|
.. code-block:: yaml
|
||||||
|
|
||||||
|
accessControl:
|
||||||
|
autologinLocal: true
|
||||||
|
autologinAs: "<yourUsername>"
|
||||||
|
localNetworks:
|
||||||
|
- "127.0.0.0/8"
|
||||||
|
- "::1/128"
|
||||||
|
- "<yourAddressRange>"
|
||||||
|
|
||||||
4. Restart OctoPrint, check that everything works.
|
4. Restart OctoPrint, check that everything works.
|
||||||
|
|
||||||
This will automatically log you in as the user you specified whenver you connect to
|
This will automatically log you in as the user you specified whenver you connect to
|
||||||
@@ -200,7 +213,7 @@ the following commands:
|
|||||||
|
|
||||||
1. ``sudo service octoprint stop``
|
1. ``sudo service octoprint stop``
|
||||||
2. ``cp ~/.octoprint/config.yaml ~/.octoprint/config.yaml.back``
|
2. ``cp ~/.octoprint/config.yaml ~/.octoprint/config.yaml.back``
|
||||||
3. ``nano ~/.octoprint/config.yaml, make the edits as described above``
|
3. ``nano ~/.octoprint/config.yaml``, make the edits as described above
|
||||||
4. ``sudo service octoprint start``
|
4. ``sudo service octoprint start``
|
||||||
|
|
||||||
If something went wrong, you can restore the config backup with
|
If something went wrong, you can restore the config backup with
|
||||||
|
|||||||
@@ -74,15 +74,39 @@
|
|||||||
|
|
||||||
:returns string: The base url to use to access OctoPrint's API.
|
:returns string: The base url to use to access OctoPrint's API.
|
||||||
|
|
||||||
.. js:function:: OctoPrintClient.getRequestHeaders(additional)
|
.. js:function:: OctoPrintClient.getCookie(name)
|
||||||
|
|
||||||
|
.. versionadded:: 1.8.3
|
||||||
|
|
||||||
|
Returns the value of the cookie with name ``name``. The port based cookie suffix and if
|
||||||
|
necessary also the script root based suffix will be automatically applied to the ``name``
|
||||||
|
prior to looking up the value.
|
||||||
|
|
||||||
|
:return string: The value of the cookie, if set & accessible, else an empty string.
|
||||||
|
|
||||||
|
.. js:function:: OctoPrintClient.getRequestHeaders(method, additional, opts)
|
||||||
|
|
||||||
|
.. versionchanged:: 1.8.3
|
||||||
|
|
||||||
Generates a dictionary of HTTP headers to use for API requests against OctoPrint with all
|
Generates a dictionary of HTTP headers to use for API requests against OctoPrint with all
|
||||||
necessary headers and any additionally provided ones.
|
necessary headers and any additionally provided ones.
|
||||||
|
|
||||||
At the moment this entails setting the ``X-Api-Key`` header based on the current value of
|
At the moment this entails setting the ``X-Api-Key`` header based on the current value of
|
||||||
``OctoPrint.options.apikey`` at a minimum.
|
``OctoPrint.options.apikey``, if set. Otherwise, for non-cross-domain requests targeting
|
||||||
|
methods other than ``GET``, ``HEAD`` or ``OPTIONS``, the current CSRF token is read from the
|
||||||
|
associated cookie and set as ``X-CSRF-Token``.
|
||||||
|
|
||||||
:param object additional: Additional headers to add to the request.
|
.. note::
|
||||||
|
|
||||||
|
Up until OctoPrint 1.8.3, this method's signature consisted only of the ``additional``
|
||||||
|
parameter. It has been changed in a backward compatible way so that calling it with the
|
||||||
|
first parameter being the set of additional headers will still work. This mode of operation
|
||||||
|
is deprecated however and will be removed in a future version.
|
||||||
|
A warning will be logged to the debug console accordingly.
|
||||||
|
|
||||||
|
:param str method: Method of the request for which to set headers
|
||||||
|
:param object additional: Additional headers to add to the request, optional.
|
||||||
|
:param object opts: Additional opts passed to the request, used to read cross domain setting, optional.
|
||||||
:returns object: HTTP headers to use for requests.
|
:returns object: HTTP headers to use for requests.
|
||||||
|
|
||||||
.. js:function:: OctoPrintClient.ajax(method, url, opts)
|
.. js:function:: OctoPrintClient.ajax(method, url, opts)
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ development environment::
|
|||||||
$ virtualenv venv
|
$ virtualenv venv
|
||||||
[...]
|
[...]
|
||||||
$ source venv/bin/activate
|
$ source venv/bin/activate
|
||||||
(venv) $ pip install -e .[develop,plugins]
|
(venv) $ pip install -e '.[develop,plugins]'
|
||||||
[...]
|
[...]
|
||||||
(venv) $ octoprint --help
|
(venv) $ octoprint --help
|
||||||
Usage: octoprint [OPTIONS] COMMAND [ARGS]...
|
Usage: octoprint [OPTIONS] COMMAND [ARGS]...
|
||||||
@@ -163,7 +163,7 @@ Then we can use the ``octoprint dev plugin:new`` command [#f1]_ to generate a ne
|
|||||||
email [you@example.com]: you@somewhere.net
|
email [you@example.com]: you@somewhere.net
|
||||||
github_username [you]: yourGithubName
|
github_username [you]: yourGithubName
|
||||||
plugin_version [0.1.0]: 1.0.0
|
plugin_version [0.1.0]: 1.0.0
|
||||||
plugin_description [TODO]: A quick "Hello World" example plugin for OCtoPrint
|
plugin_description [TODO]: A quick "Hello World" example plugin for OctoPrint
|
||||||
plugin_license [AGPLv3]:
|
plugin_license [AGPLv3]:
|
||||||
plugin_homepage [https://github.com/yourGithubName/OctoPrint-Helloworld]:
|
plugin_homepage [https://github.com/yourGithubName/OctoPrint-Helloworld]:
|
||||||
plugin_source [https://github.com/yourGithubName/OctoPrint-Helloworld]:
|
plugin_source [https://github.com/yourGithubName/OctoPrint-Helloworld]:
|
||||||
@@ -178,6 +178,9 @@ Then we can use the ``octoprint dev plugin:new`` command [#f1]_ to generate a ne
|
|||||||
This will create a project structure in the ``OctoPrint-HelloWorld`` folder we just changed to that looks like this::
|
This will create a project structure in the ``OctoPrint-HelloWorld`` folder we just changed to that looks like this::
|
||||||
|
|
||||||
extras/
|
extras/
|
||||||
|
github/
|
||||||
|
bug_report.yml
|
||||||
|
feature_request.yml
|
||||||
README.txt
|
README.txt
|
||||||
helloworld.md
|
helloworld.md
|
||||||
octoprint_helloworld/
|
octoprint_helloworld/
|
||||||
@@ -200,6 +203,7 @@ This will create a project structure in the ``OctoPrint-HelloWorld`` folder we j
|
|||||||
README.md
|
README.md
|
||||||
requirements.txt
|
requirements.txt
|
||||||
setup.py
|
setup.py
|
||||||
|
setup.cfg
|
||||||
|
|
||||||
While we'll need some of those folders later on, we'll now delete everything that we don't need right now first, that
|
While we'll need some of those folders later on, we'll now delete everything that we don't need right now first, that
|
||||||
will make it easier to understand what folder does what later on. Delete the following folders and anything in them:
|
will make it easier to understand what folder does what later on. Delete the following folders and anything in them:
|
||||||
@@ -219,6 +223,7 @@ The final project structure should look like this for now::
|
|||||||
MANIFEST.in
|
MANIFEST.in
|
||||||
README.md
|
README.md
|
||||||
requirements.txt
|
requirements.txt
|
||||||
|
setup.cfg
|
||||||
setup.py
|
setup.py
|
||||||
|
|
||||||
Out of curiosity, take a look into the ``setup.py`` file. The cookiecutter template should have prefilled all the
|
Out of curiosity, take a look into the ``setup.py`` file. The cookiecutter template should have prefilled all the
|
||||||
@@ -393,6 +398,7 @@ Our plugin's directory structure should now look like this::
|
|||||||
README.md
|
README.md
|
||||||
requirements.txt
|
requirements.txt
|
||||||
setup.py
|
setup.py
|
||||||
|
setup.cfg
|
||||||
|
|
||||||
Restart OctoPrint and open the web interface in your browser (make sure to clear your browser's cache!).
|
Restart OctoPrint and open the web interface in your browser (make sure to clear your browser's cache!).
|
||||||
|
|
||||||
@@ -648,6 +654,7 @@ look like this::
|
|||||||
README.md
|
README.md
|
||||||
requirements.txt
|
requirements.txt
|
||||||
setup.py
|
setup.py
|
||||||
|
setup.cfg
|
||||||
|
|
||||||
We need to tell OctoPrint about this new static asset so that it will properly inject it into the page. For this we
|
We need to tell OctoPrint about this new static asset so that it will properly inject it into the page. For this we
|
||||||
just need to subclass :class:`~octoprint.plugin.AssetPlugin` and override its method :func:`~octoprint.plugin.AssetPlugin.get_assets`
|
just need to subclass :class:`~octoprint.plugin.AssetPlugin` and override its method :func:`~octoprint.plugin.AssetPlugin.get_assets`
|
||||||
|
|||||||
@@ -31,9 +31,10 @@ SETUP_REQUIRES = []
|
|||||||
bundled_plugins = [
|
bundled_plugins = [
|
||||||
"OctoPrint-FileCheck>=2021.2.23",
|
"OctoPrint-FileCheck>=2021.2.23",
|
||||||
"OctoPrint-FirmwareCheck>=2021.10.11",
|
"OctoPrint-FirmwareCheck>=2021.10.11",
|
||||||
"OctoPrint-PiSupport>=2022.3.28",
|
"OctoPrint-PiSupport>=2022.6.13",
|
||||||
]
|
]
|
||||||
core_deps = [
|
core_deps = [
|
||||||
|
"argon2_cffi>=21.3.0,<22",
|
||||||
"cachelib>=0.2,<0.3",
|
"cachelib>=0.2,<0.3",
|
||||||
"Click>=8.0.3,<9",
|
"Click>=8.0.3,<9",
|
||||||
"colorlog>=6,<7",
|
"colorlog>=6,<7",
|
||||||
@@ -43,12 +44,14 @@ core_deps = [
|
|||||||
"Flask-Assets>=2.0,<3",
|
"Flask-Assets>=2.0,<3",
|
||||||
"Flask-Babel>=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-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
|
||||||
|
"Flask-Limiter>=2.6,<3",
|
||||||
"flask>=2.1,<2.2", # flask 2.2 requires werkzeug 2.2+
|
"flask>=2.1,<2.2", # flask 2.2 requires werkzeug 2.2+
|
||||||
"frozendict>=2.0,<3",
|
"frozendict>=2.0,<3",
|
||||||
"future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins
|
"future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins
|
||||||
"markdown>=3.2.2,<4",
|
"markdown>=3.2.2,<4",
|
||||||
"netaddr>=0.8,<0.9", # changelog hints at breaking changes on minor version increases
|
"netaddr>=0.8,<0.9", # changelog hints at breaking changes on minor version increases
|
||||||
"netifaces>=0.11,<1",
|
"netifaces>=0.11,<1",
|
||||||
|
"passlib>=1.7.4,<2",
|
||||||
"pathvalidate>=2.4.1,<3",
|
"pathvalidate>=2.4.1,<3",
|
||||||
"pkginfo>=1.7.1,<2",
|
"pkginfo>=1.7.1,<2",
|
||||||
"psutil>=5.8,<6",
|
"psutil>=5.8,<6",
|
||||||
@@ -63,7 +66,7 @@ core_deps = [
|
|||||||
"watchdog>=1,<2",
|
"watchdog>=1,<2",
|
||||||
"websocket-client>=1.2.1,<2",
|
"websocket-client>=1.2.1,<2",
|
||||||
"werkzeug>=2.0,<2.1", # breaking changes can happen on minor version increases, flask-login 0.5 is incompatible with 2.1
|
"werkzeug>=2.0,<2.1", # breaking changes can happen on minor version increases, flask-login 0.5 is incompatible with 2.1
|
||||||
"wrapt>=1.13.3,<1.14",
|
"wrapt>=1.14,<1.15",
|
||||||
"zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases
|
"zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases
|
||||||
"zipstream-ng>=1.3.4,<2.0.0",
|
"zipstream-ng>=1.3.4,<2.0.0",
|
||||||
]
|
]
|
||||||
|
|||||||
+124
-59
@@ -4,11 +4,13 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
|||||||
import hashlib
|
import hashlib
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import shutil
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
import wrapt
|
import wrapt
|
||||||
from flask_login import AnonymousUserMixin, UserMixin
|
from flask_login import AnonymousUserMixin, UserMixin
|
||||||
|
from passlib.hash import pbkdf2_sha256
|
||||||
from werkzeug.local import LocalProxy
|
from werkzeug.local import LocalProxy
|
||||||
|
|
||||||
from octoprint.access.groups import Group, GroupChangeListener
|
from octoprint.access.groups import Group, GroupChangeListener
|
||||||
@@ -18,6 +20,23 @@ from octoprint.util import atomic_write, deprecated, generate_api_key
|
|||||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||||
from octoprint.util import to_bytes, yaml
|
from octoprint.util import to_bytes, yaml
|
||||||
|
|
||||||
|
password_hashers = []
|
||||||
|
|
||||||
|
try:
|
||||||
|
from passlib.hash import argon2
|
||||||
|
|
||||||
|
# test if we can actually hash and verify, if not we won't use this backend
|
||||||
|
hash = argon2.hash("test")
|
||||||
|
argon2.verify("test", hash)
|
||||||
|
|
||||||
|
password_hashers.append(argon2)
|
||||||
|
except Exception:
|
||||||
|
logging.getLogger(__name__).warning(
|
||||||
|
"Argon2 passlib backend is not available, not using it for password hashing"
|
||||||
|
)
|
||||||
|
|
||||||
|
password_hashers.append(pbkdf2_sha256)
|
||||||
|
|
||||||
|
|
||||||
class UserManager(GroupChangeListener):
|
class UserManager(GroupChangeListener):
|
||||||
def __init__(self, group_manager, settings=None):
|
def __init__(self, group_manager, settings=None):
|
||||||
@@ -127,29 +146,18 @@ class UserManager(GroupChangeListener):
|
|||||||
for session, user in list(self._session_users_by_session.items()):
|
for session, user in list(self._session_users_by_session.items()):
|
||||||
if not isinstance(user, SessionUser):
|
if not isinstance(user, SessionUser):
|
||||||
continue
|
continue
|
||||||
if user.created + (24 * 60 * 60) < time.monotonic():
|
if user.touched + (15 * 60) < time.monotonic():
|
||||||
self._logger.info(
|
self._logger.info(
|
||||||
"Cleaning up user session {} for user {}".format(
|
f"Cleaning up user session {session} for user {user.get_id()}"
|
||||||
session, user.get_id()
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
self.logout_user(user, stale=True)
|
self.logout_user(user, stale=True)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def create_password_hash(password, salt=None, settings=None):
|
def create_password_hash(password, *args, **kwargs):
|
||||||
if not salt:
|
return password_hashers[0].hash(password)
|
||||||
if settings is None:
|
|
||||||
settings = s()
|
|
||||||
salt = settings.get(["accessControl", "salt"])
|
|
||||||
if salt is None:
|
|
||||||
import string
|
|
||||||
from random import choice
|
|
||||||
|
|
||||||
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
|
|
||||||
salt = "".join(choice(chars) for _ in range(32))
|
|
||||||
settings.set(["accessControl", "salt"], salt)
|
|
||||||
settings.save()
|
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_legacy_password_hash(password, salt):
|
||||||
return hashlib.sha512(
|
return hashlib.sha512(
|
||||||
to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt)
|
to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt)
|
||||||
).hexdigest()
|
).hexdigest()
|
||||||
@@ -159,23 +167,34 @@ class UserManager(GroupChangeListener):
|
|||||||
if not user:
|
if not user:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
hash = UserManager.create_password_hash(password, settings=self._settings)
|
if user.check_password(password):
|
||||||
if user.check_password(hash):
|
# password matches, correct password
|
||||||
# new hash matches, correct password
|
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
# new hash doesn't match, but maybe the old one does, so check that!
|
# new hash doesn't match, check legacy hash
|
||||||
oldHash = UserManager.create_password_hash(
|
salt = self._settings.get(["accessControl"], asdict=True, merged=True).get(
|
||||||
password, salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW", settings=self._settings
|
"salt", None
|
||||||
)
|
)
|
||||||
if user.check_password(oldHash):
|
if salt is None:
|
||||||
# old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password
|
return False
|
||||||
|
|
||||||
|
legacy_hash = UserManager.create_legacy_password_hash(password, salt)
|
||||||
|
if user.check_password(legacy_hash, legacy=True):
|
||||||
|
# legacy hash matches, we migrate the stored password hash to the new one and return True since it's the correct password
|
||||||
self.change_user_password(username, password)
|
self.change_user_password(username, password)
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
# old hash doesn't match either, wrong password
|
# legacy hash doesn't match either, wrong password
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def cleanup_legacy_hashes(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def signature_key_for_user(self, username, secret):
|
||||||
|
return hashlib.sha512(
|
||||||
|
to_bytes(username, encoding="utf-8", errors="replace") + to_bytes(secret)
|
||||||
|
).hexdigest()
|
||||||
|
|
||||||
def add_user(self, username, password, active, permissions, groups, overwrite=False):
|
def add_user(self, username, password, active, permissions, groups, overwrite=False):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -227,21 +246,28 @@ class UserManager(GroupChangeListener):
|
|||||||
del self._sessionids_by_userid[username]
|
del self._sessionids_by_userid[username]
|
||||||
|
|
||||||
def validate_user_session(self, userid, session):
|
def validate_user_session(self, userid, session):
|
||||||
|
self._cleanup_sessions()
|
||||||
|
|
||||||
if session in self._session_users_by_session:
|
if session in self._session_users_by_session:
|
||||||
user = self._session_users_by_session[session]
|
user = self._session_users_by_session[session]
|
||||||
return userid == user.get_id()
|
return userid == user.get_id()
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def find_user(self, userid=None, session=None):
|
def find_user(self, userid=None, session=None, fresh=False):
|
||||||
|
self._cleanup_sessions()
|
||||||
|
|
||||||
if session is not None and session in self._session_users_by_session:
|
if session is not None and session in self._session_users_by_session:
|
||||||
user = self._session_users_by_session[session]
|
user = self._session_users_by_session[session]
|
||||||
if userid is None or userid == user.get_id():
|
if userid is None or userid == user.get_id():
|
||||||
|
user.touch()
|
||||||
return user
|
return user
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def find_sessions_for(self, matcher):
|
def find_sessions_for(self, matcher):
|
||||||
|
self._cleanup_sessions()
|
||||||
|
|
||||||
result = []
|
result = []
|
||||||
for user in self.get_all_users():
|
for user in self.get_all_users():
|
||||||
if matcher(user):
|
if matcher(user):
|
||||||
@@ -249,7 +275,9 @@ class UserManager(GroupChangeListener):
|
|||||||
session_ids = self._sessionids_by_userid[user.get_id()]
|
session_ids = self._sessionids_by_userid[user.get_id()]
|
||||||
for session_id in session_ids:
|
for session_id in session_ids:
|
||||||
try:
|
try:
|
||||||
result.append(self._session_users_by_session[session_id])
|
session_user = self._session_users_by_session[session_id]
|
||||||
|
session_user.touch()
|
||||||
|
result.append(session_user)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
# unknown session after all
|
# unknown session after all
|
||||||
continue
|
continue
|
||||||
@@ -339,23 +367,6 @@ class UserManager(GroupChangeListener):
|
|||||||
|
|
||||||
# TODO: Remove deprecated methods in OctoPrint 1.5.0
|
# TODO: Remove deprecated methods in OctoPrint 1.5.0
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def createPasswordHash(*args, **kwargs):
|
|
||||||
"""
|
|
||||||
.. deprecated: 1.4.0
|
|
||||||
|
|
||||||
Replaced by :func:`~UserManager.create_password_hash`
|
|
||||||
"""
|
|
||||||
# we can't use the deprecated decorator here since this method is static
|
|
||||||
import warnings
|
|
||||||
|
|
||||||
warnings.warn(
|
|
||||||
"createPasswordHash has been renamed to create_password_hash",
|
|
||||||
DeprecationWarning,
|
|
||||||
stacklevel=2,
|
|
||||||
)
|
|
||||||
return UserManager.create_password_hash(*args, **kwargs)
|
|
||||||
|
|
||||||
@deprecated(
|
@deprecated(
|
||||||
"changeUserRoles has been replaced by change_user_permissions",
|
"changeUserRoles has been replaced by change_user_permissions",
|
||||||
includedoc="Replaced by :func:`change_user_permissions`",
|
includedoc="Replaced by :func:`change_user_permissions`",
|
||||||
@@ -489,6 +500,8 @@ class LoginStatusListener:
|
|||||||
|
|
||||||
|
|
||||||
class FilebasedUserManager(UserManager):
|
class FilebasedUserManager(UserManager):
|
||||||
|
FILE_VERSION = 2
|
||||||
|
|
||||||
def __init__(self, group_manager, path=None, settings=None):
|
def __init__(self, group_manager, path=None, settings=None):
|
||||||
UserManager.__init__(self, group_manager, settings=settings)
|
UserManager.__init__(self, group_manager, settings=settings)
|
||||||
|
|
||||||
@@ -520,6 +533,17 @@ class FilebasedUserManager(UserManager):
|
|||||||
)
|
)
|
||||||
raise CorruptUserStorage()
|
raise CorruptUserStorage()
|
||||||
|
|
||||||
|
version = data.pop("_version", 1)
|
||||||
|
if version != self.FILE_VERSION:
|
||||||
|
self._logger.info(
|
||||||
|
f"Making a backup of the users.yaml file before migrating from version {version} to {self.FILE_VERSION}"
|
||||||
|
)
|
||||||
|
shutil.copy(
|
||||||
|
self._userfile,
|
||||||
|
os.path.splitext(self._userfile)[0] + f".v{version}.yaml",
|
||||||
|
)
|
||||||
|
self._dirty = True
|
||||||
|
|
||||||
for name, attributes in data.items():
|
for name, attributes in data.items():
|
||||||
if not isinstance(attributes, dict):
|
if not isinstance(attributes, dict):
|
||||||
continue
|
continue
|
||||||
@@ -567,6 +591,8 @@ class FilebasedUserManager(UserManager):
|
|||||||
if self._dirty:
|
if self._dirty:
|
||||||
self._save()
|
self._save()
|
||||||
|
|
||||||
|
self.cleanup_legacy_hashes()
|
||||||
|
|
||||||
self._customized = True
|
self._customized = True
|
||||||
else:
|
else:
|
||||||
self._customized = False
|
self._customized = False
|
||||||
@@ -575,7 +601,7 @@ class FilebasedUserManager(UserManager):
|
|||||||
if not self._dirty and not force:
|
if not self._dirty and not force:
|
||||||
return
|
return
|
||||||
|
|
||||||
data = {}
|
data = {"_version": self.FILE_VERSION}
|
||||||
for name, user in self._users.items():
|
for name, user in self._users.items():
|
||||||
if not user or not isinstance(user, User):
|
if not user or not isinstance(user, User):
|
||||||
continue
|
continue
|
||||||
@@ -618,11 +644,11 @@ class FilebasedUserManager(UserManager):
|
|||||||
apikey=None,
|
apikey=None,
|
||||||
overwrite=False,
|
overwrite=False,
|
||||||
):
|
):
|
||||||
if not permissions:
|
if permissions is None:
|
||||||
permissions = []
|
permissions = []
|
||||||
permissions = self._to_permissions(*permissions)
|
permissions = self._to_permissions(*permissions)
|
||||||
|
|
||||||
if not groups:
|
if groups is None:
|
||||||
groups = self._group_manager.default_groups
|
groups = self._group_manager.default_groups
|
||||||
groups = self._to_groups(*groups)
|
groups = self._to_groups(*groups)
|
||||||
|
|
||||||
@@ -773,12 +799,42 @@ class FilebasedUserManager(UserManager):
|
|||||||
if username not in self._users:
|
if username not in self._users:
|
||||||
raise UnknownUser(username)
|
raise UnknownUser(username)
|
||||||
|
|
||||||
passwordHash = UserManager.create_password_hash(password, settings=self._settings)
|
|
||||||
user = self._users[username]
|
user = self._users[username]
|
||||||
if user._passwordHash != passwordHash:
|
user._passwordHash = UserManager.create_password_hash(password)
|
||||||
user._passwordHash = passwordHash
|
self._dirty = True
|
||||||
self._dirty = True
|
self._save()
|
||||||
self._save()
|
|
||||||
|
self._trigger_on_user_modified(user)
|
||||||
|
|
||||||
|
def cleanup_legacy_hashes(self):
|
||||||
|
no_legacy = all(
|
||||||
|
map(
|
||||||
|
lambda u: u._passwordHash.startswith("$argon2id$")
|
||||||
|
or u._passwordHash.startswith("$pbkdf2-"),
|
||||||
|
self._users.values(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
salt = self._settings.get(["accessControl"], asdict=True, merged=True).get(
|
||||||
|
"salt", None
|
||||||
|
)
|
||||||
|
|
||||||
|
if no_legacy and salt:
|
||||||
|
# no legacy hashs left, kill salt
|
||||||
|
self._settings.backup("cleanup_legacy_hashes")
|
||||||
|
self._settings.remove(["accessControl", "salt"])
|
||||||
|
self._settings.save()
|
||||||
|
|
||||||
|
def signature_key_for_user(self, username, secret):
|
||||||
|
if username == "_api":
|
||||||
|
return super().signature_key_for_user(username, secret)
|
||||||
|
if username not in self._users:
|
||||||
|
raise UnknownUser(username)
|
||||||
|
user = self._users[username]
|
||||||
|
|
||||||
|
return hashlib.sha512(
|
||||||
|
to_bytes(username + user._passwordHash, encoding="utf-8", errors="replace")
|
||||||
|
+ to_bytes(secret)
|
||||||
|
).hexdigest()
|
||||||
|
|
||||||
def change_user_setting(self, username, key, value):
|
def change_user_setting(self, username, key, value):
|
||||||
if username not in self._users:
|
if username not in self._users:
|
||||||
@@ -845,10 +901,10 @@ class FilebasedUserManager(UserManager):
|
|||||||
self._dirty = True
|
self._dirty = True
|
||||||
self._save()
|
self._save()
|
||||||
|
|
||||||
def find_user(self, userid=None, apikey=None, session=None):
|
def find_user(self, userid=None, apikey=None, session=None, fresh=False):
|
||||||
user = UserManager.find_user(self, userid=userid, session=session)
|
user = UserManager.find_user(self, userid=userid, session=session)
|
||||||
|
|
||||||
if user is not None:
|
if user is not None or (session and fresh):
|
||||||
return user
|
return user
|
||||||
|
|
||||||
if userid is not None:
|
if userid is not None:
|
||||||
@@ -1126,8 +1182,18 @@ class User(UserMixin):
|
|||||||
"roles": self._roles,
|
"roles": self._roles,
|
||||||
}
|
}
|
||||||
|
|
||||||
def check_password(self, passwordHash):
|
def check_password(self, password, legacy=False):
|
||||||
return self._passwordHash == passwordHash
|
if legacy:
|
||||||
|
return self._passwordHash == password
|
||||||
|
|
||||||
|
for password_hash in password_hashers:
|
||||||
|
if password_hash.identify(self._passwordHash):
|
||||||
|
try:
|
||||||
|
return password_hash.verify(password, self._passwordHash)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
def get_id(self):
|
def get_id(self):
|
||||||
return self.get_name()
|
return self.get_name()
|
||||||
@@ -1383,8 +1449,7 @@ class SessionUser(wrapt.ObjectProxy):
|
|||||||
wrapt.ObjectProxy.__init__(self, user)
|
wrapt.ObjectProxy.__init__(self, user)
|
||||||
|
|
||||||
self._self_session = "".join("%02X" % z for z in bytes(uuid.uuid4().bytes))
|
self._self_session = "".join("%02X" % z for z in bytes(uuid.uuid4().bytes))
|
||||||
self._self_created = time.monotonic()
|
self._self_created = self._self_touched = time.monotonic()
|
||||||
self._self_touched = time.monotonic()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def session(self):
|
def session(self):
|
||||||
|
|||||||
@@ -954,6 +954,12 @@ class LocalFileStorage(StorageInterface):
|
|||||||
source, destination, must_not_equal=True
|
source, destination, must_not_equal=True
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if not octoprint.filemanager.valid_file_type(destination_data["name"]):
|
||||||
|
raise StorageError(
|
||||||
|
f"{destination_data['name']} is an unrecognized file type",
|
||||||
|
code=StorageError.INVALID_FILE,
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
shutil.copy2(source_data["fullpath"], destination_data["fullpath"])
|
shutil.copy2(source_data["fullpath"], destination_data["fullpath"])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -983,6 +989,12 @@ class LocalFileStorage(StorageInterface):
|
|||||||
source, destination
|
source, destination
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if not octoprint.filemanager.valid_file_type(destination_data["name"]):
|
||||||
|
raise StorageError(
|
||||||
|
f"{destination_data['name']} is an unrecognized file type",
|
||||||
|
code=StorageError.INVALID_FILE,
|
||||||
|
)
|
||||||
|
|
||||||
# only a display rename? Update that and bail early
|
# only a display rename? Update that and bail early
|
||||||
if source_data["fullpath"] == destination_data["fullpath"]:
|
if source_data["fullpath"] == destination_data["fullpath"]:
|
||||||
self._set_display_metadata(destination_data)
|
self._set_display_metadata(destination_data)
|
||||||
|
|||||||
@@ -1352,8 +1352,39 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
|||||||
|
|
||||||
flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo"
|
flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo"
|
||||||
|
|
||||||
|
.. warning::
|
||||||
|
|
||||||
|
As of OctoPrint 1.8.3, endpoints provided through a ``BlueprintPlugin`` do **not** automatically fall under
|
||||||
|
OctoPrint's :ref:`CSRF protection <sec-api-general-csrf>`, for reasons of backwards compatibility. There will be a short grace period before this changes. You
|
||||||
|
can and should however already opt into CSRF protection for your endpoints by implementing ``is_blueprint_csrf_protected``
|
||||||
|
and returning ``True`` from it. You can exempt certain endpoints from CSRF protection by decorating them with
|
||||||
|
``@octoprint.plugin.BlueprintPlugin.csrf_exempt``.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
class MyPlugin(octoprint.plugin.BlueprintPlugin):
|
||||||
|
@octoprint.plugin.BlueprintPlugin.route("/hello_world", methods=["GET"])
|
||||||
|
def hello_world(self):
|
||||||
|
# This is a GET request and thus not subject to CSRF protection
|
||||||
|
return "Hello world!"
|
||||||
|
|
||||||
|
@octoprint.plugin.BlueprintPlugin.route("/hello_you", methods=["POST"])
|
||||||
|
def hello_you(self):
|
||||||
|
# This is a POST request and thus subject to CSRF protection. It is not exempt.
|
||||||
|
return "Hello you!"
|
||||||
|
|
||||||
|
@octoprint.plugin.BlueprintPlugin.route("/hello_me", methods=["POST"])
|
||||||
|
@octoprint.plugin.BlueprintPlugin.csrf_exempt()
|
||||||
|
def hello_me(self):
|
||||||
|
# This is a POST request and thus subject to CSRF protection, but this one is exempt.
|
||||||
|
return "Hello me!"
|
||||||
|
|
||||||
|
def is_blueprint_csrf_protected(self):
|
||||||
|
return True
|
||||||
|
|
||||||
``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`.
|
``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`.
|
||||||
|
|
||||||
|
.. versionchanged:: 1.8.3
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -1372,7 +1403,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
|||||||
def decorator(f):
|
def decorator(f):
|
||||||
# We attach the decorator parameters directly to the function object, because that's the only place
|
# We attach the decorator parameters directly to the function object, because that's the only place
|
||||||
# we can access right now.
|
# we can access right now.
|
||||||
# This neat little trick was adapter from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/
|
# This neat little trick was adapted from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/
|
||||||
if not hasattr(f, "_blueprint_rules") or f._blueprint_rules is None:
|
if not hasattr(f, "_blueprint_rules") or f._blueprint_rules is None:
|
||||||
f._blueprint_rules = defaultdict(list)
|
f._blueprint_rules = defaultdict(list)
|
||||||
f._blueprint_rules[f.__name__].append((rule, options))
|
f._blueprint_rules[f.__name__].append((rule, options))
|
||||||
@@ -1405,6 +1436,27 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
|||||||
|
|
||||||
return decorator
|
return decorator
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def csrf_exempt():
|
||||||
|
"""
|
||||||
|
A decorator to mark a view method in your BlueprintPlugin as exempt from :ref:`CSRF protection <sec-api-general-csrf>`. This makes sense
|
||||||
|
if you offer an authenticated API for a certain workflow (see e.g. the bundled appkeys plugin) but in most
|
||||||
|
cases should not be needed.
|
||||||
|
|
||||||
|
.. versionadded:: 1.8.3
|
||||||
|
"""
|
||||||
|
|
||||||
|
def decorator(f):
|
||||||
|
if (
|
||||||
|
not hasattr(f, "_blueprint_csrf_exempt")
|
||||||
|
or f._blueprint_csrf_exempt is None
|
||||||
|
):
|
||||||
|
f._blueprint_csrf_exempt = set()
|
||||||
|
f._blueprint_csrf_exempt.add(f.__name__)
|
||||||
|
return f
|
||||||
|
|
||||||
|
return decorator
|
||||||
|
|
||||||
# noinspection PyProtectedMember
|
# noinspection PyProtectedMember
|
||||||
def get_blueprint(self):
|
def get_blueprint(self):
|
||||||
"""
|
"""
|
||||||
@@ -1422,6 +1474,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
|||||||
|
|
||||||
import flask
|
import flask
|
||||||
|
|
||||||
|
from octoprint.server.util.csrf import add_exempt_view
|
||||||
|
|
||||||
kwargs = self.get_blueprint_kwargs()
|
kwargs = self.get_blueprint_kwargs()
|
||||||
blueprint = flask.Blueprint(self._identifier, self._identifier, **kwargs)
|
blueprint = flask.Blueprint(self._identifier, self._identifier, **kwargs)
|
||||||
|
|
||||||
@@ -1435,9 +1489,14 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
|||||||
# this attribute was annotated with our @route decorator
|
# this attribute was annotated with our @route decorator
|
||||||
for blueprint_rule in f._blueprint_rules[member]:
|
for blueprint_rule in f._blueprint_rules[member]:
|
||||||
rule, options = blueprint_rule
|
rule, options = blueprint_rule
|
||||||
blueprint.add_url_rule(
|
endpoint = options.pop("endpoint", f.__name__)
|
||||||
rule, options.pop("endpoint", f.__name__), view_func=f, **options
|
blueprint.add_url_rule(rule, endpoint, view_func=f, **options)
|
||||||
)
|
|
||||||
|
if (
|
||||||
|
hasattr(f, "_blueprint_csrf_exempt")
|
||||||
|
and member in f._blueprint_csrf_exempt
|
||||||
|
):
|
||||||
|
add_exempt_view(f"plugin.{self._identifier}.{endpoint}")
|
||||||
|
|
||||||
if (
|
if (
|
||||||
hasattr(f, "_blueprint_error_handler")
|
hasattr(f, "_blueprint_error_handler")
|
||||||
@@ -1486,6 +1545,29 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
|||||||
"""
|
"""
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
# noinspection PyMethodMayBeStatic
|
||||||
|
def is_blueprint_csrf_protected(self):
|
||||||
|
"""
|
||||||
|
Whether a blueprint's endpoints are :ref:`CSRF protected <sec-api-general-csrf>`. For now, this defaults to ``False`` to leave it up to
|
||||||
|
plugins to decide which endpoints *should* be protected. Long term, this will default to ``True`` and hence
|
||||||
|
enforce protection unless a plugin opts out by returning False here.
|
||||||
|
|
||||||
|
If you do not override this method in your mixin implementation, a warning will be logged to the console
|
||||||
|
to alert you of the requirement to make a decision here and to not rely on the default implementation, due to the
|
||||||
|
forthcoming change in implemented default behaviour.
|
||||||
|
|
||||||
|
.. versionadded:: 1.8.3
|
||||||
|
"""
|
||||||
|
self._logger.warning(
|
||||||
|
"The Blueprint of this plugin is relying on the default implementation of "
|
||||||
|
"is_blueprint_csrf_protected (newly added in OctoPrint 1.8.3), which in a future version will "
|
||||||
|
"be switched from False to True for security reasons. Plugin authors should ensure they explicitly "
|
||||||
|
"declare the CSRF protection status in their BlueprintPlugin mixin implementation. "
|
||||||
|
"Recommendation is to enable CSRF protection and exempt views that must not use it with the "
|
||||||
|
"octoprint.plugin.BlueprintPlugin.csrf_exempt decorator."
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
# noinspection PyMethodMayBeStatic
|
# noinspection PyMethodMayBeStatic
|
||||||
def get_blueprint_api_prefixes(self):
|
def get_blueprint_api_prefixes(self):
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -291,6 +291,9 @@ class AnnouncementPlugin(
|
|||||||
def is_blueprint_protected(self):
|
def is_blueprint_protected(self):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def is_blueprint_csrf_protected(self):
|
||||||
|
return True
|
||||||
|
|
||||||
##~~ EventHandlerPlugin
|
##~~ EventHandlerPlugin
|
||||||
|
|
||||||
def on_event(self, event, payload):
|
def on_event(self, event, payload):
|
||||||
|
|||||||
@@ -161,6 +161,7 @@ class AppKeysPlugin(
|
|||||||
return NO_CONTENT
|
return NO_CONTENT
|
||||||
|
|
||||||
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
|
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
|
||||||
|
@octoprint.plugin.BlueprintPlugin.csrf_exempt()
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
def handle_request(self):
|
def handle_request(self):
|
||||||
data = flask.request.json
|
data = flask.request.json
|
||||||
@@ -196,7 +197,7 @@ class AppKeysPlugin(
|
|||||||
)
|
)
|
||||||
return response
|
return response
|
||||||
|
|
||||||
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
|
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>", methods=["GET"])
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
def handle_decision_poll(self, app_token):
|
def handle_decision_poll(self, app_token):
|
||||||
result = self._get_pending_by_app_token(app_token)
|
result = self._get_pending_by_app_token(app_token)
|
||||||
@@ -214,7 +215,7 @@ class AppKeysPlugin(
|
|||||||
|
|
||||||
return flask.abort(404)
|
return flask.abort(404)
|
||||||
|
|
||||||
@octoprint.plugin.BlueprintPlugin.route("/auth/<app_token>")
|
@octoprint.plugin.BlueprintPlugin.route("/auth/<app_token>", methods=["GET"])
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
def handle_auth_dialog(self, app_token):
|
def handle_auth_dialog(self, app_token):
|
||||||
user_id = current_user.get_name()
|
user_id = current_user.get_name()
|
||||||
@@ -284,6 +285,9 @@ class AppKeysPlugin(
|
|||||||
def is_blueprint_protected(self):
|
def is_blueprint_protected(self):
|
||||||
return False # No API key required to request API access
|
return False # No API key required to request API access
|
||||||
|
|
||||||
|
def is_blueprint_csrf_protected(self):
|
||||||
|
return True # protect anything that isn't explicitly marked as exempt
|
||||||
|
|
||||||
##~~ SimpleApiPlugin mixin
|
##~~ SimpleApiPlugin mixin
|
||||||
|
|
||||||
def get_api_commands(self):
|
def get_api_commands(self):
|
||||||
|
|||||||
@@ -356,6 +356,9 @@ class BackupPlugin(
|
|||||||
def is_blueprint_protected(self):
|
def is_blueprint_protected(self):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def is_blueprint_csrf_protected(self):
|
||||||
|
return True
|
||||||
|
|
||||||
##~~ WizardPlugin
|
##~~ WizardPlugin
|
||||||
|
|
||||||
def is_wizard_required(self):
|
def is_wizard_required(self):
|
||||||
@@ -370,7 +373,7 @@ class BackupPlugin(
|
|||||||
|
|
||||||
def route_hook(self, *args, **kwargs):
|
def route_hook(self, *args, **kwargs):
|
||||||
from octoprint.server import app
|
from octoprint.server import app
|
||||||
from octoprint.server.util.flask import admin_validator
|
from octoprint.server.util.flask import permission_validator
|
||||||
from octoprint.server.util.tornado import (
|
from octoprint.server.util.tornado import (
|
||||||
LargeResponseHandler,
|
LargeResponseHandler,
|
||||||
access_validation_factory,
|
access_validation_factory,
|
||||||
@@ -378,17 +381,26 @@ class BackupPlugin(
|
|||||||
)
|
)
|
||||||
from octoprint.util import is_hidden_path
|
from octoprint.util import is_hidden_path
|
||||||
|
|
||||||
|
plugin_folder = self.get_plugin_data_folder()
|
||||||
|
|
||||||
|
def path_check(path):
|
||||||
|
joined = os.path.join(plugin_folder, path)
|
||||||
|
return not is_hidden_path(joined) and self._valid_backup(joined)
|
||||||
|
|
||||||
return [
|
return [
|
||||||
(
|
(
|
||||||
r"/download/(.*)",
|
r"/download/(.*)",
|
||||||
LargeResponseHandler,
|
LargeResponseHandler,
|
||||||
{
|
{
|
||||||
"path": self.get_plugin_data_folder(),
|
"path": plugin_folder,
|
||||||
"as_attachment": True,
|
"as_attachment": True,
|
||||||
"path_validation": path_validation_factory(
|
"path_validation": path_validation_factory(
|
||||||
lambda path: not is_hidden_path(path), status_code=404
|
path_check,
|
||||||
|
status_code=404,
|
||||||
|
),
|
||||||
|
"access_validation": access_validation_factory(
|
||||||
|
app, permission_validator, Permissions.PLUGIN_BACKUP_ACCESS
|
||||||
),
|
),
|
||||||
"access_validation": access_validation_factory(app, admin_validator),
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
@@ -730,9 +742,7 @@ class BackupPlugin(
|
|||||||
for entry in os.scandir(self.get_plugin_data_folder()):
|
for entry in os.scandir(self.get_plugin_data_folder()):
|
||||||
if is_hidden_path(entry.path):
|
if is_hidden_path(entry.path):
|
||||||
continue
|
continue
|
||||||
if not entry.is_file():
|
if not self._valid_backup(entry.path):
|
||||||
continue
|
|
||||||
if not entry.name.endswith(".zip"):
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
backups.append(
|
backups.append(
|
||||||
@@ -1359,14 +1369,18 @@ class BackupPlugin(
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _build_backup_filename(cls, settings):
|
def _build_backup_filename(cls, settings):
|
||||||
|
backup_prefix = cls._get_backup_prefix(settings)
|
||||||
|
return "{}-backup-{}.zip".format(
|
||||||
|
backup_prefix, time.strftime(BACKUP_DATE_TIME_FMT)
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _get_backup_prefix(cls, settings):
|
||||||
if settings.global_get(["appearance", "name"]) == "":
|
if settings.global_get(["appearance", "name"]) == "":
|
||||||
backup_prefix = "octoprint"
|
backup_prefix = "octoprint"
|
||||||
else:
|
else:
|
||||||
backup_prefix = settings.global_get(["appearance", "name"])
|
backup_prefix = settings.global_get(["appearance", "name"])
|
||||||
backup_prefix = sanitize(backup_prefix)
|
return sanitize(backup_prefix)
|
||||||
return "{}-backup-{}.zip".format(
|
|
||||||
backup_prefix, time.strftime(BACKUP_DATE_TIME_FMT)
|
|
||||||
)
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _restore_supported(cls, settings):
|
def _restore_supported(cls, settings):
|
||||||
@@ -1377,6 +1391,17 @@ class BackupPlugin(
|
|||||||
not in valid_boolean_trues
|
not in valid_boolean_trues
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _valid_backup(cls, path):
|
||||||
|
if not path.endswith(".zip") or not zipfile.is_zipfile(path):
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
with zipfile.ZipFile(path) as z:
|
||||||
|
return "metadata.json" in z.namelist()
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
def _send_client_message(self, message, payload=None):
|
def _send_client_message(self, message, payload=None):
|
||||||
if payload is None:
|
if payload is None:
|
||||||
payload = {}
|
payload = {}
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ $(function () {
|
|||||||
dataType: "json",
|
dataType: "json",
|
||||||
maxNumberOfFiles: 1,
|
maxNumberOfFiles: 1,
|
||||||
autoUpload: false,
|
autoUpload: false,
|
||||||
headers: OctoPrint.getRequestHeaders(),
|
|
||||||
add: function (e, data) {
|
add: function (e, data) {
|
||||||
if (data.files.length === 0) {
|
if (data.files.length === 0) {
|
||||||
// no files? ignore
|
// no files? ignore
|
||||||
|
|||||||
@@ -74,6 +74,11 @@ class CoreWizardPlugin(
|
|||||||
else:
|
else:
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
# ~~ BlueprintPlugin API
|
||||||
|
|
||||||
|
def is_blueprint_csrf_protected(self):
|
||||||
|
return True
|
||||||
|
|
||||||
# ~~ WizardPlugin API
|
# ~~ WizardPlugin API
|
||||||
|
|
||||||
def is_wizard_required(self):
|
def is_wizard_required(self):
|
||||||
|
|||||||
@@ -134,6 +134,9 @@ class DiscoveryPlugin(
|
|||||||
def is_blueprint_protected(self):
|
def is_blueprint_protected(self):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def is_blueprint_csrf_protected(self):
|
||||||
|
return True
|
||||||
|
|
||||||
##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup
|
##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup
|
||||||
|
|
||||||
def on_startup(self, host, port):
|
def on_startup(self, host, port):
|
||||||
|
|||||||
@@ -18,10 +18,10 @@ from octoprint.util.version import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
SENTRY_URL_SERVER = (
|
SENTRY_URL_SERVER = (
|
||||||
"https://32fedab787cf4ef0abb9f4fb9060f7c5@o118517.ingest.sentry.io/1373987"
|
"https://9c242ccf183444eaacd046d86d8b0ea2@o118517.ingest.sentry.io/1373987"
|
||||||
)
|
)
|
||||||
SENTRY_URL_COREUI = (
|
SENTRY_URL_COREUI = (
|
||||||
"https://09c57ca82d4047b5a37bb0655ce14187@o118517.ingest.sentry.io/1374096"
|
"https://4d9844043596415faa606ff722174b90@o118517.ingest.sentry.io/1374096"
|
||||||
)
|
)
|
||||||
|
|
||||||
SETTINGS_DEFAULTS = {
|
SETTINGS_DEFAULTS = {
|
||||||
@@ -158,7 +158,9 @@ def _enable_errortracking():
|
|||||||
|
|
||||||
unique_id = str(uuid.uuid4())
|
unique_id = str(uuid.uuid4())
|
||||||
s.set(
|
s.set(
|
||||||
["plugins", "errortracking", "unique_id"], unique_id, defaults=plugin_defaults
|
["plugins", "errortracking", "unique_id"],
|
||||||
|
unique_id,
|
||||||
|
defaults=plugin_defaults,
|
||||||
)
|
)
|
||||||
s.save()
|
s.save()
|
||||||
|
|
||||||
|
|||||||
@@ -127,6 +127,9 @@ class LoggingPlugin(
|
|||||||
def is_blueprint_protected(self):
|
def is_blueprint_protected(self):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def is_blueprint_csrf_protected(self):
|
||||||
|
return True
|
||||||
|
|
||||||
def _get_usage(self):
|
def _get_usage(self):
|
||||||
import psutil
|
import psutil
|
||||||
|
|
||||||
|
|||||||
@@ -228,7 +228,7 @@ class PluginManagerPlugin(
|
|||||||
"name": "List plugins",
|
"name": "List plugins",
|
||||||
"description": gettext("Allows to list installed plugins."),
|
"description": gettext("Allows to list installed plugins."),
|
||||||
"default_groups": [READONLY_GROUP, USER_GROUP, ADMIN_GROUP],
|
"default_groups": [READONLY_GROUP, USER_GROUP, ADMIN_GROUP],
|
||||||
"roles": ["manage"],
|
"roles": ["list"],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"key": "MANAGE",
|
"key": "MANAGE",
|
||||||
@@ -609,6 +609,9 @@ class PluginManagerPlugin(
|
|||||||
def is_blueprint_protected(self):
|
def is_blueprint_protected(self):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def is_blueprint_csrf_protected(self):
|
||||||
|
return True
|
||||||
|
|
||||||
##~~ EventHandlerPlugin
|
##~~ EventHandlerPlugin
|
||||||
|
|
||||||
def on_event(self, event, payload):
|
def on_event(self, event, payload):
|
||||||
|
|||||||
@@ -1453,6 +1453,9 @@ class SoftwareUpdatePlugin(
|
|||||||
def is_blueprint_protected(self):
|
def is_blueprint_protected(self):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def is_blueprint_csrf_protected(self):
|
||||||
|
return True
|
||||||
|
|
||||||
# ~~ Asset API
|
# ~~ Asset API
|
||||||
|
|
||||||
def get_assets(self):
|
def get_assets(self):
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ from watchdog.observers import Observer
|
|||||||
from watchdog.observers.polling import PollingObserver
|
from watchdog.observers.polling import PollingObserver
|
||||||
from werkzeug.exceptions import HTTPException
|
from werkzeug.exceptions import HTTPException
|
||||||
|
|
||||||
|
import octoprint.filemanager
|
||||||
import octoprint.util
|
import octoprint.util
|
||||||
import octoprint.util.net
|
import octoprint.util.net
|
||||||
from octoprint.server import util
|
from octoprint.server import util
|
||||||
@@ -70,6 +71,7 @@ app = Flask("octoprint")
|
|||||||
|
|
||||||
assets = None
|
assets = None
|
||||||
babel = None
|
babel = None
|
||||||
|
limiter = None
|
||||||
debug = False
|
debug = False
|
||||||
safe_mode = False
|
safe_mode = False
|
||||||
|
|
||||||
@@ -125,10 +127,11 @@ from octoprint.printer.standard import Printer
|
|||||||
from octoprint.server.util import (
|
from octoprint.server.util import (
|
||||||
corsRequestHandler,
|
corsRequestHandler,
|
||||||
corsResponseHandler,
|
corsResponseHandler,
|
||||||
|
csrfRequestHandler,
|
||||||
loginFromApiKeyRequestHandler,
|
loginFromApiKeyRequestHandler,
|
||||||
requireLoginRequestHandler,
|
requireLoginRequestHandler,
|
||||||
)
|
)
|
||||||
from octoprint.server.util.flask import PreemptiveCache
|
from octoprint.server.util.flask import PreemptiveCache, validate_session_signature
|
||||||
from octoprint.settings import settings
|
from octoprint.settings import settings
|
||||||
|
|
||||||
VERSION = __version__
|
VERSION = __version__
|
||||||
@@ -185,12 +188,25 @@ def load_user(id):
|
|||||||
else:
|
else:
|
||||||
sessionid = None
|
sessionid = None
|
||||||
|
|
||||||
|
if session and "usersession.signature" in session:
|
||||||
|
sessionsig = session["usersession.signature"]
|
||||||
|
else:
|
||||||
|
sessionsig = ""
|
||||||
|
|
||||||
if sessionid:
|
if sessionid:
|
||||||
user = userManager.find_user(userid=id, session=sessionid)
|
# session["_fresh"] is False if the session comes from a remember me cookie,
|
||||||
|
# True if it came from a use of the login dialog
|
||||||
|
user = userManager.find_user(
|
||||||
|
userid=id, session=sessionid, fresh=session.get("_fresh", False)
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
user = userManager.find_user(userid=id)
|
user = userManager.find_user(userid=id)
|
||||||
|
|
||||||
if user and user.is_active:
|
if (
|
||||||
|
user
|
||||||
|
and user.is_active
|
||||||
|
and (not sessionid or validate_session_signature(sessionsig, id, sessionid))
|
||||||
|
):
|
||||||
return user
|
return user
|
||||||
|
|
||||||
return None
|
return None
|
||||||
@@ -745,6 +761,15 @@ class Server:
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
only_known_types_validator = {
|
||||||
|
"path_validation": util.tornado.path_validation_factory(
|
||||||
|
lambda path: octoprint.filemanager.valid_file_type(
|
||||||
|
os.path.basename(path)
|
||||||
|
),
|
||||||
|
status_code=404,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
valid_timelapse = lambda path: not octoprint.util.is_hidden_path(path) and (
|
valid_timelapse = lambda path: not octoprint.util.is_hidden_path(path) and (
|
||||||
octoprint.timelapse.valid_timelapse(path)
|
octoprint.timelapse.valid_timelapse(path)
|
||||||
or octoprint.timelapse.valid_timelapse_thumbnail(path)
|
or octoprint.timelapse.valid_timelapse_thumbnail(path)
|
||||||
@@ -839,6 +864,7 @@ class Server:
|
|||||||
download_permission_validator,
|
download_permission_validator,
|
||||||
download_handler_kwargs,
|
download_handler_kwargs,
|
||||||
no_hidden_files_validator,
|
no_hidden_files_validator,
|
||||||
|
only_known_types_validator,
|
||||||
additional_mime_types,
|
additional_mime_types,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -1323,7 +1349,7 @@ class Server:
|
|||||||
):
|
):
|
||||||
return Locale.negotiate([default_language], LANGUAGES)
|
return Locale.negotiate([default_language], LANGUAGES)
|
||||||
|
|
||||||
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
|
return Locale.parse(request.accept_languages.best_match(LANGUAGES, default="en"))
|
||||||
|
|
||||||
def _setup_heartbeat_logging(self):
|
def _setup_heartbeat_logging(self):
|
||||||
logger = logging.getLogger(__name__ + ".heartbeat")
|
logger = logging.getLogger(__name__ + ".heartbeat")
|
||||||
@@ -1338,6 +1364,8 @@ class Server:
|
|||||||
timer.start()
|
timer.start()
|
||||||
|
|
||||||
def _setup_app(self, app):
|
def _setup_app(self, app):
|
||||||
|
global limiter
|
||||||
|
|
||||||
from octoprint.server.util.flask import (
|
from octoprint.server.util.flask import (
|
||||||
OctoPrintFlaskRequest,
|
OctoPrintFlaskRequest,
|
||||||
OctoPrintFlaskResponse,
|
OctoPrintFlaskResponse,
|
||||||
@@ -1352,7 +1380,9 @@ class Server:
|
|||||||
|
|
||||||
app.config["TEMPLATES_AUTO_RELOAD"] = True
|
app.config["TEMPLATES_AUTO_RELOAD"] = True
|
||||||
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
|
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
|
||||||
|
app.config["REMEMBER_COOKIE_DURATION"] = 90 * 24 * 60 * 60 # 90 days
|
||||||
app.config["REMEMBER_COOKIE_HTTPONLY"] = True
|
app.config["REMEMBER_COOKIE_HTTPONLY"] = True
|
||||||
|
# REMEMBER_COOKIE_SECURE will be taken care of by our custom cookie handling
|
||||||
|
|
||||||
# we must not set this before TEMPLATES_AUTO_RELOAD is set to True or that won't take
|
# we must not set this before TEMPLATES_AUTO_RELOAD is set to True or that won't take
|
||||||
app.debug = self._debug
|
app.debug = self._debug
|
||||||
@@ -1433,6 +1463,18 @@ class Server:
|
|||||||
|
|
||||||
MarkdownFilter(app)
|
MarkdownFilter(app)
|
||||||
|
|
||||||
|
from flask_limiter import Limiter
|
||||||
|
from flask_limiter.util import get_remote_address
|
||||||
|
|
||||||
|
app.config["RATELIMIT_STRATEGY"] = "fixed-window-elastic-expiry"
|
||||||
|
|
||||||
|
limiter = Limiter(
|
||||||
|
app,
|
||||||
|
key_func=get_remote_address,
|
||||||
|
enabled=s.getBoolean(["devel", "enableRateLimiter"]),
|
||||||
|
storage_uri="memory://",
|
||||||
|
)
|
||||||
|
|
||||||
def _setup_i18n(self, app):
|
def _setup_i18n(self, app):
|
||||||
global babel
|
global babel
|
||||||
global LOCALES
|
global LOCALES
|
||||||
@@ -1876,6 +1918,16 @@ class Server:
|
|||||||
blueprint.before_request(loginFromApiKeyRequestHandler)
|
blueprint.before_request(loginFromApiKeyRequestHandler)
|
||||||
blueprint.after_request(corsResponseHandler)
|
blueprint.after_request(corsResponseHandler)
|
||||||
|
|
||||||
|
if plugin.is_blueprint_csrf_protected():
|
||||||
|
self._logger.debug(
|
||||||
|
f"CSRF Protection for Blueprint of plugin {name} is enabled"
|
||||||
|
)
|
||||||
|
blueprint.before_request(csrfRequestHandler)
|
||||||
|
else:
|
||||||
|
self._logger.warning(
|
||||||
|
f"CSRF Protection for Blueprint of plugin {name} is DISABLED"
|
||||||
|
)
|
||||||
|
|
||||||
if plugin.is_blueprint_protected():
|
if plugin.is_blueprint_protected():
|
||||||
blueprint.before_request(requireLoginRequestHandler)
|
blueprint.before_request(requireLoginRequestHandler)
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ from octoprint.server import NO_CONTENT
|
|||||||
from octoprint.server.util import (
|
from octoprint.server.util import (
|
||||||
corsRequestHandler,
|
corsRequestHandler,
|
||||||
corsResponseHandler,
|
corsResponseHandler,
|
||||||
|
csrfRequestHandler,
|
||||||
loginFromApiKeyRequestHandler,
|
loginFromApiKeyRequestHandler,
|
||||||
loginFromAuthorizationHeaderRequestHandler,
|
loginFromAuthorizationHeaderRequestHandler,
|
||||||
noCachingExceptGetResponseHandler,
|
noCachingExceptGetResponseHandler,
|
||||||
@@ -35,8 +36,10 @@ from octoprint.server.util import (
|
|||||||
from octoprint.server.util.flask import (
|
from octoprint.server.util.flask import (
|
||||||
get_json_command_from_request,
|
get_json_command_from_request,
|
||||||
get_remote_address,
|
get_remote_address,
|
||||||
|
limit,
|
||||||
no_firstrun_access,
|
no_firstrun_access,
|
||||||
passive_login,
|
passive_login,
|
||||||
|
session_signature,
|
||||||
)
|
)
|
||||||
from octoprint.settings import settings as s
|
from octoprint.settings import settings as s
|
||||||
from octoprint.settings import valid_boolean_trues
|
from octoprint.settings import valid_boolean_trues
|
||||||
@@ -66,6 +69,7 @@ api.after_request(noCachingExceptGetResponseHandler)
|
|||||||
api.before_request(corsRequestHandler)
|
api.before_request(corsRequestHandler)
|
||||||
api.before_request(loginFromAuthorizationHeaderRequestHandler)
|
api.before_request(loginFromAuthorizationHeaderRequestHandler)
|
||||||
api.before_request(loginFromApiKeyRequestHandler)
|
api.before_request(loginFromApiKeyRequestHandler)
|
||||||
|
api.before_request(csrfRequestHandler)
|
||||||
api.after_request(corsResponseHandler)
|
api.after_request(corsResponseHandler)
|
||||||
|
|
||||||
# ~~ data from plugins
|
# ~~ data from plugins
|
||||||
@@ -281,6 +285,11 @@ def serverStatus():
|
|||||||
|
|
||||||
|
|
||||||
@api.route("/login", methods=["POST"])
|
@api.route("/login", methods=["POST"])
|
||||||
|
@limit(
|
||||||
|
"3/minute;5/10 minutes;10/hour",
|
||||||
|
deduct_when=lambda response: response.status_code == 403,
|
||||||
|
error_message="You have made too many failed login attempts. Please try again later.",
|
||||||
|
)
|
||||||
def login():
|
def login():
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
if not data:
|
if not data:
|
||||||
@@ -306,6 +315,9 @@ def login():
|
|||||||
|
|
||||||
user = octoprint.server.userManager.login_user(user)
|
user = octoprint.server.userManager.login_user(user)
|
||||||
session["usersession.id"] = user.session
|
session["usersession.id"] = user.session
|
||||||
|
session["usersession.signature"] = session_signature(
|
||||||
|
username, user.session
|
||||||
|
)
|
||||||
g.user = user
|
g.user = user
|
||||||
|
|
||||||
login_user(user, remember=remember)
|
login_user(user, remember=remember)
|
||||||
|
|||||||
@@ -25,14 +25,14 @@ def get_permissions():
|
|||||||
|
|
||||||
@api.route("/access/groups", methods=["GET"])
|
@api.route("/access/groups", methods=["GET"])
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
@Permissions.SETTINGS.require(403)
|
@Permissions.ADMIN.require(403)
|
||||||
def get_groups():
|
def get_groups():
|
||||||
return jsonify(groups=list(map(lambda g: g.as_dict(), groupManager.groups)))
|
return jsonify(groups=list(map(lambda g: g.as_dict(), groupManager.groups)))
|
||||||
|
|
||||||
|
|
||||||
@api.route("/access/groups", methods=["POST"])
|
@api.route("/access/groups", methods=["POST"])
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
@Permissions.SETTINGS.require(403)
|
@Permissions.ADMIN.require(403)
|
||||||
def add_group():
|
def add_group():
|
||||||
if "application/json" not in request.headers["Content-Type"]:
|
if "application/json" not in request.headers["Content-Type"]:
|
||||||
abort(400, description="Expected content-type JSON")
|
abort(400, description="Expected content-type JSON")
|
||||||
@@ -69,7 +69,7 @@ def add_group():
|
|||||||
|
|
||||||
@api.route("/access/groups/<key>", methods=["GET"])
|
@api.route("/access/groups/<key>", methods=["GET"])
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
@Permissions.SETTINGS.require(403)
|
@Permissions.ADMIN.require(403)
|
||||||
def get_group(key):
|
def get_group(key):
|
||||||
group = groupManager.find_group(key)
|
group = groupManager.find_group(key)
|
||||||
if group is not None:
|
if group is not None:
|
||||||
@@ -80,7 +80,7 @@ def get_group(key):
|
|||||||
|
|
||||||
@api.route("/access/groups/<key>", methods=["PUT"])
|
@api.route("/access/groups/<key>", methods=["PUT"])
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
@Permissions.SETTINGS.require(403)
|
@Permissions.ADMIN.require(403)
|
||||||
def update_group(key):
|
def update_group(key):
|
||||||
if "application/json" not in request.headers["Content-Type"]:
|
if "application/json" not in request.headers["Content-Type"]:
|
||||||
abort(400, description="Expected content-type JSON")
|
abort(400, description="Expected content-type JSON")
|
||||||
@@ -113,7 +113,7 @@ def update_group(key):
|
|||||||
|
|
||||||
@api.route("/access/groups/<key>", methods=["DELETE"])
|
@api.route("/access/groups/<key>", methods=["DELETE"])
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
@Permissions.SETTINGS.require(403)
|
@Permissions.ADMIN.require(403)
|
||||||
def remove_group(key):
|
def remove_group(key):
|
||||||
try:
|
try:
|
||||||
groupManager.remove_group(key)
|
groupManager.remove_group(key)
|
||||||
@@ -129,14 +129,14 @@ def remove_group(key):
|
|||||||
|
|
||||||
@api.route("/access/users", methods=["GET"])
|
@api.route("/access/users", methods=["GET"])
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
@Permissions.SETTINGS.require(403)
|
@Permissions.ADMIN.require(403)
|
||||||
def get_users():
|
def get_users():
|
||||||
return jsonify(users=list(map(lambda u: u.as_dict(), userManager.get_all_users())))
|
return jsonify(users=list(map(lambda u: u.as_dict(), userManager.get_all_users())))
|
||||||
|
|
||||||
|
|
||||||
@api.route("/access/users", methods=["POST"])
|
@api.route("/access/users", methods=["POST"])
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
@Permissions.SETTINGS.require(403)
|
@Permissions.ADMIN.require(403)
|
||||||
def add_user():
|
def add_user():
|
||||||
if "application/json" not in request.headers["Content-Type"]:
|
if "application/json" not in request.headers["Content-Type"]:
|
||||||
abort(400, description="Expected content-type JSON")
|
abort(400, description="Expected content-type JSON")
|
||||||
@@ -188,7 +188,7 @@ def get_user(username):
|
|||||||
|
|
||||||
@api.route("/access/users/<username>", methods=["PUT"])
|
@api.route("/access/users/<username>", methods=["PUT"])
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
@Permissions.SETTINGS.require(403)
|
@Permissions.ADMIN.require(403)
|
||||||
def update_user(username):
|
def update_user(username):
|
||||||
user = userManager.find_user(username)
|
user = userManager.find_user(username)
|
||||||
if user is not None:
|
if user is not None:
|
||||||
@@ -223,7 +223,7 @@ def update_user(username):
|
|||||||
|
|
||||||
@api.route("/access/users/<username>", methods=["DELETE"])
|
@api.route("/access/users/<username>", methods=["DELETE"])
|
||||||
@no_firstrun_access
|
@no_firstrun_access
|
||||||
@Permissions.SETTINGS.require(403)
|
@Permissions.ADMIN.require(403)
|
||||||
def remove_user(username):
|
def remove_user(username):
|
||||||
try:
|
try:
|
||||||
userManager.remove_user(username)
|
userManager.remove_user(username)
|
||||||
@@ -241,7 +241,10 @@ def change_password_for_user(username):
|
|||||||
if (
|
if (
|
||||||
current_user is not None
|
current_user is not None
|
||||||
and not current_user.is_anonymous
|
and not current_user.is_anonymous
|
||||||
and (current_user.get_name() == username or current_user.is_admin)
|
and (
|
||||||
|
current_user.get_name() == username
|
||||||
|
or current_user.has_permission(Permissions.ADMIN)
|
||||||
|
)
|
||||||
):
|
):
|
||||||
if "application/json" not in request.headers["Content-Type"]:
|
if "application/json" not in request.headers["Content-Type"]:
|
||||||
abort(400, description="Expected content-type JSON")
|
abort(400, description="Expected content-type JSON")
|
||||||
@@ -252,7 +255,14 @@ def change_password_for_user(username):
|
|||||||
abort(400, description="Malformed JSON body in request")
|
abort(400, description="Malformed JSON body in request")
|
||||||
|
|
||||||
if "password" not in data or not data["password"]:
|
if "password" not in data or not data["password"]:
|
||||||
abort(400, description="password is missing")
|
abort(400, description="new password is missing")
|
||||||
|
|
||||||
|
if not current_user.has_permission(Permissions.ADMIN) or "current" in data:
|
||||||
|
if "current" not in data or not data["current"]:
|
||||||
|
abort(400, description="current password is missing")
|
||||||
|
|
||||||
|
if not userManager.check_password(username, data["current"]):
|
||||||
|
abort(403, description="Invalid current password")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
userManager.change_user_password(username, data["password"])
|
userManager.change_user_password(username, data["password"])
|
||||||
|
|||||||
@@ -607,6 +607,15 @@ def uploadGcodeFile(target):
|
|||||||
):
|
):
|
||||||
abort(409, description="File already exists and noOverwrite was set")
|
abort(409, description="File already exists and noOverwrite was set")
|
||||||
|
|
||||||
|
if (
|
||||||
|
fileManager.file_exists(FileDestinations.LOCAL, futureFullPathInStorage)
|
||||||
|
and not Permissions.FILES_DELETE.can()
|
||||||
|
):
|
||||||
|
abort(
|
||||||
|
403,
|
||||||
|
description="File already exists, cannot overwrite due to a lack of permissions",
|
||||||
|
)
|
||||||
|
|
||||||
reselect = printer.is_current_file(futureFullPathInStorage, sd)
|
reselect = printer.is_current_file(futureFullPathInStorage, sd)
|
||||||
|
|
||||||
user = current_user.get_name()
|
user = current_user.get_name()
|
||||||
@@ -1138,42 +1147,55 @@ def gcodeFileCommand(filename, target):
|
|||||||
if not (is_file or is_folder):
|
if not (is_file or is_folder):
|
||||||
abort(400, description=f"Neither file nor folder, can't {command}")
|
abort(400, description=f"Neither file nor folder, can't {command}")
|
||||||
|
|
||||||
if command == "copy":
|
try:
|
||||||
# destination already there? error...
|
if command == "copy":
|
||||||
if _verifyFileExists(target, destination) or _verifyFolderExists(
|
# destination already there? error...
|
||||||
target, destination
|
if _verifyFileExists(target, destination) or _verifyFolderExists(
|
||||||
):
|
target, destination
|
||||||
abort(409, description="File or folder does already exist")
|
):
|
||||||
|
|
||||||
if is_file:
|
|
||||||
fileManager.copy_file(target, filename, destination)
|
|
||||||
else:
|
|
||||||
fileManager.copy_folder(target, filename, destination)
|
|
||||||
|
|
||||||
elif command == "move":
|
|
||||||
with Permissions.FILES_DELETE.require(403):
|
|
||||||
if _isBusy(target, filename):
|
|
||||||
abort(
|
|
||||||
409,
|
|
||||||
description="Trying to move a file or folder that is currently in use",
|
|
||||||
)
|
|
||||||
|
|
||||||
# destination already there AND not ourselves (= display rename)? error...
|
|
||||||
if (
|
|
||||||
_verifyFileExists(target, destination)
|
|
||||||
or _verifyFolderExists(target, destination)
|
|
||||||
) and sanitized_destination != filename:
|
|
||||||
abort(409, description="File or folder does already exist")
|
abort(409, description="File or folder does already exist")
|
||||||
|
|
||||||
# deselect the file if it's currently selected
|
|
||||||
currentOrigin, currentFilename = _getCurrentFile()
|
|
||||||
if currentFilename is not None and filename == currentFilename:
|
|
||||||
printer.unselect_file()
|
|
||||||
|
|
||||||
if is_file:
|
if is_file:
|
||||||
fileManager.move_file(target, filename, destination)
|
fileManager.copy_file(target, filename, destination)
|
||||||
else:
|
else:
|
||||||
fileManager.move_folder(target, filename, destination)
|
fileManager.copy_folder(target, filename, destination)
|
||||||
|
|
||||||
|
elif command == "move":
|
||||||
|
with Permissions.FILES_DELETE.require(403):
|
||||||
|
if _isBusy(target, filename):
|
||||||
|
abort(
|
||||||
|
409,
|
||||||
|
description="Trying to move a file or folder that is currently in use",
|
||||||
|
)
|
||||||
|
|
||||||
|
# destination already there AND not ourselves (= display rename)? error...
|
||||||
|
if (
|
||||||
|
_verifyFileExists(target, destination)
|
||||||
|
or _verifyFolderExists(target, destination)
|
||||||
|
) and sanitized_destination != filename:
|
||||||
|
abort(409, description="File or folder does already exist")
|
||||||
|
|
||||||
|
# deselect the file if it's currently selected
|
||||||
|
currentOrigin, currentFilename = _getCurrentFile()
|
||||||
|
if currentFilename is not None and filename == currentFilename:
|
||||||
|
printer.unselect_file()
|
||||||
|
|
||||||
|
if is_file:
|
||||||
|
fileManager.move_file(target, filename, destination)
|
||||||
|
else:
|
||||||
|
fileManager.move_folder(target, filename, destination)
|
||||||
|
|
||||||
|
except octoprint.filemanager.storage.StorageError as e:
|
||||||
|
if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:
|
||||||
|
abort(
|
||||||
|
415,
|
||||||
|
description=f"Could not {command} {filename} to {destination}, invalid type",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
abort(
|
||||||
|
500,
|
||||||
|
description=f"Could not {command} {filename} to {destination}",
|
||||||
|
)
|
||||||
|
|
||||||
location = url_for(
|
location = url_for(
|
||||||
".readGcodeFile",
|
".readGcodeFile",
|
||||||
|
|||||||
@@ -174,7 +174,8 @@ def deleteInstalledLanguagePack(locale, pack):
|
|||||||
def _unpack_uploaded_zipfile(path, target):
|
def _unpack_uploaded_zipfile(path, target):
|
||||||
with zipfile.ZipFile(path, "r") as zip:
|
with zipfile.ZipFile(path, "r") as zip:
|
||||||
# sanity check
|
# sanity check
|
||||||
map(_validate_archive_name, zip.namelist())
|
for info in zip.infolist():
|
||||||
|
_validate_zip_info(info, target)
|
||||||
|
|
||||||
# unpack everything
|
# unpack everything
|
||||||
zip.extractall(target)
|
zip.extractall(target)
|
||||||
@@ -183,16 +184,27 @@ def _unpack_uploaded_zipfile(path, target):
|
|||||||
def _unpack_uploaded_tarball(path, target):
|
def _unpack_uploaded_tarball(path, target):
|
||||||
with tarfile.open(path, "r") as tar:
|
with tarfile.open(path, "r") as tar:
|
||||||
# sanity check
|
# sanity check
|
||||||
map(_validate_archive_name, tar.getmembers())
|
for info in tar.getmembers():
|
||||||
|
_validate_tar_info(info, target)
|
||||||
|
|
||||||
# unpack everything
|
# unpack everything
|
||||||
tar.extractall(target)
|
tar.extractall(target)
|
||||||
|
|
||||||
|
|
||||||
def _validate_archive_name(name):
|
def _validate_archive_name(name, target):
|
||||||
if name.startswith("/") or ".." in name:
|
if not os.path.abspath(os.path.join(target, name)).startswith(target + os.path.sep):
|
||||||
raise InvalidLanguagePack(f"Provided language pack contains invalid name {name}")
|
raise InvalidLanguagePack(f"Provided language pack contains invalid name {name}")
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_zip_info(info, target):
|
||||||
|
_validate_archive_name(info.filename, target)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_tar_info(info, target):
|
||||||
|
_validate_archive_name(info.name, target)
|
||||||
|
if not (info.isfile() or info.isdir()):
|
||||||
|
raise InvalidLanguagePack("Provided language pack contains invalid file type")
|
||||||
|
|
||||||
|
|
||||||
class InvalidLanguagePack(Exception):
|
class InvalidLanguagePack(Exception):
|
||||||
pass
|
pass
|
||||||
@@ -18,8 +18,7 @@ from octoprint.settings import settings, valid_boolean_trues
|
|||||||
|
|
||||||
# ~~ settings
|
# ~~ settings
|
||||||
|
|
||||||
FOLDER_TYPES = ("uploads", "timelapse", "timelapse_tmp", "logs", "watched")
|
FOLDER_TYPES = ("uploads", "timelapse", "watched")
|
||||||
FOLDER_MAPPING = {"timelapseTmp": "timelapse_tmp"}
|
|
||||||
TIMELAPSE_BITRATE_PATTERN = re.compile(r"\d+[KMGTPEZY]?i?B?", flags=re.IGNORECASE)
|
TIMELAPSE_BITRATE_PATTERN = re.compile(r"\d+[KMGTPEZY]?i?B?", flags=re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
@@ -269,8 +268,6 @@ def getSettings():
|
|||||||
"folder": {
|
"folder": {
|
||||||
"uploads": s.getBaseFolder("uploads"),
|
"uploads": s.getBaseFolder("uploads"),
|
||||||
"timelapse": s.getBaseFolder("timelapse"),
|
"timelapse": s.getBaseFolder("timelapse"),
|
||||||
"timelapseTmp": s.getBaseFolder("timelapse_tmp"),
|
|
||||||
"logs": s.getBaseFolder("logs"),
|
|
||||||
"watched": s.getBaseFolder("watched"),
|
"watched": s.getBaseFolder("watched"),
|
||||||
},
|
},
|
||||||
"temperature": {
|
"temperature": {
|
||||||
@@ -464,10 +461,7 @@ def _saveSettings(data):
|
|||||||
|
|
||||||
if "folder" in data:
|
if "folder" in data:
|
||||||
try:
|
try:
|
||||||
folders = {
|
folders = data["folder"]
|
||||||
FOLDER_MAPPING.get(folder, folder): path
|
|
||||||
for folder, path in data["folder"].items()
|
|
||||||
}
|
|
||||||
future = {}
|
future = {}
|
||||||
for folder in FOLDER_TYPES:
|
for folder in FOLDER_TYPES:
|
||||||
future[folder] = s.getBaseFolder(folder)
|
future[folder] = s.getBaseFolder(folder)
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ def loginFromApiKeyRequestHandler():
|
|||||||
if loginUserFromApiKey():
|
if loginUserFromApiKey():
|
||||||
_flask.g.login_via_apikey = True
|
_flask.g.login_via_apikey = True
|
||||||
except InvalidApiKeyException:
|
except InvalidApiKeyException:
|
||||||
_flask.abort(403)
|
_flask.abort(403, "Invalid API key")
|
||||||
|
|
||||||
|
|
||||||
def loginFromAuthorizationHeaderRequestHandler():
|
def loginFromAuthorizationHeaderRequestHandler():
|
||||||
@@ -54,7 +54,7 @@ def loginFromAuthorizationHeaderRequestHandler():
|
|||||||
if loginUserFromAuthorizationHeader():
|
if loginUserFromAuthorizationHeader():
|
||||||
_flask.g.login_via_header = True
|
_flask.g.login_via_header = True
|
||||||
except InvalidApiKeyException:
|
except InvalidApiKeyException:
|
||||||
_flask.abort(403)
|
_flask.abort(403, "Invalid credentials in Basic Authorization header")
|
||||||
|
|
||||||
|
|
||||||
class InvalidApiKeyException(Exception):
|
class InvalidApiKeyException(Exception):
|
||||||
@@ -69,7 +69,7 @@ def loginUserFromApiKey():
|
|||||||
user = get_user_for_apikey(apikey)
|
user = get_user_for_apikey(apikey)
|
||||||
if user is None:
|
if user is None:
|
||||||
# invalid API key = no API key
|
# invalid API key = no API key
|
||||||
return False
|
raise InvalidApiKeyException("Invalid API key")
|
||||||
|
|
||||||
return loginUser(user, login_mechanism="apikey")
|
return loginUser(user, login_mechanism="apikey")
|
||||||
|
|
||||||
@@ -148,6 +148,26 @@ def corsResponseHandler(resp):
|
|||||||
return resp
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
def csrfRequestHandler():
|
||||||
|
"""
|
||||||
|
``before_request`` handler for blueprints which checks for CRFS double token on
|
||||||
|
relevant requests & methods.
|
||||||
|
"""
|
||||||
|
from octoprint.server.util.csrf import validate_csrf_request
|
||||||
|
|
||||||
|
if settings().getBoolean(["devel", "enableCsrfProtection"]):
|
||||||
|
validate_csrf_request(_flask.request)
|
||||||
|
|
||||||
|
|
||||||
|
def csrfResponseHandler(resp):
|
||||||
|
"""
|
||||||
|
``after_request`` handler for updating the CSRF cookie on each response.
|
||||||
|
"""
|
||||||
|
from octoprint.server.util.csrf import add_csrf_cookie
|
||||||
|
|
||||||
|
return add_csrf_cookie(resp)
|
||||||
|
|
||||||
|
|
||||||
def noCachingResponseHandler(resp):
|
def noCachingResponseHandler(resp):
|
||||||
"""
|
"""
|
||||||
``after_request`` handler for blueprints which shall set no caching headers
|
``after_request`` handler for blueprints which shall set no caching headers
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
"""CSRF double cookie implementation"""
|
||||||
|
|
||||||
|
__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 flask
|
||||||
|
|
||||||
|
from octoprint.server.util.flask import OctoPrintFlaskResponse
|
||||||
|
|
||||||
|
exempt_views = set()
|
||||||
|
|
||||||
|
|
||||||
|
def _get_view_location(view):
|
||||||
|
if isinstance(view, str):
|
||||||
|
return view
|
||||||
|
else:
|
||||||
|
return f"{view.__module__}.{view.__name__}"
|
||||||
|
|
||||||
|
|
||||||
|
def add_exempt_view(view):
|
||||||
|
exempt_views.add(_get_view_location(view))
|
||||||
|
|
||||||
|
|
||||||
|
def is_exempt(view):
|
||||||
|
if not view:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return _get_view_location(view) in exempt_views
|
||||||
|
|
||||||
|
|
||||||
|
def generate_csrf_token():
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
|
||||||
|
from itsdangerous import URLSafeTimedSerializer
|
||||||
|
|
||||||
|
value = hashlib.sha1(os.urandom(64)).hexdigest()
|
||||||
|
|
||||||
|
secret = flask.current_app.config["SECRET_KEY"]
|
||||||
|
s = URLSafeTimedSerializer(secret, salt="octoprint-csrf-token")
|
||||||
|
|
||||||
|
return s.dumps(value)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_csrf_tokens(cookie, header):
|
||||||
|
import hmac
|
||||||
|
|
||||||
|
from itsdangerous import URLSafeTimedSerializer
|
||||||
|
|
||||||
|
if cookie is None or header is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
secret = flask.current_app.config["SECRET_KEY"]
|
||||||
|
s = URLSafeTimedSerializer(secret, salt="octoprint-csrf-token")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# TODO: set max age for values, once we have a REST based heartbeat
|
||||||
|
# that takes care of regular cookie refresh
|
||||||
|
value_cookie = s.loads(cookie)
|
||||||
|
value_header = s.loads(header)
|
||||||
|
return hmac.compare_digest(value_cookie, value_header)
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def add_csrf_cookie(response):
|
||||||
|
if not isinstance(response, OctoPrintFlaskResponse):
|
||||||
|
response = flask.make_response(response)
|
||||||
|
|
||||||
|
token = generate_csrf_token()
|
||||||
|
response.set_cookie("csrf_token", token, httponly=False)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
def validate_csrf_request(request):
|
||||||
|
if request.method in ["GET", "HEAD", "OPTIONS"]:
|
||||||
|
# Irrelevant method for CSRF, bypass
|
||||||
|
return
|
||||||
|
|
||||||
|
session = getattr(flask, "session", {})
|
||||||
|
if len(session) == 0 or session.get("login_mechanism") == "apikey":
|
||||||
|
# empty session, not a browser context
|
||||||
|
return
|
||||||
|
|
||||||
|
if is_exempt(request.endpoint):
|
||||||
|
# marked as exempt, bypass
|
||||||
|
return
|
||||||
|
|
||||||
|
cookie = request.cookies.get("csrf_token", None)
|
||||||
|
header = request.headers.get("X-CSRF-Token", None)
|
||||||
|
|
||||||
|
if not validate_csrf_tokens(cookie, header):
|
||||||
|
flask.abort(400, "CSRF validation failed")
|
||||||
|
|
||||||
|
|
||||||
|
def csrf_exempt(view):
|
||||||
|
add_exempt_view(view)
|
||||||
|
return view
|
||||||
@@ -5,11 +5,13 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
|||||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||||
|
|
||||||
import functools
|
import functools
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
from datetime import datetime
|
from datetime import datetime, timedelta
|
||||||
from typing import Union
|
from typing import Union
|
||||||
|
|
||||||
import flask
|
import flask
|
||||||
@@ -23,6 +25,9 @@ import tornado.web
|
|||||||
import webassets.updater
|
import webassets.updater
|
||||||
import webassets.utils
|
import webassets.utils
|
||||||
from cachelib import BaseCache
|
from cachelib import BaseCache
|
||||||
|
from flask import current_app
|
||||||
|
from flask_login import COOKIE_NAME as REMEMBER_COOKIE_NAME
|
||||||
|
from flask_login.utils import decode_cookie, encode_cookie
|
||||||
from werkzeug.local import LocalProxy
|
from werkzeug.local import LocalProxy
|
||||||
from werkzeug.utils import cached_property
|
from werkzeug.utils import cached_property
|
||||||
|
|
||||||
@@ -422,6 +427,63 @@ class ReverseProxiedEnvironment:
|
|||||||
# ~~ request and response versions
|
# ~~ request and response versions
|
||||||
|
|
||||||
|
|
||||||
|
def encode_remember_me_cookie(value):
|
||||||
|
from octoprint.server import userManager
|
||||||
|
|
||||||
|
name = value.split("|")[0]
|
||||||
|
try:
|
||||||
|
remember_key = userManager.signature_key_for_user(
|
||||||
|
name, current_app.config["SECRET_KEY"]
|
||||||
|
)
|
||||||
|
timestamp = datetime.utcnow().timestamp()
|
||||||
|
return encode_cookie(f"{name}|{timestamp}", key=remember_key)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def decode_remember_me_cookie(value):
|
||||||
|
from octoprint.server import userManager
|
||||||
|
|
||||||
|
parts = value.split("|")
|
||||||
|
if len(parts) == 3:
|
||||||
|
name, created, _ = parts
|
||||||
|
|
||||||
|
try:
|
||||||
|
# valid signature?
|
||||||
|
signature_key = userManager.signature_key_for_user(
|
||||||
|
name, current_app.config["SECRET_KEY"]
|
||||||
|
)
|
||||||
|
cookie = decode_cookie(value, key=signature_key)
|
||||||
|
if cookie:
|
||||||
|
# still valid?
|
||||||
|
if (
|
||||||
|
datetime.fromtimestamp(float(created))
|
||||||
|
+ timedelta(seconds=current_app.config["REMEMBER_COOKIE_DURATION"])
|
||||||
|
> datetime.utcnow()
|
||||||
|
):
|
||||||
|
return encode_cookie(name)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
raise ValueError("Invalid remember me cookie")
|
||||||
|
|
||||||
|
|
||||||
|
def get_cookie_suffix(request):
|
||||||
|
"""
|
||||||
|
Request specific suffix for set and read cookies
|
||||||
|
|
||||||
|
We need this because cookies are not port-specific and we don't want to overwrite our
|
||||||
|
session and other cookies from one OctoPrint instance on our machine with those of another
|
||||||
|
one who happens to listen on the same address albeit a different port or script root.
|
||||||
|
"""
|
||||||
|
result = "_P" + request.server_port
|
||||||
|
if request.script_root:
|
||||||
|
return result + "_R" + request.script_root.replace("/", "|")
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
class OctoPrintFlaskRequest(flask.Request):
|
class OctoPrintFlaskRequest(flask.Request):
|
||||||
environment_wrapper = staticmethod(lambda x: x)
|
environment_wrapper = staticmethod(lambda x: x)
|
||||||
|
|
||||||
@@ -437,10 +499,23 @@ class OctoPrintFlaskRequest(flask.Request):
|
|||||||
result = {}
|
result = {}
|
||||||
desuffixed = {}
|
desuffixed = {}
|
||||||
for key, value in cookies.items():
|
for key, value in cookies.items():
|
||||||
if key.endswith(self.cookie_suffix):
|
|
||||||
desuffixed[key[: -len(self.cookie_suffix)]] = value
|
def process_value(k, v):
|
||||||
else:
|
if k == current_app.config.get(
|
||||||
result[key] = value
|
"REMEMBER_COOKIE_NAME", REMEMBER_COOKIE_NAME
|
||||||
|
):
|
||||||
|
return decode_remember_me_cookie(v)
|
||||||
|
return v
|
||||||
|
|
||||||
|
try:
|
||||||
|
if key.endswith(self.cookie_suffix):
|
||||||
|
key = key[: -len(self.cookie_suffix)]
|
||||||
|
desuffixed[key] = process_value(key, value)
|
||||||
|
else:
|
||||||
|
result[key] = process_value(key, value)
|
||||||
|
except ValueError:
|
||||||
|
# ignore broken cookies
|
||||||
|
pass
|
||||||
|
|
||||||
result.update(desuffixed)
|
result.update(desuffixed)
|
||||||
return result
|
return result
|
||||||
@@ -457,21 +532,11 @@ class OctoPrintFlaskRequest(flask.Request):
|
|||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def cookie_suffix(self):
|
def cookie_suffix(self):
|
||||||
"""
|
return get_cookie_suffix(self)
|
||||||
Request specific suffix for set and read cookies
|
|
||||||
|
|
||||||
We need this because cookies are not port-specific and we don't want to overwrite our
|
|
||||||
session and other cookies from one OctoPrint instance on our machine with those of another
|
|
||||||
one who happens to listen on the same address albeit a different port or script root.
|
|
||||||
"""
|
|
||||||
result = "_P" + self.server_port
|
|
||||||
if self.script_root:
|
|
||||||
return result + "_R" + self.script_root.replace("/", "|")
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
class OctoPrintFlaskResponse(flask.Response):
|
class OctoPrintFlaskResponse(flask.Response):
|
||||||
def set_cookie(self, key, *args, **kwargs):
|
def set_cookie(self, key, value="", *args, **kwargs):
|
||||||
# restrict cookie path to script root
|
# restrict cookie path to script root
|
||||||
kwargs["path"] = flask.request.script_root + kwargs.get("path", "/")
|
kwargs["path"] = flask.request.script_root + kwargs.get("path", "/")
|
||||||
|
|
||||||
@@ -490,9 +555,13 @@ class OctoPrintFlaskResponse(flask.Response):
|
|||||||
# set secure if necessary
|
# set secure if necessary
|
||||||
kwargs["secure"] = settings().getBoolean(["server", "cookies", "secure"])
|
kwargs["secure"] = settings().getBoolean(["server", "cookies", "secure"])
|
||||||
|
|
||||||
|
# tie account properties to remember me cookie (e.g. current password hash)
|
||||||
|
if key == current_app.config.get("REMEMBER_COOKIE_NAME", REMEMBER_COOKIE_NAME):
|
||||||
|
value = encode_remember_me_cookie(value)
|
||||||
|
|
||||||
# add request specific cookie suffix to name
|
# add request specific cookie suffix to name
|
||||||
flask.Response.set_cookie(
|
flask.Response.set_cookie(
|
||||||
self, key + flask.request.cookie_suffix, *args, **kwargs
|
self, key + flask.request.cookie_suffix, value=value, *args, **kwargs
|
||||||
)
|
)
|
||||||
|
|
||||||
def delete_cookie(self, key, path="/", domain=None):
|
def delete_cookie(self, key, path="/", domain=None):
|
||||||
@@ -608,6 +677,9 @@ def passive_login():
|
|||||||
)
|
)
|
||||||
if hasattr(u, "session"):
|
if hasattr(u, "session"):
|
||||||
flask.session["usersession.id"] = u.session
|
flask.session["usersession.id"] = u.session
|
||||||
|
flask.session["usersession.signature"] = session_signature(
|
||||||
|
u.get_id(), u.session
|
||||||
|
)
|
||||||
flask.g.user = u
|
flask.g.user = u
|
||||||
|
|
||||||
eventManager().fire(Events.USER_LOGGED_IN, payload={"username": u.get_id()})
|
eventManager().fire(Events.USER_LOGGED_IN, payload={"username": u.get_id()})
|
||||||
@@ -669,6 +741,24 @@ def passive_login():
|
|||||||
return flask.jsonify(response)
|
return flask.jsonify(response)
|
||||||
|
|
||||||
|
|
||||||
|
# ~~ rate limiting helper
|
||||||
|
|
||||||
|
|
||||||
|
def limit(*args, **kwargs):
|
||||||
|
if octoprint.server.limiter:
|
||||||
|
return octoprint.server.limiter.limit(*args, **kwargs)
|
||||||
|
else:
|
||||||
|
|
||||||
|
def decorator(f):
|
||||||
|
@functools.wraps(f)
|
||||||
|
def decorated_function(*args, **kwargs):
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
|
||||||
|
return decorated_function
|
||||||
|
|
||||||
|
return decorator
|
||||||
|
|
||||||
|
|
||||||
# ~~ cache decorator for cacheable views
|
# ~~ cache decorator for cacheable views
|
||||||
|
|
||||||
|
|
||||||
@@ -1814,3 +1904,20 @@ class OctoPrintJsonEncoder(flask.json.JSONEncoder):
|
|||||||
return JsonEncoding.encode(obj)
|
return JsonEncoding.encode(obj)
|
||||||
except TypeError:
|
except TypeError:
|
||||||
return flask.json.JSONEncoder.default(self, obj)
|
return flask.json.JSONEncoder.default(self, obj)
|
||||||
|
|
||||||
|
|
||||||
|
##~~ Session signing
|
||||||
|
|
||||||
|
|
||||||
|
def session_signature(user, session):
|
||||||
|
from octoprint.server import userManager
|
||||||
|
|
||||||
|
key = userManager.signature_key_for_user(user, current_app.config["SECRET_KEY"])
|
||||||
|
return hmac.new(
|
||||||
|
key.encode("utf-8"), session.encode("utf-8"), hashlib.sha512
|
||||||
|
).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def validate_session_signature(sig, user, session):
|
||||||
|
user_sig = session_signature(user, session)
|
||||||
|
return len(user_sig) == len(sig) and hmac.compare_digest(sig, user_sig)
|
||||||
@@ -21,9 +21,10 @@ import octoprint.vendor.sockjs.tornado.session
|
|||||||
import octoprint.vendor.sockjs.tornado.util
|
import octoprint.vendor.sockjs.tornado.util
|
||||||
from octoprint.access.groups import GroupChangeListener
|
from octoprint.access.groups import GroupChangeListener
|
||||||
from octoprint.access.permissions import Permissions
|
from octoprint.access.permissions import Permissions
|
||||||
from octoprint.access.users import LoginStatusListener
|
from octoprint.access.users import LoginStatusListener, SessionUser
|
||||||
from octoprint.events import Events
|
from octoprint.events import Events
|
||||||
from octoprint.settings import settings
|
from octoprint.settings import settings
|
||||||
|
from octoprint.util import RepeatedTimer
|
||||||
from octoprint.util.json import dumps as json_dumps
|
from octoprint.util.json import dumps as json_dumps
|
||||||
from octoprint.util.version import get_python_version_string
|
from octoprint.util.version import get_python_version_string
|
||||||
|
|
||||||
@@ -173,6 +174,10 @@ class PrinterStateConnection(
|
|||||||
self._subscriptions_active = False
|
self._subscriptions_active = False
|
||||||
self._subscriptions = {"state": False, "plugins": [], "events": []}
|
self._subscriptions = {"state": False, "plugins": [], "events": []}
|
||||||
|
|
||||||
|
self._keep_alive = RepeatedTimer(
|
||||||
|
60, self._keep_alive_callback, condition=lambda: self._authed
|
||||||
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _get_remote_address(info):
|
def _get_remote_address(info):
|
||||||
forwarded_for = info.headers.get("X-Forwarded-For")
|
forwarded_for = info.headers.get("X-Forwarded-For")
|
||||||
@@ -180,6 +185,13 @@ class PrinterStateConnection(
|
|||||||
return forwarded_for.split(",")[0]
|
return forwarded_for.split(",")[0]
|
||||||
return info.ip
|
return info.ip
|
||||||
|
|
||||||
|
def _keep_alive_callback(self):
|
||||||
|
if not self._authed:
|
||||||
|
return
|
||||||
|
if not isinstance(self._user, SessionUser):
|
||||||
|
return
|
||||||
|
self._user.touch()
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
if self._remoteAddress:
|
if self._remoteAddress:
|
||||||
return f"{self!r} connected to {self._remoteAddress}"
|
return f"{self!r} connected to {self._remoteAddress}"
|
||||||
@@ -293,6 +305,7 @@ class PrinterStateConnection(
|
|||||||
f"Unknown user/session combo: {user_id}:{user_session}"
|
f"Unknown user/session combo: {user_id}:{user_session}"
|
||||||
)
|
)
|
||||||
self._on_logout()
|
self._on_logout()
|
||||||
|
self._sendReauthRequired("stale")
|
||||||
|
|
||||||
self._register()
|
self._register()
|
||||||
|
|
||||||
@@ -442,12 +455,17 @@ class PrinterStateConnection(
|
|||||||
{
|
{
|
||||||
"serverTime": time.time(),
|
"serverTime": time.time(),
|
||||||
"temps": temperatures,
|
"temps": temperatures,
|
||||||
"logs": self._filter_logs(logs),
|
|
||||||
"messages": messages,
|
|
||||||
"busyFiles": busy_files,
|
"busyFiles": busy_files,
|
||||||
"markings": list(self._printer.get_markings()),
|
"markings": list(self._printer.get_markings()),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
if self._user.has_permission(Permissions.MONITOR_TERMINAL):
|
||||||
|
data.update(
|
||||||
|
{
|
||||||
|
"logs": self._filter_logs(logs),
|
||||||
|
"messages": messages,
|
||||||
|
}
|
||||||
|
)
|
||||||
self._emit("current", payload=data)
|
self._emit("current", payload=data)
|
||||||
|
|
||||||
def on_printer_send_initial_data(self, data):
|
def on_printer_send_initial_data(self, data):
|
||||||
@@ -457,9 +475,13 @@ class PrinterStateConnection(
|
|||||||
return
|
return
|
||||||
|
|
||||||
data_to_send = dict(data)
|
data_to_send = dict(data)
|
||||||
data_to_send["logs"] = self._filter_logs(data_to_send.get("logs", []))
|
|
||||||
data_to_send["messages"] = self._filter_messages(data_to_send.get("messages", []))
|
|
||||||
data_to_send["serverTime"] = time.time()
|
data_to_send["serverTime"] = time.time()
|
||||||
|
if self._user.has_permission(Permissions.MONITOR_TERMINAL):
|
||||||
|
data_to_send["logs"] = self._filter_logs(data_to_send.get("logs", []))
|
||||||
|
data_to_send["messages"] = self._filter_messages(
|
||||||
|
data_to_send.get("messages", [])
|
||||||
|
)
|
||||||
self._emit("history", payload=data_to_send)
|
self._emit("history", payload=data_to_send)
|
||||||
|
|
||||||
def _filter_state_subscription(self, sub, values):
|
def _filter_state_subscription(self, sub, values):
|
||||||
@@ -716,6 +738,8 @@ class PrinterStateConnection(
|
|||||||
)
|
)
|
||||||
self._authed = True
|
self._authed = True
|
||||||
|
|
||||||
|
self._keep_alive.start()
|
||||||
|
|
||||||
for name, hook in self._authed_hooks.items():
|
for name, hook in self._authed_hooks.items():
|
||||||
try:
|
try:
|
||||||
hook(self, self._user)
|
hook(self, self._user)
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ from octoprint.server.util import (
|
|||||||
require_login_with,
|
require_login_with,
|
||||||
validate_local_redirect,
|
validate_local_redirect,
|
||||||
)
|
)
|
||||||
|
from octoprint.server.util.csrf import add_csrf_cookie
|
||||||
from octoprint.settings import settings
|
from octoprint.settings import settings
|
||||||
from octoprint.util import sv, to_bytes, to_unicode
|
from octoprint.util import sv, to_bytes, to_unicode
|
||||||
from octoprint.util.version import get_python_version_string
|
from octoprint.util.version import get_python_version_string
|
||||||
@@ -223,7 +224,8 @@ def login():
|
|||||||
except Exception:
|
except Exception:
|
||||||
_logger.exception("Error processing theming CSS, ignoring")
|
_logger.exception("Error processing theming CSS, ignoring")
|
||||||
|
|
||||||
return render_template("login.jinja2", **render_kwargs)
|
resp = make_response(render_template("login.jinja2", **render_kwargs))
|
||||||
|
return add_csrf_cookie(resp)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/recovery")
|
@app.route("/recovery")
|
||||||
@@ -254,7 +256,8 @@ def recovery():
|
|||||||
except Exception:
|
except Exception:
|
||||||
_logger.exception("Error adding backup upload size info, ignoring")
|
_logger.exception("Error adding backup upload size info, ignoring")
|
||||||
|
|
||||||
return render_template("recovery.jinja2", **render_kwargs)
|
resp = make_response(render_template("recovery.jinja2", **render_kwargs))
|
||||||
|
return add_csrf_cookie(resp)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/cached.gif")
|
@app.route("/cached.gif")
|
||||||
@@ -328,6 +331,26 @@ def in_cache():
|
|||||||
return abort(404)
|
return abort(404)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/reverse_proxy_test")
|
||||||
|
@app.route("/reverse_proxy_test/")
|
||||||
|
def reverse_proxy_test():
|
||||||
|
from octoprint.server.util.flask import get_cookie_suffix, get_remote_address
|
||||||
|
|
||||||
|
remote_address = get_remote_address(request)
|
||||||
|
cookie_suffix = get_cookie_suffix(request)
|
||||||
|
|
||||||
|
return render_template(
|
||||||
|
"reverse_proxy_test.jinja2",
|
||||||
|
theming=[],
|
||||||
|
client_ip=remote_address,
|
||||||
|
server_protocol=request.environ.get("wsgi.url_scheme"),
|
||||||
|
server_name=request.environ.get("SERVER_NAME"),
|
||||||
|
server_port=request.environ.get("SERVER_PORT"),
|
||||||
|
server_path=request.script_root if request.script_root else "/",
|
||||||
|
cookie_suffix=cookie_suffix,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/")
|
@app.route("/")
|
||||||
def index():
|
def index():
|
||||||
from octoprint.server import connectivityChecker, printer
|
from octoprint.server import connectivityChecker, printer
|
||||||
@@ -694,7 +717,8 @@ def index():
|
|||||||
|
|
||||||
if response is None:
|
if response is None:
|
||||||
return abort(404)
|
return abort(404)
|
||||||
return response
|
|
||||||
|
return add_csrf_cookie(response)
|
||||||
|
|
||||||
|
|
||||||
def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
|
def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
|
||||||
|
|||||||
@@ -228,7 +228,7 @@ default_settings = {
|
|||||||
"preemptiveCache": {"exceptions": [], "until": 7},
|
"preemptiveCache": {"exceptions": [], "until": 7},
|
||||||
"ipCheck": {"enabled": True, "trustedSubnets": []},
|
"ipCheck": {"enabled": True, "trustedSubnets": []},
|
||||||
"allowFraming": False,
|
"allowFraming": False,
|
||||||
"cookies": {"secure": False, "samesite": None},
|
"cookies": {"secure": False, "samesite": "lax"},
|
||||||
},
|
},
|
||||||
"webcam": {
|
"webcam": {
|
||||||
"webcamEnabled": True,
|
"webcamEnabled": True,
|
||||||
@@ -402,7 +402,6 @@ default_settings = {
|
|||||||
"controls": [],
|
"controls": [],
|
||||||
"system": {"actions": []},
|
"system": {"actions": []},
|
||||||
"accessControl": {
|
"accessControl": {
|
||||||
"salt": None,
|
|
||||||
"userManager": "octoprint.access.users.FilebasedUserManager",
|
"userManager": "octoprint.access.users.FilebasedUserManager",
|
||||||
"groupManager": "octoprint.access.groups.FilebasedGroupManager",
|
"groupManager": "octoprint.access.groups.FilebasedGroupManager",
|
||||||
"permissionManager": "octoprint.access.permissions.PermissionManager",
|
"permissionManager": "octoprint.access.permissions.PermissionManager",
|
||||||
@@ -471,6 +470,8 @@ default_settings = {
|
|||||||
"showLoadingAnimation": True,
|
"showLoadingAnimation": True,
|
||||||
"sockJsConnectTimeout": 30,
|
"sockJsConnectTimeout": 30,
|
||||||
"pluginTimings": False,
|
"pluginTimings": False,
|
||||||
|
"enableRateLimiter": True,
|
||||||
|
"enableCsrfProtection": True,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
"""The default settings of the core application."""
|
"""The default settings of the core application."""
|
||||||
@@ -891,6 +892,7 @@ class Settings:
|
|||||||
"logs",
|
"logs",
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
self.warn_about_risky_settings()
|
||||||
|
|
||||||
def _init_basedir(self, basedir):
|
def _init_basedir(self, basedir):
|
||||||
if basedir is not None:
|
if basedir is not None:
|
||||||
@@ -923,6 +925,16 @@ class Settings:
|
|||||||
if len(folder_map.values()) != len(set(folder_map.values())):
|
if len(folder_map.values()) != len(set(folder_map.values())):
|
||||||
raise DuplicateFolderPaths(folders)
|
raise DuplicateFolderPaths(folders)
|
||||||
|
|
||||||
|
def warn_about_risky_settings(self):
|
||||||
|
if not self.getBoolean(["devel", "enableRateLimiter"]):
|
||||||
|
self._logger.warning(
|
||||||
|
"Rate limiting is disabled, this is a security risk. Do not run this in production."
|
||||||
|
)
|
||||||
|
if not self.getBoolean(["devel", "enableCsrfProtection"]):
|
||||||
|
self._logger.warning(
|
||||||
|
"CSRF Protection is disabled, this is a security risk. Do not run this in production."
|
||||||
|
)
|
||||||
|
|
||||||
def _get_default_folder(self, type):
|
def _get_default_folder(self, type):
|
||||||
folder = default_settings["folder"][type]
|
folder = default_settings["folder"][type]
|
||||||
if folder is None:
|
if folder is None:
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type="text"],.form-signin input[type="password"]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:white}#noscript{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#ffffff;z-index:12310}#noscript .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#noscript .wrapper .outer{display:table;width:100%;height:100%}#noscript .wrapper .outer .inner{display:table-cell;vertical-align:middle}#noscript .wrapper .outer .inner .content{text-align:center}
|
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type="text"],.form-signin input[type="password"]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error-credentials,#login-error-rate,#login-offline{display:none}#login-error-credentials.in,#login-error-rate.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:white}#noscript{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#ffffff;z-index:12310}#noscript .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#noscript .wrapper .outer{display:table;width:100%;height:100%}#noscript .wrapper .outer .inner{display:table-cell;vertical-align:middle}#noscript .wrapper .outer .inner .content{text-align:center}
|
||||||
@@ -176,17 +176,26 @@
|
|||||||
OctoPrintAccessUsersClient.prototype.changePassword = function (
|
OctoPrintAccessUsersClient.prototype.changePassword = function (
|
||||||
name,
|
name,
|
||||||
password,
|
password,
|
||||||
|
oldpw,
|
||||||
opts
|
opts
|
||||||
) {
|
) {
|
||||||
|
if (_.isObject(oldpw)) {
|
||||||
|
opts = oldpw;
|
||||||
|
oldpw = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
if (!name || !password) {
|
if (!name || !password) {
|
||||||
throw new OctoPrintClient.InvalidArgumentError(
|
throw new OctoPrintClient.InvalidArgumentError(
|
||||||
"user name and password must be set"
|
"user name and new password must be set"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
var data = {
|
var data = {
|
||||||
password: password
|
password: password
|
||||||
};
|
};
|
||||||
|
if (oldpw) {
|
||||||
|
data["current"] = oldpw;
|
||||||
|
}
|
||||||
return this.base.putJson(this.url(name, "password"), data, opts);
|
return this.base.putJson(this.url(name, "password"), data, opts);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -107,14 +107,84 @@
|
|||||||
return url;
|
return url;
|
||||||
};
|
};
|
||||||
|
|
||||||
OctoPrintClient.prototype.getRequestHeaders = function (additional) {
|
OctoPrintClient.prototype.getParsedBaseUrl = function (location) {
|
||||||
|
if (!this.options.baseurl) return "";
|
||||||
|
|
||||||
|
try {
|
||||||
|
var url = new URL(this.options.baseurl);
|
||||||
|
} catch (e) {
|
||||||
|
location = location || window.location;
|
||||||
|
var parsed = new URL(location);
|
||||||
|
var path = this.options.baseurl;
|
||||||
|
if (!path || path[0] !== "/") {
|
||||||
|
path = "/" + (path ? path : "");
|
||||||
|
}
|
||||||
|
var url = new URL(parsed.protocol + "//" + parsed.host + path);
|
||||||
|
}
|
||||||
|
|
||||||
|
return url;
|
||||||
|
};
|
||||||
|
|
||||||
|
OctoPrintClient.prototype.getCookieSuffix = function () {
|
||||||
|
if (!this.options.baseurl) return "";
|
||||||
|
|
||||||
|
var url = this.getParsedBaseUrl();
|
||||||
|
|
||||||
|
var port = url.port || (url.protocol === "https:" ? 443 : 80);
|
||||||
|
if (url.pathname && url.pathname !== "/") {
|
||||||
|
var path = url.pathname;
|
||||||
|
if (path.endsWith("/")) {
|
||||||
|
path = path.substring(0, path.length - 1);
|
||||||
|
}
|
||||||
|
return "_P" + port + "_R" + path.replace(/\//g, "|");
|
||||||
|
} else {
|
||||||
|
return "_P" + port;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
OctoPrintClient.prototype.getCookieName = function (name) {
|
||||||
|
return name + this.getCookieSuffix();
|
||||||
|
};
|
||||||
|
|
||||||
|
OctoPrintClient.prototype.getCookie = function (name) {
|
||||||
|
name = this.getCookieName(name);
|
||||||
|
return ("; " + document.cookie)
|
||||||
|
.split("; " + name + "=")
|
||||||
|
.pop()
|
||||||
|
.split(";")[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
OctoPrintClient.prototype.getRequestHeaders = function (method, additional, opts) {
|
||||||
|
if (arguments.length <= 1) {
|
||||||
|
// versions prior 1.8.3 don't know method and opts
|
||||||
|
if (!_.isString(method)) {
|
||||||
|
additional = method;
|
||||||
|
console.warn(
|
||||||
|
"Calling OctoPrintClient.getRequestHeaders with additional " +
|
||||||
|
"headers as the first parameter is deprecated. Please " +
|
||||||
|
"consult the docs about the current signature and adjust " +
|
||||||
|
"your code accordingly."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
method = method || "GET";
|
||||||
additional = additional || {};
|
additional = additional || {};
|
||||||
|
opts = opts || {};
|
||||||
|
|
||||||
var headers = $.extend({}, additional);
|
var headers = $.extend({}, additional);
|
||||||
|
|
||||||
if (this.options.apikey) {
|
if (this.options.apikey) {
|
||||||
headers["X-Api-Key"] = this.options.apikey;
|
headers["X-Api-Key"] = this.options.apikey;
|
||||||
|
} else {
|
||||||
|
// no API key, so browser context, so let's make sure the CSRF token
|
||||||
|
// header is set
|
||||||
|
var csrfToken = this.getCookie("csrf_token");
|
||||||
|
if (!/^(GET|HEAD|OPTIONS)$/.test(method) && csrfToken && !opts.crossDomain) {
|
||||||
|
headers["X-CSRF-Token"] = csrfToken;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.options.locale !== undefined) {
|
if (this.options.locale !== undefined) {
|
||||||
headers["X-Locale"] = this.options.locale;
|
headers["X-Locale"] = this.options.locale;
|
||||||
}
|
}
|
||||||
@@ -134,7 +204,7 @@
|
|||||||
opts.url = urlToCall;
|
opts.url = urlToCall;
|
||||||
}
|
}
|
||||||
|
|
||||||
var headers = this.getRequestHeaders(opts.headers);
|
var headers = this.getRequestHeaders(method, opts.headers, opts);
|
||||||
|
|
||||||
var params = $.extend({}, opts);
|
var params = $.extend({}, opts);
|
||||||
params.type = method;
|
params.type = method;
|
||||||
@@ -292,14 +362,15 @@
|
|||||||
deferred.notify({loaded: e.loaded, total: e.total});
|
deferred.notify({loaded: e.loaded, total: e.total});
|
||||||
});
|
});
|
||||||
|
|
||||||
var headers = this.getRequestHeaders();
|
var method = "POST";
|
||||||
|
var headers = this.getRequestHeaders(method);
|
||||||
|
|
||||||
var urlToCall = url;
|
var urlToCall = url;
|
||||||
if (!_.startsWith(url, "http://") && !_.startsWith(url, "https://")) {
|
if (!_.startsWith(url, "http://") && !_.startsWith(url, "https://")) {
|
||||||
urlToCall = this.getBaseUrl() + url;
|
urlToCall = this.getBaseUrl() + url;
|
||||||
}
|
}
|
||||||
|
|
||||||
request.open("POST", urlToCall);
|
request.open(method, urlToCall);
|
||||||
_.each(headers, function (value, key) {
|
_.each(headers, function (value, key) {
|
||||||
request.setRequestHeader(key, value);
|
request.setRequestHeader(key, value);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -202,6 +202,21 @@ $(function () {
|
|||||||
|
|
||||||
//~~ AJAX setup
|
//~~ AJAX setup
|
||||||
|
|
||||||
|
$.ajaxSetup({
|
||||||
|
beforeSend: function (xhr, settings) {
|
||||||
|
// we already do that in the js client lib, but a lot of plugins don't use
|
||||||
|
// that but rather use $.ajax directly, so we need to do it here as well
|
||||||
|
var csrfToken = OctoPrint.getCookie("csrf_token");
|
||||||
|
if (
|
||||||
|
!/^(GET|HEAD|OPTIONS)$/.test(settings.type) &&
|
||||||
|
csrfToken &&
|
||||||
|
!this.crossDomain
|
||||||
|
) {
|
||||||
|
xhr.setRequestHeader("X-CSRF-Token", csrfToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
|
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
|
||||||
// http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results
|
// http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results
|
||||||
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
|
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
|
||||||
@@ -219,7 +234,8 @@ $(function () {
|
|||||||
$.widget("blueimp.fileupload", $.blueimp.fileupload, {
|
$.widget("blueimp.fileupload", $.blueimp.fileupload, {
|
||||||
options: {
|
options: {
|
||||||
dropZone: null,
|
dropZone: null,
|
||||||
pasteZone: null
|
pasteZone: null,
|
||||||
|
headers: OctoPrint.getRequestHeaders("POST")
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -40,10 +40,12 @@ $(function () {
|
|||||||
groups: ko.observableArray([]),
|
groups: ko.observableArray([]),
|
||||||
permissions: ko.observableArray([]),
|
permissions: ko.observableArray([]),
|
||||||
password: ko.observable(undefined),
|
password: ko.observable(undefined),
|
||||||
|
currentPassword: ko.observable(undefined),
|
||||||
repeatedPassword: ko.observable(undefined),
|
repeatedPassword: ko.observable(undefined),
|
||||||
passwordMismatch: ko.pureComputed(function () {
|
passwordMismatch: ko.pureComputed(function () {
|
||||||
return self.editor.password() !== self.editor.repeatedPassword();
|
return self.editor.password() !== self.editor.repeatedPassword();
|
||||||
}),
|
}),
|
||||||
|
currentPasswordMismatch: ko.observable(false),
|
||||||
apikey: ko.observable(undefined),
|
apikey: ko.observable(undefined),
|
||||||
active: ko.observable(undefined),
|
active: ko.observable(undefined),
|
||||||
permissionSelectable: function (permission) {
|
permissionSelectable: function (permission) {
|
||||||
@@ -128,6 +130,11 @@ $(function () {
|
|||||||
}
|
}
|
||||||
self.editor.password(undefined);
|
self.editor.password(undefined);
|
||||||
self.editor.repeatedPassword(undefined);
|
self.editor.repeatedPassword(undefined);
|
||||||
|
self.editor.currentPassword(undefined);
|
||||||
|
self.editor.currentPasswordMismatch(false);
|
||||||
|
});
|
||||||
|
self.editor.currentPassword.subscribe(function () {
|
||||||
|
self.editor.currentPasswordMismatch(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
self.requestData = function () {
|
self.requestData = function () {
|
||||||
@@ -244,13 +251,21 @@ $(function () {
|
|||||||
self.confirmChangePassword = function () {
|
self.confirmChangePassword = function () {
|
||||||
if (!CONFIG_ACCESS_CONTROL) return;
|
if (!CONFIG_ACCESS_CONTROL) return;
|
||||||
|
|
||||||
self.updatePassword(self.currentUser().name, self.editor.password()).done(
|
self.updatePassword(
|
||||||
function () {
|
self.currentUser().name,
|
||||||
|
self.editor.password(),
|
||||||
|
self.editor.currentPassword()
|
||||||
|
)
|
||||||
|
.done(function () {
|
||||||
// close dialog
|
// close dialog
|
||||||
self.currentUser(undefined);
|
self.currentUser(undefined);
|
||||||
self.changePasswordDialog.modal("hide");
|
self.changePasswordDialog.modal("hide");
|
||||||
}
|
})
|
||||||
);
|
.fail(function (xhr) {
|
||||||
|
if (xhr.status === 403) {
|
||||||
|
self.currentPasswordMismatch(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
self.confirmGenerateApikey = function () {
|
self.confirmGenerateApikey = function () {
|
||||||
@@ -349,8 +364,8 @@ $(function () {
|
|||||||
.done(self.fromResponse);
|
.done(self.fromResponse);
|
||||||
};
|
};
|
||||||
|
|
||||||
self.updatePassword = function (username, password) {
|
self.updatePassword = function (username, password, current) {
|
||||||
return OctoPrint.access.users.changePassword(username, password);
|
return OctoPrint.access.users.changePassword(username, password, current);
|
||||||
};
|
};
|
||||||
|
|
||||||
self.generateApikey = function (username) {
|
self.generateApikey = function (username) {
|
||||||
@@ -847,7 +862,7 @@ $(function () {
|
|||||||
access.onUserLoggedIn =
|
access.onUserLoggedIn =
|
||||||
access.onUserLoggedOut =
|
access.onUserLoggedOut =
|
||||||
function (user) {
|
function (user) {
|
||||||
if (access.loginState.hasPermission(access.permissions.SETTINGS)) {
|
if (access.loginState.hasPermission(access.permissions.ADMIN)) {
|
||||||
access.groups.requestData().done(function () {
|
access.groups.requestData().done(function () {
|
||||||
access.users.requestData();
|
access.users.requestData();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1600,9 +1600,7 @@ $(function () {
|
|||||||
name: file.name
|
name: file.name
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
$("input", self.uploadExistsDialog)
|
$("input", self.uploadExistsDialog).val(response.suggestion);
|
||||||
.val("")
|
|
||||||
.prop("placeholder", response.suggestion);
|
|
||||||
$("a.upload-rename", self.uploadExistsDialog)
|
$("a.upload-rename", self.uploadExistsDialog)
|
||||||
.prop("disabled", false)
|
.prop("disabled", false)
|
||||||
.off("click")
|
.off("click")
|
||||||
@@ -1611,7 +1609,6 @@ $(function () {
|
|||||||
"input",
|
"input",
|
||||||
self.uploadExistsDialog
|
self.uploadExistsDialog
|
||||||
).val();
|
).val();
|
||||||
if (newName === "") newName = response.suggestion;
|
|
||||||
|
|
||||||
OctoPrint.files
|
OctoPrint.files
|
||||||
.exists("local", path, newName)
|
.exists("local", path, newName)
|
||||||
@@ -1645,13 +1642,22 @@ $(function () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
$("a.upload-overwrite", self.uploadExistsDialog)
|
if (
|
||||||
.off("click")
|
self.loginState.hasPermission(
|
||||||
.on("click", function () {
|
self.access.permissions.FILES_DELETE
|
||||||
self.uploadExistsDialog.modal("hide");
|
)
|
||||||
data.formData = formData;
|
) {
|
||||||
data.submit();
|
$("a.upload-overwrite", self.uploadExistsDialog)
|
||||||
});
|
.off("click")
|
||||||
|
.show()
|
||||||
|
.on("click", function () {
|
||||||
|
self.uploadExistsDialog.modal("hide");
|
||||||
|
data.formData = formData;
|
||||||
|
data.submit();
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
$("a.upload-overwrite", self.uploadExistsDialog).hide();
|
||||||
|
}
|
||||||
self.uploadExistsDialog.modal("show");
|
self.uploadExistsDialog.modal("show");
|
||||||
} else {
|
} else {
|
||||||
data.formData = formData;
|
data.formData = formData;
|
||||||
|
|||||||
@@ -308,7 +308,7 @@ $(function () {
|
|||||||
};
|
};
|
||||||
|
|
||||||
self.onDataUpdaterReauthRequired = function (reason) {
|
self.onDataUpdaterReauthRequired = function (reason) {
|
||||||
if (reason === "logout" || reason === "removed") {
|
if (reason === "logout" || reason === "stale" || reason === "removed") {
|
||||||
self.logout();
|
self.logout();
|
||||||
} else {
|
} else {
|
||||||
self.requestData();
|
self.requestData();
|
||||||
|
|||||||
@@ -255,8 +255,6 @@ $(function () {
|
|||||||
|
|
||||||
self.folder_uploads = ko.observable(undefined);
|
self.folder_uploads = ko.observable(undefined);
|
||||||
self.folder_timelapse = ko.observable(undefined);
|
self.folder_timelapse = ko.observable(undefined);
|
||||||
self.folder_timelapseTmp = ko.observable(undefined);
|
|
||||||
self.folder_logs = ko.observable(undefined);
|
|
||||||
self.folder_watched = ko.observable(undefined);
|
self.folder_watched = ko.observable(undefined);
|
||||||
|
|
||||||
self.scripts_gcode_beforePrintStarted = ko.observable(undefined);
|
self.scripts_gcode_beforePrintStarted = ko.observable(undefined);
|
||||||
@@ -344,7 +342,7 @@ $(function () {
|
|||||||
self.server_onlineCheckResolutionBroken(false);
|
self.server_onlineCheckResolutionBroken(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
var folderTypes = ["uploads", "timelapse", "timelapseTmp", "logs", "watched"];
|
var folderTypes = ["uploads", "timelapse", "watched"];
|
||||||
|
|
||||||
var checkForDuplicateFolders = function () {
|
var checkForDuplicateFolders = function () {
|
||||||
_.each(folderTypes, function (folderType) {
|
_.each(folderTypes, function (folderType) {
|
||||||
@@ -772,7 +770,6 @@ $(function () {
|
|||||||
dataType: "json",
|
dataType: "json",
|
||||||
maxNumberOfFiles: 1,
|
maxNumberOfFiles: 1,
|
||||||
autoUpload: false,
|
autoUpload: false,
|
||||||
headers: OctoPrint.getRequestHeaders(),
|
|
||||||
add: function (e, data) {
|
add: function (e, data) {
|
||||||
if (data.files.length == 0) {
|
if (data.files.length == 0) {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -225,6 +225,8 @@ $(function () {
|
|||||||
};
|
};
|
||||||
|
|
||||||
self._processCurrentLogData = function (data) {
|
self._processCurrentLogData = function (data) {
|
||||||
|
if (!data) return;
|
||||||
|
|
||||||
var length = self.log().length;
|
var length = self.log().length;
|
||||||
if (length >= self.upperLimit()) {
|
if (length >= self.upperLimit()) {
|
||||||
return;
|
return;
|
||||||
@@ -276,6 +278,8 @@ $(function () {
|
|||||||
};
|
};
|
||||||
|
|
||||||
self._processHistoryLogData = function (data) {
|
self._processHistoryLogData = function (data) {
|
||||||
|
if (!data) return;
|
||||||
|
|
||||||
self.plainLogLines(data);
|
self.plainLogLines(data);
|
||||||
self.log(_.map(data, self._toInternalFormat));
|
self.log(_.map(data, self._toInternalFormat));
|
||||||
self.updateOutput();
|
self.updateOutput();
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ $(function () {
|
|||||||
|
|
||||||
self.access_password = ko.observable(undefined);
|
self.access_password = ko.observable(undefined);
|
||||||
self.access_repeatedPassword = ko.observable(undefined);
|
self.access_repeatedPassword = ko.observable(undefined);
|
||||||
|
self.access_currentPassword = ko.observable(undefined);
|
||||||
|
self.access_currentPasswordMismatch = ko.observable(false);
|
||||||
self.access_apikey = ko.observable(undefined);
|
self.access_apikey = ko.observable(undefined);
|
||||||
self.interface_language = ko.observable(undefined);
|
self.interface_language = ko.observable(undefined);
|
||||||
|
|
||||||
@@ -32,6 +34,8 @@ $(function () {
|
|||||||
self.currentUser.subscribe(function (newUser) {
|
self.currentUser.subscribe(function (newUser) {
|
||||||
self.access_password(undefined);
|
self.access_password(undefined);
|
||||||
self.access_repeatedPassword(undefined);
|
self.access_repeatedPassword(undefined);
|
||||||
|
self.access_currentPassword(undefined);
|
||||||
|
self.access_currentPasswordMismatch(false);
|
||||||
self.access_apikey(undefined);
|
self.access_apikey(undefined);
|
||||||
self.interface_language("_default");
|
self.interface_language("_default");
|
||||||
|
|
||||||
@@ -45,6 +49,9 @@ $(function () {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
self.access_currentPassword.subscribe(function () {
|
||||||
|
self.access_currentPasswordMismatch(false);
|
||||||
|
});
|
||||||
|
|
||||||
self.passwordMismatch = ko.pureComputed(function () {
|
self.passwordMismatch = ko.pureComputed(function () {
|
||||||
return self.access_password() !== self.access_repeatedPassword();
|
return self.access_password() !== self.access_repeatedPassword();
|
||||||
@@ -81,25 +88,38 @@ $(function () {
|
|||||||
|
|
||||||
self.userSettingsDialog.trigger("beforeSave");
|
self.userSettingsDialog.trigger("beforeSave");
|
||||||
|
|
||||||
if (self.access_password() && !self.passwordMismatch()) {
|
function saveSettings() {
|
||||||
self.users.updatePassword(
|
var settings = {
|
||||||
self.currentUser().name,
|
interface: {
|
||||||
self.access_password(),
|
language: self.interface_language()
|
||||||
function () {}
|
}
|
||||||
);
|
};
|
||||||
|
self.updateSettings(self.currentUser().name, settings).done(function () {
|
||||||
|
// close dialog
|
||||||
|
self.currentUser(undefined);
|
||||||
|
self.userSettingsDialog.modal("hide");
|
||||||
|
self.loginState.reloadUser();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
var settings = {
|
if (self.access_password() && !self.passwordMismatch()) {
|
||||||
interface: {
|
self.users
|
||||||
language: self.interface_language()
|
.updatePassword(
|
||||||
}
|
self.currentUser().name,
|
||||||
};
|
self.access_password(),
|
||||||
self.updateSettings(self.currentUser().name, settings).done(function () {
|
self.access_currentPassword()
|
||||||
// close dialog
|
)
|
||||||
self.currentUser(undefined);
|
.done(function () {
|
||||||
self.userSettingsDialog.modal("hide");
|
saveSettings();
|
||||||
self.loginState.reloadUser();
|
})
|
||||||
});
|
.fail(function (xhr) {
|
||||||
|
if (xhr.status === 403) {
|
||||||
|
self.access_currentPasswordMismatch(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
saveSettings();
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
self.copyApikey = function () {
|
self.copyApikey = function () {
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ $(function () {
|
|||||||
};
|
};
|
||||||
|
|
||||||
var overlayElement = $("#login-overlay");
|
var overlayElement = $("#login-overlay");
|
||||||
var errorElement = $("#login-error");
|
var errorCredentialsElement = $("#login-error-credentials");
|
||||||
|
var errorRateElement = $("#login-error-rate");
|
||||||
var offlineElement = $("#login-offline");
|
var offlineElement = $("#login-offline");
|
||||||
var buttonElement = $("#login-button");
|
var buttonElement = $("#login-button");
|
||||||
var reconnectElement = $("#login-reconnect");
|
var reconnectElement = $("#login-reconnect");
|
||||||
@@ -28,7 +29,8 @@ $(function () {
|
|||||||
var remember = rememberElement.prop("checked");
|
var remember = rememberElement.prop("checked");
|
||||||
|
|
||||||
overlayElement.addClass("in");
|
overlayElement.addClass("in");
|
||||||
errorElement.removeClass("in");
|
errorCredentialsElement.removeClass("in");
|
||||||
|
errorRateElement.removeClass("in");
|
||||||
|
|
||||||
OctoPrint.browser
|
OctoPrint.browser
|
||||||
.login(username, password, remember)
|
.login(username, password, remember)
|
||||||
@@ -36,7 +38,7 @@ $(function () {
|
|||||||
ignoreDisconnect = true;
|
ignoreDisconnect = true;
|
||||||
window.location.href = REDIRECT_URL;
|
window.location.href = REDIRECT_URL;
|
||||||
})
|
})
|
||||||
.fail(function () {
|
.fail(function (xhr) {
|
||||||
usernameElement.val(USER_ID);
|
usernameElement.val(USER_ID);
|
||||||
passwordElement.val("");
|
passwordElement.val("");
|
||||||
|
|
||||||
@@ -47,7 +49,11 @@ $(function () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
overlayElement.removeClass("in");
|
overlayElement.removeClass("in");
|
||||||
errorElement.addClass("in");
|
if (xhr.status === 429) {
|
||||||
|
errorRateElement.addClass("in");
|
||||||
|
} else {
|
||||||
|
errorCredentialsElement.addClass("in");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
$(function () {
|
||||||
|
//~~ OctoPrint client setup
|
||||||
|
|
||||||
|
var OctoPrint = window.OctoPrint;
|
||||||
|
OctoPrint.options.baseurl = BASE_URL;
|
||||||
|
|
||||||
|
//~~ Lodash setup
|
||||||
|
|
||||||
|
_.mixin({sprintf: sprintf, vsprintf: vsprintf});
|
||||||
|
|
||||||
|
//~~ View Model
|
||||||
|
|
||||||
|
function ReverseProxyTestViewModel() {
|
||||||
|
var self = this;
|
||||||
|
|
||||||
|
var url = OctoPrint.getParsedBaseUrl();
|
||||||
|
var cookieSuffix = OctoPrint.getCookieSuffix();
|
||||||
|
var protocol = url.protocol;
|
||||||
|
var path = url.pathname || "/";
|
||||||
|
|
||||||
|
if (path && path !== "/") {
|
||||||
|
if (path.endsWith("/")) {
|
||||||
|
path = path.substring(0, path.length - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.serverProtocol = protocol.substring(0, protocol.length - 1);
|
||||||
|
self.serverName = url.hostname;
|
||||||
|
self.serverPort = url.port || (url.protocol === "https:" ? 443 : 80);
|
||||||
|
self.serverPath = path;
|
||||||
|
self.cookieSuffix = cookieSuffix;
|
||||||
|
|
||||||
|
self.serverProtocolMatch = self.serverProtocol == SERVER_PROTOCOL;
|
||||||
|
self.serverNameMatch = self.serverName == SERVER_NAME;
|
||||||
|
self.serverPortMatch = self.serverPort == SERVER_PORT;
|
||||||
|
self.serverPathMatch = self.serverPath == SERVER_PATH;
|
||||||
|
self.cookieSuffixMatch = self.cookieSuffix == COOKIE_SUFFIX;
|
||||||
|
}
|
||||||
|
|
||||||
|
var viewModel = new ReverseProxyTestViewModel();
|
||||||
|
|
||||||
|
ko.applyBindings(viewModel, document.getElementById("reverse_proxy_test"));
|
||||||
|
});
|
||||||
@@ -31,7 +31,8 @@ body {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#login-error,
|
#login-error-credentials,
|
||||||
|
#login-error-rate,
|
||||||
#login-offline {
|
#login-offline {
|
||||||
display: none;
|
display: none;
|
||||||
|
|
||||||
|
|||||||
@@ -92,7 +92,7 @@
|
|||||||
<div data-bind="visible: languagePacksAvailable()">
|
<div data-bind="visible: languagePacksAvailable()">
|
||||||
<div id="settings_appearance_managelanguagesdialog_list" data-bind="foreach: translations.paginatedItems">
|
<div id="settings_appearance_managelanguagesdialog_list" data-bind="foreach: translations.paginatedItems">
|
||||||
<div class="entry">
|
<div class="entry">
|
||||||
<strong><a href="#" class="fas" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.entry', container: '.packs' }"><i class="fas fa-caret-down"></i> <span data-bind="text: $root.languagePackDisplay($data)"></span></a></strong>
|
<strong><a href="#" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.entry', container: '.packs' }"><i class="fas fa-caret-down"></i> <span data-bind="text: $root.languagePackDisplay($data)"></span></a></strong>
|
||||||
<div class="packs">
|
<div class="packs">
|
||||||
<!-- ko foreach: $data.packs -->
|
<!-- ko foreach: $data.packs -->
|
||||||
<div class="row-fluid">
|
<div class="row-fluid">
|
||||||
|
|||||||
@@ -20,26 +20,6 @@
|
|||||||
<span class="help-block" data-bind="visible: testFolderConfigBroken.timelapse() || testFolderConfigOk.timelapse(), text: testFolderConfigText.timelapse"></span>
|
<span class="help-block" data-bind="visible: testFolderConfigBroken.timelapse() || testFolderConfigOk.timelapse(), text: testFolderConfigText.timelapse"></span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<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, 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="fas 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: 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, 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="fas 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: testFolderConfigError.watched, success: testFolderConfigSuccess.watched}">
|
<div class="control-group" data-bind="css: {error: testFolderConfigError.watched, success: testFolderConfigSuccess.watched}">
|
||||||
<label class="control-label" for="settings-folderWatched">{{ _('Watched Folder') }}</label>
|
<label class="control-label" for="settings-folderWatched">{{ _('Watched Folder') }}</label>
|
||||||
<div class="controls">
|
<div class="controls">
|
||||||
@@ -65,6 +45,11 @@
|
|||||||
{% endtrans %}
|
{% endtrans %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<p>{% trans %}
|
||||||
|
Please note: Not all of the folders used by OctoPrint can be configured through the UI, only those most commonly moved to other places. If you need to configure other folders,
|
||||||
|
please do so by manually editing the configuration. See the docs for details.
|
||||||
|
{% endtrans %}</p>
|
||||||
|
|
||||||
<h3>{{ _('Disk space thresholds') }}</h3>
|
<h3>{{ _('Disk space thresholds') }}</h3>
|
||||||
|
|
||||||
<p>{{ _('If the free disk space falls below these thresholds, OctoPrint will warn the user.') }}</p>
|
<p>{{ _('If the free disk space falls below these thresholds, OctoPrint will warn the user.') }}</p>
|
||||||
|
|||||||
@@ -4,6 +4,13 @@
|
|||||||
<p>
|
<p>
|
||||||
{{ _('If you do not wish to change your password, just leave the following fields empty.') }}
|
{{ _('If you do not wish to change your password, just leave the following fields empty.') }}
|
||||||
</p>
|
</p>
|
||||||
|
<div class="control-group" data-bind="css: {error: access_currentPasswordMismatch()}">
|
||||||
|
<label class="control-label" for="userSettings-access_currentPassword">{{ _('Current Password') }}</label>
|
||||||
|
<div class="controls">
|
||||||
|
<input type="password" class="input-block-level" id="userSettings-access_currentPassword" data-bind="value: access_currentPassword, valueUpdate: 'afterkeydown'" required>
|
||||||
|
<span class="help-inline" data-bind="visible: access_currentPasswordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="control-group">
|
<div class="control-group">
|
||||||
<label class="control-label" for="userSettings-access_password">{{ _('New Password') }}</label>
|
<label class="control-label" for="userSettings-access_password">{{ _('New Password') }}</label>
|
||||||
<div class="controls">
|
<div class="controls">
|
||||||
@@ -17,6 +24,9 @@
|
|||||||
<span class="help-inline" data-bind="visible: passwordMismatch()">{{ _('Passwords do not match') }}</span>
|
<span class="help-inline" data-bind="visible: passwordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<p>{% trans %}
|
||||||
|
Please note that you will be <strong>logged out immediately</strong> after changing your password and asked to login again.
|
||||||
|
{% endtrans %}</p>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<fieldset>
|
<fieldset>
|
||||||
<legend>{{ _('API Key') }}</legend>
|
<legend>{{ _('API Key') }}</legend>
|
||||||
|
|||||||
@@ -65,7 +65,8 @@
|
|||||||
<form class="form-signin">
|
<form class="form-signin">
|
||||||
<h2 class="form-signin-heading" data-test-id="login-title">{{ _('Please log in') }}</h2>
|
<h2 class="form-signin-heading" data-test-id="login-title">{{ _('Please log in') }}</h2>
|
||||||
|
|
||||||
<div id="login-error" class="alert alert-error" data-test-id="login-error">{{ _('Incorrect username or password. Hint: Both are case sensitive!') }}</div>
|
<div id="login-error-credentials" class="alert alert-error" data-test-id="login-error">{{ _('Incorrect username or password. Hint: Both are case sensitive!') }}</div>
|
||||||
|
<div id="login-error-rate" class="alert alert-error" data-test-id="login-error-rate">{{ _('You have made too many failed login attempts. Please try again later.') }}</div>
|
||||||
<div id="login-offline" class="alert alert-error">{{ _('Server is currently offline.') }} <a id="login-reconnect" href="javascript:void(0)">{{ _('Reconnect...') }}</a></div>
|
<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>
|
{% if user_id %}<p>
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>OctoPrint Reverse Proxy Test</title>
|
||||||
|
|
||||||
|
<link rel="shortcut icon" href="{{ url_for('static', filename='img/tentacle-32x32.png') }}">
|
||||||
|
<link rel="mask-icon" href="{{ url_for('static', filename='img/mask.svg') }}" color="#56BE37">
|
||||||
|
<link rel="mask-icon-theme" href="{{ url_for('static', filename='img/mask-theme.svg') }}" color="#56BE37">
|
||||||
|
<link rel="apple-touch-icon" sizes="114x114" href="{{ url_for('static', filename='img/apple-touch-icon-114x114.png') }}">
|
||||||
|
<link rel="apple-touch-icon" sizes="144x144" href="{{ url_for('static', filename='img/apple-touch-icon-144x144.png') }}">
|
||||||
|
|
||||||
|
<!-- le CSS -->
|
||||||
|
|
||||||
|
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.min.css") }}">
|
||||||
|
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap-responsive.min.css") }}">
|
||||||
|
<link rel="stylesheet" href="{{ url_for("static", filename="vendor/font-awesome-5.15.1/css/all.min.css") }}">
|
||||||
|
<link rel="stylesheet" href="{{ url_for("static", filename="vendor/font-awesome-5.15.1/css/v4-shims.min") }}">
|
||||||
|
|
||||||
|
{% for url in theming %}
|
||||||
|
<link rel="stylesheet" href="{{ url }}">
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
<!-- le javascript -->
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var BASE_URL = "{{ url_for('index') }}";
|
||||||
|
|
||||||
|
var CLIENT_IP = "{{ client_ip }}";
|
||||||
|
var SERVER_PROTOCOL = "{{ server_protocol }}";
|
||||||
|
var SERVER_NAME = "{{ server_name }}";
|
||||||
|
var SERVER_PORT = {{ server_port }};
|
||||||
|
var SERVER_PATH = "{{ server_path }}";
|
||||||
|
var COOKIE_SUFFIX = "{{ cookie_suffix }}";
|
||||||
|
</script>
|
||||||
|
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
|
||||||
|
<script src="{{ url_for("static", filename="js/lib/knockout.js") }}"></script>
|
||||||
|
<script src="{{ url_for("static", filename="js/lib/bootstrap/bootstrap.js") }}"></script>
|
||||||
|
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
|
||||||
|
<script src="{{ url_for("static", filename="js/lib/sprintf.min.js") }}"></script>
|
||||||
|
|
||||||
|
{% assets "js_client" %}
|
||||||
|
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||||
|
{% endassets %}
|
||||||
|
|
||||||
|
<script src="{{ url_for("static", filename="js/app/helpers.js") }}"></script>
|
||||||
|
<script src="{{ url_for("static", filename="js/reverse_proxy_test/reverse_proxy_test.js") }}"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="navbar" class="navbar navbar-inverse navbar-static-top">
|
||||||
|
<div class="navbar-inner">
|
||||||
|
<span class="brand">OctoPrint Reverse Proxy Test</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="reverse_proxy_test" class="container" style="padding-top: 1em">
|
||||||
|
<div class="alert alert-error" data-bind="visible: !cookieSuffixMatch">
|
||||||
|
<strong>Warning!</strong> The used cookie suffix doesn't match between client and server. That means that OctoPrint's
|
||||||
|
UI won't work properly. Please check your configuration and fix it.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
This page helps you identify issues in your reverse proxy configuration. It will show you information about
|
||||||
|
some of the variables that OctoPrint uses to set cookies and generate fully qualified URLs. If you see
|
||||||
|
any mismatches highlighted in red below, that means that something is not configured properly and you
|
||||||
|
need to fix it.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
The table also shows you the client IP that your server saw you as. Make sure that this client IP is what
|
||||||
|
OctoPrint should be seeing, and not for example your reverse proxy itself.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
For each variable, information is displayed what influences the value the server sees and thus where to
|
||||||
|
start debugging in case of any observed mismatches.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table class="table table-bordered table-hover">
|
||||||
|
<thead>
|
||||||
|
<th>Variable</th>
|
||||||
|
<th>Source</th>
|
||||||
|
<th>Client</th>
|
||||||
|
<th>Server</th>
|
||||||
|
</thead>
|
||||||
|
<tr>
|
||||||
|
<td>Client IP</td>
|
||||||
|
<td><code>X-Forwarded-For</code></td>
|
||||||
|
<td>-</td>
|
||||||
|
<td>{{ client_ip }}</td>
|
||||||
|
</tr>
|
||||||
|
<tr data-bind="css: { success: serverProtocolMatch, error: !serverProtocolMatch }">
|
||||||
|
<td>Protocol</td>
|
||||||
|
<td><code>X-Forwarded-Protocol</code>, <code>X-Scheme</code> or config</td>
|
||||||
|
<td data-bind="text: serverProtocol"></td>
|
||||||
|
<td>{{ server_protocol }}</td>
|
||||||
|
</tr>
|
||||||
|
<tr data-bind="css: { success: serverNameMatch, error: !serverNameMatch }">
|
||||||
|
<td>Host</td>
|
||||||
|
<td><code>X-Forwarded-Host</code>, <code>Host</code>, <code>X-Forwarded-Server</code> or config</td>
|
||||||
|
<td data-bind="text: serverName"></td>
|
||||||
|
<td>{{ server_name }}</td>
|
||||||
|
</tr>
|
||||||
|
<tr data-bind="css: { success: serverPortMatch, error: !serverPortMatch }">
|
||||||
|
<td>Port</td>
|
||||||
|
<td><code>X-Forwarded-Host</code>, <code>Host</code>, <code>X-Forwarded-Port</code>, <code>X-Forwarded-Protocol</code>, <code>X-Scheme</code> or config</td>
|
||||||
|
<td data-bind="text: serverPort"></td>
|
||||||
|
<td>{{ server_port }}</td>
|
||||||
|
</tr>
|
||||||
|
<tr data-bind="css: { success: serverPathMatch, error: !serverPathMatch }">
|
||||||
|
<td>Path</td>
|
||||||
|
<td><code>X-Script-Name</code> or config</td>
|
||||||
|
<td data-bind="text: serverPath"></td>
|
||||||
|
<td>{{ server_path }}</td>
|
||||||
|
</tr>
|
||||||
|
<tr data-bind="css: { success: cookieSuffixMatch, error: !cookieSuffixMatch }">
|
||||||
|
<td>Cookie Suffix</td>
|
||||||
|
<td>Built from port & path</td>
|
||||||
|
<td data-bind="text: cookieSuffix"></td>
|
||||||
|
<td>{{ cookie_suffix }}</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
Please refer to <a href="https://faq.octoprint.org/reverse-proxy" target="_blank" rel="noopener noreferrer">the Reverse Proxy FAQ entry</a>
|
||||||
|
for information on correct configuration and examples.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -18,7 +18,6 @@ class UserManagerTest(unittest.TestCase):
|
|||||||
"""Test for issue #1891"""
|
"""Test for issue #1891"""
|
||||||
|
|
||||||
password = "password with ümläutß"
|
password = "password with ümläutß"
|
||||||
salt = "abc"
|
|
||||||
|
|
||||||
# should not throw an exception
|
# should not throw an exception
|
||||||
octoprint.access.users.UserManager.create_password_hash(password, salt=salt)
|
octoprint.access.users.UserManager.create_password_hash(password)
|
||||||
@@ -1,4 +1,11 @@
|
|||||||
import {prepare_server, await_coreui, await_loginui, login} from "../util/util";
|
import {
|
||||||
|
prepare_server,
|
||||||
|
await_coreui,
|
||||||
|
await_loginui,
|
||||||
|
login,
|
||||||
|
get_cookie_name,
|
||||||
|
get_full_url
|
||||||
|
} from "../util/util";
|
||||||
|
|
||||||
context("Login tests", () => {
|
context("Login tests", () => {
|
||||||
const username = "admin";
|
const username = "admin";
|
||||||
@@ -13,7 +20,7 @@ context("Login tests", () => {
|
|||||||
cy.visit("/?l10n=en");
|
cy.visit("/?l10n=en");
|
||||||
await_loginui();
|
await_loginui();
|
||||||
cy.location().should((loc) => {
|
cy.location().should((loc) => {
|
||||||
expect(loc.pathname).to.eq("/login/");
|
expect(loc.pathname).to.eq(get_full_url("/login/"));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -27,8 +34,8 @@ context("Login tests", () => {
|
|||||||
await_coreui();
|
await_coreui();
|
||||||
|
|
||||||
cy.get("[data-test-id=login-menu-title]").should("contain", username);
|
cy.get("[data-test-id=login-menu-title]").should("contain", username);
|
||||||
cy.getCookie("session_P5000").should("exist");
|
cy.getCookie(get_cookie_name("session")).should("exist");
|
||||||
cy.getCookie("remember_token_P5000").should("not.exist");
|
cy.getCookie(get_cookie_name("remember_token")).should("not.exist");
|
||||||
cy.location().should((loc) => {
|
cy.location().should((loc) => {
|
||||||
expect(loc.hash).to.eq("#temp");
|
expect(loc.hash).to.eq("#temp");
|
||||||
});
|
});
|
||||||
@@ -45,8 +52,8 @@ context("Login tests", () => {
|
|||||||
await_coreui();
|
await_coreui();
|
||||||
|
|
||||||
cy.get("[data-test-id=login-menu-title]").should("contain", username);
|
cy.get("[data-test-id=login-menu-title]").should("contain", username);
|
||||||
cy.getCookie("session_P5000").should("exist");
|
cy.getCookie(get_cookie_name("session")).should("exist");
|
||||||
cy.getCookie("remember_token_P5000").should(($cookie) => {
|
cy.getCookie(get_cookie_name("remember_token")).should(($cookie) => {
|
||||||
expect($cookie).to.have.property("value");
|
expect($cookie).to.have.property("value");
|
||||||
expect($cookie.value).to.match(new RegExp("^" + username + "|"));
|
expect($cookie.value).to.match(new RegExp("^" + username + "|"));
|
||||||
});
|
});
|
||||||
@@ -71,7 +78,7 @@ context("Login tests", () => {
|
|||||||
|
|
||||||
await_loginui();
|
await_loginui();
|
||||||
cy.location().should((loc) => {
|
cy.location().should((loc) => {
|
||||||
expect(loc.pathname).to.eq("/login/");
|
expect(loc.pathname).to.eq(get_full_url("/login/"));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -81,7 +88,7 @@ context("Login tests", () => {
|
|||||||
cy.visit("/?l10n=en");
|
cy.visit("/?l10n=en");
|
||||||
await_loginui();
|
await_loginui();
|
||||||
cy.location().should((loc) => {
|
cy.location().should((loc) => {
|
||||||
expect(loc.pathname).to.eq("/login/");
|
expect(loc.pathname).to.eq(get_full_url("/login/"));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Generated
+9
-6
@@ -1237,9 +1237,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/minimist": {
|
"node_modules/minimist": {
|
||||||
"version": "1.2.5",
|
"version": "1.2.7",
|
||||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
|
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz",
|
||||||
"integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw=="
|
"integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"node_modules/ms": {
|
"node_modules/ms": {
|
||||||
"version": "2.1.2",
|
"version": "2.1.2",
|
||||||
@@ -2602,9 +2605,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"minimist": {
|
"minimist": {
|
||||||
"version": "1.2.5",
|
"version": "1.2.7",
|
||||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
|
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz",
|
||||||
"integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw=="
|
"integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g=="
|
||||||
},
|
},
|
||||||
"ms": {
|
"ms": {
|
||||||
"version": "2.1.2",
|
"version": "2.1.2",
|
||||||
|
|||||||
+50
-13
@@ -1,12 +1,16 @@
|
|||||||
export const prepare_server = () => {
|
export const prepare_server = () => {
|
||||||
cy.intercept("POST", "/api/login").as("login");
|
cy.intercept("POST", get_full_url("/api/login")).as("login");
|
||||||
cy.intercept("POST", "/api/logout").as("logout");
|
cy.intercept("POST", get_full_url("/api/logout")).as("logout");
|
||||||
cy.intercept("GET", "/api/settings").as("settings");
|
cy.intercept("GET", get_full_url("/api/settings")).as("settings");
|
||||||
cy.intercept("GET", "/api/files?recursive=true").as("files");
|
cy.intercept("GET", get_full_url("/api/files?recursive=true")).as("files");
|
||||||
cy.intercept("GET", "/plugin/softwareupdate/check").as("softwareupdate");
|
cy.intercept("GET", get_full_url("/plugin/softwareupdate/check")).as(
|
||||||
cy.intercept("GET", "/plugin/pluginmanager/plugins").as("pluginmanager");
|
"softwareupdate"
|
||||||
cy.intercept("POST", "/api/connection").as("connectionCommand");
|
);
|
||||||
cy.intercept("GET", "/api/connection").as("connectionDetails");
|
cy.intercept("GET", get_full_url("/plugin/pluginmanager/plugins")).as(
|
||||||
|
"pluginmanager"
|
||||||
|
);
|
||||||
|
cy.intercept("POST", get_full_url("/api/connection")).as("connectionCommand");
|
||||||
|
cy.intercept("GET", get_full_url("/api/connection")).as("connectionDetails");
|
||||||
};
|
};
|
||||||
|
|
||||||
export const await_loginui = () => {
|
export const await_loginui = () => {
|
||||||
@@ -24,7 +28,7 @@ export const await_coreui = () => {
|
|||||||
export const login = (username, password) => {
|
export const login = (username, password) => {
|
||||||
cy.request({
|
cy.request({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
url: "/api/login",
|
url: get_full_url("/api/login"),
|
||||||
body: {
|
body: {
|
||||||
user: username,
|
user: username,
|
||||||
pass: password
|
pass: password
|
||||||
@@ -35,7 +39,7 @@ export const login = (username, password) => {
|
|||||||
export const logout = () => {
|
export const logout = () => {
|
||||||
cy.request({
|
cy.request({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
url: "/api/logout"
|
url: get_full_url("/api/logout")
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -44,7 +48,7 @@ export const connect = (port, baudrate) => {
|
|||||||
baudrate = baudrate || 0;
|
baudrate = baudrate || 0;
|
||||||
cy.request({
|
cy.request({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
url: "/api/connection",
|
url: get_full_url("/api/connection"),
|
||||||
body: {
|
body: {
|
||||||
command: "connect",
|
command: "connect",
|
||||||
port: port,
|
port: port,
|
||||||
@@ -56,7 +60,7 @@ export const connect = (port, baudrate) => {
|
|||||||
export const disconnect = () => {
|
export const disconnect = () => {
|
||||||
cy.request({
|
cy.request({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
url: "/api/connection",
|
url: get_full_url("/api/connection"),
|
||||||
body: {
|
body: {
|
||||||
command: "disconnect"
|
command: "disconnect"
|
||||||
}
|
}
|
||||||
@@ -66,7 +70,40 @@ export const disconnect = () => {
|
|||||||
export const ensure_file_unknown = (location, name) => {
|
export const ensure_file_unknown = (location, name) => {
|
||||||
cy.request({
|
cy.request({
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
url: `/api/files/${location}/${name}`,
|
url: get_full_url(`/api/files/${location}/${name}`),
|
||||||
failOnStatusCode: false
|
failOnStatusCode: false
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const get_cookie_name = (cookie) => {
|
||||||
|
const url = new URL(Cypress.config("baseUrl"));
|
||||||
|
const port = url.port || (url.protocol === "https:" ? 443 : 80);
|
||||||
|
if (url.pathname && url.pathname !== "/") {
|
||||||
|
let path = url.pathname;
|
||||||
|
if (path.endsWith("/")) {
|
||||||
|
path = path.substring(0, path.length - 1);
|
||||||
|
}
|
||||||
|
return `${cookie}_P${port}_R${path.replace(/\//, "|")}`;
|
||||||
|
} else {
|
||||||
|
return `${cookie}_P${port}`;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const get_full_url = (url) => {
|
||||||
|
const parsed = new URL(Cypress.config("baseUrl"));
|
||||||
|
|
||||||
|
let path = "";
|
||||||
|
if (parsed.pathname) {
|
||||||
|
path = parsed.pathname;
|
||||||
|
}
|
||||||
|
if (path.endsWith("/")) {
|
||||||
|
path = path.substring(0, path.length - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let url2 = url;
|
||||||
|
if (url2.startsWith("/")) {
|
||||||
|
url2 = url2.substring(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return path + "/" + url2;
|
||||||
|
};
|
||||||
@@ -10,6 +10,7 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms
|
|||||||
import unittest
|
import unittest
|
||||||
from unittest import mock
|
from unittest import mock
|
||||||
|
|
||||||
|
import flask
|
||||||
from ddt import data, ddt, unpack
|
from ddt import data, ddt, unpack
|
||||||
|
|
||||||
from octoprint.server.util.flask import (
|
from octoprint.server.util.flask import (
|
||||||
@@ -424,6 +425,9 @@ class OctoPrintFlaskRequestTest(unittest.TestCase):
|
|||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.orig_environment_wrapper = OctoPrintFlaskRequest.environment_wrapper
|
self.orig_environment_wrapper = OctoPrintFlaskRequest.environment_wrapper
|
||||||
|
|
||||||
|
self.app = flask.Flask("testapp")
|
||||||
|
self.app.config["SECRET_KEY"] = "secret"
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
OctoPrintFlaskRequest.environment_wrapper = staticmethod(
|
OctoPrintFlaskRequest.environment_wrapper = staticmethod(
|
||||||
self.orig_environment_wrapper
|
self.orig_environment_wrapper
|
||||||
@@ -470,7 +474,8 @@ class OctoPrintFlaskRequestTest(unittest.TestCase):
|
|||||||
|
|
||||||
request = OctoPrintFlaskRequest(environ)
|
request = OctoPrintFlaskRequest(environ)
|
||||||
|
|
||||||
cookies = request.cookies
|
with self.app.app_context():
|
||||||
|
cookies = request.cookies
|
||||||
self.assertDictEqual(
|
self.assertDictEqual(
|
||||||
{
|
{
|
||||||
"postfixed": "postfixed_value",
|
"postfixed": "postfixed_value",
|
||||||
@@ -495,6 +500,9 @@ class OctoPrintFlaskResponseTest(unittest.TestCase):
|
|||||||
self.settings = mock.MagicMock()
|
self.settings = mock.MagicMock()
|
||||||
self.settings_getter.return_value = self.settings
|
self.settings_getter.return_value = self.settings
|
||||||
|
|
||||||
|
self.app = flask.Flask("testapp")
|
||||||
|
self.app.config["SECRET_KEY"] = "secret"
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
self.settings_patcher.stop()
|
self.settings_patcher.stop()
|
||||||
|
|
||||||
@@ -545,13 +553,14 @@ class OctoPrintFlaskResponseTest(unittest.TestCase):
|
|||||||
|
|
||||||
# test set_cookie
|
# test set_cookie
|
||||||
with mock.patch("flask.Response.set_cookie") as set_cookie_mock:
|
with mock.patch("flask.Response.set_cookie") as set_cookie_mock:
|
||||||
response.set_cookie("some_key", "some_value", **kwargs)
|
with self.app.app_context():
|
||||||
|
response.set_cookie("some_key", "some_value", **kwargs)
|
||||||
|
|
||||||
# set_cookie should have key and path values adjusted
|
# set_cookie should have key and path values adjusted
|
||||||
set_cookie_mock.assert_called_once_with(
|
set_cookie_mock.assert_called_once_with(
|
||||||
response,
|
response,
|
||||||
"some_key" + expected_suffix,
|
"some_key" + expected_suffix,
|
||||||
"some_value",
|
value="some_value",
|
||||||
path=expected_path_set,
|
path=expected_path_set,
|
||||||
secure=secure,
|
secure=secure,
|
||||||
samesite=expected_samesite,
|
samesite=expected_samesite,
|
||||||
@@ -560,7 +569,8 @@ class OctoPrintFlaskResponseTest(unittest.TestCase):
|
|||||||
# test delete_cookie
|
# test delete_cookie
|
||||||
with mock.patch("flask.Response.set_cookie") as set_cookie_mock:
|
with mock.patch("flask.Response.set_cookie") as set_cookie_mock:
|
||||||
with mock.patch("flask.Response.delete_cookie") as delete_cookie_mock:
|
with mock.patch("flask.Response.delete_cookie") as delete_cookie_mock:
|
||||||
response.delete_cookie("some_key", **kwargs)
|
with self.app.app_context():
|
||||||
|
response.delete_cookie("some_key", **kwargs)
|
||||||
|
|
||||||
# delete_cookie internally calls set_cookie - so our delete_cookie call still uses the non modified
|
# delete_cookie internally calls set_cookie - so our delete_cookie call still uses the non modified
|
||||||
# key and path values, set_cookie will translate those (as tested above)
|
# key and path values, set_cookie will translate those (as tested above)
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<title>src/octoprint/static/js/app/client/base.js Tests</title>
|
||||||
|
<link rel="stylesheet" href="lib/qunit-1.18.0.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="qunit"></div>
|
||||||
|
<div id="qunit-fixture"></div>
|
||||||
|
<script src="lib/qunit-1.18.0.js"></script>
|
||||||
|
<script src="lib/qunit-parameterize.js"></script>
|
||||||
|
<script src="../../../src/octoprint/static/js/lib/lodash.min.js"></script>
|
||||||
|
<script src="../../../src/octoprint/static/js/lib/sprintf.min.js"></script>
|
||||||
|
<script src="../../../src/octoprint/static/js/app/client/base.js"></script>
|
||||||
|
<script src="test-client-base.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
_.mixin({sprintf: sprintf, vsprintf: vsprintf});
|
||||||
|
|
||||||
|
QUnit.module("getParsedBaseUrl");
|
||||||
|
QUnit.cases(
|
||||||
|
(function () {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
title: "fully qualified baseurl",
|
||||||
|
baseurl: "https://example.com",
|
||||||
|
location: undefined,
|
||||||
|
expected: "https://example.com/"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "fully qualified baseurl with http",
|
||||||
|
baseurl: "http://example.com",
|
||||||
|
location: undefined,
|
||||||
|
expected: "http://example.com/"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "fully qualified baseurl with custom port",
|
||||||
|
baseurl: "https://example.com:5000",
|
||||||
|
location: undefined,
|
||||||
|
expected: "https://example.com:5000/"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "website root",
|
||||||
|
baseurl: "/",
|
||||||
|
location: "https://example.com",
|
||||||
|
expected: "https://example.com/"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "website root with custom port",
|
||||||
|
baseurl: "/",
|
||||||
|
location: "https://example.com:5000",
|
||||||
|
expected: "https://example.com:5000/"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "single level prefix",
|
||||||
|
baseurl: "/octoprint/",
|
||||||
|
location: "https://example.com",
|
||||||
|
expected: "https://example.com/octoprint/"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "multi level prefix",
|
||||||
|
baseurl: "/path/to/octoprint/",
|
||||||
|
location: "https://example.com",
|
||||||
|
expected: "https://example.com/path/to/octoprint/"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "multi level prefix with http and custom port",
|
||||||
|
baseurl: "/path/to/octoprint/",
|
||||||
|
location: "http://example.com:5000",
|
||||||
|
expected: "http://example.com:5000/path/to/octoprint/"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "multi level prefix with https, custom port, no trailing slash",
|
||||||
|
baseurl: "/path/to/octoprint",
|
||||||
|
location: "https://example.com:5001",
|
||||||
|
expected: "https://example.com:5001/path/to/octoprint"
|
||||||
|
}
|
||||||
|
];
|
||||||
|
})()
|
||||||
|
).test("getParsedBaseUrl", function (params, assert) {
|
||||||
|
OctoPrint.options.baseurl = params.baseurl;
|
||||||
|
assert.equal(
|
||||||
|
OctoPrint.getParsedBaseUrl(params.location).toString(),
|
||||||
|
params.expected,
|
||||||
|
"Expected: " + String(params.expected)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
QUnit.module("getCookieSuffix");
|
||||||
|
QUnit.cases(
|
||||||
|
(function () {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
title: "http with default port",
|
||||||
|
baseurl: "http://example.com",
|
||||||
|
expected: "_P80"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "https with default port",
|
||||||
|
baseurl: "https://example.com",
|
||||||
|
expected: "_P443"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "custom port",
|
||||||
|
baseurl: "http://example.com:5000",
|
||||||
|
expected: "_P5000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "single level prefix",
|
||||||
|
baseurl: "https://example.com/octoprint/",
|
||||||
|
expected: "_P443_R|octoprint"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "multi level prefix",
|
||||||
|
baseurl: "https://example.com/path/to/octoprint",
|
||||||
|
expected: "_P443_R|path|to|octoprint"
|
||||||
|
}
|
||||||
|
];
|
||||||
|
})()
|
||||||
|
).test("getCookieSuffix", function (params, assert) {
|
||||||
|
OctoPrint.options.baseurl = params.baseurl;
|
||||||
|
assert.equal(
|
||||||
|
OctoPrint.getCookieSuffix(),
|
||||||
|
params.expected,
|
||||||
|
"Expected: " + String(params.expected)
|
||||||
|
);
|
||||||
|
});
|
||||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
+597
-578
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user