]> git.aero2k.de Git - sirius.git/commitdiff
Add Chromium renderer, password change and Pi deployment
authorThorsten <mail@aero2k.de>
Fri, 27 Nov 2026 09:22:25 +0000 (10:22 +0100)
committerThorsten <mail@aero2k.de>
Fri, 27 Nov 2026 09:22:25 +0000 (10:22 +0100)
- renderer/: headless Chromium in its own container replaces PhantomJS
  for HTML prints, with network access limited to public addresses
- Local login: change password page, forced change on first login,
  reset_password management command
- deploy/pi/: setup script, systemd user units and guide for running
  sirius on a Raspberry Pi with rootless podman

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
33 files changed:
.dockerignore
Dockerfile
README.md
deploy/pi/README.md [new file with mode: 0644]
deploy/pi/setup.sh [new file with mode: 0644]
deploy/pi/sirius-db.service [new file with mode: 0644]
deploy/pi/sirius-renderer.service [new file with mode: 0644]
deploy/pi/sirius.service [new file with mode: 0644]
docker-compose.yml
manage.py
migrations/versions/7c1e4f2a9b30_add_local_password.py [new file with mode: 0644]
pyproject.toml
renderer/Dockerfile [new file with mode: 0644]
renderer/README.md [new file with mode: 0644]
renderer/server.py [new file with mode: 0644]
renderer/test_server.py [new file with mode: 0644]
sirius/coding/image_encoding.py
sirius/coding/snapshots/snap_test_image_coding_snapshots/ImageCodingSnapshotCase::test_snapshot_fixtures hello_world.png
sirius/coding/snapshots/snap_test_image_coding_snapshots/ImageCodingSnapshotCase::test_snapshot_template_fixtures hello_world.png
sirius/config.py
sirius/models/user.py
sirius/web/local_login.py
sirius/web/templates/base.html
sirius/web/templates/change_password.html [new file with mode: 0644]
sirius/web/test_local_login.py
tests/browser/README.md
tests/browser/compose.spec.js
tests/browser/helpers.js
tests/browser/password.spec.js [new file with mode: 0644]
tests/browser/playwright.config.js
tests/browser/run-server.sh
tests/browser/server.py
tests/browser/teardown.js

index 5c68a991002793067887daa5244779c0e7ef379f..a1d55a738af27b7e5da36c9e9648a9d695ecac62 100644 (file)
@@ -3,3 +3,4 @@ notes
 docker-compose*
 *.md
 **/node_modules
+renderer
index f252726112c87ff7ac0e75992175b53ab0e1e200..28e5ad78dcba2f150be53519648214b91ebee12c 100644 (file)
@@ -15,25 +15,15 @@ RUN apt-get update -y && \
   python3-dev \
   python3-pip \
   libfreetype6-dev \
-  libgstreamer1.0-dev \
   libjpeg-dev \
   libpq-dev \
   zlib1g-dev \
-  bzip2 \
-  fontconfig \
   gcc \
-  phantomjs \
-  wget \
   postgresql-11 \
   git
 
 RUN apt-get autoremove -y
 
-RUN wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
-RUN tar jxf phantomjs-2.1.1-linux-x86_64.tar.bz2 && \
-  rm phantomjs-2.1.1-linux-x86_64.tar.bz2 && \
-  mv phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin/phantomjs
-
 RUN pip install --upgrade pip setuptools wheel
 ADD ./pyproject.toml /sirius/pyproject.toml
 RUN pip install --no-cache-dir .[test]
index bf81150da98e7a79040d0e65d6fb46cecafd5ceb..ce2644ad1f5405d93cc7d880de54fe2e77b7902c 100644 (file)
--- a/README.md
+++ b/README.md
@@ -63,13 +63,18 @@ TWITTER_OAUTH_CLIENT_SECRET=...
 OAUTH_REDIRECT_URI=...
 LOCAL_LOGIN_USERNAME=...
 LOCAL_LOGIN_PASSWORD_HASH=...
+LOCAL_LOGIN_REQUIRE_PASSWORD_CHANGE=...
 FLASK_CONFIG=...
 DATABASE_URL=...
 ```
 
 Setting both `LOCAL_LOGIN_*` variables enables a single local account at
-`/login/local`, replacing the Twitter button on the landing page. Generate the
-hash with:
+`/login/local`, replacing the Twitter button on the landing page. The hash is
+for the initial password. The account can choose its own under "Change
+password", which is kept in the database and replaces the initial one. Setting
+`LOCAL_LOGIN_REQUIRE_PASSWORD_CHANGE` makes that the first thing to do after
+signing in, and `python manage.py reset_password` goes back to the initial
+password when the other one is forgotten. Generate the hash with:
 
 ```sh
 python -c "from getpass import getpass; from werkzeug.security import generate_password_hash as g; print(g(getpass()))"
