docker-compose*
*.md
**/node_modules
+renderer
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]
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()))"
--- /dev/null
+# 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.
--- /dev/null
+#!/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"
--- /dev/null
+# 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
--- /dev/null
+# 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
--- /dev/null
+# 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
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
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()
--- /dev/null
+"""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")
"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",
"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",
--- /dev/null
+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"]
--- /dev/null
+# 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
+```
--- /dev/null
+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()
--- /dev/null
+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)
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)]
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):
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):
"""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
# 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")
)
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(
)
+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."),
+ ],
)
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)
+ )
</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 %}
--- /dev/null
+{% 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 %}
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
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(
```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
```
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();
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"]');
}
--- /dev/null
+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");
+});
const { defineConfig } = require("@playwright/test");
const PORT = 5077;
+const RENDERER_PORT = 5078;
const REPO = path.resolve(__dirname, "../..");
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",
+ },
+ ],
});
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
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
// 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" });
};