diff --git a/.dockerignore b/.dockerignore index 36da7ee2..b8bde8de 100644 --- a/.dockerignore +++ b/.dockerignore @@ -13,9 +13,8 @@ backups **/*.swo **/console/cert.pem* **/dhcpd.* -webvirtcloud/settings.py -# the copy the README has Docker users keep next to the compose file -settings.py +# a settings.py older versions had Docker users mount from next to the compose file +/settings.py **/staticfiles # virtualenvs, caches and editor files diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 68c4f092..fe8d3619 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -42,6 +42,7 @@ jobs: --health-retries 10 env: + SECRET_KEY: ci-only-not-a-secret WEBVIRTCLOUD_DB_HOST: ${{ matrix.database == 'postgresql' && 'localhost' || '' }} WEBVIRTCLOUD_DB_PASSWORD: webvirtcloud @@ -79,12 +80,6 @@ jobs: python -m pip install --upgrade pip setuptools pip install -r dev/requirements.txt - - name: Configure WebVirtCloud Settings - run: | - cp webvirtcloud/settings.py.template webvirtcloud/settings.py - SECRET_KEY=$(python -c 'import secrets; print(secrets.token_urlsafe(50))') - sed -i "s|^SECRET_KEY = .*|SECRET_KEY = \"${SECRET_KEY}\"|" webvirtcloud/settings.py - - name: Check For Missing Migrations run: python manage.py makemigrations --check --dry-run @@ -152,8 +147,7 @@ jobs: - name: Plant Secret Sentinels run: | mkdir -p data - for f in data/secret_key data/admin_password settings.py webvirtcloud/settings.py.bak \ - 'webvirtcloud/settings.py~' webvirtcloud/.settings.py.swp; do + for f in data/secret_key data/admin_password data/local_settings.py data/local_settings.py~ settings.py; do echo sentinel > "$f" done @@ -175,8 +169,7 @@ jobs: run: | docker run --rm --entrypoint sh webvirtcloud:ci -c ' cd /srv/webvirtcloud - for f in data/secret_key data/admin_password settings.py webvirtcloud/settings.py.bak \ - "webvirtcloud/settings.py~" webvirtcloud/.settings.py.swp; do + for f in data/secret_key data/admin_password data/local_settings.py data/local_settings.py~ settings.py; do if [ -e "$f" ]; then echo "$f is in the image"; exit 1; fi done' diff --git a/.gitignore b/.gitignore index bab099bf..2ade3823 100644 --- a/.gitignore +++ b/.gitignore @@ -12,8 +12,6 @@ test_db*.sqlite3* console/cert.pem* tags dhcpd.* -webvirtcloud/settings.py -/settings.py .coverage htmlcov *.log diff --git a/Dockerfile b/Dockerfile index 87defc3f..ae75b611 100644 --- a/Dockerfile +++ b/Dockerfile @@ -51,11 +51,9 @@ COPY --from=build /srv/webvirtcloud/venv venv COPY . . # The code stays root's: the panel writes only to its data and backup -# directories (made its own at start). A settings file and a key exist only -# for collectstatic. -RUN cp webvirtcloud/settings.py.template webvirtcloud/settings.py \ - && SECRET_KEY=build-only WEBVIRTCLOUD_LOG_FILE=/tmp/build.log venv/bin/python3 manage.py collectstatic --noinput \ - && rm -f webvirtcloud/settings.py /tmp/build.log # the log handler makes the file at its first line only +# directories (made its own at start). A key exists only for collectstatic. +RUN SECRET_KEY=build-only WEBVIRTCLOUD_LOG_FILE=/tmp/build.log venv/bin/python3 manage.py collectstatic --noinput \ + && rm -f /tmp/build.log # the log handler makes the file at its first line only COPY conf/docker/nginx.conf /etc/nginx/nginx.conf COPY conf/nginx/webvirtcloud.conf /etc/nginx/conf.d/ diff --git a/README.md b/README.md index c689ae33..825b82a8 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ WebVirtCloud and `virt-manager`/`virsh` can manage the same libvirt host **concu 1. [Installation](#installation): [installer](#installer), [Docker](#docker), [manual](#manual-installation), [first login](#first-login) 2. [Adding a Compute Node](#adding-a-compute-node) -3. [Configuration](#configuration): [environment variables](#environment-variables), [HTTPS and reverse proxy](#https-and-reverse-proxy), [cloud-init datasource](#cloud-init-datasource), [LDAP](#ldap), [OTP](#two-factor-login-otp), [serial console](#serial-console) +3. [Configuration](#configuration): [environment variables](#environment-variables), [local settings](#local-settings), [HTTPS and reverse proxy](#https-and-reverse-proxy), [cloud-init datasource](#cloud-init-datasource), [LDAP](#ldap), [OTP](#two-factor-login-otp), [serial console](#serial-console) 4. [Backups](#backups): [off-site copy](#off-site-copy), [VM backups](#vm-backups) 5. [Updating](#updating): [Docker](#docker-1), [installer and manual](#installer-and-manual-installation), [restore and rollback](#restore-and-rollback), [moving to a new machine](#moving-to-a-new-machine), [behavior changes](#behavior-changes) 6. [Usage](#usage): [users and permissions](#users-roles-and-permissions), [REST API](#rest-api), [screenshots](#screenshots) @@ -80,7 +80,7 @@ chmod 744 install.sh sudo ./install.sh ``` -The installer writes the server's names and IPs to `ALLOWED_HOSTS`. Running it again keeps `settings.py`, the database, the secret key and the main nginx config, but replaces `/etc/nginx/conf.d/webvirtcloud.conf` and the systemd units; back up your own lines in the nginx config (TLS) first. Put your own service settings in `/etc/default/webvirtcloud` or in drop-ins (`systemctl edit webvirt-cloud`), which a re-run keeps. +The installer writes the server's names and IPs to `ALLOWED_HOSTS`. Running it again keeps `data/local_settings.py`, the database, the secret key and the main nginx config, but replaces `/etc/nginx/conf.d/webvirtcloud.conf` and the systemd units; back up your own lines in the nginx config (TLS) first. Put your own service settings in `/etc/default/webvirtcloud` or in drop-ins (`systemctl edit webvirt-cloud`), which a re-run keeps. ### Docker @@ -119,10 +119,10 @@ apt-get update && apt-get -y install git python3-venv python3-dev python3-lxml p git clone https://github.com/retspen/webvirtcloud /srv/webvirtcloud cd /srv/webvirtcloud -# 3. Settings, allowed hosts and secret key -cp webvirtcloud/settings.py.template webvirtcloud/settings.py -sed -i 's|^ALLOWED_HOSTS = .*|ALLOWED_HOSTS = ["wvc.example.com", "192.0.2.10", "localhost", "127.0.0.1", "[::1]"]|' webvirtcloud/settings.py -mkdir -p data && python3 conf/secret_generator.py > data/secret_key && chmod 600 data/secret_key +# 3. This installation's settings (data/local_settings.py, see Configuration) and secret key +mkdir -p -m 700 data && (umask 077 && + echo 'ALLOWED_HOSTS += ["wvc.example.com", "192.0.2.10"]' > data/local_settings.py && + python3 conf/secret_generator.py > data/secret_key) # 4. Virtualenv and dependencies python3 -m venv --system-site-packages venv @@ -141,7 +141,7 @@ rm -f /etc/nginx/sites-enabled/default # 7. Ownership, private files, start (the groups let the services reach a local libvirt and KVM) chown -R www-data:www-data /srv/webvirtcloud usermod -a -G libvirt,kvm www-data 2>/dev/null || true # on a KVM host -chmod 700 data && chmod 600 webvirtcloud/settings.py db.sqlite3 +chmod 700 data && chmod 600 data/local_settings.py data/secret_key db.sqlite3 systemctl daemon-reload && systemctl enable --now webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker webvirt-backup.timer nginx -t && systemctl restart nginx ``` @@ -157,10 +157,10 @@ dnf -y install git python3-devel libvirt-devel python3-libvirt python3-lxml cyru git clone https://github.com/retspen/webvirtcloud /srv/webvirtcloud cd /srv/webvirtcloud -# 3. Settings, allowed hosts and secret key -cp webvirtcloud/settings.py.template webvirtcloud/settings.py -sed -i 's|^ALLOWED_HOSTS = .*|ALLOWED_HOSTS = ["wvc.example.com", "192.0.2.10", "localhost", "127.0.0.1", "[::1]"]|' webvirtcloud/settings.py -mkdir -p data && python3 conf/secret_generator.py > data/secret_key && chmod 600 data/secret_key +# 3. This installation's settings (data/local_settings.py, see Configuration) and secret key +mkdir -p -m 700 data && (umask 077 && + echo 'ALLOWED_HOSTS += ["wvc.example.com", "192.0.2.10"]' > data/local_settings.py && + python3 conf/secret_generator.py > data/secret_key) # 4. Virtualenv and dependencies python3 -m venv --system-site-packages venv @@ -180,7 +180,7 @@ cp conf/nginx/webvirtcloud.conf /etc/nginx/conf.d/ # 7. Ownership, private files, SELinux, firewall, start (the groups let the services reach a local libvirt and KVM) chown -R nginx:nginx /srv/webvirtcloud usermod -a -G libvirt,kvm nginx 2>/dev/null || true # on a KVM host -chmod 700 data && chmod 600 webvirtcloud/settings.py db.sqlite3 +chmod 700 data && chmod 600 data/local_settings.py data/secret_key db.sqlite3 # nginx reads the static files, systemd runs the virtualenv's programs semanage fcontext -a -t httpd_sys_content_t "/srv/webvirtcloud(/.*)?" 2>/dev/null || true semanage fcontext -a -t bin_t "/srv/webvirtcloud/venv/bin(/.*)?" 2>/dev/null || true @@ -204,10 +204,10 @@ zypper --non-interactive install -y git hostname python311 python311-base python git clone https://github.com/retspen/webvirtcloud /srv/webvirtcloud cd /srv/webvirtcloud -# 3. Settings, allowed hosts and secret key -cp webvirtcloud/settings.py.template webvirtcloud/settings.py -sed -i 's|^ALLOWED_HOSTS = .*|ALLOWED_HOSTS = ["wvc.example.com", "192.0.2.10", "localhost", "127.0.0.1", "[::1]"]|' webvirtcloud/settings.py -mkdir -p data && python3.11 conf/secret_generator.py > data/secret_key && chmod 600 data/secret_key +# 3. This installation's settings (data/local_settings.py, see Configuration) and secret key +mkdir -p -m 700 data && (umask 077 && + echo 'ALLOWED_HOSTS += ["wvc.example.com", "192.0.2.10"]' > data/local_settings.py && + python3.11 conf/secret_generator.py > data/secret_key) # 4. Virtualenv and dependencies python3.11 -m venv --system-site-packages venv @@ -227,7 +227,7 @@ cp conf/nginx/webvirtcloud.conf /etc/nginx/conf.d/ # 7. Ownership, private files, start (the groups let the services reach a local libvirt and KVM) chown -R nginx:nginx /srv/webvirtcloud usermod -a -G libvirt,kvm nginx 2>/dev/null || true # on a KVM host -chmod 700 data && chmod 600 webvirtcloud/settings.py db.sqlite3 +chmod 700 data && chmod 600 data/local_settings.py data/secret_key db.sqlite3 systemctl daemon-reload && systemctl enable --now webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker webvirt-backup.timer systemctl enable nginx && nginx -t && systemctl restart nginx ``` @@ -354,7 +354,7 @@ If libvirt warns `Host SMBIOS information is not available`, install `dmidecode` | `WEBVIRTCLOUD_DEBUG=1` | Django debug mode: error pages show the traceback and settings; for trying things out only, never on a panel others use | | `WEBVIRTCLOUD_DB_HOST` | use PostgreSQL instead of sqlite (new installs); `WEBVIRTCLOUD_DB_PORT`/`_NAME`/`_USER`/`_PASSWORD` default to 5432/webvirtcloud/webvirtcloud/empty | | `EMAIL_HOST`, `EMAIL_PORT`, `EMAIL_HOST_USER`, `EMAIL_HOST_PASSWORD`, `EMAIL_USE_TLS`, `DEFAULT_FROM_EMAIL` | SMTP for e-mail OTP; `EMAIL_USE_TLS` is 1 (STARTTLS, the default) or 0; the sender `DEFAULT_FROM_EMAIL` defaults to `EMAIL_HOST_USER` | -| `TZ` | time zone of the panel's dates and times and, in Docker, of the container (its daily backup), e.g. `Europe/Istanbul`; default UTC (the installer writes the server's zone into `settings.py` instead) | +| `TZ` | time zone of the panel's dates and times and, in Docker, of the container (its daily backup), e.g. `Europe/Istanbul`; default UTC (the installer writes the server's zone into `data/local_settings.py`, which wins) | | `WEBVIRTCLOUD_LOG_FILE` | log file (default `data/webvirtcloud.log`; a relative path is from the panel's directory; rotated at 10 MB × 5) | | `SECRET_KEY` | Django secret key (default: the `data/secret_key` file) | | `ADMIN_USERNAME`, `ADMIN_PASSWORD` | the first superuser, read by the first `migrate` only, see [First login](#first-login) | @@ -364,27 +364,22 @@ The on/off variables take `1` or `0`; any other value, such as `true`, stops the Where to set them: - **Docker:** the `environment:` list of `docker-compose.override.yml`; every process in the container gets it. -- **Installer and manual installation:** `/etc/default/webvirtcloud` (root, mode 600), one `NAME='value'` per line (single quotes: systemd and the shell then read the same value); the panel's services read it. `settings.py` does not read these names: a line `WEBVIRTCLOUD_HTTPS = 1` there does nothing. To set an option in `settings.py` instead, change the setting the template fills from the variable, e.g. `SERIAL_CONSOLE_ENABLED = True`. Then `systemctl restart webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker`, and load the file before running `manage.py`: `set -a; . /etc/default/webvirtcloud; set +a`. - -Some options exist only in `settings.py` (LDAP, `OTP_ENABLED`, `LOGIN_TRUSTED_PROXIES`). Docker builds that file from the template in each new container; to keep such options there, mount your own copy and update it from the template after each update: - -```bash -docker compose exec webvirtcloud cat webvirtcloud/settings.py > settings.py # then edit it -``` - -add it to `docker-compose.override.yml` and run `docker compose up -d`: - -```yaml -services: - webvirtcloud: - volumes: - - ./settings.py:/srv/webvirtcloud/webvirtcloud/settings.py -``` - -The container makes the file the panel user's (uid 33) with mode 600; edit it as root. +- **Installer and manual installation:** `/etc/default/webvirtcloud` (root, mode 600), one `NAME='value'` per line (single quotes: systemd and the shell then read the same value); the panel's services read it. [`data/local_settings.py`](#local-settings) does not read these names: a line `WEBVIRTCLOUD_HTTPS = 1` there does nothing; it sets the setting the variable fills, e.g. `SERIAL_CONSOLE_ENABLED = True`. Then `systemctl restart webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker`, and load the file before running `manage.py`: `set -a; . /etc/default/webvirtcloud; set +a`. gunicorn runs at most 8 workers (fewer on hosts with under 4 CPUs), in Docker 4, of 4 threads each; each worker takes about 140 MB and sends at most 2 requests at a time to one compute. To change it, set `GUNICORN_CMD_ARGS=--workers N` in a drop-in of `webvirt-cloud` (`systemctl edit webvirt-cloud`: `[Service]` and `Environment="GUNICORN_CMD_ARGS=--workers N"`) or in `docker-compose.override.yml`. +### Local settings + +Options that are not environment variables (LDAP, `OTP_ENABLED`, `LOGIN_TRUSTED_PROXIES` or any other setting of `webvirtcloud/settings.py`) go into `data/local_settings.py`. `settings.py` runs it after its own defaults and with their names, so it sets or changes any of them, and its values win over the environment's; updates replace `settings.py` and leave this file alone. For example: + +```python +TIME_ZONE = "Europe/Istanbul" +ALLOWED_HOSTS += ["wvc.example.com"] +OTP_ENABLED = True +``` + +The installer writes the server's time zone, the noVNC port and its names and IPs into it. A value `settings.py` works out from another before the file runs stays as it was: with `EMAIL_HOST_USER` set here, set `DEFAULT_FROM_EMAIL` here too; the log file is set with `WEBVIRTCLOUD_LOG_FILE` in the environment. It may hold passwords (LDAP): keep it the panel user's with mode 600. After a change, `systemctl restart webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker`. Docker keeps it in the `webvirtcloud-data` volume: write it next to the compose file, then `docker compose cp local_settings.py webvirtcloud:/srv/webvirtcloud/data/` and `docker compose restart webvirtcloud` (the start makes it the panel user's). + ### HTTPS and reverse proxy For a panel served over HTTPS: @@ -392,7 +387,7 @@ For a panel served over HTTPS: - set `WEBVIRTCLOUD_HTTPS=1`: session and CSRF cookies become HTTPS-only, HTTP is redirected to HTTPS (except `/datasource/`, which VMs fetch over HTTP), and HSTS is sent for one year; - add the HTTPS origin to `CSRF_TRUSTED_ORIGINS`, e.g. `CSRF_TRUSTED_ORIGINS=https://wvc.example.com` and `WEBVIRTCLOUD_HTTPS=1` in `/etc/default/webvirtcloud`. -TLS can end at the bundled nginx or at a proxy in front of it; such a proxy must send `X-Forwarded-Proto: https`. Failed logins are counted per client address, which the bundled nginx passes in `X-Real-IP`. A proxy that replaces the bundled nginx must set `X-Real-IP` itself; one on another machine (gunicorn bound beyond 127.0.0.1) must also be in `LOGIN_TRUSTED_PROXIES` in `settings.py`. With a proxy in front of the bundled nginx, configure nginx's `set_real_ip_from` / `real_ip_header` for that proxy, or all clients share its address. +TLS can end at the bundled nginx or at a proxy in front of it; such a proxy must send `X-Forwarded-Proto: https`. Failed logins are counted per client address, which the bundled nginx passes in `X-Real-IP`. A proxy that replaces the bundled nginx must set `X-Real-IP` itself; one on another machine (gunicorn bound beyond 127.0.0.1) must also be in `LOGIN_TRUSTED_PROXIES` in [`data/local_settings.py`](#local-settings). With a proxy in front of the bundled nginx, configure nginx's `set_real_ip_from` / `real_ip_header` for that proxy, or all clients share its address. Every page is sent with `X-Frame-Options: DENY` and `Content-Security-Policy: script-src 'self'; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'`: the panel runs only scripts it serves itself, cannot be shown in a frame, and its forms post only to its own origin. @@ -410,7 +405,7 @@ Without the network: tick **Cloud-init seed** (Advanced) when creating a VM. The ### LDAP -The options below are set in `webvirtcloud/settings.py` (Docker: see [Environment variables](#environment-variables) for keeping your own). Variants for Active Directory and OpenLDAP are shown; this is a minimal config, see the [django-auth-ldap documentation](https://django-auth-ldap.readthedocs.io) for more. +The options below go into [`data/local_settings.py`](#local-settings), which has `ldap`, `LDAPSearch` and `NestedActiveDirectoryGroupType` at hand. Variants for Active Directory and OpenLDAP are shown; this is a minimal config, see the [django-auth-ldap documentation](https://django-auth-ldap.readthedocs.io) for more. The Docker image includes the LDAP packages. On an installer or manual install, add them to the virtualenv first; pip builds `python-ldap` against these headers: @@ -423,8 +418,8 @@ zypper --non-interactive install -y openldap2-devel cyrus-sasl-devel # openSUS Enable the LDAP backend: -```bash -sudo sed -i "s~#\"django_auth_ldap.backend.LDAPBackend\",~\"django_auth_ldap.backend.LDAPBackend\",~g" /srv/webvirtcloud/webvirtcloud/settings.py +```python +AUTHENTICATION_BACKENDS.append("django_auth_ldap.backend.LDAPBackend") ``` Set the LDAP server and bind DN: @@ -460,7 +455,8 @@ AUTH_LDAP_USER_SEARCH = LDAPSearch( AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "ou=groups,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=groupOfUniqueNames)" ) -AUTH_LDAP_GROUP_TYPE = GroupOfUniqueNamesType() # import needs to be changed at the top of settings.py +from django_auth_ldap.config import GroupOfUniqueNamesType +AUTH_LDAP_GROUP_TYPE = GroupOfUniqueNamesType() ``` Set the group required to access WebVirtCloud (`False` disables this filter): @@ -487,7 +483,7 @@ An LDAP user is authenticated by LDAP and authorized through the WebVirtCloud pe ### Two-factor login (OTP) -Set `OTP_ENABLED = True` in `settings.py` to ask for a one-time code at login. It is per user: a user without a confirmed device signs in with the password alone. +Set `OTP_ENABLED = True` in [`data/local_settings.py`](#local-settings) to ask for a one-time code at login. It is per user: a user without a confirmed device signs in with the password alone. The QR code is mailed as a link to a page that shows it, good for one hour: the mail does not hold the code's secret. Email OTP QR code on a user's page (Users) sends it; Lost OTP? on the login page sends it to an enrolled user who gives their address. @@ -499,7 +495,7 @@ On the Settings page (Alerts), **Alert e-mail addresses** get a mail, through th ### Serial console -A VM without graphics (no `` device, a ``) opens a serial console (xterm.js) instead of VNC. It is off by default. To turn it on, set `WEBVIRTCLOUD_SERIAL_CONSOLE=1` (Docker: in `docker-compose.override.yml`, then `docker compose up -d`) or `SERIAL_CONSOLE_ENABLED = True` in `settings.py` and `systemctl restart webvirt-cloud webvirt-socketiod`. +A VM without graphics (no `` device, a ``) opens a serial console (xterm.js) instead of VNC. It is off by default. To turn it on, set `WEBVIRTCLOUD_SERIAL_CONSOLE=1` (Docker: in `docker-compose.override.yml`, then `docker compose up -d`) or `SERIAL_CONSOLE_ENABLED = True` in [`data/local_settings.py`](#local-settings) and `systemctl restart webvirt-cloud webvirt-socketiod`. - The VM page's Settings → Console switches a shut-off VM between VNC and serial (Console type). A new VNC console takes the form's other fields; on a TCP or TLS compute it needs Listen on: All interfaces (SSH and socket computes reach a localhost console). - The guest must use its serial port: a login prompt needs `systemctl enable --now serial-getty@ttyS0`, boot messages need the kernel parameter `console=ttyS0,115200`. The console shows only what the guest writes after it opens; press Enter for a new prompt. @@ -513,7 +509,7 @@ A VM without graphics (no `` device, a ``) opens a The panel backs itself up every day at 03:15 (cron in Docker; otherwise `webvirt-backup.timer`, within 10 minutes after and at the next boot if the server was off) into a new directory under `/srv/webvirtcloud/backups`, in Docker the `webvirtcloud-backups` volume, and keeps the newest 7. A backup holds: - `db.sqlite3`: a consistent copy taken while the panel runs, checked with `PRAGMA integrity_check`; with PostgreSQL it is left out, so back up that database yourself -- `secret_key`, `node_id` and `settings.py` +- `secret_key`, `node_id` and `local_settings.py` - `ssh/`: the SSH keys of the panel's user, which the SSH computes accept - `pki/`: the TLS client certificates of the panel's user, which the TLS computes accept - `commit`, outside Docker @@ -630,11 +626,11 @@ The panel does not copy VM backups off site: the target's storage does. ## Updating -Every update starts with a backup in its own directory (mode 700, named by date) that holds the database, the commit it was taken from, for Docker the TLS client certificates and, for installer and manual installations, `settings.py`, the nginx config, `/etc/default/webvirtcloud` if there is one and migrations an old installer generated (`local-migrations.tar`). The database is copied with SQLite's backup API, which also finishes a write interrupted by a crash. This covers sqlite only; with PostgreSQL (`WEBVIRTCLOUD_DB_HOST`), back up that database yourself before updating. +Every update starts with a backup in its own directory (mode 700, named by date) that holds the database, the commit it was taken from, for Docker the TLS client certificates and, for installer and manual installations, `data/local_settings.py` (and a `settings.py` of an older version), the nginx config, `/etc/default/webvirtcloud` if there is one and migrations an old installer generated (`local-migrations.tar`). The database is copied with SQLite's backup API, which also finishes a write interrupted by a crash. This covers sqlite only; with PostgreSQL (`WEBVIRTCLOUD_DB_HOST`), back up that database yourself before updating. ### Docker -Each new container builds `settings.py` from the template and runs the migrations at start; the database and the secret key stay in the `webvirtcloud-data` volume. Keep your settings in `docker-compose.override.yml` (at least `ALLOWED_HOSTS`, see [Docker](#docker)). +Each new container runs the migrations at start; the database, the secret key and [`data/local_settings.py`](#local-settings) stay in the `webvirtcloud-data` volume. Keep your environment in `docker-compose.override.yml` (at least `ALLOWED_HOSTS`, see [Docker](#docker)). An override that mounts your own `settings.py` (`./settings.py:/srv/webvirtcloud/webvirtcloud/settings.py`, as older versions of this README said) would keep that old file: remove the mount and move your own values into `data/local_settings.py`. Run the commands in the directory you installed from. Compose names the deployment after that directory (`webvirtcloud`), so another clone in a directory of the same name acts on the same containers and volumes. @@ -671,7 +667,7 @@ Move the `environment=` values of that config into `/etc/default/webvirtcloud` ( ### Installer and manual installation -`git pull` never overwrites `webvirtcloud/settings.py` or `/etc/nginx/conf.d/webvirtcloud.conf`; steps 2 and 4 bring them up to date. Run the steps from a root shell; they use `$b`, so in a new shell set it again to the backup directory. +`git pull` never changes `data/` (the database, the secret key, [`data/local_settings.py`](#local-settings)) or `/etc/nginx/conf.d/webvirtcloud.conf`; step 4 brings the nginx config up to date. Run the steps from a root shell; they use `$b`, so in a new shell set it again to the backup directory. 1. Stop the panel, back up and pull: @@ -685,7 +681,9 @@ Move the `environment=` values of that config into `/etc/default/webvirtcloud` ( mkdir -m 700 "$b" && venv/bin/python3 -c "import sqlite3,sys; sqlite3.connect('db.sqlite3').backup(sqlite3.connect(sys.argv[1]))" "$b/db.sqlite3.part" && mv "$b/db.sqlite3.part" "$b/db.sqlite3" && - cp -p webvirtcloud/settings.py /etc/nginx/conf.d/webvirtcloud.conf "$b"/ && + cp -p /etc/nginx/conf.d/webvirtcloud.conf "$b"/ && + { [ ! -f data/local_settings.py ] || cp -p data/local_settings.py "$b"/; } && + { git ls-files --error-unmatch webvirtcloud/settings.py >/dev/null 2>&1 || [ ! -f webvirtcloud/settings.py ] || mv webvirtcloud/settings.py "$b"/; } && { [ ! -f /etc/default/webvirtcloud ] || cp -p /etc/default/webvirtcloud "$b"/; } && git rev-parse HEAD > "$b/commit" && git ls-files -z --others --exclude-standard -- '*/migrations/*.py' | tar --null -T - --remove-files -cf "$b/local-migrations.tar" && @@ -693,16 +691,15 @@ Move the `environment=` values of that config into `/etc/default/webvirtcloud` ( git checkout master && git pull ``` - Older installers collected static files into the tracked `static/` and deleted the tracked `install.sh` and `webvirtcloud.sh`; the second-to-last line puts those files back, so that `git pull` can update them. + Older installers collected static files into the tracked `static/` and deleted the tracked `install.sh` and `webvirtcloud.sh`; the second-to-last line puts those files back, so that `git pull` can update them. Older versions also had a `settings.py` of their own, not in the repository: step 1 moves it into the backup, as `git pull` now brings `settings.py`. -2. Rebuild `settings.py` from the template (the file keeps its owner and mode), then put back your own values; the `diff` lists them: +2. Once, coming from a version with its own `settings.py` (step 1 moved it to `$b`): put your own values into [`data/local_settings.py`](#local-settings); the `diff` lists them: ```bash - cat webvirtcloud/settings.py.template > webvirtcloud/settings.py diff "$b/settings.py" webvirtcloud/settings.py ``` - Typical ones are `TIME_ZONE`, `WS_*`, `ALLOWED_HOSTS`, `CSRF_TRUSTED_ORIGINS`, LDAP and, with PostgreSQL, your `DATABASES`: the template's is sqlite, so without it `migrate` would make a new, empty sqlite database and the panel would start on that. Two need care: + Typical ones are `TIME_ZONE`, `WS_*`, `ALLOWED_HOSTS`, `CSRF_TRUSTED_ORIGINS`, LDAP and, with PostgreSQL, your `DATABASES`: the default is sqlite, so without it `migrate` would make a new, empty sqlite database and the panel would start on that. Two need care: - a literal `SECRET_KEY = "..."` (older installers wrote it there): put the value into `data/secret_key` instead (`mkdir -p data` first if there is no `data/`). With no key, `migrate` in step 3 stops with "The SECRET_KEY setting must not be empty" and every page fails; with another key, every user is signed out; - `SHOW_PROFILE_EDIT_PASSWORD`: keep it for this one `migrate` if you have it (migration `accounts.0008` reads it), then delete it. @@ -716,12 +713,12 @@ Move the `environment=` values of that config into `/etc/default/webvirtcloud` ( venv/bin/python3 manage.py migrate && venv/bin/python3 manage.py collectstatic --noinput && chown -R www-data:www-data /srv/webvirtcloud && - chmod -R go-rwx data webvirtcloud/settings.py db.sqlite3 + chmod -R go-rwx data db.sqlite3 ``` Installers from before September 2025 generated migrations of their own; step 1 moved them into `local-migrations.tar`. One of them has the name of a tracked migration, which `migrate` would skip; the second line marks it unapplied so that the tracked one runs. -4. Update the nginx config the same way as `settings.py`: +4. Update the nginx config, then put back your own lines; the `diff` lists them: ```bash cp conf/nginx/webvirtcloud.conf /etc/nginx/conf.d/webvirtcloud.conf @@ -751,7 +748,7 @@ Older versions collected static files into `static/`; `git clean -n static/` lis ### Restore and rollback -Restoring puts back the database as it was at the backup; changes made since are lost. Migrations are not reversed. This covers sqlite; restore a PostgreSQL database from your own backup before rolling back the code. Set `b` to the backup directory to restore. To restore the database without rolling back the code, leave out the `build` line and every line that takes another file from `$b`: the commit, `local-migrations.tar`, `settings.py`, the nginx config and `/etc/default/webvirtcloud`. +Restoring puts back the database as it was at the backup; changes made since are lost. Migrations are not reversed. This covers sqlite; restore a PostgreSQL database from your own backup before rolling back the code. Set `b` to the backup directory to restore. To restore the database without rolling back the code, leave out the `build` line and every line that takes another file from `$b`: the commit, `local-migrations.tar`, `settings.py` and `local_settings.py`, the nginx config and `/etc/default/webvirtcloud`. Docker, in the directory you installed from: @@ -769,7 +766,7 @@ docker compose start && docker compose exec webvirtcloud chown -R www-data:www-data /var/www/.pki ``` -The container fixes the ownership and modes of the database and keys at start; the last line gives the TLS client certificates to `www-data` also in an image of v4.3.0 or older, which neither does that nor keeps them in a volume. +A version from before `data/local_settings.py` builds its `settings.py` from a template and does not read that file: to roll back to one, mount your `settings.py` again as that version's README says. The container fixes the ownership and modes of the database and keys at start; the last line gives the TLS client certificates to `www-data` also in an image of v4.3.0 or older, which neither does that nor keeps them in a volume. Installer and manual installation, from a root shell (`nginx:nginx` on RHEL / openSUSE): @@ -782,16 +779,19 @@ git checkout -- $(git ls-files -m -- static/css dev/scss) && git checkout "$(cat "$b/commit")" && { [ ! -f "$b/local-migrations.tar" ] || tar -xf "$b/local-migrations.tar"; } && venv/bin/python3 -c "import os,sqlite3,sys; [os.remove(p) for p in ('db.sqlite3-journal','db.sqlite3-wal','db.sqlite3-shm') if os.path.exists(p)]; sqlite3.connect(sys.argv[1]).backup(sqlite3.connect('db.sqlite3'))" "$b/db.sqlite3" && -cp "$b/settings.py" webvirtcloud/settings.py && +{ [ ! -f "$b/settings.py" ] || cp "$b/settings.py" webvirtcloud/settings.py; } && +{ [ ! -f "$b/local_settings.py" ] || cp -p "$b/local_settings.py" data/; } && { [ ! -f "$b/webvirtcloud.conf" ] || cp "$b/webvirtcloud.conf" /etc/nginx/conf.d/webvirtcloud.conf; } && { [ ! -f "$b/webvirtcloud" ] || { set -a; . "$b/webvirtcloud"; set +a; }; } && venv/bin/pip3 install -r conf/requirements.txt && venv/bin/python3 manage.py migrate && venv/bin/python3 manage.py collectstatic --noinput && chown -R www-data:www-data /srv/webvirtcloud && -chmod 600 db.sqlite3 webvirtcloud/settings.py +chmod 600 db.sqlite3 && { [ ! -f "$b/settings.py" ] || chmod 600 webvirtcloud/settings.py; } ``` +A backup of a version that had its own `settings.py` (not in the repository) holds that file: the steps put it back for the older code. + Put back `/etc/default/webvirtcloud` if the backup has it (`cp -p "$b/webvirtcloud" /etc/default/`), then reload nginx and start the panel: ```bash @@ -813,13 +813,14 @@ docker compose stop -t 95 && docker compose run --rm --no-deps -T --entrypoint /srv/webvirtcloud/venv/bin/python3 webvirtcloud \ -c "import os,sqlite3,sys,tempfile; t=tempfile.mktemp(); open(t,'wb').write(sys.stdin.buffer.read()); [os.remove(p) for p in ('data/db.sqlite3-journal','data/db.sqlite3-wal','data/db.sqlite3-shm') if os.path.exists(p)]; sqlite3.connect(t).backup(sqlite3.connect('data/db.sqlite3'))" < "$b/db.sqlite3" && { [ ! -f "$b/secret_key" ] || docker compose cp "$b/secret_key" webvirtcloud:/srv/webvirtcloud/data/; } && +{ [ ! -f "$b/local_settings.py" ] || docker compose cp "$b/local_settings.py" webvirtcloud:/srv/webvirtcloud/data/; } && docker compose cp "$b/node_id" webvirtcloud:/srv/webvirtcloud/data/ && { [ ! -d "$b/ssh" ] || docker compose cp "$b/ssh/." webvirtcloud:/var/www/.ssh/; } && { [ ! -d "$b/pki" ] || docker compose cp "$b/pki/." webvirtcloud:/var/www/.pki/; } && docker compose up -d # the container migrates and fixes ownership and modes at start ``` -Installer and manual installation, from a root shell (`nginx` instead of `www-data` on RHEL / openSUSE). Compare `$b/settings.py` with `webvirtcloud/settings.py` and carry your own values over: +Installer and manual installation, from a root shell (`nginx` instead of `www-data` on RHEL / openSUSE). A backup of an older version has a `settings.py` instead of `local_settings.py`: carry your own values from it into [`data/local_settings.py`](#local-settings). ```bash b=/root/webvirtcloud-backup-YYYYMMDD-HHMMSS @@ -827,11 +828,12 @@ systemctl stop webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker cd /srv/webvirtcloud && venv/bin/python3 -c "import os,sqlite3,sys; [os.remove(p) for p in ('db.sqlite3-journal','db.sqlite3-wal','db.sqlite3-shm') if os.path.exists(p)]; sqlite3.connect(sys.argv[1]).backup(sqlite3.connect('db.sqlite3'))" "$b/db.sqlite3" && cp "$b/node_id" data/ && { [ ! -f "$b/secret_key" ] || cp "$b/secret_key" data/; } && +{ [ ! -f "$b/local_settings.py" ] || cp "$b/local_settings.py" data/; } && mkdir -p ~www-data/.ssh && { [ ! -d "$b/ssh" ] || cp -r "$b"/ssh/. ~www-data/.ssh/; } && mkdir -p ~www-data/.pki && { [ ! -d "$b/pki" ] || cp -r "$b"/pki/. ~www-data/.pki/; } && venv/bin/python3 manage.py migrate && chown -R www-data:www-data data ~www-data/.ssh ~www-data/.pki && -chmod 700 data ~www-data/.ssh ~www-data/.pki && { [ ! -f db.sqlite3 ] || chmod 600 db.sqlite3; } && +chmod 700 data ~www-data/.ssh ~www-data/.pki && chmod -R go-rwx data && { [ ! -f db.sqlite3 ] || chmod 600 db.sqlite3; } && systemctl start webvirt-cloud webvirt-novncd webvirt-socketiod webvirt-worker ``` @@ -847,8 +849,8 @@ What an update from an older version changes for operators and users. `manage.py - The admin's first-login password change survives losing `data/admin_password` (migration `accounts.0007`); run `migrate` as a user who can read that file. - A new VM and each clone get a random VNC password of their own (clones no longer share their source's). The console page sends it for a user with **Open a console without the VM's console password**, which a new user has unless unticked; others are asked for it. Existing VMs keep theirs. - An `admin` account that still has the password `admin` (the first user of versions up to v2.0.0) must change it at its next login, and its API tokens are refused until then (migration `accounts.0013`). -- A `settings.py` kept from an older version must match the template (apps, middleware, the SQLite `OPTIONS`, the REST framework, knox, axes and password settings): rebuild it from the template and carry your own values over, as step 2 of the update does. -- The VNC console connects to `/novncd/` on the panel's own address through nginx, and the serial console to `/socket.io/`: they work on HTTPS and behind another proxy without settings. `WS_PUBLIC_PORT`, `WS_PUBLIC_HOST`, `WS_PUBLIC_PATH`, `WS_CERT` and `SOCKETIO_PUBLIC_HOST`/`_PORT`/`_PATH` are gone; remove them from `docker-compose.override.yml`, `/etc/default/webvirtcloud` or a kept `settings.py`, set `WS_HOST = "127.0.0.1"` in a kept `settings.py`, and close port 6080 in the firewall. +- `webvirtcloud/settings.py` is part of the code, and every update replaces it; an installation's own settings are in [`data/local_settings.py`](#local-settings). Step 2 of the update moves them there once from an older version's own `settings.py`; in Docker, remove a mounted `settings.py` from `docker-compose.override.yml`. +- The VNC console connects to `/novncd/` on the panel's own address through nginx, and the serial console to `/socket.io/`: they work on HTTPS and behind another proxy without settings. `WS_PUBLIC_PORT`, `WS_PUBLIC_HOST`, `WS_PUBLIC_PATH`, `WS_CERT` and `SOCKETIO_PUBLIC_HOST`/`_PORT`/`_PATH` are gone; remove them from `docker-compose.override.yml`, `/etc/default/webvirtcloud` or `data/local_settings.py`, and close port 6080 in the firewall. - Installer and manual installations run the panel as systemd units (`webvirt-cloud`, `webvirt-novncd`, `webvirt-socketiod`, `webvirt-worker`, `webvirt-backup.timer`) and computes run `webvirt-gstfsd`, instead of supervisor; see [Moving from supervisor to systemd](#moving-from-supervisor-to-systemd). Service settings go into `/etc/default/webvirtcloud`, service output into the journal (`journalctl -u webvirt-cloud`); the app log stays in `data/`. novncd and socketiod run sandboxed (read-only system directories, no `/home`). - gstfsd does only what the panel signs with the host's key: it does not start without `GSTFSD_KEY` in `/etc/default/webvirt-gstfsd`. On every compute, update gstfsd and its unit and make the key as in [Adding a Compute Node](#adding-a-compute-node), step 3 (a remote panel's `GSTFSD_BIND_HOST` and `GSTFSD_ALLOW_REMOTE` move into that file from `systemctl edit webvirt-gstfsd`), then enter the key on each compute's edit page. - LDAP login's packages are in `conf/requirements-ldap.txt` and no longer installed by default, nor their build headers by the installer; the Docker image keeps them. An existing virtualenv keeps them, but only installing that file updates them (see [LDAP](#ldap)). @@ -937,10 +939,9 @@ Run every step as your normal user, not with `sudo`: if `manage.py` ever runs as pip install -r dev/requirements.txt ``` -3. Settings and secret key: +3. Secret key (your own settings go into [`data/local_settings.py`](#local-settings)): ```bash - cp webvirtcloud/settings.py.template webvirtcloud/settings.py mkdir -p data && python conf/secret_generator.py > data/secret_key && chmod 600 data/secret_key ``` @@ -1016,7 +1017,7 @@ python manage.py test HOME=$PWD/.vagrant/tls TEST_LIBVIRT_TYPE=3 TEST_LIBVIRT_SSH_HOST= python manage.py test # compute1 again, over TLS # a socket compute is the panel's own libvirt: the committed HEAD runs inside compute1 git archive HEAD | vagrant ssh compute1 -c "sudo sh -c 'rm -rf /root/wvc && mkdir /root/wvc && tar -x -C /root/wvc'" -vagrant ssh compute1 -c "sudo -i sh -ec 'dnf -y install python3-devel openldap-devel cyrus-sasl-devel gcc; cd /root/wvc; python3 -m venv --system-site-packages venv; venv/bin/pip install -r dev/requirements.txt; cp webvirtcloud/settings.py.template webvirtcloud/settings.py; mkdir data; venv/bin/python conf/secret_generator.py > data/secret_key; TEST_LIBVIRT_HOST=localhost TEST_LIBVIRT_TYPE=4 TEST_LIBVIRT_LOGIN=wvc TEST_LIBVIRT_PASSWORD=wvc-test TEST_LIBVIRT_LVM_DEVICE=/dev/vdb TEST_LIBVIRT_ISCSI_TARGET=iqn.2026-10.test.wvc:lun TEST_LIBVIRT_NFS_EXPORT=/srv/wvc-nfs venv/bin/python manage.py test'" +vagrant ssh compute1 -c "sudo -i sh -ec 'dnf -y install python3-devel openldap-devel cyrus-sasl-devel gcc; cd /root/wvc; python3 -m venv --system-site-packages venv; venv/bin/pip install -r dev/requirements.txt; mkdir data; venv/bin/python conf/secret_generator.py > data/secret_key; TEST_LIBVIRT_HOST=localhost TEST_LIBVIRT_TYPE=4 TEST_LIBVIRT_LOGIN=wvc TEST_LIBVIRT_PASSWORD=wvc-test TEST_LIBVIRT_LVM_DEVICE=/dev/vdb TEST_LIBVIRT_ISCSI_TARGET=iqn.2026-10.test.wvc:lun TEST_LIBVIRT_NFS_EXPORT=/srv/wvc-nfs venv/bin/python manage.py test'" vagrant destroy -f ``` diff --git a/accounts/checks.py b/accounts/checks.py index 88cd90de..1ef972c6 100644 --- a/accounts/checks.py +++ b/accounts/checks.py @@ -14,7 +14,7 @@ def password_change_middleware_check(app_configs, **kwargs): return [ Error( "ForcePasswordChangeMiddleware must follow AuthenticationMiddleware.", - hint=f"Add '{required}' to MIDDLEWARE in webvirtcloud/settings.py, as settings.py.template does.", + hint=f"data/local_settings.py sets MIDDLEWARE: keep '{required}' after AuthenticationMiddleware, as webvirtcloud/settings.py has it.", id="accounts.E001", ) ] @@ -30,8 +30,8 @@ def login_required_middleware_check(app_configs, **kwargs): return [ Error( "MIDDLEWARE must use Django's LoginRequiredMiddleware.", - hint=f"In webvirtcloud/settings.py replace '{old}' with '{required}' " - "and delete LOGIN_REQUIRED_IGNORE_VIEW_NAMES, as settings.py.template does.", + hint=f"data/local_settings.py sets MIDDLEWARE: replace '{old}' with '{required}' " + "and delete LOGIN_REQUIRED_IGNORE_VIEW_NAMES, as webvirtcloud/settings.py has it.", id="accounts.E002", ) ] @@ -44,7 +44,7 @@ def obsolete_settings_check(app_configs, **kwargs): return [ Warning( "SHOW_PROFILE_EDIT_PASSWORD is no longer used.", - hint="Remove it from webvirtcloud/settings.py. Whether a user may change their own " + hint="Remove it from data/local_settings.py. Whether a user may change their own " "password is the 'Can change password' permission, per user or group.", id="accounts.W001", ) diff --git a/appsettings/management/commands/backup.py b/appsettings/management/commands/backup.py index a8a8d6d1..8229a67e 100644 --- a/appsettings/management/commands/backup.py +++ b/appsettings/management/commands/backup.py @@ -15,7 +15,7 @@ PREFIX = "webvirtcloud-backup-" class Command(BaseCommand): - help = ("Copy the database, secret key, worker id, settings and the SSH keys and TLS certificates of the " + help = ("Copy the database, secret key, worker id, local settings and the SSH keys and TLS certificates of the " "panel's user into a new directory in backups/, then delete all but the newest --keep backups.") def add_arguments(self, parser): @@ -70,7 +70,7 @@ class Command(BaseCommand): # the key in use: SECRET_KEY from the environment has no data/secret_key (to / "secret_key").write_text(settings.SECRET_KEY + "\n") data = settings.BASE_DIR / "data" - for source in (data / "node_id", settings.BASE_DIR / "webvirtcloud" / "settings.py"): + for source in (data / "node_id", data / "local_settings.py"): if source.is_file(): shutil.copyfile(source, to / source.name) ssh = Path.home() / ".ssh" diff --git a/appsettings/tests/test_backup.py b/appsettings/tests/test_backup.py index 4a6790a3..a8f23c93 100644 --- a/appsettings/tests/test_backup.py +++ b/appsettings/tests/test_backup.py @@ -30,7 +30,7 @@ class BackupTests(SimpleTestCase): self.addCleanup(shutil.rmtree, self.base) self.addCleanup(os.umask, os.umask(0o022)) # the command sets its own for path, text in (("data/secret_key", "key"), ("data/node_id", "a1b2c3"), - ("webvirtcloud/settings.py", "DEBUG = False"), ("home/.ssh/id_ed25519", "private")): + ("data/local_settings.py", "DEBUG = False"), ("home/.ssh/id_ed25519", "private")): (self.base / path).parent.mkdir(parents=True, exist_ok=True) (self.base / path).write_text(text) (self.base / "home/.ssh/agent").symlink_to(self.base / "data/secret_key") @@ -66,7 +66,7 @@ class BackupTests(SimpleTestCase): backup = self.backup() with closing(sqlite3.connect(backup / "db.sqlite3")) as db: self.assertEqual(db.execute("SELECT name FROM computes_compute").fetchall(), [("kept",)]) - self.assertEqual(sorted(p.name for p in backup.iterdir()), ["db.sqlite3", "node_id", "secret_key", "settings.py", "ssh"]) + self.assertEqual(sorted(p.name for p in backup.iterdir()), ["db.sqlite3", "local_settings.py", "node_id", "secret_key", "ssh"]) # the key in use, also when it came from the environment and not data/secret_key self.assertEqual((backup / "secret_key").read_text(), "key in use\n") self.assertEqual(oct((backup / "secret_key").stat().st_mode & 0o777), "0o600") diff --git a/conf/docker/start b/conf/docker/start index e68ebab5..a644f470 100644 --- a/conf/docker/start +++ b/conf/docker/start @@ -1,10 +1,9 @@ #!/bin/sh -# The container's start: settings, secret key and database in place, the +# The container's start: secret key and database in place, the # data the panel's own, migrations run; then the command (supervisord). set -eu cd /srv/webvirtcloud -[ -f webvirtcloud/settings.py ] || cp webvirtcloud/settings.py.template webvirtcloud/settings.py if [ -z "${SECRET_KEY:-}" ] && [ ! -s data/secret_key ]; then (umask 077 && venv/bin/python3 -c 'import secrets; print(secrets.token_urlsafe(50))' > data/secret_key) fi @@ -12,12 +11,14 @@ fi touch data/db.sqlite3 ln -sfn /srv/webvirtcloud/data/db.sqlite3 db.sqlite3 -# The database holds compute passwords and password hashes: the data, keys, -# settings and backups are readable by the panel's user only. +# The database holds compute passwords and password hashes: the data (the +# database, the key, local_settings.py), keys and backups are readable by the +# panel's user only. chown -R www-data:www-data data /var/www/.ssh /var/www/.pki -chown www-data:www-data backups webvirtcloud/settings.py +chown www-data:www-data backups chmod 700 data backups /var/www/.ssh /var/www/.pki -chmod 600 data/db.sqlite3 webvirtcloud/settings.py +chmod 600 data/db.sqlite3 +[ ! -f data/local_settings.py ] || chmod 600 data/local_settings.py # cron starts its jobs with an empty environment: the backup reads this one (umask 077 && export -p > /run/webvirtcloud.env) diff --git a/conf/install-lib.sh b/conf/install-lib.sh index c1b6f6fe..d0eaf8e2 100755 --- a/conf/install-lib.sh +++ b/conf/install-lib.sh @@ -19,27 +19,33 @@ wvc_ensure_secret_key() { [ -s "$key_file" ] } -# Copy settings.py from the template only when it does not already exist, so a -# re-run never overwrites local edits. 0 + "created" on first copy; 1 + "kept" -# when it already exists. -wvc_ensure_settings() { - local template="$1" target="$2" - if [ -f "$target" ]; then +# Write /local_settings.py (mode 600) from stdin only when it does not +# exist: the installation's own settings, which a re-run and updates keep. +# 0 + "created" when written; 1 + "kept" when it already exists; 2 when it could +# not be written (no file is left). +wvc_ensure_local_settings() { + local data_dir="$1" file + file="$data_dir/local_settings.py" + if [ -f "$file" ]; then echo "kept" return 1 fi - cp "$template" "$target" + if ! ( umask 077; cat > "$file.part" ) || ! mv "$file.part" "$file"; then + rm -f "$file.part" + return 2 + fi echo "created" return 0 } -# Restrict modes so the secret, settings, and db are not world-readable. +# Restrict modes so the secret, the local settings and the db are not world-readable. wvc_harden_modes() { - local settings="$1" db="$2" data_dir="$3" - [ -e "$settings" ] && chmod 600 "$settings" + local db="$1" data_dir="$2" file [ -e "$db" ] && chmod 600 "$db" [ -d "$data_dir" ] && chmod 700 "$data_dir" - [ -e "$data_dir/secret_key" ] && chmod 600 "$data_dir/secret_key" + for file in secret_key local_settings.py; do + [ -e "$data_dir/$file" ] && chmod 600 "$data_dir/$file" + done return 0 } diff --git a/dev/test-installer.sh b/dev/test-installer.sh index 734bd983..dba9e13e 100755 --- a/dev/test-installer.sh +++ b/dev/test-installer.sh @@ -1,7 +1,8 @@ #!/bin/bash # Installs the panel with install.sh in a systemd container of one distribution -# and checks that it answers: its services run, it has a secret key and an -# admin password, and the login page loads. It installs the committed HEAD. +# and checks that it answers: its services run, it has a secret key, an admin +# password and its local settings, and the login page loads. It installs the +# committed HEAD. # # Usage, from the repository root (needs docker): # dev/test-installer.sh IMAGE e.g. debian:13, almalinux:10, opensuse/leap:15.6 @@ -55,6 +56,7 @@ docker exec "$name" bash -c ' docker exec "$name" bash -e -c ' test -s /srv/webvirtcloud/data/secret_key || { echo "No secret key"; exit 1; } test -s /srv/webvirtcloud/data/admin_password || { echo "No admin password"; exit 1; } + test -s /srv/webvirtcloud/data/local_settings.py || { echo "No local settings"; exit 1; } # curl is not on every distribution; the panel'"'"'s Python is /srv/webvirtcloud/venv/bin/python3 - <&2; exit 1; } - echo "* Configuring settings.py file." - if wvc_ensure_settings "$APP_PATH/webvirtcloud/settings.py.template" "$APP_PATH/webvirtcloud/settings.py" >/dev/null; then - # first install only: apply instance values. SECRET_KEY is NOT written here; - # settings.py reads data/secret_key, so the key persists across re-runs. - tzone_escape="$(echo -n "$tzone"|sed -e 's/[](){}<>=:\!\?\+\|\/\&$*.^[]/\\&/g')" - novncd_port_escape="$(echo -n "$novncd_port"|sed -e 's/[](){}<>=:\!\?\+\|\/\&$*.^[]/\\&/g')" + echo "* Writing this installation's settings (data/local_settings.py, kept by re-runs and updates)." + host_ips="$(hostname -I 2>/dev/null)" + origins="'http://$fqdn', 'http://127.0.0.1'" + for ip in $host_ips; do + case "$ip" in *:*) ip="[$ip]" ;; esac # an IPv6 origin is bracketed, as browsers send it + origins+=", 'http://$ip'" + done + # shellcheck disable=SC2086 + # added to the lists: hosts and origins from the environment stay + wvc_ensure_local_settings "$APP_PATH/data" >/dev/null <&2; exit 1 ;; + esac - #TODO escape SED delimiter in variables - sed -i "s|^\\(TIME_ZONE = \\).*|\\1$tzone_escape|" "$APP_PATH/webvirtcloud/settings.py" - sed -i "s|^\\(WS_PORT = \\).*|\\1$novncd_port_escape|" "$APP_PATH/webvirtcloud/settings.py" - - # set CSRF TRUSTED ORIGINS - host_ip="'http://127.0.0.1', " - if command -v hostname >/dev/null 2>&1; then - for i in $(hostname -I 2>/dev/null); do - host_ip+="'http://$i', " - done - fi - sed -i "s|^\\(CSRF_TRUSTED_ORIGINS = \\).*|\\1\[ \'http://$fqdn\', $host_ip ]|" "$APP_PATH/webvirtcloud/settings.py" - # shellcheck disable=SC2046 - allowed_hosts="$(wvc_allowed_hosts "$fqdn" $(hostname -I 2>/dev/null))" - sed -i "s|^ALLOWED_HOSTS = .*|ALLOWED_HOSTS = $allowed_hosts|" "$APP_PATH/webvirtcloud/settings.py" - else - echo "* Keeping existing settings.py (not overwritten)." - fi - - # Restrict modes before the long-running pip/migrate steps, so settings and the - # key are not left world-readable during installation. The db is hardened again - # after migrate creates it. - wvc_harden_modes "$APP_PATH/webvirtcloud/settings.py" "" "$APP_PATH/data" + # Restrict modes before the long-running pip/migrate steps, so the key and the + # settings are not left world-readable during installation. The db is hardened + # again after migrate creates it. + wvc_harden_modes "" "$APP_PATH/data" echo "* Activate virtual environment." activate_python_environment @@ -324,7 +320,7 @@ install_webvirtcloud () { log "$PYTHON $APP_PATH/manage.py collectstatic --noinput" || { echo "manage.py collectstatic failed: see /var/log/webvirtcloud-install.log." >&2; exit 1; } echo "* Restricting file modes on secret, settings and database." - wvc_harden_modes "$APP_PATH/webvirtcloud/settings.py" "$APP_PATH/db.sqlite3" "$APP_PATH/data" + wvc_harden_modes "$APP_PATH/db.sqlite3" "$APP_PATH/data" chown -R "$nginx_group":"$nginx_group" "$APP_PATH" } @@ -487,10 +483,21 @@ until [[ $setupfqdn == "yes" ]] || [[ $setupfqdn == "no" ]]; do esac done +# written into Python and nginx as it is +if ! [[ $fqdn =~ ^[A-Za-z0-9.-]+$ ]]; then + echo "Not a host name: $fqdn" >&2 + exit 1 +fi + echo -n " Q. NOVNC service port number?(Default: 6080) " read -r novncd_port if [ -z "$novncd_port" ]; then readonly novncd_port=6080 +elif [[ $novncd_port =~ ^[0-9]{1,5}$ ]] && (( 10#$novncd_port >= 1 && 10#$novncd_port <= 65535 )); then + novncd_port=$((10#$novncd_port)) # 06080 is no Python number +else + echo "The port is a number from 1 to 65535: $novncd_port" >&2 + exit 1 fi echo " Setting novnc service port $novncd_port" echo "" diff --git a/webvirtcloud/settings.py.template b/webvirtcloud/settings.py similarity index 93% rename from webvirtcloud/settings.py.template rename to webvirtcloud/settings.py index e9a70934..fc8b1e48 100644 --- a/webvirtcloud/settings.py.template +++ b/webvirtcloud/settings.py @@ -7,7 +7,8 @@ import os import sys try: import ldap - from django_auth_ldap.config import LDAPSearch, NestedActiveDirectoryGroupType + # data/local_settings.py sets up LDAP with these (README, LDAP) + from django_auth_ldap.config import LDAPSearch, NestedActiveDirectoryGroupType # noqa: F401 HAS_LDAP = True except ImportError: HAS_LDAP = False @@ -190,7 +191,6 @@ AUTHENTICATION_BACKENDS = [ # first: refuses logins that are locked out "axes.backends.AxesStandaloneBackend", "django.contrib.auth.backends.ModelBackend", - #"django_auth_ldap.backend.LDAPBackend", ] AUTH_PASSWORD_VALIDATORS = [ @@ -446,29 +446,21 @@ DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL") or EMAIL_HOST_USER or "webm # seconds an SMTP server may take to answer; without it a server that stops answering holds the request for good EMAIL_TIMEOUT = 10 -# LDAP Config -# - +# LDAP, set up in data/local_settings.py (README, LDAP): seconds to connect and for +# each answer, as python-ldap waits for a server without end if HAS_LDAP: - AUTH_LDAP_SERVER_URI = "ldap://example.com" - AUTH_LDAP_BIND_DN = "username@example.com" - AUTH_LDAP_BIND_PASSWORD = "password" - # seconds to connect and for each answer: python-ldap waits for a server without end AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_NETWORK_TIMEOUT: 5, ldap.OPT_TIMEOUT: 10} - AUTH_LDAP_USER_SEARCH = LDAPSearch( - "CN=Users,DC=example,DC=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" - ) - AUTH_LDAP_GROUP_SEARCH = LDAPSearch( - "CN=Users,DC=example,DC=com", ldap.SCOPE_SUBTREE, "(objectClass=group)" - ) - AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() - AUTH_LDAP_REQUIRE_GROUP = "CN=WebVirtCloud Access,CN=Users,DC=example,DC=com" - AUTH_LDAP_USER_FLAGS_BY_GROUP = { - "is_staff": "CN=WebVirtCloud Staff,CN=Users,DC=example,DC=com", - "is_superuser": "CN=WebVirtCloud Admins,CN=Users,DC=example,DC=com", - } - AUTH_LDAP_USER_ATTR_MAP = { - "first_name": "givenName", - "last_name": "sn", - "email": "mail", - } + +# This installation's own settings: data/local_settings.py, which updates do not +# change (Docker keeps it in the data volume). It runs here, after the defaults +# above and with their names, so it sets or changes any of them, for example +# ALLOWED_HOSTS += ["panel.example.com"] +# or the LDAP options (README, LDAP). A value worked out above from another +# (DEFAULT_FROM_EMAIL, the log file) is not worked out again. +LOCAL_SETTINGS = BASE_DIR / "data" / "local_settings.py" +try: + local_settings = LOCAL_SETTINGS.read_bytes() # bytes: Python reads its encoding, a BOM too +except FileNotFoundError: # one that cannot be read stops the panel, not silently + local_settings = None +if local_settings is not None: + exec(compile(local_settings, str(LOCAL_SETTINGS), "exec")) diff --git a/webvirtcloud/tests/sh/install_lib.test.sh b/webvirtcloud/tests/sh/install_lib.test.sh index 2afab7bc..4f7469dd 100755 --- a/webvirtcloud/tests/sh/install_lib.test.sh +++ b/webvirtcloud/tests/sh/install_lib.test.sh @@ -25,20 +25,22 @@ check "data dir is 700" "[ \"\$(stat -c %a '$tmp/data')\" = 700 ]" rm "$tmp/data/secret_key" check "fails when python cannot run" "! wvc_ensure_secret_key '$tmp/data' no-such-python 2>/dev/null" -# wvc_ensure_settings: creates once, keeps on re-run -echo "TEMPLATE" > "$tmp/tpl" -check "ensure_settings returns 0 on create" "wvc_ensure_settings '$tmp/tpl' '$tmp/settings.py'" -check "settings created from the template" "[ \"\$(cat '$tmp/settings.py')\" = TEMPLATE ]" -echo "EDITED" > "$tmp/settings.py" -check "ensure_settings returns 1 when present" "! wvc_ensure_settings '$tmp/tpl' '$tmp/settings.py'" -check "existing settings kept" "[ \"\$(cat '$tmp/settings.py')\" = EDITED ]" +# wvc_ensure_local_settings: writes once, mode 600, keeps on re-run +check "local settings return 0 on create" "echo FIRST | wvc_ensure_local_settings '$tmp/data' >/dev/null" +check "local settings written" "[ \"\$(cat '$tmp/data/local_settings.py')\" = FIRST ]" +check "local settings mode 600" "[ \"\$(stat -c %a '$tmp/data/local_settings.py')\" = 600 ]" +check "local settings return 1 when present" "! echo SECOND | wvc_ensure_local_settings '$tmp/data' >/dev/null" +check "existing local settings kept" "[ \"\$(cat '$tmp/data/local_settings.py')\" = FIRST ]" +mkdir "$tmp/ro" && chmod 500 "$tmp/ro" +wvc_ensure_local_settings "$tmp/ro" < /dev/null 2>/dev/null; rc=$? +check "a failed write returns 2 and leaves no file" "[ $rc = 2 ] && [ ! -e '$tmp/ro/local_settings.py' ] && [ ! -e '$tmp/ro/local_settings.py.part' ]" # wvc_harden_modes -mkdir -p "$tmp/app/webvirtcloud" "$tmp/app/data" -echo x > "$tmp/app/webvirtcloud/settings.py"; echo x > "$tmp/app/db.sqlite3" -echo k > "$tmp/app/data/secret_key" -wvc_harden_modes "$tmp/app/webvirtcloud/settings.py" "$tmp/app/db.sqlite3" "$tmp/app/data" -check "settings 600" "[ \"\$(stat -c %a '$tmp/app/webvirtcloud/settings.py')\" = 600 ]" +mkdir -p "$tmp/app/data" +echo x > "$tmp/app/db.sqlite3" +echo k > "$tmp/app/data/secret_key"; echo s > "$tmp/app/data/local_settings.py"; chmod 644 "$tmp/app/data/local_settings.py" +wvc_harden_modes "$tmp/app/db.sqlite3" "$tmp/app/data" +check "local settings 600" "[ \"\$(stat -c %a '$tmp/app/data/local_settings.py')\" = 600 ]" check "db 600" "[ \"\$(stat -c %a '$tmp/app/db.sqlite3')\" = 600 ]" check "data 700" "[ \"\$(stat -c %a '$tmp/app/data')\" = 700 ]" check "secret 600" "[ \"\$(stat -c %a '$tmp/app/data/secret_key')\" = 600 ]" diff --git a/webvirtcloud/tests/test_local_settings.py b/webvirtcloud/tests/test_local_settings.py new file mode 100644 index 00000000..673d5070 --- /dev/null +++ b/webvirtcloud/tests/test_local_settings.py @@ -0,0 +1,42 @@ +"""data/local_settings.py: an installation's own settings, run at the end of settings.py.""" + +import runpy +import shutil +import tempfile +from pathlib import Path + +from django.conf import settings +from django.test import SimpleTestCase + + +class LocalSettingsTests(SimpleTestCase): + def setUp(self): + self.base = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.base) + (self.base / "webvirtcloud").mkdir() + (self.base / "data").mkdir() + shutil.copy(settings.BASE_DIR / "webvirtcloud" / "settings.py", self.base / "webvirtcloud" / "settings.py") + + def load(self): + return runpy.run_path(str(self.base / "webvirtcloud" / "settings.py")) + + def test_it_sets_and_changes_the_defaults(self): + (self.base / "data" / "local_settings.py").write_text( + 'TIME_ZONE = "Europe/Istanbul"\nALLOWED_HOSTS += ["panel.example.com"]\n') + values = self.load() + self.assertEqual(values["TIME_ZONE"], "Europe/Istanbul") + self.assertIn("panel.example.com", values["ALLOWED_HOSTS"]) + self.assertIn("localhost", values["ALLOWED_HOSTS"]) # the defaults it added to stay + + def test_a_file_saved_with_a_byte_order_mark_is_read(self): + (self.base / "data" / "local_settings.py").write_bytes(b'\xef\xbb\xbfTIME_ZONE = "Europe/Istanbul"\n') + self.assertEqual(self.load()["TIME_ZONE"], "Europe/Istanbul") + + def test_without_it_the_defaults_hold(self): + self.assertEqual(self.load()["WS_PORT"], 6080) + + def test_an_error_in_it_names_the_file(self): + (self.base / "data" / "local_settings.py").write_text("ALLOWED_HOSTS = [\n") + with self.assertRaises(SyntaxError) as error: + self.load() + self.assertEqual(error.exception.filename, str(self.base / "data" / "local_settings.py"))