diff --git a/deploy/pi/README.md b/deploy/pi/README.md
new file mode 100644 (file)
index 0000000..99e6477
--- /dev/null
@@ -0,0 +1,103 @@
+# Running sirius on a Raspberry Pi
+
+This runs sirius, its Postgres and the HTML renderer as rootless podman
+containers, started by systemd as services of one user. The web UI and the
+bridge's websocket are on port 8016, plain HTTP, so keep it on your LAN.
+
+Tested on a Pi 3 with 1 GB RAM running Debian 12 (podman 4.3). It builds,
+passes the test suite and survives a reboot. A Pi 4 or 5 will be faster. The
+first HTML print after a start takes about 15 s on the Pi 3, later ones 2 s.
+
+## Before you start
+
+These need root, once:
+
+```bash
+# Without the recommended packages podman lacks networking helpers
+sudo apt install podman iptables
+# Keep the services running when you are not logged in
+sudo loginctl enable-linger $USER
+```
+
+Raspberry Pi kernels have the memory cgroup off, and the renderer needs it for
+its memory limit. Add `cgroup_enable=memory` to the end of the single line in
+`/boot/firmware/cmdline.txt` and reboot. `cat /sys/fs/cgroup/cgroup.controllers`
+should then list `memory`.
+
+If `podman info --format '{{.Store.GraphDriverName}}'` says `vfs`, switch to
+overlay before building, or the images fill the SD card:
+
+```bash
+mkdir -p ~/.config/containers
+printf '[storage]\ndriver = "overlay"\n' > ~/.config/containers/storage.conf
+podman system reset
+```
+
+Give the Pi a fixed address, for example a DHCP reservation on your router.
+The bridge is configured with it.
+
+## Install
+
+```bash
+git clone https://git.aero2k.de/git/sirius.git ~/sirius
+bash ~/sirius/deploy/pi/setup.sh <login name>
+```
+
+The first build takes about 50 minutes on a Pi 3. The script creates
+`~/.config/sirius/env` with fresh secrets and prints where it put the initial
+password. Open `http://<pi address>:8016/`, sign in, and you are asked to choose
+your own password. After that you can delete `~/.config/sirius/initial-password`.
+
+If you forget your password, go back to the initial one:
+
+```bash
+podman exec sirius python manage.py reset_password
+```
+
+## Connect the bridge
+
+On the bridge, set the endpoint to the Pi and restart it:
+
+```bash
+mount -o remount,rw /
+echo 'http://<pi address>:8016/' > /usr/local/bergcloud-bridge/endpoint.override
+reboot
+```
+
+The bridge needs the port written out, and it needs to be on a cable. Then
+claim the printer in the web UI with a claim code: reset the printer with a
+paperclip, then press its button.
+
+## Everyday use
+
+```bash
+systemctl --user status sirius sirius-db sirius-renderer
+journalctl --user -u sirius -f
+```
+
+To update, get the new code and run the setup script again. It keeps your
+settings and data:
+
+```bash
+cd ~/sirius && git pull && bash deploy/pi/setup.sh
+```
+
+## Backups
+
+The database lives in the podman volume `sirius-db`. It holds your login,
+the printer claim and print keys. To back it up and restore it:
+
+```bash
+podman exec sirius-db pg_dump -U sirius sirius > sirius-backup.sql
+```
+
+```bash
+systemctl --user stop sirius
+podman exec sirius-db dropdb -U sirius sirius
+podman exec sirius-db createdb -U sirius sirius
+podman exec -i sirius-db psql -q -U sirius sirius < sirius-backup.sql > /dev/null
+systemctl --user start sirius
+```
+
+Keep `~/.config/sirius/env` with the backup: it holds the secret key and the
+database password.
diff --git a/deploy/pi/setup.sh b/deploy/pi/setup.sh
new file mode 100644 (file)
index 0000000..1f460a0
--- /dev/null
@@ -0,0 +1,59 @@
+#!/bin/bash
+# Installs sirius as podman user services for the current user. Run it as that
+# user, from anywhere: bash deploy/pi/setup.sh [login name]
+# Running it again rebuilds the images and restarts, and keeps the settings.
+set -euo pipefail
+
+repo=$(cd "$(dirname "$0")/../.." && pwd)
+login=${1:-admin}
+conf=$HOME/.config/sirius
+units=$HOME/.config/systemd/user
+
+if [ "$(loginctl show-user "$USER" --property=Linger --value)" != yes ]; then
+  echo "Run 'sudo loginctl enable-linger $USER' first, or the services stop when you log out." >&2
+  exit 1
+fi
+if ! grep -qw memory /sys/fs/cgroup/cgroup.controllers; then
+  echo "The memory cgroup is off, so the renderer can not be limited to 1 GB." >&2
+  echo "Add cgroup_enable=memory to /boot/firmware/cmdline.txt and reboot." >&2
+  exit 1
+fi
+
+echo "Building images, this takes a while the first time"
+podman build -t localhost/sirius:latest "$repo"
+podman build -t localhost/sirius-renderer:latest "$repo/renderer"
+podman pull docker.io/library/postgres:16-alpine
+
+for network in sirius sirius-renderer; do
+  podman network exists "$network" || podman network create "$network"
+done
+
+if [ ! -f "$conf/env" ]; then
+  mkdir -p "$conf"
+  umask 077
+  secret() { python3 -c 'import secrets; print(secrets.token_urlsafe(16))'; }
+  password=$(secret)
+  db_password=$(secret)
+  hash=$(echo "$password" | podman run --rm -i localhost/sirius:latest python -c \
+    'import sys; from werkzeug.security import generate_password_hash; print(generate_password_hash(sys.stdin.readline().strip()))')
+  cat > "$conf/env" <<EOF
+FLASK_CONFIG=production
+SECRET_KEY=$(secret)
+DATABASE_URL=postgresql://sirius:$db_password@sirius-db/sirius
+POSTGRES_USER=sirius
+POSTGRES_DB=sirius
+POSTGRES_PASSWORD=$db_password
+LOCAL_LOGIN_USERNAME=$login
+LOCAL_LOGIN_PASSWORD_HASH=$hash
+LOCAL_LOGIN_REQUIRE_PASSWORD_CHANGE=1
+EOF
+  echo "$password" > "$conf/initial-password"
+  echo "Sign in as '$login' with the password in $conf/initial-password"
+fi
+
+mkdir -p "$units"
+cp "$repo"/deploy/pi/*.service "$units/"
+systemctl --user daemon-reload
+systemctl --user enable sirius-db sirius-renderer sirius
+systemctl --user restart sirius-db sirius-renderer sirius
+echo "Sirius is starting on port 8016"
diff --git a/deploy/pi/sirius-db.service b/deploy/pi/sirius-db.service
new file mode 100644 (file)
index 0000000..b3cc593
--- /dev/null
@@ -0,0 +1,25 @@
+# Postgres for sirius, as a rootless podman user service.
+# The data lives in the podman volume "sirius-db".
+
+[Unit]
+Description=Sirius Postgres
+
+[Service]
+Environment=PODMAN_SYSTEMD_UNIT=%n
+Restart=always
+RestartSec=5
+TimeoutStopSec=70
+ExecStartPre=/bin/rm -f %t/%n.ctr-id
+ExecStart=/usr/bin/podman run --cidfile=%t/%n.ctr-id --cgroups=no-conmon --rm \
+  --sdnotify=conmon --replace -d --name sirius-db \
+  --env-file %h/.config/sirius/env \
+  --volume sirius-db:/var/lib/postgresql/data \
+  --network sirius \
+  docker.io/library/postgres:16-alpine
+ExecStop=/usr/bin/podman stop --ignore -t 10 --cidfile=%t/%n.ctr-id
+ExecStopPost=/usr/bin/podman rm -f --ignore -t 10 --cidfile=%t/%n.ctr-id
+Type=notify
+NotifyAccess=all
+
+[Install]
+WantedBy=default.target
diff --git a/deploy/pi/sirius-renderer.service b/deploy/pi/sirius-renderer.service
new file mode 100644 (file)
index 0000000..21be5ea
--- /dev/null
@@ -0,0 +1,26 @@
+# Turns HTML prints into images. Prints can contain anything, so this has no
+# secrets, is not on the database network, and can not write anywhere but /tmp.
+
+[Unit]
+Description=Sirius renderer (headless Chromium)
+
+[Service]
+Environment=PODMAN_SYSTEMD_UNIT=%n
+Restart=always
+RestartSec=5
+TimeoutStopSec=70
+ExecStartPre=/bin/rm -f %t/%n.ctr-id
+ExecStart=/usr/bin/podman run --cidfile=%t/%n.ctr-id --cgroups=no-conmon --rm \
+  --sdnotify=conmon --replace -d --name sirius-renderer \
+  --user 65534 --env HOME=/tmp --read-only --tmpfs /tmp \
+  --cap-drop all --security-opt no-new-privileges \
+  --memory 1g --pids-limit 256 \
+  --network sirius-renderer \
+  localhost/sirius-renderer:latest
+ExecStop=/usr/bin/podman stop --ignore -t 10 --cidfile=%t/%n.ctr-id
+ExecStopPost=/usr/bin/podman rm -f --ignore -t 10 --cidfile=%t/%n.ctr-id
+Type=notify
+NotifyAccess=all
+
+[Install]
+WantedBy=default.target
diff --git a/deploy/pi/sirius.service b/deploy/pi/sirius.service
new file mode 100644 (file)
index 0000000..fe67803
--- /dev/null
@@ -0,0 +1,29 @@
+# The sirius web app. It serves the web UI and the bridge's websocket on
+# port 8016 of the Pi.
+
+[Unit]
+Description=Sirius (Little Printer backend)
+Requires=sirius-db.service sirius-renderer.service
+After=sirius-db.service sirius-renderer.service
+
+[Service]
+Environment=PODMAN_SYSTEMD_UNIT=%n
+# Fails until Postgres accepts connections, so retry
+Restart=on-failure
+RestartSec=5
+TimeoutStopSec=70
+ExecStartPre=/bin/rm -f %t/%n.ctr-id
+# Applies migrations, then honcho runs the Procfile (gunicorn on :5000)
+ExecStart=/usr/bin/podman run --cidfile=%t/%n.ctr-id --cgroups=no-conmon --rm \
+  --sdnotify=conmon --replace -d --name sirius \
+  --env-file %h/.config/sirius/env \
+  --publish 8016:5000 \
+  --network sirius --network sirius-renderer \
+  localhost/sirius:latest bash bin/docker-entrypoint.sh
+ExecStop=/usr/bin/podman stop --ignore -t 10 --cidfile=%t/%n.ctr-id
+ExecStopPost=/usr/bin/podman rm -f --ignore -t 10 --cidfile=%t/%n.ctr-id
+Type=notify
+NotifyAccess=all
+
+[Install]
+WantedBy=default.target
index fb324831e12049ecf3c22cea8254a313943c4459..469af211f04d8d8df13714f8ed5a3fee696b44c1 100644 (file)
@@ -7,9 +7,12 @@ services:
       dockerfile: ./Dockerfile
     depends_on:
       - sirius-web
+      - sirius-renderer
     command: "bin/wait-for-it.sh sirius-database:5432 -- bin/docker-entrypoint.sh"
-    environment:
-      - OPENSSL_CONF=/etc/ssl/
+
+  sirius-renderer:
+    build:
+      context: ./renderer
 
   sirius-web:
     image: jwilder/nginx-proxy
index 00d5cc1361c6be0e7615cb785e0bb7ba95d70aa5..3b418128c5fe3028477c8aa0ae4334a25f4d3243 100755 (executable)
--- a/manage.py
+++ b/manage.py
@@ -40,6 +40,14 @@ def deploy():
        upgrade()
 
 
+@manager.command
+def reset_password():
+       """Put the local account back on the initial password from the environment."""
+       from sirius.web import local_login
+
+       print('Done.' if local_login.reset_password() else 'That account has not signed in yet.')
+
+
 if __name__ == '__main__':
     manager.run()
 
diff --git a/migrations/versions/7c1e4f2a9b30_add_local_password.py b/migrations/versions/7c1e4f2a9b30_add_local_password.py
new file mode 100644 (file)
index 0000000..786bc96
--- /dev/null
@@ -0,0 +1,22 @@
+"""add local password
+
+Revision ID: 7c1e4f2a9b30
+Revises: 89a031bd9657
+Create Date: 2026-11-07 01:30:00.000000
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = "7c1e4f2a9b30"
+down_revision = "89a031bd9657"
+
+from alembic import op
+import sqlalchemy as sa
+
+
+def upgrade():
+    op.add_column("user", sa.Column("password_hash", sa.String(), nullable=True))
+
+
+def downgrade():
+    op.drop_column("user", "password_hash")
index fbc91077d560fdba3477631cf0c8d9b4776e1f15..df8c97c54c0d990430ddabc4396424794d3c71d2 100644 (file)
@@ -19,7 +19,7 @@ dependencies = [
     "Jinja2==2.10.1",
     "Mako==1.1.0",
     "MarkupSafe==1.1.1",
-    "Pillow==6.1.0",
+    "Pillow==9.5.0",
     "SQLAlchemy==1.3.8",
     "WTForms==2.2.1",
     "Werkzeug==0.15.6",
@@ -40,7 +40,6 @@ dependencies = [
     "redis==3.3.8",
     "requests==2.22.0",
     "requests-oauthlib==1.3.1",
-    "selenium==3.141.0",
     "six==1.12.0",
     "twitter==1.18.0",
     "websocket-client==0.56.0",
diff --git a/renderer/Dockerfile b/renderer/Dockerfile
new file mode 100644 (file)
index 0000000..f80c863
--- /dev/null
@@ -0,0 +1,19 @@
+FROM python:3.13-slim
+
+WORKDIR /renderer
+
+# Pillow is only for the tests
+RUN pip install --no-cache-dir playwright==1.55.0 httpx==0.28.1 pillow==11.3.0
+
+# Browsers go where the read-only container can still reach them
+ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
+RUN playwright install --with-deps --only-shell chromium
+
+# Helvetica and Arial in prints come out as Liberation Sans, which has their metrics
+RUN apt-get install -y --no-install-recommends fontconfig fonts-liberation fonts-dejavu-core fonts-noto-color-emoji
+
+ADD . .
+
+EXPOSE 8000
+
+CMD ["python", "server.py"]
diff --git a/renderer/README.md b/renderer/README.md
new file mode 100644 (file)
index 0000000..03a65e8
--- /dev/null
@@ -0,0 +1,15 @@
+# Renderer
+
+Turns the HTML of a print into a PNG, 384 pixels wide, with headless Chromium.
+`POST /render` takes the HTML as the body.
+
+Prints can contain anything that someone with a print key sends, including
+scripts, so this runs apart from the app: a container of its own that has no
+secrets and can't reach the database. Inside, Chromium has no network at all.
+Its requests go through `fetch_for_page`, which only lets through addresses on
+the public internet, so scripts and images from other sites keep working.
+
+```sh
+podman build -t localhost/sirius-renderer:latest .
+podman run --rm localhost/sirius-renderer:latest python -m unittest
+```
diff --git a/renderer/server.py b/renderer/server.py
new file mode 100644 (file)
index 0000000..5e5ee59
--- /dev/null
@@ -0,0 +1,163 @@
+import http.server
+import ipaddress
+import socket
+import urllib.parse
+
+import httpx
+from playwright.sync_api import Error as PlaywrightError
+from playwright.sync_api import sync_playwright
+
+
+PORT = 8000
+WIDTH = 384
+MAX_HTML_BYTES = 64 * 1024 * 1024
+MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024
+RENDER_TIMEOUT_MS = 20000
+FETCH_TIMEOUT_SECONDS = 8
+# Nothing listens here. Requests that get past the route handler don't get anywhere.
+NOWHERE = "http://127.0.0.1:9"
+CHROMIUM_ARGS = ["--force-webrtc-ip-handling-policy=disable_non_proxied_udp"]
+# Not passed on, because httpx has decoded the body and reads it into memory.
+DROPPED_RESPONSE_HEADERS = {"content-encoding", "content-length", "transfer-encoding"}
+
+
+class Forbidden(Exception):
+    pass
+
+
+def public_address(hostname, port):
+    """An address to connect to, once all of the hostname's addresses are public."""
+    addresses = {
+        info[4][0].split("%")[0] for info in socket.getaddrinfo(hostname, port)
+    }
+    if not addresses:
+        raise Forbidden(hostname)
+    for address in addresses:
+        if not ipaddress.ip_address(address).is_global:
+            raise Forbidden(hostname)
+    return sorted(addresses)[0]
+
+
+def fetch_for_page(method, url, headers, body):
+    """Downloads for a page, from the address that was checked.
+
+    Leaving this to Chromium would look up the name again, and the answer could
+    be a private address by then.
+    """
+    parts = urllib.parse.urlsplit(url)
+    if parts.scheme not in ("http", "https") or not parts.hostname:
+        raise Forbidden(url)
+
+    port = parts.port or (443 if parts.scheme == "https" else 80)
+    address = public_address(parts.hostname, port)
+    host = "[{}]".format(address) if ":" in address else address
+    pinned_url = urllib.parse.urlunsplit(
+        (parts.scheme, "{}:{}".format(host, port), parts.path, parts.query, "")
+    )
+    headers = {k: v for k, v in headers.items() if k.lower() != "host"}
+    headers["Host"] = parts.netloc.rsplit("@", 1)[-1]
+
+    with httpx.Client(timeout=FETCH_TIMEOUT_SECONDS) as client:
+        request = client.build_request(
+            method,
+            pinned_url,
+            headers=headers,
+            content=body,
+            extensions={"sni_hostname": parts.hostname},
+        )
+        response = client.send(request, stream=True)
+        data = b""
+        for chunk in response.iter_bytes():
+            data += chunk
+            if len(data) > MAX_DOWNLOAD_BYTES:
+                raise Forbidden(url)
+        response_headers = {
+            k: v
+            for k, v in response.headers.items()
+            if k.lower() not in DROPPED_RESPONSE_HEADERS
+        }
+        response.close()
+        return response.status_code, response_headers, data
+
+
+def handle_route(route):
+    request = route.request
+    try:
+        status, headers, body = fetch_for_page(
+            request.method, request.url, request.headers, request.post_data_buffer
+        )
+    except (Forbidden, httpx.HTTPError, OSError, ValueError):
+        route.abort()
+        return
+    route.fulfill(status=status, headers=headers, body=body)
+
+
+class Renderer:
+    def __init__(self):
+        self.playwright = sync_playwright().start()
+        self.browser = None
+
+    def _context(self):
+        if self.browser is None or not self.browser.is_connected():
+            self.browser = self.playwright.chromium.launch(
+                args=CHROMIUM_ARGS, proxy={"server": NOWHERE}
+            )
+        return self.browser.new_context(
+            viewport={"width": WIDTH, "height": 5},
+            service_workers="block",
+        )
+
+    def render(self, html):
+        context = self._context()
+        try:
+            page = context.new_page()
+            page.set_default_timeout(RENDER_TIMEOUT_MS)
+            page.route("**/*", handle_route)
+            page.route_web_socket("**/*", lambda ws: ws.close())
+            # Not a file, so that the page has no access to any.
+            page.set_content(html, wait_until="load")
+            return page.screenshot(full_page=True, type="png")
+        except PlaywrightError:
+            # A script that never ends leaves the browser unusable.
+            self.browser.close()
+            self.browser = None
+            raise
+        finally:
+            if self.browser is not None:
+                context.close()
+
+
+renderer = None
+
+
+class Handler(http.server.BaseHTTPRequestHandler):
+    def do_GET(self):
+        self.send_response(200 if self.path == "/health" else 404)
+        self.send_header("Content-Length", "0")
+        self.end_headers()
+
+    def do_POST(self):
+        length = int(self.headers.get("Content-Length", 0))
+        if self.path != "/render" or length > MAX_HTML_BYTES:
+            self.send_error(404 if self.path != "/render" else 413)
+            return
+
+        html = self.rfile.read(length).decode("utf-8", "replace")
+        try:
+            png = renderer.render(html)
+        except PlaywrightError as error:
+            self.log_error("could not render: %s", error)
+            self.send_error(500)
+            return
+
+        self.send_response(200)
+        self.send_header("Content-Type", "image/png")
+        self.send_header("Content-Length", str(len(png)))
+        self.end_headers()
+        self.wfile.write(png)
+
+
+if __name__ == "__main__":
+    renderer = Renderer()
+    # One at a time on purpose: Playwright stays on this thread, and printers are slow anyway.
+    http.server.HTTPServer(("0.0.0.0", PORT), Handler).serve_forever()
diff --git a/renderer/test_server.py b/renderer/test_server.py
new file mode 100644 (file)
index 0000000..3b845ab
--- /dev/null
@@ -0,0 +1,181 @@
+import base64
+import http.server
+import io
+import threading
+import unittest
+from unittest import mock
+
+import httpx
+import server
+from PIL import Image
+
+
+BLACK_PAGE = b"<html><body style='margin:0;background:#000;height:400px'></body></html>"
+
+
+class Canary(http.server.BaseHTTPRequestHandler):
+    """A service on localhost, like the database or the app would be."""
+
+    requests = []
+
+    def do_GET(self):
+        Canary.requests.append(self.path)
+        self.send_response(200)
+        self.send_header("Content-Type", "text/html")
+        self.end_headers()
+        self.wfile.write(BLACK_PAGE)
+
+    def log_message(self, *args):
+        pass
+
+
+def looks_black(html, renderer):
+    """Whether what a page tried to do turned the top left of the print black."""
+    image = Image.open(io.BytesIO(renderer.render(html))).convert("L")
+    return image.getpixel((5, 5)) < 128
+
+
+def black_if(condition):
+    return """<html><body style="margin:0"><div id="o" style="height:50px"></div><script>
+    if ({}) document.getElementById("o").style.background = "#000";
+    </script></body></html>""".format(condition)
+
+
+class TestRenderer(unittest.TestCase):
+    @classmethod
+    def setUpClass(cls):
+        cls.canary = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Canary)
+        cls.canary_url = "http://127.0.0.1:{}/".format(cls.canary.server_address[1])
+        threading.Thread(target=cls.canary.serve_forever, daemon=True).start()
+        cls.renderer = server.Renderer()
+
+    def setUp(self):
+        Canary.requests.clear()
+
+    def size(self, html):
+        return Image.open(io.BytesIO(self.renderer.render(html))).size
+
+    def test_size_follows_the_page(self):
+        self.assertEqual(self.size("<body style='margin:0;height:10px'></body>"), (384, 10))
+        self.assertEqual(self.size("<body style='margin:0;height:3000px'></body>"), (384, 3000))
+
+    def test_scripts_run(self):
+        self.assertTrue(looks_black(black_if("true"), self.renderer))
+
+    def test_data_images_work(self):
+        png = io.BytesIO()
+        Image.new("L", (1, 1), 0).save(png, "PNG")
+        black_pixel = "data:image/png;base64," + base64.b64encode(png.getvalue()).decode()
+        html = "<body style='margin:0'><img width=100 height=100 src='{}'></body>".format(black_pixel)
+        self.assertTrue(looks_black(html, self.renderer))
+
+    def test_fonts_for_prints_are_there(self):
+        self.assertEqual(self.size("<p style='font-family: Helvetica, Arial'>🙂 hello</p>")[0], 384)
+
+    def test_public_sites_can_be_used(self):
+        # The canary stands in for a site on the internet.
+        with mock.patch.object(
+            server.ipaddress.IPv4Address, "is_global", new_callable=mock.PropertyMock, return_value=True
+        ):
+            html = "<body style='margin:0'><iframe src='{}' style='border:0;width:380px;height:100px'></iframe></body>".format(
+                self.canary_url
+            )
+            self.assertTrue(looks_black(html, self.renderer))
+        self.assertEqual(Canary.requests, ["/"])
+
+    def assert_never_reached_canary(self, html):
+        self.renderer.render(html)
+        self.assertEqual(Canary.requests, [])
+
+    def test_local_services_cant_be_reached(self):
+        url = self.canary_url
+        for html in (
+            "<iframe src='{}'></iframe>".format(url),
+            "<img src='{}'>".format(url),
+            "<link rel=stylesheet href='{}'>".format(url),
+            "<script src='{}'></script>".format(url),
+            "<script>fetch('{}')</script>".format(url),
+            "<script>new WebSocket('{}')</script>".format(url.replace("http", "ws")),
+            "<meta http-equiv=refresh content='0;url={}'>".format(url),
+            "<script>location='{}'</script>".format(url),
+        ):
+            with self.subTest(html):
+                self.assert_never_reached_canary(html)
+
+    def test_redirects_go_back_through_the_checks(self):
+        # Answering with the redirect means that Chromium asks for its target, which is then checked.
+        def redirect(request):
+            return httpx.Response(302, headers={"Location": self.canary_url})
+
+        transport = httpx.MockTransport(redirect)
+        real_client = httpx.Client
+        with mock.patch.object(server.httpx, "Client", lambda **kw: real_client(transport=transport, **kw)), mock.patch.object(
+            server, "public_address", side_effect=lambda hostname, port: self._only_public(hostname)
+        ):
+            self.assert_never_reached_canary("<img src='http://public.example/'>")
+
+    @staticmethod
+    def _only_public(hostname):
+        if hostname == "127.0.0.1":
+            raise server.Forbidden(hostname)
+        return "93.184.216.34"
+
+    def test_scripts_cant_read_files(self):
+        html = black_if("""(function () {
+            try {
+              var x = new XMLHttpRequest();
+              x.open("GET", "file:///etc/passwd", false);
+              x.send();
+              return x.responseText.length > 0;
+            } catch (e) { return false; }
+        })()""")
+        self.assertFalse(looks_black(html, self.renderer))
+
+    def test_frames_cant_show_files(self):
+        def frame(src):
+            return "<body style='margin:0'><iframe src='{}' style='border:0;width:380px;height:300px'></iframe></body>".format(src)
+
+        missing = self.renderer.render(frame("file:///no/such/file"))
+        self.assertEqual(self.renderer.render(frame("file:///etc/passwd")), missing)
+
+    def test_page_has_no_origin_with_access(self):
+        self.assertTrue(
+            looks_black(black_if("location.protocol !== 'file:'"), self.renderer)
+        )
+
+    def test_recovers_from_a_script_that_never_ends(self):
+        with mock.patch.object(server, "RENDER_TIMEOUT_MS", 1500):
+            renderer = server.Renderer.__new__(server.Renderer)
+            renderer.playwright = self.renderer.playwright
+            renderer.browser = None
+            with self.assertRaises(server.PlaywrightError):
+                renderer.render("<script>while (true) {}</script>")
+            self.assertEqual(
+                Image.open(io.BytesIO(renderer.render("<body style='margin:0;height:10px'>"))).size,
+                (384, 10),
+            )
+
+
+class TestAddressChecks(unittest.TestCase):
+    def test_private_addresses_are_refused(self):
+        for hostname in ("127.0.0.1", "localhost", "10.0.0.1", "192.168.1.1", "172.16.0.1", "169.254.169.254", "::1"):
+            with self.subTest(hostname):
+                with self.assertRaises((server.Forbidden, OSError)):
+                    server.public_address(hostname, 80)
+
+    def test_one_private_address_is_enough_to_refuse(self):
+        answers = [(0, 0, 0, "", ("93.184.216.34", 80)), (0, 0, 0, "", ("10.0.0.1", 80))]
+        with mock.patch.object(server.socket, "getaddrinfo", return_value=answers):
+            with self.assertRaises(server.Forbidden):
+                server.public_address("rebind.example", 80)
+
+    def test_public_address_is_used(self):
+        answers = [(0, 0, 0, "", ("93.184.216.34", 80))]
+        with mock.patch.object(server.socket, "getaddrinfo", return_value=answers):
+            self.assertEqual(server.public_address("example.com", 80), "93.184.216.34")
+
+    def test_other_schemes_are_refused(self):
+        for url in ("file:///etc/passwd", "ftp://example.com/", "gopher://example.com/"):
+            with self.subTest(url):
+                with self.assertRaises(server.Forbidden):
+                    server.fetch_for_page("GET", url, {}, None)
index 62625bbaa88a34d533c504ebf4ff8562483639a5..591e99ee79c5b92548e8651e1ad5b83db60308a2 100644 (file)
@@ -1,12 +1,16 @@
 from PIL import Image
 from itertools import groupby
