From 6bf82b382b5b56a1e1b8b72ef3339b976e1e721f Mon Sep 17 00:00:00 2001 From: Thorsten Date: Fri, 27 Nov 2026 10:22:25 +0100 Subject: [PATCH] Add Chromium renderer, password change and Pi deployment - 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 --- .dockerignore | 1 + Dockerfile | 10 - README.md | 9 +- deploy/pi/README.md | 103 ++++++++++ deploy/pi/setup.sh | 59 ++++++ deploy/pi/sirius-db.service | 25 +++ deploy/pi/sirius-renderer.service | 26 +++ deploy/pi/sirius.service | 29 +++ docker-compose.yml | 7 +- manage.py | 8 + .../7c1e4f2a9b30_add_local_password.py | 22 +++ pyproject.toml | 3 +- renderer/Dockerfile | 19 ++ renderer/README.md | 15 ++ renderer/server.py | 163 ++++++++++++++++ renderer/test_server.py | 181 ++++++++++++++++++ sirius/coding/image_encoding.py | 47 ++--- ...se::test_snapshot_fixtures hello_world.png | Bin 1254 -> 1523 bytes ...snapshot_template_fixtures hello_world.png | Bin 8313 -> 6652 bytes sirius/config.py | 4 + sirius/models/user.py | 5 +- sirius/web/local_login.py | 123 +++++++++++- sirius/web/templates/base.html | 3 + sirius/web/templates/change_password.html | 32 ++++ sirius/web/test_local_login.py | 160 ++++++++++++++++ tests/browser/README.md | 1 + tests/browser/compose.spec.js | 2 +- tests/browser/helpers.js | 2 +- tests/browser/password.spec.js | 56 ++++++ tests/browser/playwright.config.js | 33 +++- tests/browser/run-server.sh | 4 - tests/browser/server.py | 2 +- tests/browser/teardown.js | 2 +- 33 files changed, 1088 insertions(+), 68 deletions(-) create mode 100644 deploy/pi/README.md create mode 100644 deploy/pi/setup.sh create mode 100644 deploy/pi/sirius-db.service create mode 100644 deploy/pi/sirius-renderer.service create mode 100644 deploy/pi/sirius.service create mode 100644 migrations/versions/7c1e4f2a9b30_add_local_password.py create mode 100644 renderer/Dockerfile create mode 100644 renderer/README.md create mode 100644 renderer/server.py create mode 100644 renderer/test_server.py create mode 100644 sirius/web/templates/change_password.html create mode 100644 tests/browser/password.spec.js diff --git a/.dockerignore b/.dockerignore index 5c68a99..a1d55a7 100644 --- a/.dockerignore +++ b/.dockerignore @@ -3,3 +3,4 @@ notes docker-compose* *.md **/node_modules +renderer diff --git a/Dockerfile b/Dockerfile index f252726..28e5ad7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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] diff --git a/README.md b/README.md index bf81150..ce2644a 100644 --- 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 index 0000000..99e6477 --- /dev/null +++ b/deploy/pi/README.md @@ -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 +``` + +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://: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://: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 index 0000000..1f460a0 --- /dev/null +++ b/deploy/pi/setup.sh @@ -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" < "$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 index 0000000..b3cc593 --- /dev/null +++ b/deploy/pi/sirius-db.service @@ -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 index 0000000..21be5ea --- /dev/null +++ b/deploy/pi/sirius-renderer.service @@ -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 index 0000000..fe67803 --- /dev/null +++ b/deploy/pi/sirius.service @@ -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 diff --git a/docker-compose.yml b/docker-compose.yml index fb32483..469af21 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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 diff --git a/manage.py b/manage.py index 00d5cc1..3b41812 100755 --- 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 index 0000000..786bc96 --- /dev/null +++ b/migrations/versions/7c1e4f2a9b30_add_local_password.py @@ -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") diff --git a/pyproject.toml b/pyproject.toml index fbc9107..df8c97c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 index 0000000..f80c863 --- /dev/null +++ b/renderer/Dockerfile @@ -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 index 0000000..03a65e8 --- /dev/null +++ b/renderer/README.md @@ -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 index 0000000..5e5ee59 --- /dev/null +++ b/renderer/server.py @@ -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 index 0000000..3b845ab --- /dev/null +++ b/renderer/test_server.py @@ -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"" + + +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 """
""".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(""), (384, 10)) + self.assertEqual(self.size(""), (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 = "".format(black_pixel) + self.assertTrue(looks_black(html, self.renderer)) + + def test_fonts_for_prints_are_there(self): + self.assertEqual(self.size("

🙂 hello

")[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 = "".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 ( + "".format(url), + "".format(url), + "".format(url), + "".format(url), + "".format(url), + "".format(url.replace("http", "ws")), + "".format(url), + "".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("") + + @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 "".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("") + self.assertEqual( + Image.open(io.BytesIO(renderer.render(""))).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) diff --git a/sirius/coding/image_encoding.py b/sirius/coding/image_encoding.py index 62625bb..591e99e 100644 --- a/sirius/coding/image_encoding.py +++ b/sirius/coding/image_encoding.py @@ -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: - - - - """ - 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): diff --git a/sirius/coding/snapshots/snap_test_image_coding_snapshots/ImageCodingSnapshotCase::test_snapshot_fixtures hello_world.png b/sirius/coding/snapshots/snap_test_image_coding_snapshots/ImageCodingSnapshotCase::test_snapshot_fixtures hello_world.png index b8389f2d3c69a0ac8ba7b0e68ba27823f877c005..a4f5df25cdfaff2d0f989ffa6345296a7ae840a2 100644 GIT binary pat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<|a@Z^1Haa^6^hQuq8IDj)8PJdbA5P zB|~l;mvNxt7>FQ7^tW4wc{ml?KY#w1?X<@4-4qeQ>tjZnK|rM26ciNuR!P#AoCfnh zWDi(YAFWpX>gsA4t#G8fe3=~d`q1!j3jQe=gp{Dd!tt49=U(K9uQRW zX_0=}%hQqD8M#vFx)u)D`1>mlDcl5zBmLvz7+KtA=&BFq;(m2@@>kvu&T>b%7 diff --git a/sirius/config.py b/sirius/config.py index b9d8f24..09a1b74 100755 --- a/sirius/config.py +++ b/sirius/config.py @@ -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): diff --git a/sirius/models/user.py b/sirius/models/user.py index 8edafa9..1d2fe18 100644 --- a/sirius/models/user.py +++ b/sirius/models/user.py @@ -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") ) diff --git a/sirius/web/local_login.py b/sirius/web/local_login.py index 3be9f1c..e856f99 100644 --- a/sirius/web/local_login.py +++ b/sirius/web/local_login.py @@ -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) + ) diff --git a/sirius/web/templates/base.html b/sirius/web/templates/base.html index ebf82b9..96352b0 100644 --- a/sirius/web/templates/base.html +++ b/sirius/web/templates/base.html @@ -27,6 +27,9 @@ {% if current_user.is_authenticated %} {% endif %} diff --git a/sirius/web/templates/change_password.html b/sirius/web/templates/change_password.html new file mode 100644 index 0000000..34a3e83 --- /dev/null +++ b/sirius/web/templates/change_password.html @@ -0,0 +1,32 @@ +{% extends "base.html" %} + +{% block title %}Change password{% endblock %} + +{% block page_content %} +
+
+ +

Change password

+ +{% if must_change %} +

This is still the initial password, please choose your own before going on.

+{% endif %} + +
+ {{ form.csrf_token }} + + {% for field, autocomplete in [(form.current_password, "current-password"), (form.new_password, "new-password"), (form.confirm_password, "new-password")] %} +
+ + {{ field(class="form-control", autocomplete=autocomplete) }} + {% for error in field.errors %} + {{ error }} + {% endfor %} +
+ {% endfor %} + +
+ +
+
+{% endblock %} diff --git a/sirius/web/test_local_login.py b/sirius/web/test_local_login.py index 5185284..f526cc0 100644 --- a/sirius/web/test_local_login.py +++ b/sirius/web/test_local_login.py @@ -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( diff --git a/tests/browser/README.md b/tests/browser/README.md index 139d498..ef9afc8 100644 --- a/tests/browser/README.md +++ b/tests/browser/README.md @@ -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 ``` diff --git a/tests/browser/compose.spec.js b/tests/browser/compose.spec.js index ccf5297..a70ee5f 100644 --- a/tests/browser/compose.spec.js +++ b/tests/browser/compose.spec.js @@ -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(); diff --git a/tests/browser/helpers.js b/tests/browser/helpers.js index dbc3dd9..1aa65c8 100644 --- a/tests/browser/helpers.js +++ b/tests/browser/helpers.js @@ -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 index 0000000..579542b --- /dev/null +++ b/tests/browser/password.spec.js @@ -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"); +}); diff --git a/tests/browser/playwright.config.js b/tests/browser/playwright.config.js index 9104e14..3b20202 100644 --- a/tests/browser/playwright.config.js +++ b/tests/browser/playwright.config.js @@ -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", + }, + ], }); diff --git a/tests/browser/run-server.sh b/tests/browser/run-server.sh index 477d41e..cf5e997 100644 --- a/tests/browser/run-server.sh +++ b/tests/browser/run-server.sh @@ -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 diff --git a/tests/browser/server.py b/tests/browser/server.py index a56dbbd..e26ff56 100644 --- a/tests/browser/server.py +++ b/tests/browser/server.py @@ -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 diff --git a/tests/browser/teardown.js b/tests/browser/teardown.js index 93453d4..9bf40dc 100644 --- a/tests/browser/teardown.js +++ b/tests/browser/teardown.js @@ -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" }); }; -- 2.47.3