+import os
 import struct
 import io
-import tempfile
+
+import requests
 
 WHITE = '\xff'
 BLACK = '\x00'
 THRESHOLD = 127
+RENDERER_URL = os.getenv('RENDERER_URL', 'http://sirius-renderer:8000')
+RENDER_TIMEOUT_SECONDS = 40
 TRANSLATE = [(1536, 255), (1152, 254), (768, 253), (384, 252), (251, 251)]
 
 
@@ -101,35 +105,18 @@ def rle_from_bw(bw_image):
 
 
 def html_to_png(html):
-    """ This works:
-    <html><body style="width: 384px; margin: 0;">
-    <img src="https://dl.dropboxusercontent.com/u/165957/Escher.gif">
-    </body></html>
-    """
-    from selenium import webdriver
-    driver = None
-    try:
-        caps = {'acceptSslCerts': True}
-        driver = webdriver.PhantomJS(
-            'phantomjs', desired_capabilities=caps,
-            service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any'])
-        driver.set_window_size(384, 5)
-
-        # note that the .html suffix is required to make phantomjs
-        # pick up the mime-type and render correctly.
-        with tempfile.NamedTemporaryFile(suffix='.html') as f:
-            if isinstance(html, str):
-                f.write(html.encode('utf8'))
-            else:
-                f.write(html)
-            f.flush()
-            driver.get('file://' + f.name)
-            data = io.BytesIO(driver.get_screenshot_as_png())
-
-        return data
-    finally:
-        if driver:
-            driver.quit()
+    """Prints can contain anything, so this happens in a container of its own, see renderer/."""
+    if isinstance(html, str):
+        html = html.encode('utf8')
+
+    response = requests.post(
+        RENDERER_URL + '/render',
+        data=html,
+        headers={'Content-Type': 'text/html; charset=utf-8'},
+        timeout=RENDER_TIMEOUT_SECONDS,
+    )
+    response.raise_for_status()
+    return io.BytesIO(response.content)
 
 
 def default_pipeline(html):
index b8389f2d3c69a0ac8ba7b0e68ba27823f877c005..a4f5df25cdfaff2d0f989ffa6345296a7ae840a2 100644 (file)
Binary files a/sirius/coding/snapshots/snap_test_image_coding_snapshots/ImageCodingSnapshotCase::test_snapshot_fixtures hello_world.png and b/sirius/coding/snapshots/snap_test_image_coding_snapshots/ImageCodingSnapshotCase::test_snapshot_fixtures hello_world.png differ
index 15104fb4461eeb39c616206a241597984ca444ea..fe323c63e3bb0375e43ff31db5a696694c4572e2 100644 (file)
Binary files a/sirius/coding/snapshots/snap_test_image_coding_snapshots/ImageCodingSnapshotCase::test_snapshot_template_fixtures hello_world.png and b/sirius/coding/snapshots/snap_test_image_coding_snapshots/ImageCodingSnapshotCase::test_snapshot_template_fixtures hello_world.png differ
index b9d8f242c53156ee4d25b76b56757b361c649471..09a1b7420cd129c0335eb3202e1976c130d26e94 100755 (executable)
@@ -14,6 +14,10 @@ class Config:
     OAUTH_REDIRECT_URI = os.getenv("OAUTH_REDIRECT_URI")
     LOCAL_LOGIN_USERNAME = os.getenv("LOCAL_LOGIN_USERNAME")
     LOCAL_LOGIN_PASSWORD_HASH = os.getenv("LOCAL_LOGIN_PASSWORD_HASH")
+    # For an initial password that was given to someone else.
+    LOCAL_LOGIN_REQUIRE_PASSWORD_CHANGE = bool(
+        os.getenv("LOCAL_LOGIN_REQUIRE_PASSWORD_CHANGE")
+    )
 
     @staticmethod
     def init_app(app):
index 8edafa95a7c765c8ba67e0d2745186a789026455..1d2fe1867dd7a01f601d98d33fd1eeed31904ced 100644 (file)
@@ -1,6 +1,5 @@
 """User models. Login via twitter, or a single local account configured
-through the environment, to avoid the whole forgot-password/reset-password
-dance.
+through the environment, which can choose its own password after that.
 """
 import collections
 import datetime
@@ -29,6 +28,8 @@ class User(db.Model):
     # username can't be unique because we may have multiple identity
     # providers. For now we just copy the  twitter handle.
     username = db.Column(db.String)
+    # Set by the local account once it has replaced the initial password.
+    password_hash = db.Column(db.String)
     twitter_oauth = db.relationship(
         "TwitterOAuth", uselist=False, backref=db.backref("user")
     )
index 3be9f1cc692d6a835d1f7b845b05be2dc0545b65..e856f99c27fd9bc1d2fb32f2cd34af9bd6be23f8 100644 (file)
@@ -2,13 +2,17 @@ import flask
 import flask_login as login
 import flask_wtf
 import wtforms
-from werkzeug.security import check_password_hash
+from werkzeug.security import check_password_hash, generate_password_hash
 
 from sirius.models import user as user_model
 from sirius.models.db import db
 
 blueprint = flask.Blueprint("local_login", __name__)
 
+MIN_PASSWORD_LENGTH = 8
+# What's left working while the initial password still has to be replaced.
+ALLOWED_BEFORE_PASSWORD_CHANGE = ("local_login.change_password", "twitter.twitter_logout", "static")
+
 
 class LoginForm(flask_wtf.FlaskForm):
     username = wtforms.StringField(
@@ -21,10 +25,72 @@ class LoginForm(flask_wtf.FlaskForm):
     )
 
 
+def initial_password_valid(password):
+    return check_password_hash(
+        flask.current_app.config["LOCAL_LOGIN_PASSWORD_HASH"], password
+    )
+
+
+def password_valid(user, password):
+    """The account's own password, or the initial one until it has its own."""
+    if user is not None and user.password_hash:
+        return check_password_hash(user.password_hash, password)
+    return initial_password_valid(password)
+
+
+def local_user():
+    return user_model.User.query.filter_by(
+        username=flask.current_app.config["LOCAL_LOGIN_USERNAME"]
+    ).first()
+
+
 def credentials_valid(username, password):
+    if username != flask.current_app.config["LOCAL_LOGIN_USERNAME"]:
+        return False
+    return password_valid(local_user(), password)
+
+
+def is_local_account(user):
     config = flask.current_app.config
-    return username == config["LOCAL_LOGIN_USERNAME"] and check_password_hash(
-        config["LOCAL_LOGIN_PASSWORD_HASH"], password
+    return (
+        user.is_authenticated
+        and bool(config["LOCAL_LOGIN_USERNAME"] and config["LOCAL_LOGIN_PASSWORD_HASH"])
+        and user.username == config["LOCAL_LOGIN_USERNAME"]
+    )
+
+
+def reset_password():
+    """Back to the initial password, for when the account's own is forgotten."""
+    user = local_user()
+    if user is None:
+        return False
+
+    user.password_hash = None
+    db.session.commit()
+    return True
+
+
+class ChangePasswordForm(flask_wtf.FlaskForm):
+    current_password = wtforms.PasswordField(
+        "Current password",
+        validators=[wtforms.validators.DataRequired()],
+    )
+    new_password = wtforms.PasswordField(
+        "New password",
+        validators=[
+            wtforms.validators.DataRequired(),
+            wtforms.validators.Length(
+                min=MIN_PASSWORD_LENGTH,
+                message="Please use at least {} characters.".format(MIN_PASSWORD_LENGTH),
+            ),
+        ],
+    )
+    confirm_password = wtforms.PasswordField(
+        "New password again",
+        validators=[
+            wtforms.validators.DataRequired(),
+            wtforms.validators.EqualTo("new_password", message="These don't match."),
+        ],
     )
 
 
@@ -60,3 +126,54 @@ def local_login():
         flask.flash("Wrong username or password.")
 
     return flask.render_template("local_login.html", form=form)
+
+
+def must_change_password(user):
+    return (
+        flask.current_app.config["LOCAL_LOGIN_REQUIRE_PASSWORD_CHANGE"]
+        and is_local_account(user)
+        and not user.password_hash
+    )
+
+
+@blueprint.before_app_request
+def require_password_change():
+    # Programs can't do anything with this page, same as with the login.
+    if flask.request.path.startswith("/ext_api/"):
+        return None
+
+    if (
+        flask.request.endpoint not in ALLOWED_BEFORE_PASSWORD_CHANGE
+        and must_change_password(login.current_user)
+    ):
+        return flask.redirect(flask.url_for("local_login.change_password"))
+    return None
+
+
+@blueprint.app_context_processor
+def template_helpers():
+    return dict(can_change_password=is_local_account(login.current_user))
+
+
+@blueprint.route("/password", methods=["GET", "POST"])
+@login.login_required
+def change_password():
+    user = login.current_user
+    if not is_local_account(user):
+        flask.abort(404)
+
+    form = ChangePasswordForm()
+    if form.validate_on_submit():
+        if not password_valid(user, form.current_password.data):
+            form.current_password.errors.append("That's not your current password.")
+        elif password_valid(user, form.new_password.data):
+            form.new_password.errors.append("That's the password you have already.")
+        else:
+            user.password_hash = generate_password_hash(form.new_password.data)
+            db.session.commit()
+            flask.flash("Your password has been changed.")
+            return flask.redirect("/")
+
+    return flask.render_template(
+        "change_password.html", form=form, must_change=must_change_password(user)
+    )
index ebf82b91c09253002677629cc94fd4a5277e9bc7..96352b046123755d159a63b77df94cf633df1ec6 100644 (file)
@@ -27,6 +27,9 @@
                        </ul>
                        {% if current_user.is_authenticated %}
                        <ul class="nav navbar-nav navbar-right">
+                               {% if can_change_password %}
+                               <li><a href="{{ url_for('local_login.change_password') }}">Change password</a></li>
+                               {% endif %}
                                <li><a href="/login/twitter/logout">Sign out</a></li>
                        </ul>
                        {% endif %}
diff --git a/sirius/web/templates/change_password.html b/sirius/web/templates/change_password.html
new file mode 100644 (file)
index 0000000..34a3e83
--- /dev/null
@@ -0,0 +1,32 @@
+{% extends "base.html" %}
+
+{% block title %}Change password{% endblock %}
+
+{% block page_content %}
+<div class="row">
+       <div class="col-md-4">
+
+<h1>Change password</h1>
+
+{% if must_change %}
+<p>This is still the initial password, please choose your own before going on.</p>
+{% endif %}
+
+<form method="POST">
+       {{ form.csrf_token }}
+
+       {% for field, autocomplete in [(form.current_password, "current-password"), (form.new_password, "new-password"), (form.confirm_password, "new-password")] %}
+       <div class="form-group {% if field.errors %}has-error{% endif %}">
+               <label>{{ field.label }}</label>
+               {{ field(class="form-control", autocomplete=autocomplete) }}
+               {% for error in field.errors %}
+               <span class="help-block">{{ error }}</span>
+               {% endfor %}
+       </div>
+       {% endfor %}
+       <button class="btn btn-primary" type="submit">Change password</button>
+</form>
+
+</div>
+</div>
+{% endblock %}
index 5185284b8c28e4627043f6f10ee8fae6332be7e9..f526cc0ae6669e8f1bfd8ef25c07dc88865d9d5e 100644 (file)
@@ -5,6 +5,7 @@ from werkzeug.security import generate_password_hash
 from sirius.models import hardware
 from sirius.models import user as user_model
 from sirius.testing import base
+from sirius.web import local_login
 
 
 # pylint: disable=no-member
@@ -79,6 +80,165 @@ class TestLocalLogin(base.Base):
         self.assertIn(b"/login/local", self.client.get("/").data)
 
 
+class TestChangePassword(base.Base):
+    def create_app(self):
+        app = super().create_app()
+        app.config["LOCAL_LOGIN_USERNAME"] = "localuser"
+        app.config["LOCAL_LOGIN_PASSWORD_HASH"] = generate_password_hash("sesame")
+        app.config["LOCAL_LOGIN_REQUIRE_PASSWORD_CHANGE"] = False
+        return app
+
+    def sign_in(self, password="sesame"):
+        return self.client.post(
+            "/login/local", data=dict(username="localuser", password=password)
+        )
+
+    def sign_out(self):
+        self.client.get("/login/twitter/logout")
+
+    def signed_in(self):
+        with self.client.session_transaction() as session:
+            return session.get("user_id") is not None
+
+    def change(self, current="sesame", new="correct horse", confirm=None):
+        return self.client.post(
+            "/login/password",
+            data=dict(
+                current_password=current,
+                new_password=new,
+                confirm_password=new if confirm is None else confirm,
+            ),
+        )
+
+    def local_user(self):
+        return user_model.User.query.filter_by(username="localuser").one()
+
+    def test_new_password_replaces_the_initial_one(self):
+        self.sign_in()
+        self.assertRedirects(self.change(), "/")
+        self.sign_out()
+
+        self.sign_in("sesame")
+        self.assertFalse(self.signed_in())
+        self.sign_in("correct horse")
+        self.assertTrue(self.signed_in())
+
+    def test_password_is_stored_hashed(self):
+        self.sign_in()
+        self.change()
+        self.assertNotIn("correct horse", self.local_user().password_hash)
+
+    def test_can_be_changed_again(self):
+        self.sign_in()
+        self.change()
+        self.assertRedirects(self.change("correct horse", "battery staple"), "/")
+        self.sign_out()
+        self.sign_in("correct horse")
+        self.assertFalse(self.signed_in())
+        self.sign_in("battery staple")
+        self.assertTrue(self.signed_in())
+
+    def assert_refused(self, response):
+        self.assert200(response)
+        self.assertIsNone(self.local_user().password_hash)
+
+    def test_needs_the_current_password(self):
+        self.sign_in()
+        self.assert_refused(self.change(current="wrong"))
+
+    def test_new_password_must_be_confirmed(self):
+        self.sign_in()
+        self.assert_refused(self.change(confirm="something else"))
+
+    def test_new_password_must_be_long_enough(self):
+        self.sign_in()
+        self.assert_refused(self.change(new="short"))
+
+    def test_new_password_must_be_new(self):
+        self.sign_in()
+        self.change()
+        before = self.local_user().password_hash
+        self.assert200(self.change("correct horse", "correct horse"))
+        self.assertEqual(self.local_user().password_hash, before)
+
+    def test_needs_signing_in(self):
+        self.assertRedirects(self.client.get("/login/password"), "/login/local?next=%2Flogin%2Fpassword")
+
+    def test_only_for_the_local_account(self):
+        self.autologin()
+        self.assert404(self.client.get("/login/password"))
+
+    def test_link_is_only_there_for_the_local_account(self):
+        self.autologin()
+        self.assertNotIn(b"/login/password", self.client.get("/about").data)
+        self.sign_out()
+        self.sign_in()
+        self.assertIn(b"/login/password", self.client.get("/about").data)
+
+    def test_reset_goes_back_to_the_initial_password(self):
+        self.sign_in()
+        self.change()
+        self.sign_out()
+        self.assertTrue(local_login.reset_password())
+        self.sign_in("correct horse")
+        self.assertFalse(self.signed_in())
+        self.sign_in("sesame")
+        self.assertTrue(self.signed_in())
+
+    def test_reset_without_an_account(self):
+        self.assertFalse(local_login.reset_password())
+
+
+class TestRequiredPasswordChange(base.Base):
+    def create_app(self):
+        app = super().create_app()
+        app.config["LOCAL_LOGIN_USERNAME"] = "localuser"
+        app.config["LOCAL_LOGIN_PASSWORD_HASH"] = generate_password_hash("sesame")
+        app.config["LOCAL_LOGIN_REQUIRE_PASSWORD_CHANGE"] = True
+        return app
+
+    def setUp(self):
+        base.Base.setUp(self)
+        self.client.post(
+            "/login/local", data=dict(username="localuser", password="sesame")
+        )
+
+    def test_pages_lead_to_the_change_page(self):
+        for path in ("/", "/about", "/printer/1"):
+            self.assertRedirects(self.client.get(path), "/login/password")
+
+    def test_page_says_why(self):
+        self.assertIn(b"initial password", self.client.get("/login/password").data)
+
+    def test_signing_out_still_works(self):
+        self.assert_status(self.client.get("/login/twitter/logout"), 302)
+        self.assert200(self.client.get("/about"))
+
+    def test_done_after_changing(self):
+        self.client.post(
+            "/login/password",
+            data=dict(
+                current_password="sesame",
+                new_password="correct horse",
+                confirm_password="correct horse",
+            ),
+        )
+        self.assert200(self.client.get("/about"))
+
+    def test_api_gets_no_redirect(self):
+        response = self.client.post("/ext_api/v1/printer/999/print_html")
+        self.assertNotEqual(response.status_code, 302)
+
+    def test_signed_out_visitors_are_not_affected(self):
+        self.client.get("/login/twitter/logout")
+        self.assert200(self.client.get("/about"))
+
+    def test_other_accounts_are_not_affected(self):
+        self.client.get("/login/twitter/logout")
+        self.autologin()
+        self.assert200(self.client.get("/about"))
+
+
 class TestLocalLoginDisabled(base.Base):
     def test_not_found_when_unconfigured(self):
         with mock.patch.dict(
index 139d498240f7ee77972347fc6d9bf5b06f07cc5c..ef9afc80f10f9014379c2a5222955102f8192f51 100644 (file)
@@ -6,6 +6,7 @@ used.
 
 ```sh
 podman build -t localhost/sirius:latest ../..
+podman build -t localhost/sirius-renderer:latest ../../renderer
 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm install --no-bin-links
 npm test
 ```
index ccf529728250747be82a0f6fa603b3c64d8d3133..a70ee5f3e1449b2c8a247e9a3c5ca644425b34e4 100644 (file)
@@ -59,7 +59,7 @@ test("signing in leads back to the page you wanted", async ({ browser, baseURL }
   await page.goto(COMPOSE);
   await expect(page).toHaveURL(/\/login\/local\?next=/);
   await page.fill("#username", "tester");
-  await page.fill("#password", "secret");
+  await page.fill("#password", "initial-password");
   await page.click('[type="submit"]');
   await expect(page).toHaveURL(COMPOSE);
   await context.close();
index dbc3dd910d15e0cf619fd515158d68c316d77416..1aa65c878430a8dece3041b018d1ddf10958322e 100644 (file)
@@ -40,7 +40,7 @@ const inked = (row) => row.includes("0");
 async function signIn(page) {
   await page.goto("/login/local");
   await page.fill("#username", "tester");
-  await page.fill("#password", "secret");
+  await page.fill("#password", "initial-password");
   await page.click('[type="submit"]');
 }
 
diff --git a/tests/browser/password.spec.js b/tests/browser/password.spec.js
new file mode 100644 (file)
index 0000000..579542b
--- /dev/null
@@ -0,0 +1,56 @@
+const { test, expect } = require("@playwright/test");
+const { signIn } = require("./helpers");
+
+const INITIAL = "initial-password";
+
+async function fillIn(page, current, next, confirm = next) {
+  await page.goto("/login/password");
+  await page.fill("#current_password", current);
+  await page.fill("#new_password", next);
+  await page.fill("#confirm_password", confirm);
+  await page.click('button[type="submit"]');
+}
+
+async function trySignIn(page, password) {
+  await page.goto("/login/local");
+  await page.fill("#username", "tester");
+  await page.fill("#password", password);
+  await page.click('[type="submit"]');
+}
+
+test("changing the password from the menu, and signing in with it", async ({ page }) => {
+  await signIn(page);
+  await page.click("text=Change password");
+  await expect(page).toHaveURL("/login/password");
+
+  await fillIn(page, INITIAL, "a whole new password");
+  try {
+    await expect(page).toHaveURL("/");
+    await expect(page.locator(".alert")).toContainText("has been changed");
+    await page.click("text=Sign out");
+
+    await trySignIn(page, INITIAL);
+    await expect(page.locator(".alert")).toContainText("Wrong username or password");
+
+    await trySignIn(page, "a whole new password");
+    await expect(page.locator("text=Sign out")).toBeVisible();
+  } finally {
+    // The other tests sign in with the first one.
+    await fillIn(page, "a whole new password", INITIAL);
+  }
+});
+
+test("mistakes are explained", async ({ page }) => {
+  await signIn(page);
+  await fillIn(page, "wrong", "long enough password");
+  await expect(page.locator(".help-block")).toContainText("not your current password");
+
+  await fillIn(page, INITIAL, "short");
+  await expect(page.locator(".help-block")).toContainText("at least 8");
+
+  await fillIn(page, INITIAL, "long enough password", "something different");
+  await expect(page.locator(".help-block")).toContainText("don't match");
+
+  await fillIn(page, INITIAL, INITIAL);
+  await expect(page.locator(".help-block")).toContainText("already");
+});
index 9104e14c68c21cb58158658cd62bc08fe727693b..3b2020287675313a6a22e509e98f72f223c03cfd 100644 (file)
@@ -2,6 +2,7 @@ const path = require("path");
 const { defineConfig } = require("@playwright/test");
 
 const PORT = 5077;
+const RENDERER_PORT = 5078;
 const REPO = path.resolve(__dirname, "../..");
 
 module.exports = defineConfig({
@@ -16,13 +17,27 @@ module.exports = defineConfig({
       executablePath: process.env.CHROMIUM_PATH || "/usr/bin/chromium",
     },
   },
-  webServer: {
-    command:
-      `podman run --rm --replace --name sirius-browser-tests ` +
-      `-p 127.0.0.1:${PORT}:5000 -v ${REPO}:/sirius:ro ` +
-      `localhost/sirius:latest sh tests/browser/run-server.sh`,
-    url: `http://127.0.0.1:${PORT}/`,
-    timeout: 60000,
-    stdout: "pipe",
-  },
+  webServer: [
+    {
+      command:
+        `podman network create --ignore sirius-browser-tests && ` +
+        `podman run --rm --replace --name sirius-browser-renderer ` +
+        `--network sirius-browser-tests --network-alias sirius-renderer ` +
+        `-p 127.0.0.1:${RENDERER_PORT}:8000 localhost/sirius-renderer:latest`,
+      url: `http://127.0.0.1:${RENDERER_PORT}/health`,
+      timeout: 60000,
+      stdout: "pipe",
+    },
+    {
+      command:
+        `podman network create --ignore sirius-browser-tests && ` +
+        `podman run --rm --replace --name sirius-browser-tests ` +
+        `--network sirius-browser-tests ` +
+        `-p 127.0.0.1:${PORT}:5000 -v ${REPO}:/sirius:ro ` +
+        `localhost/sirius:latest sh tests/browser/run-server.sh`,
+      url: `http://127.0.0.1:${PORT}/`,
+      timeout: 60000,
+      stdout: "pipe",
+    },
+  ],
 });
index 477d41e01389969395516e1991ad1b229076e4f8..cf5e997ddea8abff63b48d0a9757554047bfe594 100644 (file)
@@ -4,9 +4,5 @@ set -e
 service postgresql start
 su postgres -c "psql -c \"ALTER USER postgres PASSWORD 'test'\""
 su postgres -c "createdb sirius_browser_tests"
-# PhantomJS, which renders plain text messages, fails without this.
-export OPENSSL_CONF=/etc/ssl/
 export DATABASE_URL=postgresql://postgres:test@127.0.0.1/sirius_browser_tests
-# PhantomJS writes a log to the current directory, and the repo is read-only.
-cd /tmp
 exec python -B /sirius/tests/browser/server.py
index a56dbbd454034022dfc40c80a2afe318d658af6c..e26ff568a661eb1e3df00d8778d73db0585a1331 100644 (file)
@@ -9,7 +9,7 @@ from werkzeug.security import generate_password_hash
 sys.path.insert(0, "/sirius")
 
 os.environ["LOCAL_LOGIN_USERNAME"] = "tester"
-os.environ["LOCAL_LOGIN_PASSWORD_HASH"] = generate_password_hash("secret")
+os.environ["LOCAL_LOGIN_PASSWORD_HASH"] = generate_password_hash("initial-password")
 
 import flask
 from PIL import Image
index 93453d4d2e455ca91eb456d304d2d6790a54ea21..9bf40dc6e3713184e85fc9d6a7f8ab5c56583201 100644 (file)
@@ -2,5 +2,5 @@ const { execSync } = require("child_process");
 
 // Stopping the podman client that Playwright started leaves the container running.
 module.exports = () => {
-  execSync("podman rm -f -t 0 sirius-browser-tests", { stdio: "ignore" });
+  execSync("podman rm -f -t 0 sirius-browser-tests sirius-browser-renderer", { stdio: "ignore" });
 };