diff --git a/.github/workflows/0.8-development-ci.yml b/.github/workflows/0.8-development-ci.yml index 11fe5331..2adb10cb 100644 --- a/.github/workflows/0.8-development-ci.yml +++ b/.github/workflows/0.8-development-ci.yml @@ -35,7 +35,8 @@ jobs: run: python -m unittest discover -s tests -v ubuntu-22-source-compat: - name: Ubuntu 22.04 / Python 3.10 source compatibility + name: Ubuntu 22.04 / Python 3.10 source compatibility (informational) + continue-on-error: true runs-on: ubuntu-22.04 steps: - name: Check out 0.8 source @@ -61,6 +62,11 @@ jobs: uses: actions/setup-python@v5 with: python-version: '3.12' + - name: Validate installer source and maintainer scripts + run: | + python -m compileall -q src scripts + sh -n packaging/debian/preinst packaging/debian/postinst packaging/debian/prerm packaging/debian/postrm packaging/debian/cmndctl + sh -n packaging/cmnd-linux/config packaging/cmnd-linux/postinst packaging/cmnd-linux/prerm packaging/cmnd-linux/postrm - name: Build payload and user-facing meta packages env: PYTHONPATH: src @@ -69,6 +75,39 @@ jobs: python scripts/build_meta_deb.py dpkg-deb -I dist/linux-cmnd_0.8.0_amd64.deb dpkg-deb -I dist/cmnd-linux_0.8.0_all.deb + - name: Smoke-install generated packages without runtime activation + shell: bash + run: | + set -euo pipefail + make_stub() { + name="$1"; version="$2" + root="$(mktemp -d)" + mkdir -p "$root/DEBIAN" + cat >"$root/DEBIAN/control" < + Description: CI dependency stub only + EOF + dpkg-deb --build "$root" "dist/${name}_${version}_all.deb" >/dev/null + rm -rf "$root" + } + make_stub cmnd-vendor-759 7.5.9-1 + make_stub cmnd-tomcat9 9.0.121-1 + sudo env DEBIAN_FRONTEND=noninteractive apt-get update + sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y \ + ./dist/linux-cmnd_0.8.0_amd64.deb \ + ./dist/cmnd-vendor-759_7.5.9-1_all.deb \ + ./dist/cmnd-tomcat9_9.0.121-1_all.deb \ + ./dist/cmnd-linux_0.8.0_all.deb + test "$(dpkg-query -W -f='${Status}' cmnd-linux)" = "install ok installed" + test -x /usr/bin/cmndctl + test ! -e /var/lib/cmnd-deployment + sudo env DEBIAN_FRONTEND=noninteractive apt-get remove -y cmnd-linux + test ! -e /var/lib/cmnd-deployment safety-diff: name: Frozen 0.7.1 ancestry check diff --git a/.github/workflows/0.8-full-build.yml b/.github/workflows/0.8-full-build.yml new file mode 100644 index 00000000..cb3e3623 --- /dev/null +++ b/.github/workflows/0.8-full-build.yml @@ -0,0 +1,79 @@ +name: 0.8 Full Ubuntu 24.04 Build + +on: + push: + branches: + - develop/0.8.0 + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + name: Build 0.8 Ubuntu 24.04 test bundle + runs-on: ubuntu-24.04 + steps: + - name: Check out exact 0.8 source + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install release-build tools + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends ca-certificates curl + + - name: Download pinned Philips and Tomcat inputs + shell: bash + run: | + set -euo pipefail + curl --fail --location --proto '=https' --proto-redir '=https' --tlsv1.2 \ + --retry 3 --output /tmp/cmnd-vendor-7.5.9.zip \ + https://github.com/MusicCityTelecom/linux-cmnd/releases/download/v0.7.1/cmnd-vendor-7.5.9.zip + curl --fail --location --proto '=https' --proto-redir '=https' --tlsv1.2 \ + --retry 3 --output /tmp/apache-tomcat-9.0.121.tar.gz \ + https://archive.apache.org/dist/tomcat/tomcat-9/v9.0.121/bin/apache-tomcat-9.0.121.tar.gz + + - name: Verify inputs and build all APT packages + env: + PYTHONPATH: src + run: | + python - <<'PY' + from pathlib import Path + import sys + sys.path.insert(0, 'scripts') + from vendor_bundle import verify + print(verify(Path('/tmp/cmnd-vendor-7.5.9.zip'))) + PY + python scripts/build_release.py \ + --vendor-bundle /tmp/cmnd-vendor-7.5.9.zip \ + --tomcat-archive /tmp/apache-tomcat-9.0.121.tar.gz + dpkg-deb -I dist/linux-cmnd_0.8.0_amd64.deb + dpkg-deb -I dist/cmnd-linux_0.8.0_all.deb + dpkg-deb -I dist/cmnd-vendor-759_7.5.9-1_all.deb + dpkg-deb -I dist/cmnd-tomcat9_9.0.121-1_all.deb + sha256sum \ + dist/linux-cmnd_0.8.0_amd64.deb \ + dist/cmnd-linux_0.8.0_all.deb \ + dist/cmnd-vendor-759_7.5.9-1_all.deb \ + dist/cmnd-tomcat9_9.0.121-1_all.deb \ + > dist/SHA256SUMS-APT + + - name: Upload Ubuntu 24.04 test bundle + uses: actions/upload-artifact@v4 + with: + name: cmnd-linux-0.8.0-ubuntu24-test + retention-days: 14 + if-no-files-found: error + path: | + dist/linux-cmnd_0.8.0_amd64.deb + dist/cmnd-linux_0.8.0_all.deb + dist/cmnd-vendor-759_7.5.9-1_all.deb + dist/cmnd-tomcat9_9.0.121-1_all.deb + dist/SHA256SUMS-APT diff --git a/CHANGELOG.md b/CHANGELOG.md index 552fec13..8d4af3e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,20 @@ are never repository inputs. - Added branch-only CI for Ubuntu and Windows source regressions, package-build smoke tests and verification that 0.8 remains descended from exact `v0.7.1`. +- Completed the four-package APT transaction model: `linux-cmnd`, + `cmnd-vendor-759`, `cmnd-tomcat9` and user-facing `cmnd-linux`. Ubuntu + 24.04 CI now executes maintainer-script syntax checks and a real non-activating + `apt-get install`/remove smoke test of the generated packages. +- Main and private CMND listeners are collision-aware. Historical ports remain + the defaults, while Tomcat, SmartCMS/Apache, isolated database, PHP-FPM and + management listeners move only when the host already owns those ports. +- Existing shared MySQL reuse now requires the reviewed MySQL 5.7 global profile + to be present already; CMND does not alter unrelated server-wide settings. + Failed fresh shared-database activation has bounded rollback for only the CMND + schemas/accounts created by that transaction. +- Added a repeatable Ubuntu 24.04 full-build workflow that consumes the verified + Philips 7.5.9 release bundle and pinned Tomcat archive and emits the four + development test packages as one Actions artifact. - Ubuntu 24.04 remains the qualified runtime baseline. Ubuntu 22.04 and 26.04 are development targets and must be separately qualified before being called supported. Docker/Compose production deployment remains a later 0.8 milestone. diff --git a/README.md b/README.md index 95e24a6c..1d18e03f 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,21 @@ Windows/Linux database table-name case compatibility for fresh installs. Existin installs need the explicit, backed-up [database case repair](docs/DATABASE-CASE.md) after updating the tooling. Do not delete or re-upload your packages to fix this. +## 0.8.0 development + +Version 0.8.0 is being developed independently from the frozen `v0.7.1` +release. The current development target is Ubuntu 24.04 amd64 and adds an +environment-aware APT installation path, existing-service coexistence planning, +collision-aware CMND ports, a verified four-package dependency graph, and a +separate Docker/Compose candidate. + +For the current Ubuntu 24.04 test procedure, package behavior, safety defaults +and post-install checks, see +[the 0.8 Ubuntu 24.04 test guide](docs/0.8.0-UBUNTU-24.04-TEST.md). + +Ubuntu 22.04 and 26.04 are not yet release-qualified for the 0.8 APT path. +Published `v0.7.1` assets remain unchanged. + ## Quick installation Start with the [complete Ubuntu 24.04 walkthrough](docs/UBUNTU-24.04.md), including diff --git a/docs/0.8.0-UBUNTU-24.04-TEST.md b/docs/0.8.0-UBUNTU-24.04-TEST.md new file mode 100644 index 00000000..ca013165 --- /dev/null +++ b/docs/0.8.0-UBUNTU-24.04-TEST.md @@ -0,0 +1,242 @@ +# CMND Linux 0.8.0 — Ubuntu 24.04 Test Guide + +This guide is for the isolated **0.8.0 development line** only. The published +`v0.7.1` release remains the frozen working reference and is not modified by +0.8 development. + +## Test target + +Use a disposable or dedicated Ubuntu Server **24.04 LTS amd64** host. + +Recommended minimums: + +- 6 GiB RAM +- 40 GiB disk, with at least 10 GiB free under `/var/lib` +- stable IPv4 address on the TV-management LAN +- working DNS and Internet access during dependency/container preparation +- sudo/root access + +Do not begin with a machine that already contains a CMND deployment. Existing +Apache/nginx, Docker, and MySQL/MariaDB services are acceptable because 0.8 +inventories them and plans coexistence before activation. + +## What the 0.8 APT bundle contains + +The test bundle contains four Debian packages: + +```text +linux-cmnd_0.8.0_amd64.deb +cmnd-vendor-759_7.5.9-1_all.deb +cmnd-tomcat9_9.0.121-1_all.deb +cmnd-linux_0.8.0_all.deb +``` + +`cmnd-linux` is the user-facing installation package. It requires the exact +matching tooling package, the hash-verified Philips CMND 7.5.9 inputs, and the +pinned Tomcat 9.0.121 archive. + +The Philips inputs remain outside Git source history. The vendor package is +generated only from the exact input set already verified by the project. + +## Before activation + +After the tooling package is installed, these commands are read-only: + +```sh +sudo cmndctl environment +sudo cmndctl plan-install +``` + +The environment report inventories web/database/runtime services and listeners. +The plan does not modify the host. + +The planner preserves unrelated listeners. CMND prefers its historical ports +when free and moves only CMND-owned listeners when necessary: + +- Tomcat HTTP: 8080 +- Tomcat HTTPS: 8443 +- SmartCMS/Apache HTTP: 8082 +- SmartCMS/Apache HTTPS: 8444 +- database: 3306 +- private PHP-FPM: 9000 +- private management UI: 9078 + +## Installing the four-package test bundle + +From the directory containing all four packages: + +```sh +sudo apt update +sudo apt install \ + ./linux-cmnd_0.8.0_amd64.deb \ + ./cmnd-vendor-759_7.5.9-1_all.deb \ + ./cmnd-tomcat9_9.0.121-1_all.deb \ + ./cmnd-linux_0.8.0_all.deb +``` + +The package configuration asks for: + +1. Server IPv4 address. `auto` prefers the IPv4 source selected by the host's + default route. +2. Database mode: + - `auto` — reuse an existing database only if it already passes the strict + shared-server gate; otherwise use the isolated MySQL 5.7 runtime. + - `existing` — require a compatible existing database and refuse fallback. + - `isolated` — leave any host database alone and use the qualified isolated + MySQL 5.7 runtime. +3. Database administrator user/password only when required for an existing + database. The password is transferred through a root-only temporary file and + cleared from debconf after the activation attempt. +4. Apache mode: + - `auto` — use an already-running supported Debian/Ubuntu Apache service via + one CMND-owned configuration fragment; otherwise use standalone CMND Apache. + - `host` — require host Apache. + - `standalone` — do not attach CMND to the host Apache service. +5. Explicit acceptance of the legacy PHP 5.6 / MySQL 5.7 compatibility profile. + +If legacy-runtime acceptance is not granted, the packages install but CMND is +not activated. Activation can then be revisited through package reconfiguration. + +## Existing MySQL/MariaDB safety + +0.8 does **not** change server-wide database settings to make an unrelated +database service compatible. + +Automatic shared-database reuse currently requires the already-qualified +MySQL 5.7 family and the reviewed global profile, including: + +- `lower_case_table_names=1` +- `event_scheduler=ON` +- `local_infile=OFF` +- reviewed `sql_mode=NO_ENGINE_SUBSTITUTION` +- server not read-only +- no existing CMND schema/user namespace + +MariaDB and MySQL 8 remain unqualified as shared CMND databases. In `auto` +mode they are preserved and CMND uses its isolated database fallback. + +A failed fresh shared-database activation removes only the fixed CMND schemas and +application accounts that the same fresh transaction created. It does not alter +unrelated schemas/users. + +## Existing Apache/nginx safety + +When reusing a supported host Apache installation, CMND owns only: + +```text +/etc/apache2/conf-available/cmnd-linux.conf +``` + +The installer does not replace `apache2.conf`, `ports.conf`, or unrelated +sites. It config-tests Apache before relying on the fragment and removes its own +fragment on a failed attach. + +An existing nginx installation is preserved. If Apache is not being reused, +CMND runs its own standalone Apache process on CMND-owned listeners. + +## First-install network safety + +A fresh APT-generated configuration starts with: + +```toml +[safety] +permitted_ranges = ["127.0.0.0/8"] + +[tv] +allowlist = [] +``` + +Installing CMND does not authorize a physical TV for write operations. Keep the +TV allowlist empty until server/browser qualification has passed and the first +physical-TV procedure is intentionally started. + +## Expected first-start duration + +The Java applications can have a long cold start. Previous qualification on a +6 GiB VM observed startup taking roughly 11 minutes. Do not assume installation +failed only because vendor pages are not immediately available. + +## Verification after installation + +Start with: + +```sh +sudo cmndctl environment +sudo cmndctl native-health --seconds 900 +sudo systemctl --no-pager --full status \ + cmnd-egress.service \ + cmnd-php.service \ + cmnd-tomcat.service \ + cmnd-admin.service +``` + +If the isolated database/standalone Apache path was selected, also check: + +```sh +sudo systemctl --no-pager --full status cmnd-mysql.service cmnd-apache.service +``` + +If host Apache was selected: + +```sh +sudo apache2ctl configtest +sudo systemctl --no-pager --full status apache2.service +``` + +Confirm the deployment marker: + +```sh +sudo cat /etc/cmnd/deployment.json +``` + +A successful APT-managed activation should identify itself as +`linux-cmnd-apt` with state `active`. + +## Initial administrator credentials + +The first generated administrator credentials are root-readable at: + +```text +/var/lib/cmnd-deployment/initial-admin.json +``` + +Treat this file as a secret. Do not paste it into issue reports or commit it. + +## Evidence and troubleshooting + +Useful state/log locations include: + +```text +/etc/cmnd/ +/var/lib/cmnd-deployment/ +/var/log/cmnd/ +/var/cache/linux-cmnd/bootstrap/php-build.log +``` + +If activation fails, preserve `/var/lib/cmnd-deployment` and the private logs +before changing anything. A failed deployment intentionally stops CMND +application services rather than trying to hide partial state. + +## Package removal + +Removing `cmnd-linux` stops/disables CMND-owned services and detaches the +CMND-owned host-Apache fragment when present. Package removal deliberately +retains CMND data, configuration, certificates, logs and database state. + +Do not use package removal as a data-erasure operation. + +## Scope of this test + +For 0.8 right now: + +- Ubuntu 24.04 amd64 is the primary test target. +- Ubuntu 22.04/Python 3.10 is an informational compatibility lane, not a supported + APT target yet. +- Ubuntu 26.04 remains unqualified. +- Docker/Compose rendering exists but host-network physical-TV discovery/control + is not yet qualified. +- RF/DekTec/modulator and remaining Windows-only MGate-dependent workflows are + not implied to be complete by a successful APT installation. + +A successful package/source CI run is not a replacement for this clean-host +runtime test with the actual vendor payload. diff --git a/packaging/cmnd-linux/config b/packaging/cmnd-linux/config new file mode 100644 index 00000000..8d215878 --- /dev/null +++ b/packaging/cmnd-linux/config @@ -0,0 +1,27 @@ +#!/bin/sh +set -eu +. /usr/share/debconf/confmodule + +db_input high cmnd-linux/server-ip || true +db_input high cmnd-linux/database-mode || true +db_input medium cmnd-linux/database-admin-user || true +db_input medium cmnd-linux/apache-mode || true +db_input high cmnd-linux/accept-legacy-runtime || true + +db_get cmnd-linux/database-mode +case "$RET" in + auto|existing) + socket_ok=0 + for client in mariadb mysql; do + if command -v "$client" >/dev/null 2>&1 && \ + "$client" --protocol=socket -uroot --batch --skip-column-names -e 'SELECT 1' >/dev/null 2>&1; then + socket_ok=1 + break + fi + done + [ "$socket_ok" -eq 1 ] || db_input medium cmnd-linux/database-admin-password || true + ;; +esac + +db_go +exit 0 diff --git a/packaging/cmnd-linux/postinst b/packaging/cmnd-linux/postinst new file mode 100644 index 00000000..389560ba --- /dev/null +++ b/packaging/cmnd-linux/postinst @@ -0,0 +1,64 @@ +#!/bin/sh +set -eu +. /usr/share/debconf/confmodule + +[ "${1:-}" = configure ] || exit 0 + +if [ -f /etc/cmnd/deployment.json ] && [ ! -L /etc/cmnd/deployment.json ]; then + if python3 - <<'PY' +import json, os, pathlib, sys +p = pathlib.Path('/etc/cmnd/deployment.json') +try: + st = p.stat() + data = json.loads(p.read_text(encoding='utf-8')) +except Exception: + sys.exit(1) +safe = st.st_uid == 0 and not (st.st_mode & 0o022) and st.st_size < 65536 +managed = data.get('managed_by') in {'linux-cmnd-apt', 'linux-cmnd-native', 'linux-cmnd-coexist'} +active = data.get('state') == 'active' +sys.exit(0 if safe and managed and active else 1) +PY + then + echo "cmnd-linux: existing active CMND deployment preserved; fresh activation skipped." + exit 0 + fi + echo "cmnd-linux: unrecognized or unsafe deployment marker; refusing package reconfiguration." >&2 + exit 1 +fi + +db_get cmnd-linux/accept-legacy-runtime +if [ "$RET" != true ]; then + echo "cmnd-linux installed but not activated: legacy runtime acceptance was not granted." >&2 + echo "Run: sudo dpkg-reconfigure cmnd-linux" >&2 + exit 0 +fi + +db_get cmnd-linux/server-ip; server_ip=$RET +db_get cmnd-linux/database-mode; database_mode=$RET +db_get cmnd-linux/database-admin-user; database_user=$RET +db_get cmnd-linux/apache-mode; apache_mode=$RET +db_get cmnd-linux/database-admin-password; database_password=$RET + +password_file= +cleanup() { + if [ -n "$password_file" ]; then rm -f -- "$password_file"; fi + db_set cmnd-linux/database-admin-password '' || true +} +trap cleanup EXIT HUP INT TERM + +if [ -n "$database_password" ]; then + old_umask=$(umask) + umask 077 + password_file=$(mktemp /run/cmnd-linux-dbadmin.XXXXXX) + printf '%s\n' "$database_password" > "$password_file" + chmod 0600 "$password_file" + umask "$old_umask" +fi + +set -- apt-activate --database-mode "$database_mode" --apache-mode "$apache_mode" \ + --database-admin-user "${database_user:-root}" --accept-legacy-runtime --execute +if [ -n "$server_ip" ] && [ "$server_ip" != auto ]; then set -- "$@" --server-ip "$server_ip"; fi +if [ -n "$password_file" ]; then set -- "$@" --database-admin-password-file "$password_file"; fi + +/usr/bin/cmndctl "$@" +exit 0 diff --git a/packaging/cmnd-linux/postrm b/packaging/cmnd-linux/postrm new file mode 100644 index 00000000..58a1cd42 --- /dev/null +++ b/packaging/cmnd-linux/postrm @@ -0,0 +1,6 @@ +#!/bin/sh +set -eu +# Intentionally retain /etc/cmnd, /opt/cmnd, /var/lib/cmnd*, databases, +# certificates, logs and customer content. Destructive purge requires a +# separately reviewed operator command; package removal never deletes site data. +exit 0 diff --git a/packaging/cmnd-linux/prerm b/packaging/cmnd-linux/prerm new file mode 100644 index 00000000..7772c602 --- /dev/null +++ b/packaging/cmnd-linux/prerm @@ -0,0 +1,19 @@ +#!/bin/sh +set -eu + +case "${1:-}" in + remove) + if command -v systemctl >/dev/null 2>&1; then + systemctl disable --now cmnd-update.path cmnd-tomcat.service cmnd-apache.service cmnd-php.service cmnd-mysql.service cmnd-admin.service cmnd-egress.service 2>/dev/null || true + fi + if [ -x /usr/bin/cmndctl ] && [ -f /etc/cmnd/deployment.json ]; then + /usr/bin/cmndctl apache-detach --execute 2>/dev/null || true + fi + ;; + upgrade|deconfigure) + # Preserve the active runtime across package replacement. The new package's + # postinst validates/preserves the deployment marker instead of re-running + # a destructive fresh-install transaction. + ;; +esac +exit 0 diff --git a/packaging/cmnd-linux/templates b/packaging/cmnd-linux/templates new file mode 100644 index 00000000..ce679b8c --- /dev/null +++ b/packaging/cmnd-linux/templates @@ -0,0 +1,36 @@ +Template: cmnd-linux/server-ip +Type: string +Default: auto +Description: IPv4 address CMND should use: + Enter an IPv4 address already assigned to this server. Use "auto" to select the first active non-loopback IPv4 address. + +Template: cmnd-linux/database-mode +Type: select +Choices: auto, existing, isolated +Default: auto +Description: Database integration mode: + "auto" reuses an existing MySQL service only if it passes the CMND compatibility gate; otherwise it uses the isolated pinned MySQL runtime. "existing" refuses fallback. "isolated" never changes an existing database service. + +Template: cmnd-linux/database-admin-user +Type: string +Default: root +Description: Existing database administrator user: + Used only when an existing database requires password authentication. The password is never stored in CMND persistent configuration. + +Template: cmnd-linux/database-admin-password +Type: password +Description: Existing database administrator password: + Leave blank to let auto mode use the isolated database fallback. This value is used only during package configuration and is cleared after the activation attempt. + +Template: cmnd-linux/apache-mode +Type: select +Choices: auto, host, standalone +Default: auto +Description: Apache integration mode: + "auto" attaches a CMND-owned fragment to an already-running Debian/Ubuntu Apache service, otherwise it runs an isolated CMND Apache process. Existing unrelated sites and listeners are preserved. + +Template: cmnd-linux/accept-legacy-runtime +Type: boolean +Default: false +Description: Accept CMND's legacy PHP 5.6 / MySQL 5.7 compatibility runtime? + The original Philips CMND 7.5.9 application requires legacy compatibility components. They are isolated where practical and should not be exposed directly to the Internet. diff --git a/packaging/debian/postinst b/packaging/debian/postinst index 25c2934d..e76b87a3 100644 --- a/packaging/debian/postinst +++ b/packaging/debian/postinst @@ -17,14 +17,20 @@ if [ -e /etc/cmnd/deployment.json ] || [ -L /etc/cmnd/deployment.json ]; then import json, pathlib, sys p=pathlib.Path("/etc/cmnd/deployment.json") safe=p.is_file() and not p.is_symlink() and p.stat().st_uid==0 and not p.stat().st_mode & 0o022 and p.stat().st_size<65536 -sys.exit(0 if safe and json.loads(p.read_text()).get("managed_by")=="linux-cmnd-native" else 1) +data=json.loads(p.read_text()) +managed=data.get("managed_by") in {"linux-cmnd-native","linux-cmnd-apt","linux-cmnd-coexist"} +sys.exit(0 if safe and managed and data.get("state")=="active" else 1) ' else CMND_CONFIG=/etc/cmnd/cmnd.toml PYTHONPATH="/opt/linux-cmnd/releases/$VERSION/src" \ python3 -m cmnd_linux render-runtime-config --output /etc/cmnd --execute fi for rendered in tomcat.env apache.env compose.env; do - chown root:cmnd "/etc/cmnd/$rendered" - chmod 0640 "/etc/cmnd/$rendered" + path="/etc/cmnd/$rendered" + if [ -e "$path" ] || [ -L "$path" ]; then + [ -f "$path" ] && [ ! -L "$path" ] || { echo "Unsafe CMND rendered config: $path" >&2; exit 1; } + chown root:cmnd "$path" + chmod 0640 "$path" + fi done exit 0 diff --git a/scripts/build_apt_repository.py b/scripts/build_apt_repository.py index 9a5fd34e..4310ca13 100644 --- a/scripts/build_apt_repository.py +++ b/scripts/build_apt_repository.py @@ -1,178 +1,60 @@ #!/usr/bin/env python3 """Build a bounded signed Debian/Ubuntu repository from reviewed CMND .deb files.""" from __future__ import annotations - import argparse -from datetime import datetime, timezone -import gzip -import json -import os +from datetime import datetime,timezone +import gzip,json,os,re,shutil,subprocess from pathlib import Path -import re -import shutil -import subprocess - - -REQUIRED_PACKAGES = {'linux-cmnd', 'cmnd-linux', 'cmnd-vendor-759'} -ALLOWED_PACKAGES = set(REQUIRED_PACKAGES) -ALLOWED_ARCHITECTURES = {'amd64', 'all'} -SUITES = {'development', 'testing', 'stable'} -VENDOR_VERSION = '7.5.9-1' - - -def run(args, *, cwd: Path | None = None, input_text: str | None = None) -> str: - result = subprocess.run(list(map(str, args)), cwd=cwd, input=input_text, text=True, - capture_output=True, check=False) - if result.returncode: - raise RuntimeError(f'command failed: {args[0]}: {result.stderr.strip()[:1000]}') - return result.stdout - - -def require_command(name: str) -> str: - path = shutil.which(name) - if not path: - raise RuntimeError(f'required repository build command is missing: {name}') - return path - - -def deb_field(path: Path, field: str) -> str: - return run((require_command('dpkg-deb'), '-f', path, field)).strip() - - -def validate_deb(path: Path) -> dict[str, str | int]: - if not path.is_file() or path.is_symlink(): - raise ValueError(f'Debian package must be a regular non-symlink file: {path}') - if path.stat().st_size <= 0 or path.stat().st_size > 4 * 1024**3: - raise ValueError(f'Debian package size outside repository bound: {path.name}') - package = deb_field(path, 'Package') - version = deb_field(path, 'Version') - architecture = deb_field(path, 'Architecture') - if package not in ALLOWED_PACKAGES: - raise ValueError(f'unexpected package for CMND repository: {package}') - if architecture not in ALLOWED_ARCHITECTURES: - raise ValueError(f'unexpected architecture for {package}: {architecture}') - if not re.fullmatch(r'[0-9][A-Za-z0-9.+:~_-]*', version): - raise ValueError(f'invalid Debian version: {version}') - return {'package': package, 'version': version, 'architecture': architecture, 'size': path.stat().st_size} - - -def release_date() -> str: - epoch = int(os.environ.get('SOURCE_DATE_EPOCH', '0')) - when = datetime.fromtimestamp(epoch, timezone.utc) if epoch else datetime.now(timezone.utc) - return when.strftime('%a, %d %b %Y %H:%M:%S +0000') - - -def gzip_file(source: Path, destination: Path) -> None: - epoch = int(os.environ.get('SOURCE_DATE_EPOCH', '0')) - with source.open('rb') as inp, destination.open('wb') as raw: - with gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=epoch or 0) as zipped: - shutil.copyfileobj(inp, zipped) - -def build_repository(output: Path, debs: list[Path], *, codename: str, suite: str, - signing_key: str | None, allow_unsigned_development: bool, - execute: bool = False) -> dict: - if not re.fullmatch(r'[a-z0-9][a-z0-9.-]{1,31}', codename): - raise ValueError('invalid repository codename') - if suite not in SUITES: - raise ValueError('invalid repository suite') - if not debs: - raise ValueError('at least one .deb is required') - metadata = [validate_deb(path) for path in debs] - by_name = {str(item['package']): item for item in metadata} - if set(by_name) != REQUIRED_PACKAGES or len(metadata) != len(REQUIRED_PACKAGES): - raise ValueError('repository build requires exactly linux-cmnd, cmnd-linux and cmnd-vendor-759 packages') - tooling_version = str(by_name['linux-cmnd']['version']) - if str(by_name['cmnd-linux']['version']) != tooling_version: - raise ValueError('cmnd-linux and linux-cmnd repository packages must use the same version') - if str(by_name['cmnd-vendor-759']['version']) != VENDOR_VERSION: - raise ValueError(f'cmnd-vendor-759 must use the reviewed vendor package version {VENDOR_VERSION}') - if not signing_key and not (suite == 'development' and allow_unsigned_development): - raise ValueError('signed repository metadata is required; unsigned output is allowed only for explicit development builds') - if output.exists() and any(output.iterdir()): - raise ValueError('repository output directory must be absent or empty') - - plan = { - 'executed': execute, - 'output': str(output), - 'codename': codename, - 'suite': suite, - 'tooling_version': tooling_version, - 'vendor_version': VENDOR_VERSION, - 'packages': metadata, - 'signed': bool(signing_key), - } - if not execute: - return plan - - apt_ftparchive = require_command('apt-ftparchive') - if signing_key: - require_command('gpg') - output.mkdir(parents=True, exist_ok=True) - for source, info in zip(debs, metadata): - package = str(info['package']) - initial = package[0] - target = output / 'pool' / 'main' / initial / package / source.name - target.parent.mkdir(parents=True, exist_ok=True) - shutil.copyfile(source, target) - target.chmod(0o644) - - binary = output / 'dists' / codename / 'main' / 'binary-amd64' - binary.mkdir(parents=True) - packages = binary / 'Packages' - packages.write_text(run((apt_ftparchive, 'packages', 'pool/main'), cwd=output), encoding='utf-8') - gzip_file(packages, binary / 'Packages.gz') - - dist = output / 'dists' / codename - body = run((apt_ftparchive, 'release', f'dists/{codename}'), cwd=output) - header = ( - 'Origin: Music City Telecom\n' - 'Label: CMND Linux\n' - f'Suite: {suite}\n' - f'Codename: {codename}\n' - 'Architectures: amd64\n' - 'Components: main\n' - 'Description: CMND for Linux packages\n' - f'Date: {release_date()}\n' - ) - release = dist / 'Release' - release.write_text(header + body, encoding='utf-8') - - if signing_key: - run(('gpg', '--batch', '--yes', '--local-user', signing_key, '--digest-algo', 'SHA256', - '--clearsign', '--output', dist / 'InRelease', release)) - run(('gpg', '--batch', '--yes', '--local-user', signing_key, '--digest-algo', 'SHA256', - '--armor', '--detach-sign', '--output', dist / 'Release.gpg', release)) - - plan['files'] = sorted(str(path.relative_to(output)) for path in output.rglob('*') if path.is_file()) - return plan - - -def parser() -> argparse.ArgumentParser: - p = argparse.ArgumentParser() - p.add_argument('--output', required=True, type=Path) - p.add_argument('--deb', action='append', required=True, type=Path) - p.add_argument('--codename', default='noble') - p.add_argument('--suite', choices=sorted(SUITES), default='development') - p.add_argument('--signing-key', help='GPG key fingerprint/key ID; private key material is never read from the repository') - p.add_argument('--allow-unsigned-development', action='store_true') - p.add_argument('--execute', action='store_true') +REQUIRED_PACKAGES={'linux-cmnd','cmnd-linux','cmnd-vendor-759','cmnd-tomcat9'} +ALLOWED_ARCHITECTURES={'amd64','all'}; SUITES={'development','testing','stable'} +VENDOR_VERSION='7.5.9-1'; TOMCAT_VERSION='9.0.121-1' +def run(args,*,cwd=None,input_text=None): + r=subprocess.run(list(map(str,args)),cwd=cwd,input=input_text,text=True,capture_output=True,check=False) + if r.returncode:raise RuntimeError(f'command failed: {args[0]}: {r.stderr.strip()[:1000]}') + return r.stdout +def require(name): + p=shutil.which(name) + if not p:raise RuntimeError('required repository build command is missing: '+name) return p - - -def main(argv=None) -> int: - args = parser().parse_args(argv) - try: - result = build_repository(args.output, args.deb, codename=args.codename, suite=args.suite, - signing_key=args.signing_key, - allow_unsigned_development=args.allow_unsigned_development, - execute=args.execute) - except (OSError, RuntimeError, ValueError) as exc: - print(f'build-apt-repository: {exc}', file=os.sys.stderr) - return 2 - print(json.dumps(result, indent=2, sort_keys=True)) - return 0 - - -if __name__ == '__main__': - raise SystemExit(main()) +def field(path,name):return run((require('dpkg-deb'),'-f',path,name)).strip() +def validate(path): + if not path.is_file() or path.is_symlink():raise ValueError('Debian package must be a regular non-symlink file: '+str(path)) + if not 0 Path: - version = (ROOT / 'VERSION').read_text().strip() - control = f'''Package: cmnd-linux +def build()->Path: + version=(ROOT/'VERSION').read_text().strip() + payload=ROOT/'dist'/f'linux-cmnd_{version}_amd64.deb' + if not payload.exists():payload=build_payload_deb() + if not payload.is_file() or payload.is_symlink():raise ValueError('matching linux-cmnd payload package is missing or unsafe') + control=f'''Package: cmnd-linux Version: {version} Section: admin Priority: optional Architecture: all -Depends: linux-cmnd (= {version}), cmnd-vendor-759 (= {VENDOR_PACKAGE_VERSION}) +Pre-Depends: debconf (>= 1.5.0) | debconf-2.0 +Depends: linux-cmnd (= {version}), cmnd-vendor-759 (= {VENDOR_PACKAGE_VERSION}), cmnd-tomcat9 (= {TOMCAT_PACKAGE_VERSION}), python3 (>= 3.11), adduser, ca-certificates, openssl, iproute2, iptables, 7zip, openjdk-17-jre-headless, apache2-bin, media-types, docker.io | docker-ce Maintainer: Music City Telecom Description: Philips CMND for Linux installation entry point - User-facing APT package for CMND for Linux. The version-matched linux-cmnd - payload provides deployment/runtime integration and cmnd-vendor-759 provides - the separately packaged hash-verified Philips CMND 7.5.9 application inputs. + Environment-aware APT installer for CMND for Linux. Reuses compatible existing + services where qualified, preserves unrelated applications and falls back to + isolated compatibility runtimes rather than changing unsafe host configuration. '''.encode() - notice = ( - 'cmnd-linux is the user-facing APT installation package.\n' - f'It requires exact linux-cmnd {version} and cmnd-vendor-759 {VENDOR_PACKAGE_VERSION}.\n' - 'Philips vendor applications retain their original ownership and attribution.\n' - ).encode() - deb = b'!\n' + ar_member('debian-binary', b'2.0\n') - deb += ar_member('control.tar.gz', tar_blob([(None, 'control', 0o644, control)])) - deb += ar_member('data.tar.gz', tar_blob([ - (None, 'usr/share/doc/cmnd-linux/README', 0o644, notice), - ])) - output = ROOT / 'dist' / f'cmnd-linux_{version}_all.deb' - output.parent.mkdir(exist_ok=True) - output.write_bytes(deb) - Path(str(output) + '.sha256').write_text(f'{sha256(deb).hexdigest()} {output.name}\n') - return output - - -if __name__ == '__main__': - print(build()) + ctl=[ + (None,'control',0o644,control), + (ROOT/'packaging/cmnd-linux/templates','templates',0o644,None), + (ROOT/'packaging/cmnd-linux/config','config',0o755,None), + (ROOT/'packaging/cmnd-linux/postinst','postinst',0o755,None), + (ROOT/'packaging/cmnd-linux/prerm','prerm',0o755,None), + (ROOT/'packaging/cmnd-linux/postrm','postrm',0o755,None), + ] + notice=(f'cmnd-linux {version} is the APT entry package.\n' + f'Requires linux-cmnd {version}, cmnd-vendor-759 {VENDOR_PACKAGE_VERSION}, and cmnd-tomcat9 {TOMCAT_PACKAGE_VERSION}.\n' + 'Philips/TP Vision components retain their original ownership and attribution.\n').encode() + data=[(None,'usr/share/doc/cmnd-linux/README',0o644,notice), + (payload,f'usr/lib/cmnd/packages/{payload.name}',0o600,None)] + deb=b'!\n'+ar_member('debian-binary',b'2.0\n')+ar_member('control.tar.gz',tar_blob(ctl))+ar_member('data.tar.gz',tar_blob(data)) + out=ROOT/'dist'/f'cmnd-linux_{version}_all.deb'; out.parent.mkdir(exist_ok=True); out.write_bytes(deb) + Path(str(out)+'.sha256').write_text(f'{sha256(deb).hexdigest()} {out.name}\n'); return out + +if __name__=='__main__':print(build()) diff --git a/scripts/build_release.py b/scripts/build_release.py index 9deb1a34..a8748f91 100644 --- a/scripts/build_release.py +++ b/scripts/build_release.py @@ -1,94 +1,35 @@ -"""Build tooling plus the explicitly authorized, pinned original vendor bundle.""" -import argparse -import hashlib -import json +"""Build tooling plus the authorized vendor bundle and pinned runtime packages.""" +import argparse,hashlib,json,shutil,subprocess from pathlib import Path -import shutil -import subprocess - -from build_deb import build as build_payload_deb, ROOT +from build_deb import build as build_payload_deb,ROOT from build_meta_deb import build as build_meta_deb from build_vendor_deb import build as build_vendor_deb -from vendor_bundle import verify as verify_vendor_bundle, NAME as VENDOR_BUNDLE_NAME - -RELEASE_PATHS = ['src', 'scripts', 'deploy', 'config', 'packaging', 'tests', 'docs', - 'VERSION', 'pyproject.toml', 'README.md', 'LICENSE', 'CHANGELOG.md', - 'AGENTS.md', '.gitattributes', '.gitignore'] - - -def stream_digest(stream, algorithm='sha256'): - digest = hashlib.new(algorithm) - for chunk in iter(lambda: stream.read(1024 * 1024), b''): - digest.update(chunk) - return digest.hexdigest() - - +from build_tomcat_deb import build as build_tomcat_deb +from vendor_bundle import verify as verify_vendor_bundle,NAME as VENDOR_BUNDLE_NAME +RELEASE_PATHS=['src','scripts','deploy','config','packaging','tests','docs','.github','VERSION','pyproject.toml','README.md','LICENSE','CHANGELOG.md','AGENTS.md','.gitattributes','.gitignore'] def validate_sources(): - # Build inputs must match the exact commit exported as the release source. - # Include ignored files: a local ignored file must not slip into the package. - inputs = RELEASE_PATHS - subprocess.run(['git', 'diff', '--exit-code', 'HEAD', '--', *inputs], cwd=ROOT, check=True) - untracked = subprocess.check_output( - ['git', 'ls-files', '--others', '--', *inputs], cwd=ROOT, text=True).splitlines() - untracked = [name for name in untracked - if '__pycache__' not in Path(name).parts and Path(name).suffix != '.pyc'] - if untracked: - raise SystemExit('Uncommitted release inputs detected; commit or remove them before building') - tracked = subprocess.check_output(['git', 'ls-files'], cwd=ROOT, text=True).splitlines() - forbidden = {'.war', '.jar', '.exe', '.zip', '.sql', '.key', '.crt', '.pem', '.p12', '.pfx', '.pcap', '.pcapng', '.log'} - if any(Path(name).suffix.lower() in forbidden or name.startswith(('.lab/', '.private-staging/')) for name in tracked): - raise SystemExit('Private/vendor input detected in tracked release sources') - - + subprocess.run(['git','diff','--exit-code','HEAD','--',*RELEASE_PATHS],cwd=ROOT,check=True) + untracked=subprocess.check_output(['git','ls-files','--others','--',*RELEASE_PATHS],cwd=ROOT,text=True).splitlines(); untracked=[n for n in untracked if '__pycache__' not in Path(n).parts and Path(n).suffix!='.pyc'] + if untracked:raise SystemExit('Uncommitted release inputs detected; commit or remove them before building') + tracked=subprocess.check_output(['git','ls-files'],cwd=ROOT,text=True).splitlines(); forbidden={'.war','.jar','.exe','.zip','.sql','.key','.crt','.pem','.p12','.pfx','.pcap','.pcapng','.log'} + if any(Path(n).suffix.lower() in forbidden or n.startswith(('.lab/','.private-staging/')) for n in tracked):raise SystemExit('Private/vendor input detected in tracked release sources') +def digest(path): + h=hashlib.sha256() + with path.open('rb') as s: + for chunk in iter(lambda:s.read(1024*1024),b''):h.update(chunk) + return h.hexdigest() def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--vendor-bundle', type=Path, required=True, - help='authorized, exact original-input ZIP; never a live installation backup') - args = parser.parse_args() - vendor_metadata = verify_vendor_bundle(args.vendor_bundle) - validate_sources() - package = build_payload_deb() - meta_package = build_meta_deb() - vendor_package = build_vendor_deb(args.vendor_bundle) - version = (ROOT / 'VERSION').read_text().strip() - destination = ROOT / 'dist' - installer = destination / 'install.sh' - installer.write_bytes((ROOT / 'scripts/install-native.sh').read_bytes().replace(b'\r\n', b'\n')) - manifest = destination / 'linux-cmnd-update.json' - manifest.write_text(json.dumps({'schema': 1, 'version': version, 'minimum_version': '0.4.0', - 'scope': 'tooling-only', 'vendor': '7.5.9', 'database_migration': False, - 'vendor_payload_changed': False}, indent=2) + '\n', encoding='utf-8') - source = destination / f'linux-cmnd-{version}-source.tar.gz' - subprocess.run(['git', 'archive', '--format=tar.gz', f'--prefix=linux-cmnd-{version}/', - '-o', str(source), 'HEAD', '--', *RELEASE_PATHS], cwd=ROOT, check=True) - guide = destination / 'EVALUATION-GUIDE.md' - shutil.copyfile(ROOT / 'docs/EVALUATION-GUIDE.md', guide) - configuration = destination / 'cmnd.example.toml' - shutil.copyfile(ROOT / 'config/cmnd.install.toml', configuration) - bootstrap = destination / 'bootstrap.py' - bootstrap.write_bytes((ROOT / 'scripts/bootstrap.py').read_bytes().replace(b'\r\n', b'\n')) - artifacts = [package, meta_package, vendor_package, installer, manifest, source, guide, configuration, bootstrap] - bundled = destination / VENDOR_BUNDLE_NAME + p=argparse.ArgumentParser(description=__doc__); p.add_argument('--vendor-bundle',type=Path,required=True); p.add_argument('--tomcat-archive',type=Path,required=True); a=p.parse_args(); vendor_meta=verify_vendor_bundle(a.vendor_bundle); validate_sources() + payload=build_payload_deb(); vendor=build_vendor_deb(a.vendor_bundle); tomcat=build_tomcat_deb(a.tomcat_archive); meta=build_meta_deb(); version=(ROOT/'VERSION').read_text().strip(); dest=ROOT/'dist' + installer=dest/'install.sh'; installer.write_bytes((ROOT/'scripts/install-native.sh').read_bytes().replace(b'\r\n',b'\n')) + manifest=dest/'linux-cmnd-update.json'; manifest.write_text(json.dumps({'schema':1,'version':version,'minimum_version':'0.4.0','scope':'tooling-only','vendor':'7.5.9','database_migration':False,'vendor_payload_changed':False},indent=2)+'\n') + source=dest/f'linux-cmnd-{version}-source.tar.gz'; subprocess.run(['git','archive','--format=tar.gz',f'--prefix=linux-cmnd-{version}/','-o',str(source),'HEAD','--',*RELEASE_PATHS],cwd=ROOT,check=True) + guide=dest/'EVALUATION-GUIDE.md'; shutil.copyfile(ROOT/'docs/EVALUATION-GUIDE.md',guide); cfg=dest/'cmnd.example.toml'; shutil.copyfile(ROOT/'config/cmnd.install.toml',cfg); bootstrap=dest/'bootstrap.py'; bootstrap.write_bytes((ROOT/'scripts/bootstrap.py').read_bytes().replace(b'\r\n',b'\n')) + artifacts=[payload,meta,vendor,tomcat,installer,manifest,source,guide,cfg,bootstrap]; bundled=dest/VENDOR_BUNDLE_NAME if bundled.exists(): - if verify_vendor_bundle(bundled) != vendor_metadata: - raise SystemExit('Existing release vendor bundle differs; refusing overwrite') - else: - shutil.copyfile(args.vendor_bundle, bundled) - if verify_vendor_bundle(bundled) != vendor_metadata: - raise SystemExit('Vendor bundle changed while copying') - vendor_manifest = destination / 'vendor-bundle.json' - vendor_manifest.write_text(json.dumps(vendor_metadata, indent=2) + '\n', encoding='utf-8') - artifacts += [bundled, vendor_manifest] - checksums = destination / 'SHA256SUMS' - lines = [] - for path in artifacts: - with path.open('rb') as stream: - lines.append(f'{stream_digest(stream)} {path.name}\n') - checksums.write_text(''.join(lines), encoding='ascii') - print(json.dumps({'version': version, 'assets': [str(path) for path in artifacts + [checksums]], - 'apt_packages': [package.name, meta_package.name, vendor_package.name], - 'vendor_payload_included': True, 'vendor_bundle': vendor_metadata}, indent=2)) - - -if __name__ == '__main__': - main() \ No newline at end of file + if verify_vendor_bundle(bundled)!=vendor_meta:raise SystemExit('Existing release vendor bundle differs; refusing overwrite') + else:shutil.copyfile(a.vendor_bundle,bundled) + if verify_vendor_bundle(bundled)!=vendor_meta:raise SystemExit('Vendor bundle changed while copying') + vm=dest/'vendor-bundle.json'; vm.write_text(json.dumps(vendor_meta,indent=2)+'\n'); artifacts += [bundled,vm]; checks=dest/'SHA256SUMS'; checks.write_text(''.join(f'{digest(x)} {x.name}\n' for x in artifacts),encoding='ascii') + print(json.dumps({'version':version,'assets':[str(x) for x in artifacts+[checks]],'apt_packages':[payload.name,meta.name,vendor.name,tomcat.name],'vendor_payload_included':True,'vendor_bundle':vendor_meta},indent=2)) +if __name__=='__main__':main() diff --git a/scripts/build_tomcat_deb.py b/scripts/build_tomcat_deb.py new file mode 100644 index 00000000..72fcaa22 --- /dev/null +++ b/scripts/build_tomcat_deb.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Build the pinned CMND Tomcat 9 archive package.""" +from __future__ import annotations +from hashlib import sha256 +from io import BytesIO +from pathlib import Path +import gzip, os, shutil, sys, tarfile, tempfile +ROOT=Path(__file__).resolve().parents[1]; sys.path.insert(0,str(ROOT/'src')) +from cmnd_linux.application_stage import TOMCAT_SHA512,TOMCAT_VERSION,_tomcat_members +PACKAGE='cmnd-tomcat9'; PACKAGE_VERSION=TOMCAT_VERSION+'-1'; INSTALL_DIR='usr/lib/cmnd/tomcat'; EPOCH=int(os.environ.get('SOURCE_DATE_EPOCH','1788835200')) +def _info(name,size,mode): + x=tarfile.TarInfo(name); x.size=size; x.mode=mode; x.mtime=EPOCH; x.uid=x.gid=0; x.uname=x.gname='root'; return x +def _dir(a,name):x=_info(name,0,0o755); x.type=tarfile.DIRTYPE; a.addfile(x) +def _control(path): + data=f'Package: {PACKAGE}\nVersion: {PACKAGE_VERSION}\nSection: admin\nPriority: optional\nArchitecture: all\nMaintainer: Music City Telecom \nDescription: Pinned Apache Tomcat runtime archive for CMND Linux\n Exact Apache Tomcat {TOMCAT_VERSION} archive used by CMND for Linux.\n'.encode() + with path.open('wb') as raw,gzip.GzipFile(filename='',mode='wb',fileobj=raw,mtime=EPOCH) as gz,tarfile.open(fileobj=gz,mode='w') as a:a.addfile(_info('control',len(data),0o644),BytesIO(data)) +def _data(path,source): + note=f'Apache Tomcat {TOMCAT_VERSION}.\nExpected SHA-512: {TOMCAT_SHA512}\n'.encode() + with path.open('wb') as raw,gzip.GzipFile(filename='',mode='wb',fileobj=raw,mtime=EPOCH) as gz,tarfile.open(fileobj=gz,mode='w') as a: + for d in ('usr','usr/lib','usr/lib/cmnd',INSTALL_DIR,'usr/share','usr/share/doc',f'usr/share/doc/{PACKAGE}'):_dir(a,d) + with source.open('rb') as s:a.addfile(_info(f'{INSTALL_DIR}/apache-tomcat-{TOMCAT_VERSION}.tar.gz',source.stat().st_size,0o644),s) + a.addfile(_info(f'usr/share/doc/{PACKAGE}/ATTRIBUTION',len(note),0o644),BytesIO(note)) +def _ar(out,name,source): + size=source.stat().st_size; out.write((name+'/').encode().ljust(16,b' ')+str(EPOCH).encode().ljust(12,b' ')+b'0 0 100644 '+str(size).encode().ljust(10,b' ')+b'`\n') + with source.open('rb') as s:shutil.copyfileobj(s,out,1024*1024) + if size%2:out.write(b'\n') +def build(archive): + archive=Path(archive) + if not archive.is_file() or archive.is_symlink():raise ValueError('Tomcat input must be a regular non-symlink file') + _tomcat_members(archive); output=ROOT/'dist'/f'{PACKAGE}_{PACKAGE_VERSION}_all.deb'; output.parent.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix='cmnd-tomcat-deb-') as t: + r=Path(t); c=r/'control.tar.gz'; d=r/'data.tar.gz'; b=r/'debian-binary'; _control(c); _data(d,archive); b.write_bytes(b'2.0\n') + with output.open('wb') as o:o.write(b'!\n'); _ar(o,'debian-binary',b); _ar(o,'control.tar.gz',c); _ar(o,'data.tar.gz',d) + h=sha256(); + with output.open('rb') as s: + for chunk in iter(lambda:s.read(1024*1024),b''):h.update(chunk) + Path(str(output)+'.sha256').write_text(f'{h.hexdigest()} {output.name}\n'); return output +def main(argv=None): + import argparse; p=argparse.ArgumentParser(); p.add_argument('archive',type=Path); a=p.parse_args(argv) + try:print(build(a.archive)) + except (OSError,ValueError) as e:print('build-tomcat-deb: '+str(e),file=sys.stderr); return 2 + return 0 +if __name__=='__main__':raise SystemExit(main()) diff --git a/src/cmnd_linux/__main__.py b/src/cmnd_linux/__main__.py index 9ebe6aef..2a33114d 100644 --- a/src/cmnd_linux/__main__.py +++ b/src/cmnd_linux/__main__.py @@ -1,18 +1,31 @@ import sys +args = sys.argv[1:] -# Keep the first 0.8.0 coexistence probes isolated from the qualified 0.7.1 CLI -# dispatcher. The Debian cmndctl wrapper invokes `python3 -m cmnd_linux`, so -# these read-only commands do not change existing command behavior. -if sys.argv[1:] == ['environment']: - from .environment import main as environment_main - - raise SystemExit(environment_main()) -if sys.argv[1:] == ['plan-install']: - from .install_plan import main as plan_main - - raise SystemExit(plan_main()) +if args == ['environment']: + from .environment import main as command + raise SystemExit(command()) +if args == ['plan-install']: + from .install_plan import main as command + raise SystemExit(command()) +if args and args[0] == 'apt-activate': + from .apt_installer import main as command + raise SystemExit(command(args[1:])) +if args == ['shared-wait-database']: + from .shared_database import wait_shared_database + wait_shared_database() + raise SystemExit(0) +if args and args[0] == 'apache-detach': + from .apache_integration import detach + import json + execute = args[1:] == ['--execute'] + if args[1:] not in ([], ['--execute']): + raise SystemExit('Usage: cmndctl apache-detach [--execute]') + print(json.dumps(detach(execute=execute), indent=2, sort_keys=True)) + raise SystemExit(0) +if args and args[0] == 'docker-render': + from .docker_bundle import main as command + raise SystemExit(command(args[1:])) from .cli import main - raise SystemExit(main()) diff --git a/src/cmnd_linux/apache_integration.py b/src/cmnd_linux/apache_integration.py new file mode 100644 index 00000000..48eebeda --- /dev/null +++ b/src/cmnd_linux/apache_integration.py @@ -0,0 +1,155 @@ +"""Scoped integration with an already-running Debian/Ubuntu Apache service. + +CMND owns exactly one conf-available fragment and never edits ports.conf, +apache2.conf, existing sites, or unrelated module configuration. The caller +must choose free CMND ports before applying this fragment. +""" +from __future__ import annotations + +import hashlib +import os +from pathlib import Path +import shutil +import subprocess + +from .config import Config, ConfigError +from .native_config import NativeLayout, native_endpoint + +CONF_AVAILABLE = Path('/etc/apache2/conf-available/cmnd-linux.conf') +CONF_ENABLED = Path('/etc/apache2/conf-enabled/cmnd-linux.conf') +MODULES = ('alias', 'dir', 'proxy', 'proxy_fcgi', 'proxy_http', 'ssl', 'rewrite', + 'headers', 'expires', 'filter', 'deflate') + + +def supported() -> bool: + return (Path('/etc/apache2/apache2.conf').is_file() + and all(shutil.which(name) for name in ('apache2ctl', 'a2enmod', 'a2enconf', 'a2disconf', 'systemctl'))) + + +def render(config: Config, *, layout: NativeLayout = NativeLayout(), management_port: int | None = None) -> str: + host, _ = native_endpoint(config) + management_port = layout.management_port if management_port is None else management_port + if type(management_port) is not int or not 1024 <= management_port <= 65535: + raise ConfigError('invalid management port for host Apache integration') + if layout.fpm_port in {config.apache_http, config.apache_https, management_port}: + raise ConfigError('host Apache integration port collision') + return f'''# Managed by CMND Linux 0.8. Do not merge this file into unrelated sites. +Listen {config.bind}:{config.apache_http} +Listen {config.bind}:{config.apache_https} + + + ServerName {host} + Redirect / https://{host}:{config.apache_https}/ + + + + ServerName {host} + DocumentRoot {layout.cms} + SSLEngine on + SSLProtocol -all +TLSv1.2 +TLSv1.3 + SSLCertificateFile {layout.certificate} + SSLCertificateKeyFile {layout.key} + ProxyTimeout 900 + ProxyRequests Off + + Alias /SmartCMS {layout.cms} + + LimitRequestBody 0 + Require all granted + AllowOverride All + Options FollowSymLinks + DirectoryIndex index.php + + Require all denied + + + SetHandler "proxy:fcgi://127.0.0.1:{layout.fpm_port}" + + + + + AllowOverride None + Options -ExecCGI -Indexes + Require all granted + + Require all denied + + + + ProxyPass /linux-cmnd/ http://127.0.0.1:{management_port}/ connectiontimeout=5 timeout=30 + ProxyPassReverse /linux-cmnd/ http://127.0.0.1:{management_port}/ + + Require all granted + + +''' + + +def _run(args: list[str], *, timeout: int = 60) -> subprocess.CompletedProcess[str]: + result = subprocess.run(args, capture_output=True, text=True, timeout=timeout, check=False) + if result.returncode: + raise RuntimeError('host Apache command failed: ' + Path(args[0]).name + '; inspect journal/configtest output locally') + return result + + +def apply(config: Config, *, execute: bool = False, + layout: NativeLayout = NativeLayout(), management_port: int | None = None) -> dict: + content = render(config, layout=layout, management_port=management_port) + if not supported(): + raise ConfigError('existing Apache is not a supported Debian/Ubuntu apache2 layout') + if CONF_AVAILABLE.exists() or CONF_AVAILABLE.is_symlink() or CONF_ENABLED.exists() or CONF_ENABLED.is_symlink(): + raise ConfigError('CMND host Apache fragment already exists; refusing overwrite') + enabled_before = {module: (Path('/etc/apache2/mods-enabled') / f'{module}.load').exists() for module in MODULES} + report = {'executed': execute, 'configuration': str(CONF_AVAILABLE), + 'sha256': hashlib.sha256(content.encode()).hexdigest(), + 'modules_already_enabled': sorted(name for name, enabled in enabled_before.items() if enabled), + 'host_apache_reloaded': False} + if not execute: + return report + + fd = os.open(CONF_AVAILABLE, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) + enabled_by_us: list[str] = [] + try: + with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as handle: + handle.write(content) + for module, already in enabled_before.items(): + if not already: + _run([shutil.which('a2enmod') or 'a2enmod', module]) + enabled_by_us.append(module) + _run([shutil.which('a2enconf') or 'a2enconf', 'cmnd-linux']) + _run([shutil.which('apache2ctl') or 'apache2ctl', 'configtest']) + _run([shutil.which('systemctl') or 'systemctl', 'reload', 'apache2.service']) + report['host_apache_reloaded'] = True + report['modules_enabled_by_cmnd'] = enabled_by_us + return report + except Exception: + subprocess.run([shutil.which('a2disconf') or 'a2disconf', 'cmnd-linux'], capture_output=True, timeout=20) + if CONF_AVAILABLE.is_file() and not CONF_AVAILABLE.is_symlink(): + try: + if CONF_AVAILABLE.read_text(encoding='utf-8', errors='replace').startswith('# Managed by CMND Linux 0.8.'): + CONF_AVAILABLE.unlink() + except OSError: + pass + subprocess.run([shutil.which('apache2ctl') or 'apache2ctl', 'configtest'], capture_output=True, timeout=20) + subprocess.run([shutil.which('systemctl') or 'systemctl', 'reload', 'apache2.service'], capture_output=True, timeout=30) + raise + + +def detach(*, execute: bool = False) -> dict: + if not CONF_AVAILABLE.exists() and not CONF_ENABLED.exists(): + return {'executed': execute, 'present': False} + if CONF_AVAILABLE.is_symlink(): + raise ConfigError('unexpected symlink at CMND Apache source fragment') + if CONF_AVAILABLE.exists(): + text = CONF_AVAILABLE.read_text(encoding='utf-8', errors='replace') + if not text.startswith('# Managed by CMND Linux 0.8.'): + raise ConfigError('existing Apache fragment is not recognized as CMND-owned') + report = {'executed': execute, 'present': True, 'configuration': str(CONF_AVAILABLE)} + if not execute: + return report + subprocess.run([shutil.which('a2disconf') or 'a2disconf', 'cmnd-linux'], capture_output=True, timeout=20) + _run([shutil.which('apache2ctl') or 'apache2ctl', 'configtest']) + _run([shutil.which('systemctl') or 'systemctl', 'reload', 'apache2.service']) + if CONF_AVAILABLE.exists(): + CONF_AVAILABLE.unlink() + return report | {'detached': True} diff --git a/src/cmnd_linux/apt_installer.py b/src/cmnd_linux/apt_installer.py new file mode 100644 index 00000000..ac7ff942 --- /dev/null +++ b/src/cmnd_linux/apt_installer.py @@ -0,0 +1,207 @@ +"""APT-managed CMND 0.8 activation. + +Versioned Debian packages place tooling, exact Philips inputs and pinned Tomcat +on disk first. This module inventories the host, selects coexistence modes, +prepares runtime images and hands activation to coexist_deploy. Database admin +passwords are accepted only through root-only temporary files and never persisted. +""" +from __future__ import annotations +import argparse, json, os, re, shutil, socket, subprocess, tempfile +from pathlib import Path +from . import __version__ +from .config import ConfigError, load_config +from .coexist_deploy import CoexistInputs, deploy +from .environment import DEFAULT_PORTS, host_inventory +from .install_plan import allocate_port, build_plan +from .native_deploy import BASELINE, MYSQL_IMAGE, validate_baseline +from .shared_database import SharedDatabaseSession + +VENDOR_ROOT=Path('/usr/lib/cmnd/vendor/7.5.9') +TOMCAT_ARCHIVE=Path('/usr/lib/cmnd/tomcat/apache-tomcat-9.0.121.tar.gz') +PACKAGE_ARCHIVE=Path(f'/usr/lib/cmnd/packages/linux-cmnd_{__version__}_amd64.deb') +DEFAULT_CONFIG=Path('/opt/linux-cmnd/current/config/cmnd.install.toml') +CONFIG=Path('/etc/cmnd/cmnd.toml'); CACHE=Path('/var/cache/linux-cmnd/bootstrap') +PHP_IID=CACHE/'php-image.id'; PHP_BUILD_LOG=CACHE/'php-build.log' + +def _run(args,*,timeout=1800): return subprocess.run(args,capture_output=True,timeout=timeout,check=False) +def _require_root(): + if os.name!='posix' or not hasattr(os,'geteuid') or os.geteuid()!=0: raise ConfigError('APT activation must run as root') +def _safe_password_file(path): + path=Path(path) + if not path.is_file() or path.is_symlink() or any(p.is_symlink() for p in path.parents): raise ConfigError('database administrator password file must be a regular non-symlink file') + if path.stat().st_size>4096 or (os.name=='posix' and path.stat().st_mode&0o077): raise ConfigError('database administrator password file must be mode 0600 or stricter') + value=path.read_text(encoding='utf-8').rstrip('\r\n') + if not value or any(c in value for c in ('\x00','\n','\r')): raise ConfigError('database administrator password is empty or contains unsupported control characters') + return value +def _option_quote(value): return '"'+value.replace('\\','\\\\').replace('"','\\"')+'"' +def _db_defaults_file(directory,user,password): + if not re.fullmatch(r'[A-Za-z0-9_@.-]{1,64}',user): raise ConfigError('invalid database administrator username') + path=directory/'database-admin.cnf'; fd=os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600) + with os.fdopen(fd,'w',encoding='utf-8',newline='\n') as h:h.write(f'[client]\nuser={_option_quote(user)}\npassword={_option_quote(password)}\n') + return path + +def _assigned_ipv4(): + r=_run(['ip','-j','-4','address','show'],timeout=10) + if r.returncode:return [] + try:interfaces=json.loads(r.stdout) + except Exception:return [] + return [a['local'] for i in interfaces if 'UP' in i.get('flags',[]) for a in i.get('addr_info',[]) if a.get('family')=='inet' and isinstance(a.get('local'),str)] +def _default_route_ipv4(assigned): + # This is a local routing-table lookup; it does not contact 1.1.1.1. + result=_run(['ip','-j','route','get','1.1.1.1'],timeout=10) + if result.returncode: + return None + try: + routes=json.loads(result.stdout) + except Exception: + return None + for route in routes if isinstance(routes,list) else []: + candidate=route.get('prefsrc') or route.get('src') + if isinstance(candidate,str) and candidate in assigned and not candidate.startswith('127.'): + return candidate + return None + +def choose_server_ip(requested=None): + assigned=_assigned_ipv4() + if requested: + try:socket.inet_aton(requested) + except OSError as e:raise ConfigError('server IP must be a literal IPv4 address') from e + if requested!='127.0.0.1' and requested not in assigned: raise ConfigError('requested server IP is not assigned to an active local interface') + return requested + preferred=_default_route_ipv4(assigned) + if preferred: + return preferred + values=[v for v in assigned if not v.startswith('127.')] + return values[0] if values else '127.0.0.1' +def _occupied(inv): return {int(x['port']) for x in inv.get('listeners',{}).get('entries',[]) if isinstance(x,dict) and isinstance(x.get('port'),int)} +def _planned_ports(inv,plan,database_mode): + occupied=_occupied(inv) + c=plan['components'] + ports={ + 'tomcat_http':int(c['tomcat']['ports']['http']), + 'tomcat_https':int(c['tomcat']['ports']['https']), + 'apache_http':int(c['apache']['ports']['http']), + 'apache_https':int(c['apache']['ports']['https']), + } + reserved=set(ports.values()) + if database_mode=='shared': + ports['database']=int(c['database'].get('port') or DEFAULT_PORTS['database']) + else: + ports['database']=allocate_port(DEFAULT_PORTS['database'],occupied,reserved) + reserved.add(ports['database']) + ports['php_fpm']=allocate_port(DEFAULT_PORTS['php_fpm'],occupied,reserved) + reserved.add(ports['php_fpm']) + ports['management']=allocate_port(DEFAULT_PORTS['management'],occupied,reserved) + if len(set(ports.values()))!=len(ports): + raise ConfigError('installation planner produced colliding CMND ports') + return ports +def render_config(ip,ports): + mode='isolated' if ip.startswith('127.') else 'lab' + return f'''# Generated by CMND Linux 0.8 APT activation. No TVs are authorized.\n[safety]\nmode = "{mode}"\npermitted_ranges = ["127.0.0.0/8"]\n\n[network]\nbind = "{ip}"\ncallback_base_url = "http://{ip}:{ports['tomcat_http']}"\ntimeout_seconds = 5\n\n[ports]\ntomcat_http = {ports['tomcat_http']}\ntomcat_https = {ports['tomcat_https']}\napache_http = {ports['apache_http']}\napache_https = {ports['apache_https']}\ndatabase = {ports['database']}\n\n[tv]\nallowlist = []\n''' +def _install_config(content): + CONFIG.parent.mkdir(mode=0o750,parents=True,exist_ok=True) + if CONFIG.exists() or CONFIG.is_symlink(): + if CONFIG.is_symlink() or not CONFIG.is_file():raise ConfigError('existing CMND configuration path is unsafe') + if DEFAULT_CONFIG.is_file() and CONFIG.read_bytes()!=DEFAULT_CONFIG.read_bytes():load_config(CONFIG); return CONFIG + backup=CONFIG.with_name('cmnd.toml.package-default') + if not backup.exists():backup.write_bytes(CONFIG.read_bytes()); backup.chmod(0o600) + temp=CONFIG.with_name('.cmnd.toml.apt-new') + if temp.exists() or temp.is_symlink():raise ConfigError('stale temporary CMND configuration exists') + fd=os.open(temp,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o640) + with os.fdopen(fd,'w',encoding='utf-8',newline='\n') as h:h.write(content) + os.replace(temp,CONFIG); load_config(CONFIG); return CONFIG +def _find_db_client(inv): + db=inv.get('database',{}) + for name in ('mariadb_client','mysql_client'): + r=db.get(name,{}) + if isinstance(r,dict) and r.get('present') and r.get('path'):return str(r['path']) + return shutil.which('mariadb') or shutil.which('mysql') +def _shared_session(inv,password_file,admin_user,temp): + client=_find_db_client(inv) + if not client:return None + db=inv.get('database',{}); sockets=db.get('socket_candidates') or [] + if db.get('root_socket_auth')=='available' and sockets and admin_user=='root':s=SharedDatabaseSession(client,3306,socket_path=str(sockets[0]),admin_user='root') + elif password_file is not None:s=SharedDatabaseSession(client,3306,socket_path=str(sockets[0]) if sockets else None,admin_defaults_file=_db_defaults_file(temp,admin_user,_safe_password_file(password_file)),admin_user=admin_user) + else:return None + try: + port=s.execute('SELECT @@port;',timeout=10).decode(errors='replace').strip() + if port.isdigit():s.port=int(port) + except RuntimeError:return None + return s +def _select_modes(inv,plan,requested_database,requested_apache,password_file,admin_user,temp): + notes=[]; session=None + if requested_database in {'auto','existing'}: + session=_shared_session(inv,password_file,admin_user,temp) + if session: + try:session.validate_for_fresh_cmnd(); dbmode='shared'; notes.append('Existing MySQL passed shared-database gate.') + except (ConfigError,RuntimeError) as e: + if requested_database=='existing':raise + session=None; dbmode='isolated'; notes.append('Existing database preserved but not reused: '+str(e)) + elif requested_database=='existing':raise ConfigError('existing database mode requested but no authenticated administrator session is available') + else:dbmode='isolated'; notes.append('No qualified authenticated host DB; using isolated MySQL fallback.') + elif requested_database=='isolated':dbmode='isolated' + else:raise ConfigError('database mode must be auto, existing, or isolated') + ap=inv.get('web',{}).get('apache_service',{}); present=bool(plan['components']['apache'].get('existing_apache')) + if requested_apache=='auto':webmode='host' if present and ap.get('active') else 'standalone' + elif requested_apache in {'host','standalone'}:webmode=requested_apache + else:raise ConfigError('Apache mode must be auto, host, or standalone') + if webmode=='host' and not present:raise ConfigError('host Apache mode requested but no existing Apache installation was detected') + notes.append('Apache mode: '+webmode); return dbmode,webmode,session,notes +def _ensure_docker(): + if not shutil.which('docker'):raise ConfigError('Docker runtime is required by current legacy PHP profile') + r=_run(['docker','info'],timeout=20) + if r.returncode and shutil.which('systemctl'):_run(['systemctl','enable','--now','docker.service'],timeout=120); r=_run(['docker','info'],timeout=20) + if r.returncode:raise ConfigError('Docker daemon unavailable') +def _ensure_image(image): + if _run(['docker','image','inspect',image],timeout=30).returncode==0:return + if _run(['docker','pull',image],timeout=1800).returncode:raise ConfigError('required pinned container image could not be pulled') +def _php_image(): + if PHP_IID.is_file() and not PHP_IID.is_symlink(): + image=PHP_IID.read_text().strip() + if image and _run(['docker','image','inspect',image],timeout=30).returncode==0:return image + CACHE.mkdir(parents=True,mode=0o700,exist_ok=True); dockerfile=Path('/opt/linux-cmnd/current/deploy/php/Dockerfile.lab'); context=dockerfile.parent + if not dockerfile.is_file():raise ConfigError('packaged legacy PHP Dockerfile is missing') + partial=PHP_IID.with_suffix('.partial'); partial.unlink(missing_ok=True) + with PHP_BUILD_LOG.open('wb') as log:r=subprocess.run(['docker','build','-f',str(dockerfile),'--iidfile',str(partial),str(context)],stdout=log,stderr=subprocess.STDOUT,timeout=3600,check=False) + if r.returncode or not partial.is_file():raise ConfigError('legacy PHP image build failed; inspect /var/cache/linux-cmnd/bootstrap/php-build.log') + image=partial.read_text().strip() + if not re.fullmatch(r'sha256:[0-9a-f]{64}',image):raise ConfigError('unexpected PHP image identifier') + os.replace(partial,PHP_IID); PHP_IID.chmod(0o600); PHP_BUILD_LOG.chmod(0o600); return image +def _install_baseline(): + if not PACKAGE_ARCHIVE.is_file() or PACKAGE_ARCHIVE.is_symlink():raise ConfigError('matching rollback package is missing from cmnd-linux') + CACHE.mkdir(parents=True,mode=0o700,exist_ok=True) + if BASELINE.is_symlink():raise ConfigError('rollback package path is unsafe symlink') + if not BASELINE.exists():shutil.copyfile(PACKAGE_ARCHIVE,BASELINE); BASELINE.chmod(0o600) + validate_baseline() +def plan(server_ip=None,database_mode='auto',apache_mode='auto',password_file=None,admin_user='root'): + inv=host_inventory(); base=build_plan(inv) + if not base.get('fresh_install_allowed'):raise ConfigError('existing active CMND runtime detected') + with tempfile.TemporaryDirectory(prefix='cmnd-apt-plan-') as d: + db,web,session,notes=_select_modes(inv,base,database_mode,apache_mode,password_file,admin_user,Path(d)); ports=_planned_ports(inv,base,db) + if db=='shared':ports['database']=session.port + return {'schema':1,'executed':False,'server_ip':choose_server_ip(server_ip),'database_mode':db,'apache_mode':web,'ports':ports,'notes':notes,'base_plan':base,'shared_database_qualified':db=='shared'} +def activate(server_ip,database_mode,apache_mode,password_file,admin_user,execute,accept_legacy): + if not execute:return plan(server_ip,database_mode,apache_mode,password_file,admin_user) + _require_root() + if not accept_legacy:raise ConfigError('legacy PHP 5.6/MySQL 5.7 runtime acceptance is required') + if not VENDOR_ROOT.is_dir() or VENDOR_ROOT.is_symlink():raise ConfigError('verified Philips vendor package is not installed') + if not TOMCAT_ARCHIVE.is_file() or TOMCAT_ARCHIVE.is_symlink():raise ConfigError('pinned CMND Tomcat package is not installed') + inv=host_inventory(); base=build_plan(inv) + if not base.get('fresh_install_allowed'):raise ConfigError('existing active CMND runtime detected; use upgrade workflow') + os.umask(0o077) + with tempfile.TemporaryDirectory(prefix='cmnd-apt-admin-',dir='/run' if Path('/run').is_dir() else None) as d: + db,web,session,notes=_select_modes(inv,base,database_mode,apache_mode,password_file,admin_user,Path(d)); ports=_planned_ports(inv,base,db) + if db=='shared':ports['database']=session.port + address=choose_server_ip(server_ip); config=_install_config(render_config(address,ports)); cfg=load_config(config) + if db=='shared' and cfg.database_port!=session.port:raise ConfigError('preserved config DB port does not match shared server') + _ensure_docker(); _ensure_image(MYSQL_IMAGE) if db=='isolated' else None; php=_php_image(); _install_baseline() + result=deploy(CoexistInputs( + config,VENDOR_ROOT,TOMCAT_ARCHIVE,php,Path('/usr/lib/jvm/java-17-openjdk-amd64'), + db,web,session,True,ports['php_fpm'],ports['management'] + ),execute=True,accept_legacy=True) + result['apt_activation']={'server_ip':address,'database_mode':db,'apache_mode':web,'notes':notes}; return result +def main(argv=None): + p=argparse.ArgumentParser(prog='cmndctl apt-activate'); p.add_argument('--server-ip'); p.add_argument('--database-mode',choices=('auto','existing','isolated'),default='auto'); p.add_argument('--apache-mode',choices=('auto','host','standalone'),default='auto'); p.add_argument('--database-admin-user',default='root'); p.add_argument('--database-admin-password-file',type=Path); p.add_argument('--accept-legacy-runtime',action='store_true'); p.add_argument('--execute',action='store_true'); p.add_argument('--dry-run',action='store_true'); a=p.parse_args(argv) + try:r=activate(a.server_ip,a.database_mode,a.apache_mode,a.database_admin_password_file,a.database_admin_user,a.execute and not a.dry_run,a.accept_legacy_runtime) + except (ConfigError,RuntimeError,OSError,subprocess.SubprocessError) as e:print('cmndctl apt-activate: '+str(e),file=os.sys.stderr); return 2 + print(json.dumps(r,indent=2,sort_keys=True)); return 0 diff --git a/src/cmnd_linux/coexist_deploy.py b/src/cmnd_linux/coexist_deploy.py new file mode 100644 index 00000000..9d6d0198 --- /dev/null +++ b/src/cmnd_linux/coexist_deploy.py @@ -0,0 +1,263 @@ +"""0.8 coexistence-aware fresh deployment engine. + +The v0.7.1-derived native_deploy module remains unchanged. This module reuses its +verified primitives while allowing a pre-qualified host MySQL service and/or a +CMND-owned fragment in an existing Debian/Ubuntu Apache service. +""" +from __future__ import annotations +from dataclasses import dataclass +import hashlib, json, os, platform, re, secrets, shutil, socket, ssl, subprocess, time +from pathlib import Path +from urllib.error import HTTPError, URLError +from urllib.parse import urlsplit +from urllib.request import HTTPSHandler, HTTPRedirectHandler, ProxyHandler, build_opener + +from .apache_integration import apply as apache_apply, detach as apache_detach, supported as apache_supported +from .application_stage import ApplicationInputs, VENDOR_INPUT_HASHES, _tomcat_members, stage_application +from .artifacts import file_hash +from .certificates import CertificateConfig, provision_certificates +from .config import Config, ConfigError, load_config +from .egress import EgressPolicy, apply_policy +from .native_config import NativeLayout, native_endpoint, render_native_files +from .native_deploy import (BASELINE, ETC, LAYOUT, MANAGEMENT, MYSQL_IMAGE, SCHEMAS, STATE, + _mysql, _owned_tree, https_origin, mysql_server_options, run, validate_baseline, + validate_image, wait_database, wait_php, write_new) +from .shared_database import (SharedDatabaseSession, migration_histories as shared_histories, + wait_shared_database, write_health_files) +from .vendor_config import REQUIRED_SECRETS + +@dataclass(frozen=True) +class CoexistInputs: + config: Path; vendor: Path; tomcat_archive: Path; php_image: str; java_home: Path + database_mode: str='isolated'; apache_mode: str='standalone' + shared_database: SharedDatabaseSession|None=None; apt_managed: bool=True + php_fpm_port: int=9000; management_port: int=9078 + + def layout(self) -> NativeLayout: + return NativeLayout(fpm_port=self.php_fpm_port, management_port=self.management_port) + +def os_support(content,machine): + values={} + for line in content.splitlines(): + if '=' in line and not line.startswith('#'): + k,v=line.split('=',1); values[k]=v.strip('"\'') + selected=(values.get('ID',''),values.get('VERSION_ID','')) + if selected not in {('ubuntu','22.04'),('ubuntu','24.04'),('ubuntu','26.04'),('debian','12'),('debian','13')}: + raise ConfigError('0.8 supports Ubuntu 22.04/24.04/26.04 or Debian 12/13 candidates') + if machine not in {'x86_64','amd64'}: raise ConfigError('CMND requires amd64') + return selected + +def _units(java_home,db_mode,apache_mode,apt_managed=True): + if db_mode not in {'isolated','shared'} or apache_mode not in {'standalone','host'}: raise ConfigError('invalid coexistence mode') + dbreq='Requires=cmnd-mysql.service\nAfter=cmnd-mysql.service\n' if db_mode=='isolated' else 'After=network-online.target\n' + dbwait='/usr/bin/cmndctl native-wait-database' if db_mode=='isolated' else '/usr/bin/cmndctl shared-wait-database' + before='cmnd-php.service cmnd-tomcat.service'+(' cmnd-mysql.service' if db_mode=='isolated' else '')+(' cmnd-apache.service' if apache_mode=='standalone' else '') + u={ + 'cmnd-egress.service':f'''[Unit]\nDescription=CMND egress isolation\nAfter=local-fs.target\nBefore={before}\n[Service]\nType=oneshot\nRemainAfterExit=yes\nEnvironment=PATH=/usr/sbin:/usr/bin:/sbin:/bin\nExecStart=/usr/bin/python3 /etc/cmnd/egress.py --policy /etc/cmnd/egress.json --execute\nRuntimeDirectory=cmnd\nRuntimeDirectoryMode=0755\nNoNewPrivileges=true\nProtectHome=true\nProtectSystem=strict\nReadWritePaths=/run\nCapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW\n[Install]\nWantedBy=multi-user.target\n''', + 'cmnd-php.service':f'''[Unit]\nDescription=CMND legacy PHP runtime\nRequires=cmnd-egress.service docker.service\nAfter=cmnd-egress.service docker.service\n{dbreq}[Service]\nType=simple\nExecStartPre={dbwait}\nExecStart=/usr/bin/docker start -a cmnd-native-php\nExecStop=/usr/bin/docker stop -t 30 cmnd-native-php\nRestart=on-failure\nTimeoutStartSec=180\n[Install]\nWantedBy=multi-user.target\n''', + 'cmnd-tomcat.service':f'''[Unit]\nDescription=Philips CMND Java applications\nRequires=cmnd-egress.service\nAfter=cmnd-egress.service\n{dbreq}[Service]\nType=simple\nUser=cmnd\nGroup=cmnd\nEnvironment=JAVA_HOME={java_home}\nEnvironmentFile=/etc/cmnd/native-tomcat.env\nWorkingDirectory=/opt/cmnd/tomcat\nExecStartPre=+/usr/bin/cmndctl native-hardware-access --execute\nExecStartPre=+{dbwait}\nExecStart=/opt/cmnd/tomcat/bin/catalina.sh run\nSuccessExitStatus=143\nRestart=on-failure\nUMask=0027\nNoNewPrivileges=true\nPrivateTmp=true\nProtectHome=true\nProtectSystem=strict\nReadWritePaths=/opt/Philips /opt/cmnd/tomcat /var/lib/cmnd /var/log/cmnd\n[Install]\nWantedBy=multi-user.target\n''', + 'cmnd-admin.service':'''[Unit]\nDescription=Linux CMND administration GUI\nAfter=network-online.target\n[Service]\nType=simple\nUser=cmnd-admin\nGroup=cmnd-admin\nExecStart=/usr/bin/cmndctl update-gui --settings /etc/linux-cmnd-management/admin.json\nRestart=on-failure\nUMask=0077\nNoNewPrivileges=true\nProtectSystem=strict\nProtectHome=true\nReadWritePaths=/var/lib/cmnd-update-requests\n[Install]\nWantedBy=multi-user.target\n'''} + if db_mode=='isolated': u['cmnd-mysql.service']='''[Unit]\nDescription=CMND isolated MySQL\nRequires=cmnd-egress.service docker.service\nAfter=cmnd-egress.service docker.service\n[Service]\nType=simple\nExecStart=/usr/bin/docker start -a cmnd-native-mysql\nExecStop=/usr/bin/docker stop -t 30 cmnd-native-mysql\nRestart=on-failure\n[Install]\nWantedBy=multi-user.target\n''' + if apache_mode=='standalone': u['cmnd-apache.service']='''[Unit]\nDescription=CMND standalone Apache\nRequires=cmnd-php.service\nAfter=cmnd-php.service\n[Service]\nType=simple\nExecStart=/usr/sbin/apache2 -f /etc/cmnd/apache.conf -DFOREGROUND\nExecReload=/usr/sbin/apache2 -f /etc/cmnd/apache.conf -k graceful\nRestart=on-failure\nNoNewPrivileges=true\nProtectSystem=strict\nProtectHome=true\nReadWritePaths=/run/cmnd /var/log/cmnd /opt/cmnd/SmartCMS/sites/default/files\n[Install]\nWantedBy=multi-user.target\n''' + return u + +def _port_free(port): + with socket.socket() as s: + try:s.bind(('0.0.0.0',port)); return True + except OSError:return False + +def _wait_php(port,seconds=60): + if type(port) is not int or not 1<=port<=65535: + raise ConfigError('invalid PHP-FPM readiness port') + deadline=time.monotonic()+seconds + while time.monotonic() DatabaseCompatibility: if read_only in {'1', 'ON', 'TRUE', 'YES'}: reasons.append('server is read-only') + event_scheduler = normalized.get('event_scheduler', '').upper() + if event_scheduler not in {'ON', '1'}: + reasons.append('event_scheduler must already be ON; CMND will not change a shared server global setting') + + local_infile = normalized.get('local_infile', '').upper() + if local_infile not in {'OFF', '0'}: + reasons.append('local_infile must already be OFF for the reviewed shared-server profile') + + sql_mode = normalized.get('sql_mode', '') + modes = {item.strip().upper() for item in sql_mode.split(',') if item.strip()} + if modes != {'NO_ENGINE_SUBSTITUTION'}: + reasons.append('sql_mode must already match the reviewed NO_ENGINE_SUBSTITUTION profile') + if family == 'mysql' and version.startswith('5.7.'): qualification = 'matches-current-qualified-family' elif family in {'mysql', 'mariadb'}: diff --git a/src/cmnd_linux/docker_bundle.py b/src/cmnd_linux/docker_bundle.py new file mode 100644 index 00000000..084625bb --- /dev/null +++ b/src/cmnd_linux/docker_bundle.py @@ -0,0 +1,66 @@ +"""Render a self-contained Docker Compose candidate from the same CMND staging code. + +This path is intentionally separate from the qualified native runtime. It builds +a root-owned bundle for review and never starts containers automatically because +Philips TV LAN/discovery behavior under Docker host networking is not yet qualified. +""" +from __future__ import annotations +import argparse, hashlib, json, os, secrets, shutil, socket +from pathlib import Path +from urllib.parse import urlsplit +from .application_stage import ApplicationInputs, VENDOR_INPUT_HASHES, _tomcat_members, stage_application +from .artifacts import file_hash +from .certificates import CertificateConfig, provision_certificates +from .config import ConfigError, load_config +from .native_deploy import SCHEMAS +from .vendor_config import REQUIRED_SECRETS + +VENDOR_ROOT=Path('/usr/lib/cmnd/vendor/7.5.9') +TOMCAT_ARCHIVE=Path('/usr/lib/cmnd/tomcat/apache-tomcat-9.0.121.tar.gz') +DEFAULT_JAVA_IMAGE='eclipse-temurin:17-jre-jammy' +MYSQL_IMAGE='mysql@sha256:4bc6bc963e6d8443453676cae56536f4b8156d78bae03c0145cbe47c2aad73bb' + +def _write(path,data,mode=0o600): + path.parent.mkdir(parents=True,exist_ok=True); raw=data.encode() if isinstance(data,str) else data + fd=os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY,mode) + with os.fdopen(fd,'wb') as h:h.write(raw) +def _sql_quote(v):return "'"+v.replace('\\','\\\\').replace("'","''")+"'" +def _bootstrap_sql(vendor,values,admin_password): + parts=[b'SET sql_mode="NO_ENGINE_SUBSTITUTION";\n'] + for schema,user,folder,numbers in SCHEMAS: + pw=values[folder+'_db_password']; parts.append((f'CREATE DATABASE `{schema}` CHARACTER SET utf8 COLLATE utf8_general_ci;\nCREATE USER {_sql_quote(user)}@\'%\' IDENTIFIED BY {_sql_quote(pw)};\nGRANT ALL ON `{schema}`.* TO {_sql_quote(user)}@\'%\';\nUSE `{schema}`;\n').encode()) + for n in numbers:parts += [(vendor/'SQLScripts'/folder/f'sql_{n}.sql').read_bytes(),b'\n'] + digest=hashlib.md5(admin_password.encode()).hexdigest(); parts.append(("USE `cas`; DELETE FROM users; INSERT INTO users(username,password,role) VALUES"+f"('admin','{digest}','ADMIN');\n").encode()); return b''.join(parts) +def _compose(java_image): + return f'''name: cmnd-linux\nservices:\n db:\n image: {MYSQL_IMAGE}\n network_mode: host\n restart: unless-stopped\n command: ["--bind-address=127.0.0.1", "--port=${{CMND_DB_PORT}}", "--event-scheduler=ON", "--local-infile=0", "--sql-mode=NO_ENGINE_SUBSTITUTION", "--lower-case-table-names=1"]\n environment:\n MYSQL_ROOT_PASSWORD_FILE: /run/secrets/mysql_root\n volumes:\n - ./state/mysql:/var/lib/mysql\n - ./secrets/mysql-root-password:/run/secrets/mysql_root:ro\n - ./mysql-init:/docker-entrypoint-initdb.d:ro\n php:\n build: ./php-image\n network_mode: host\n restart: unless-stopped\n read_only: true\n security_opt: ["no-new-privileges:true"]\n cap_drop: ["ALL"]\n tmpfs: ["/tmp:rw,nosuid,noexec,size=256m"]\n volumes:\n - ./payload/SmartCMS:/opt/cmnd/SmartCMS:ro\n - ./state/cms-files:/opt/cmnd/SmartCMS/sites/default/files\n - ./state/php-uploads:/var/lib/cmnd/php-uploads\n - ./state/cas-pgt:/var/lib/cmnd/cas-pgt\n - ./config/php-fpm.conf:/usr/local/etc/php-fpm.conf:ro\n - /etc/ssl/certs:/etc/ssl/certs:ro\n depends_on: [db]\n tomcat:\n image: {java_image}\n network_mode: host\n restart: unless-stopped\n working_dir: /opt/cmnd/tomcat\n command: ["/opt/cmnd/tomcat/bin/catalina.sh", "run"]\n environment:\n JAVA_HOME: /opt/java/openjdk\n CATALINA_OPTS: -Xms512m -Xmx4096m -Djava.awt.headless=true -Djavax.net.ssl.trustStore=/etc/cmnd/java-cacerts\n volumes:\n - ./payload/tomcat:/opt/cmnd/tomcat\n - ./payload/Philips:/opt/Philips\n - ./config/java-cacerts:/etc/cmnd/java-cacerts:ro\n - /sys/class/dmi/id:/sys/class/dmi/id:ro\n depends_on: [db]\n apache:\n build: ./apache-image\n network_mode: host\n restart: unless-stopped\n volumes:\n - ./payload/SmartCMS:/opt/cmnd/SmartCMS:ro\n - ./state/cms-files:/opt/cmnd/SmartCMS/sites/default/files\n - ./config/apache.conf:/etc/cmnd/apache.conf:ro\n - ./payload/tls:/etc/cmnd/tls:ro\n - ./state/log:/var/log/cmnd\n - ./state/run:/run/cmnd\n depends_on: [php]\n''' +def render(config_path,output,*,java_image=DEFAULT_JAVA_IMAGE,execute=False): + config=load_config(config_path) + if not java_image or any(c.isspace() for c in java_image):raise ConfigError('invalid Java container image reference') + for p in (VENDOR_ROOT,TOMCAT_ARCHIVE): + if not p.exists() or p.is_symlink():raise ConfigError('required packaged Docker input missing: '+str(p)) + for name,expected in VENDOR_INPUT_HASHES.items(): + p=VENDOR_ROOT/name + if not p.is_file() or file_hash(p)!=expected:raise ConfigError('vendor package does not match pinned input: '+name) + _tomcat_members(TOMCAT_ARCHIVE) + report={'executed':execute,'output':str(output),'java_image':java_image,'mysql_image':MYSQL_IMAGE,'network_mode':'host','qualified':False,'warning':'Docker host-network TV discovery/control is not yet physical-TV qualified; review before starting containers.'} + if not execute:return report + if os.geteuid()!=0:raise ConfigError('docker bundle rendering requires root') + if output.exists() or output.is_symlink():raise ConfigError('Docker bundle output must not already exist') + output.mkdir(parents=True,mode=0o700); os.umask(0o077) + try: + values={k:secrets.token_hex(24) for k in (*REQUIRED_SECRETS,'tpvision_db_password')}; admin=secrets.token_hex(24); root=secrets.token_hex(32); certpass=output/'secrets/certificate-password'; _write(certpass,values['cert_ca_password']) + addresses=[config.bind] if config.bind!='0.0.0.0' else []; public=urlsplit(config.callback_base_url).hostname or config.bind + certs=provision_certificates(CertificateConfig(output/'certificates',public,addresses,socket.gethostname(),certpass,certpass)); stage=output/'stage'; stage_application(ApplicationInputs(VENDOR_ROOT,TOMCAT_ARCHIVE,certs),config,values,stage,execute=True,database_host='127.0.0.1'); shutil.move(str(stage/'payload'),str(output/'payload')); shutil.move(str(stage/'native-config'),str(output/'config')); shutil.rmtree(stage) + _write(output/'secrets/mysql-root-password',root); _write(output/'mysql-init/00-cmnd.sql',_bootstrap_sql(VENDOR_ROOT,values,admin)); _write(output/'initial-admin.json',json.dumps({'username':'admin','password':admin},indent=2)+'\n'); _write(output/'.env',f'CMND_DB_PORT={config.database_port}\n'); _write(output/'compose.yaml',_compose(java_image)) + shutil.copytree(Path('/opt/linux-cmnd/current/deploy/php'),output/'php-image'); _write(output/'apache-image/Dockerfile','FROM ubuntu:24.04\nENV DEBIAN_FRONTEND=noninteractive\nRUN apt-get update && apt-get install -y --no-install-recommends apache2-bin media-types ca-certificates && rm -rf /var/lib/apt/lists/*\nCMD ["/usr/sbin/apache2","-f","/etc/cmnd/apache.conf","-DFOREGROUND"]\n') + for d in ('state/mysql','state/cms-files','state/php-uploads','state/cas-pgt','state/log','state/run'):(output/d).mkdir(parents=True,exist_ok=True) + _write(output/'README.txt','CMND Linux 0.8 Docker candidate\n\nReview compose.yaml and manifest.json before starting.\nStart: docker compose --env-file .env -f compose.yaml up -d --build\nStop: docker compose --env-file .env -f compose.yaml down\n\nHost-network discovery/control is not yet physical-TV qualified. Do not expose legacy services to the Internet.\n'); report['initial_admin_file']='initial-admin.json'; report['state']='rendered-not-started'; _write(output/'manifest.json',json.dumps(report,indent=2)+'\n'); return report + except Exception: + try:_write(output/'FAILED','Docker bundle rendering failed; preserve for diagnosis.\n') + except Exception:pass + raise +def main(argv=None): + p=argparse.ArgumentParser(prog='cmndctl docker-render'); p.add_argument('--config',type=Path,default=Path('/etc/cmnd/cmnd.toml')); p.add_argument('--output',type=Path,required=True); p.add_argument('--java-image',default=DEFAULT_JAVA_IMAGE); p.add_argument('--execute',action='store_true'); a=p.parse_args(argv) + try:r=render(a.config,a.output,java_image=a.java_image,execute=a.execute) + except (ConfigError,RuntimeError,OSError) as e:print('cmndctl docker-render: '+str(e),file=os.sys.stderr); return 2 + print(json.dumps(r,indent=2,sort_keys=True)); return 0 diff --git a/src/cmnd_linux/environment.py b/src/cmnd_linux/environment.py index 405a39b1..225deb08 100644 --- a/src/cmnd_linux/environment.py +++ b/src/cmnd_linux/environment.py @@ -268,10 +268,23 @@ def runtime_inventory() -> dict[str, object]: def cmnd_inventory() -> dict[str, object]: - paths = ('/opt/linux-cmnd', '/opt/cmnd', '/etc/cmnd', '/var/lib/cmnd-deployment') + # Installing the linux-cmnd tooling package itself creates /opt/linux-cmnd, + # /opt/cmnd/releases and /etc/cmnd. Those paths are NOT proof that the + # Philips application runtime has been activated. + tooling_paths = ('/opt/linux-cmnd', '/opt/cmnd', '/etc/cmnd') + runtime_paths = ( + '/var/lib/cmnd-deployment', + '/opt/cmnd/tomcat', + '/opt/cmnd/SmartCMS', + '/opt/Philips', + '/etc/cmnd/deployment.json', + ) + runtime = {path: Path(path).exists() for path in runtime_paths} return { 'package_version': package_version('linux-cmnd'), - 'paths': {path: Path(path).exists() for path in paths}, + 'paths': {path: Path(path).exists() for path in tooling_paths}, + 'runtime_paths': runtime, + 'active_runtime_detected': any(runtime.values()), 'services': {name: service_state(name) for name in ( 'cmnd-egress.service', 'cmnd-mysql.service', 'cmnd-php.service', 'cmnd-apache.service', 'cmnd-tomcat.service', diff --git a/src/cmnd_linux/install_plan.py b/src/cmnd_linux/install_plan.py index 04b3891e..ac28a347 100644 --- a/src/cmnd_linux/install_plan.py +++ b/src/cmnd_linux/install_plan.py @@ -170,10 +170,14 @@ def _docker_plan(inventory: dict, database_plan: dict) -> dict: def build_plan(inventory: dict) -> dict: occupied = _occupied(inventory) - reserved: set[int] = set() + # Reserve the legacy private defaults so public CMND listeners never consume them. + # apt_installer may move these private listeners if the host already uses them. + reserved: set[int] = {DEFAULT_PORTS['php_fpm'], DEFAULT_PORTS['management']} cmnd = inventory.get('cmnd', {}) - existing_paths = cmnd.get('paths', {}) if isinstance(cmnd, dict) else {} - existing_cmnd = bool(cmnd.get('package_version')) or any(bool(value) for value in existing_paths.values()) + runtime_paths = cmnd.get('runtime_paths', {}) if isinstance(cmnd, dict) else {} + existing_cmnd = bool(cmnd.get('active_runtime_detected')) or any( + bool(value) for value in runtime_paths.values() + ) database = _database_plan(inventory, occupied, reserved) tomcat = _tomcat_plan(inventory, occupied, reserved) diff --git a/src/cmnd_linux/native_config.py b/src/cmnd_linux/native_config.py index 94ab61ab..41b1f8af 100644 --- a/src/cmnd_linux/native_config.py +++ b/src/cmnd_linux/native_config.py @@ -35,6 +35,7 @@ class NativeLayout: php_uploads: str = '/var/lib/cmnd/php-uploads' php_user: str = 'cmnd-cms' fpm_port: int = 9000 + management_port: int = 9078 def validate(self) -> None: for name in ('tomcat', 'cms', 'configuration', 'log', 'run', 'certificate', 'key', 'ca_bundle', 'pgt', 'php_uploads'): @@ -49,6 +50,10 @@ def validate(self) -> None: raise ConfigError('invalid PHP service account') if type(self.fpm_port) is not int or not 1024 <= self.fpm_port <= 65535: raise ConfigError('PHP-FPM port must be an unprivileged integer port') + if type(self.management_port) is not int or not 1024 <= self.management_port <= 65535: + raise ConfigError('management port must be an unprivileged integer port') + if self.management_port == self.fpm_port: + raise ConfigError('management and PHP-FPM ports must be distinct') def native_endpoint(config: Config) -> tuple[str, dict[str, int]]: @@ -164,8 +169,8 @@ def render_native_files(config: Config, secrets: dict[str, str], layout: NativeL ''' if port == config.apache_https: apache += f'SSLEngine on\nSSLCertificateFile {layout.certificate}\nSSLCertificateKeyFile {layout.key}\n' - apache += ('ProxyRequests Off\nProxyPass /linux-cmnd/ http://127.0.0.1:9078/ connectiontimeout=5 timeout=30\n' - 'ProxyPassReverse /linux-cmnd/ http://127.0.0.1:9078/\n\nRequire all granted\n\n') + apache += (f'ProxyRequests Off\nProxyPass /linux-cmnd/ http://127.0.0.1:{layout.management_port}/ connectiontimeout=5 timeout=30\n' + f'ProxyPassReverse /linux-cmnd/ http://127.0.0.1:{layout.management_port}/\n\nRequire all granted\n\n') else: apache += f'Redirect /linux-cmnd/ https://{host}:{config.apache_https}/linux-cmnd/\n' apache += '\n' diff --git a/src/cmnd_linux/shared_database.py b/src/cmnd_linux/shared_database.py new file mode 100644 index 00000000..0347c004 --- /dev/null +++ b/src/cmnd_linux/shared_database.py @@ -0,0 +1,270 @@ +"""Coexistence-safe use of an already-installed MySQL service for CMND 0.8. + +This module never changes global MySQL options. It only accepts a server that +already matches the reviewed Windows-compatible lookup semantics, refuses any +pre-existing CMND schema/user namespace, and creates/drops only the CMND objects +that this invocation created. Administrator credentials are supplied through a +root-only temporary defaults file or local root socket authentication and are +never written to CMND persistent state. +""" +from __future__ import annotations + +from dataclasses import dataclass +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import time +from typing import Mapping + +from .application_stage import VENDOR_INPUT_HASHES +from .artifacts import file_hash +from .config import ConfigError +from .database_compatibility import REQUIRED_VARIABLES, assess, parse_variable_rows + +SCHEMA_SPECS = ( + ('smartinstall', 'siuser', 'smartinstall', (2, 3)), + ('cas', 'cas', 'cas', (2,)), + ('tpvision', 'tpvision', 'tpvision', tuple(range(2, 14))), + ('smartcontroldb', 'smartcontrol', 'smartcontrol', (2,)), + ('smartcms', 'smartcms', 'smartcms', (2, 3)), +) +APP_HOSTS = ('127.0.0.1', 'localhost') +HEALTH_DIR = Path('/etc/cmnd/shared-database') + + +def _valid_client(path: str) -> str: + candidate = Path(path) + if not candidate.is_absolute() or not candidate.is_file() or not os.access(candidate, os.X_OK): + raise ConfigError('shared database client must be an executable absolute path') + return str(candidate) + + +def _validate_defaults_file(path: Path) -> Path: + path = Path(path) + if not path.is_file() or path.is_symlink(): + raise ConfigError('database administrator defaults file must be a regular file') + if os.name == 'posix' and path.stat().st_mode & 0o077: + raise ConfigError('database administrator defaults file must be mode 0600 or stricter') + return path + + +def _sql_string(value: str) -> str: + if not re.fullmatch(r'[A-Za-z0-9._@%+:/=-]{1,255}', value): + raise ConfigError('unsafe SQL credential/identifier literal') + return "'" + value.replace("'", "''") + "'" + + +@dataclass +class SharedDatabaseSession: + client: str + port: int + socket_path: str | None = None + admin_defaults_file: Path | None = None + admin_user: str = 'root' + + def __post_init__(self) -> None: + self.client = _valid_client(self.client) + if type(self.port) is not int or not 1 <= self.port <= 65535: + raise ConfigError('invalid shared database port') + if self.socket_path is not None: + socket = Path(self.socket_path) + if not socket.exists() or socket.is_symlink(): + raise ConfigError('shared database socket does not exist or is unsafe') + self.socket_path = str(socket) + if self.admin_defaults_file is not None: + self.admin_defaults_file = _validate_defaults_file(self.admin_defaults_file) + if not re.fullmatch(r'[A-Za-z0-9_@.-]{1,64}', self.admin_user): + raise ConfigError('invalid database administrator user') + + def _command(self, database: str | None = None) -> list[str]: + command = [self.client] + if self.admin_defaults_file is not None: + command.append(f'--defaults-extra-file={self.admin_defaults_file}') + command += ['--batch', '--skip-column-names', '--binary-mode=1', '--connect-timeout=5'] + if self.socket_path: + command += ['--protocol=socket', f'--socket={self.socket_path}'] + else: + command += ['--protocol=tcp', '-h127.0.0.1', f'-P{self.port}'] + if self.admin_defaults_file is None: + command.append(f'-u{self.admin_user}') + if database: + if not re.fullmatch(r'[A-Za-z0-9_]{1,64}', database): + raise ConfigError('unsafe database name') + command.append(database) + return command + + def execute(self, sql: bytes | str, database: str | None = None, *, timeout: int = 900) -> bytes: + data = sql.encode() if isinstance(sql, str) else sql + result = subprocess.run(self._command(database), input=data, capture_output=True, + timeout=timeout, check=False) + if result.returncode: + raise RuntimeError('shared database command failed; administrator output intentionally withheld') + return result.stdout + + def compatibility(self) -> dict: + names = ','.join("'" + name + "'" for name in REQUIRED_VARIABLES) + output = self.execute('SELECT VERSION(); SHOW VARIABLES WHERE Variable_name IN (' + names + ');', timeout=20) + lines = output.decode(errors='replace').splitlines() + if not lines: + raise ConfigError('shared database compatibility probe returned no output') + result = assess(lines[0].strip(), parse_variable_rows('\n'.join(lines[1:]))).as_dict() + result['connected'] = True + return result + + def namespace_conflicts(self) -> dict[str, list[str]]: + schemas = ','.join(_sql_string(spec[0]) for spec in SCHEMA_SPECS) + users = ','.join(_sql_string(spec[1]) for spec in SCHEMA_SPECS) + schema_rows = self.execute( + f'SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME IN ({schemas});', timeout=20 + ).decode(errors='replace').splitlines() + user_rows = self.execute( + f'SELECT CONCAT(User,"@",Host) FROM mysql.user WHERE User IN ({users});', timeout=20 + ).decode(errors='replace').splitlines() + return {'schemas': sorted(filter(None, map(str.strip, schema_rows))), + 'users': sorted(filter(None, map(str.strip, user_rows)))} + + def validate_for_fresh_cmnd(self) -> dict: + compatibility = self.compatibility() + if not compatibility.get('compatible'): + reasons = compatibility.get('reasons') or [compatibility.get('qualification', 'incompatible')] + raise ConfigError('existing database is not qualified for shared CMND use: ' + '; '.join(map(str, reasons))) + conflicts = self.namespace_conflicts() + if conflicts['schemas'] or conflicts['users']: + raise ConfigError('existing CMND database/user namespace detected; fresh shared-database install refused') + probe = subprocess.run( + [self.client, '--batch', '--skip-column-names', '--connect-timeout=3', + '--protocol=tcp', '-h127.0.0.1', f'-P{self.port}', '-u__cmnd_preflight_nonexistent__', '-e', 'SELECT 1'], + capture_output=True, timeout=8, check=False, + ) + combined = (probe.stdout + probe.stderr).decode(errors='replace') + if probe.returncode and ('2002' in combined or '2003' in combined or "Can't connect" in combined): + raise ConfigError('existing database is not reachable on TCP loopback at the planned CMND port') + return {'compatible': True, 'namespace_clear': True, 'tcp_loopback_reachable': True, + 'changes_performed': False, 'compatibility': compatibility} + + def rollback_fresh(self) -> dict: + """Remove only the fixed CMND namespaces from a failed fresh install. + + Callers may use this only after this session successfully passed the + namespace-clear gate and created the fresh CMND objects. + """ + removed_users: list[str] = [] + removed_schemas: list[str] = [] + for _schema, user, _folder, _numbers in reversed(SCHEMA_SPECS): + for host in reversed(APP_HOSTS): + self.execute(f'DROP USER IF EXISTS {_sql_string(user)}@{_sql_string(host)};', timeout=20) + removed_users.append(f'{user}@{host}') + for schema, _user, _folder, _numbers in reversed(SCHEMA_SPECS): + self.execute(f'DROP DATABASE IF EXISTS `{schema}`;', timeout=60) + removed_schemas.append(schema) + return {'users_removed': removed_users, 'schemas_removed': removed_schemas} + + def initialize(self, vendor: Path, values: Mapping[str, str]) -> dict: + self.validate_for_fresh_cmnd() + vendor = Path(vendor) + for name, expected in VENDOR_INPUT_HASHES.items(): + path = vendor / name + if not path.is_file() or path.is_symlink() or file_hash(path) != expected: + raise ConfigError('unrecognized or missing pinned vendor input: ' + name) + required_keys = {folder + '_db_password' for _, _, folder, _ in SCHEMA_SPECS} + required_keys.add('tpvision_db_password') + missing = sorted(key for key in required_keys if not values.get(key)) + if missing: + raise ConfigError('missing generated CMND database credentials: ' + ', '.join(missing)) + + created_schemas: list[str] = [] + created_users: list[tuple[str, str]] = [] + try: + for schema, user, folder, numbers in SCHEMA_SPECS: + key = folder + '_db_password' + password = values[key] + self.execute(f'CREATE DATABASE `{schema}` CHARACTER SET utf8 COLLATE utf8_general_ci;') + created_schemas.append(schema) + for host in APP_HOSTS: + self.execute(f'CREATE USER {_sql_string(user)}@{_sql_string(host)} IDENTIFIED BY {_sql_string(password)};') + created_users.append((user, host)) + self.execute(f'GRANT ALL ON `{schema}`.* TO {_sql_string(user)}@{_sql_string(host)};') + for number in numbers: + self.execute((vendor / 'SQLScripts' / folder / f'sql_{number}.sql').read_bytes(), schema) + return {'schemas_created': created_schemas, + 'users_created': [f'{user}@{host}' for user, host in created_users], + 'shared_database': True} + except Exception: + for user, host in reversed(created_users): + subprocess.run(self._command(), input=f'DROP USER IF EXISTS {_sql_string(user)}@{_sql_string(host)};'.encode(), + capture_output=True, timeout=20, check=False) + for schema in reversed(created_schemas): + subprocess.run(self._command(), input=f'DROP DATABASE IF EXISTS `{schema}`;'.encode(), + capture_output=True, timeout=60, check=False) + raise + + +def write_health_files(values: Mapping[str, str], port: int, *, root: Path = HEALTH_DIR) -> dict[str, str]: + if root.exists() or root.is_symlink(): + raise ConfigError('shared database health configuration already exists') + root.mkdir(parents=True, mode=0o700) + result: dict[str, str] = {} + for schema, user, folder in (('smartinstall', 'siuser', 'smartinstall'), + ('smartcontroldb', 'smartcontrol', 'smartcontrol')): + password = values[folder + '_db_password'] + content = (f'[client]\nuser={user}\npassword={password}\nhost=127.0.0.1\n' + f'port={port}\nprotocol=tcp\n') + path = root / f'{schema}.cnf' + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as handle: + handle.write(content) + result[schema] = str(path) + marker = root / 'state.json' + marker.write_text(json.dumps({'port': port, 'files': result}, indent=2) + '\n', encoding='utf-8') + marker.chmod(0o600) + return result + + +def _health_query(schema: str, sql: str, *, root: Path = HEALTH_DIR, timeout: int = 10) -> bytes: + state_path = root / 'state.json' + if not state_path.is_file() or state_path.is_symlink(): + raise ConfigError('shared database health state is missing') + state = json.loads(state_path.read_text(encoding='utf-8')) + path = Path(state['files'][schema]) + _validate_defaults_file(path) + client = shutil.which('mariadb') or shutil.which('mysql') + if not client: + raise ConfigError('mysql/mariadb client unavailable for shared database health check') + result = subprocess.run([client, f'--defaults-extra-file={path}', '--batch', '--skip-column-names', schema, '-e', sql], + capture_output=True, timeout=timeout, check=False) + if result.returncode: + raise RuntimeError('shared database health query failed') + return result.stdout + + +def wait_shared_database(seconds: int = 120) -> None: + if type(seconds) is not int or not 1 <= seconds <= 600: + raise ConfigError('shared database readiness timeout must be 1..600 seconds') + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + try: + if _health_query('smartinstall', 'SELECT 1;').strip() == b'1': + return + except Exception: + pass + time.sleep(1) + raise RuntimeError('shared database did not become ready') + + +def migration_histories() -> dict[str, bool]: + checks = ( + ('smartinstall', 'flyway_schema_history', 122, '9.7'), + ('smartcontroldb', 'schema_version', 27, '1.5.1'), + ) + result: dict[str, bool] = {} + for schema, table, count, version in checks: + try: + lines = _health_query(schema, f'SELECT version,success FROM {schema}.{table} ORDER BY installed_rank;').decode().splitlines() + result[schema] = bool(lines and len(lines) == count and lines[-1].split('\t')[0] == version + and all(line.endswith('\t1') for line in lines)) + except Exception: + result[schema] = False + return result diff --git a/src/cmnd_linux/update_gui.py b/src/cmnd_linux/update_gui.py index e3e9c4f7..56303c79 100644 --- a/src/cmnd_linux/update_gui.py +++ b/src/cmnd_linux/update_gui.py @@ -210,8 +210,11 @@ def do_POST(self): def serve(config_path: Path): config = json.loads(config_path.read_text()) + port = config.get('listen_port', 9078) + if type(port) is not int or not 1024 <= port <= 65535: + raise ValueError('management listen_port must be an unprivileged integer port') state = GuiState(config) - server = ManagementServer(('127.0.0.1', 9078), handler(state)) + server = ManagementServer(('127.0.0.1', port), handler(state)) if config.get('check_on_startup', True): state.check() server.serve_forever() diff --git a/tests/test_08_coexistence.py b/tests/test_08_coexistence.py new file mode 100644 index 00000000..0ba31a20 --- /dev/null +++ b/tests/test_08_coexistence.py @@ -0,0 +1,138 @@ +from pathlib import Path +import unittest +from unittest.mock import patch +import subprocess + +from cmnd_linux import apt_installer +from cmnd_linux.apt_installer import _planned_ports, render_config +from cmnd_linux.apache_integration import render as render_apache +from cmnd_linux.config import Config +from cmnd_linux.install_plan import build_plan +from cmnd_linux.shared_database import _sql_string + + +def inventory(): + return { + 'os': {'id': 'ubuntu', 'version_id': '24.04', 'qualification': 'qualified-baseline'}, + 'packages': {'linux-cmnd': '0.8.0'}, + 'listeners': {'available': True, 'entries': []}, + 'web': { + 'apache': {'present': False}, 'apache_ctl': {'present': False}, + 'apache_service': {'active': False}, 'nginx': {'present': False}, + }, + 'database': { + 'mariadb_client': {'present': False}, 'mysql_client': {'present': False}, + 'packages': {}, 'root_socket_auth': 'not-tested', + }, + 'docker': {'docker': {'present': True}, 'daemon_access': True, 'running_containers': []}, + 'runtime': {'java': {'present': True, 'version': 'openjdk version "17.0.12"', 'path': '/usr/bin/java'}}, + 'cmnd': { + 'package_version': '0.8.0', + 'paths': {'/opt/linux-cmnd': True, '/opt/cmnd': True, '/etc/cmnd': True}, + 'runtime_paths': { + '/var/lib/cmnd-deployment': False, + '/opt/cmnd/tomcat': False, + '/opt/cmnd/SmartCMS': False, + '/opt/Philips': False, + '/etc/cmnd/deployment.json': False, + }, + 'active_runtime_detected': False, + }, + } + + +class AptCoexistenceTests(unittest.TestCase): + def test_tooling_only_host_can_be_planned_for_first_activation(self): + inv = inventory() + plan = build_plan(inv) + self.assertTrue(plan['fresh_install_allowed']) + ports = _planned_ports(inv, plan, 'isolated') + self.assertEqual(ports['tomcat_http'], 8080) + self.assertEqual(ports['tomcat_https'], 8443) + self.assertEqual(ports['apache_http'], 8082) + self.assertEqual(ports['apache_https'], 8444) + self.assertEqual(ports['database'], 3306) + + def test_main_cmnd_ports_move_without_taking_existing_listener(self): + inv = inventory() + inv['listeners']['entries'] = [ + {'port': 8080, 'process': 'other-java'}, + {'port': 8082, 'process': 'other-web'}, + {'port': 3306, 'process': 'other-db'}, + ] + plan = build_plan(inv) + ports = _planned_ports(inv, plan, 'isolated') + self.assertNotIn(8080, ports.values()) + self.assertNotIn(8082, ports.values()) + self.assertNotIn(3306, ports.values()) + + def test_auto_server_ip_prefers_default_route_source(self): + def fake_run(args, timeout=1800): + if args[:4] == ['ip', '-j', 'route', 'get']: + return subprocess.CompletedProcess(args, 0, '[{\"prefsrc\":\"10.1.10.14\"}]', '') + raise AssertionError(args) + with patch.object(apt_installer, '_assigned_ipv4', return_value=['172.17.0.1', '10.1.10.14']), \ + patch.object(apt_installer, '_run', side_effect=fake_run): + self.assertEqual(apt_installer.choose_server_ip(), '10.1.10.14') + + def test_private_cmnd_ports_move_when_occupied(self): + inv = inventory() + inv['listeners']['entries'] = [ + {'port': 9000, 'process': 'existing-fpm'}, + {'port': 9078, 'process': 'existing-admin'}, + ] + plan = build_plan(inv) + ports = _planned_ports(inv, plan, 'isolated') + self.assertNotEqual(ports['php_fpm'], 9000) + self.assertNotEqual(ports['management'], 9078) + self.assertEqual(len(set(ports.values())), len(ports)) + + def test_generated_config_has_empty_tv_allowlist(self): + text = render_config('10.1.10.14', { + 'tomcat_http': 8080, 'tomcat_https': 8443, + 'apache_http': 8082, 'apache_https': 8444, 'database': 3306, + }) + self.assertIn('bind = "10.1.10.14"', text) + self.assertIn('allowlist = []', text) + self.assertIn('permitted_ranges = ["127.0.0.0/8"]', text) + + def test_host_apache_fragment_is_scoped_and_does_not_include_host_sites(self): + config = Config( + mode='lab', bind='10.1.10.14', + callback_base_url='http://10.1.10.14:8080', + permitted_ranges=('127.0.0.0/8',), allowed_tvs=(), + ) + from cmnd_linux.native_config import NativeLayout + text = render_apache(config, layout=NativeLayout(fpm_port=9100, management_port=9178)) + self.assertIn('# Managed by CMND Linux 0.8.', text) + self.assertIn('Listen 10.1.10.14:8082', text) + self.assertIn('127.0.0.1:9100', text) + self.assertIn('127.0.0.1:9178', text) + self.assertNotIn('IncludeOptional sites-enabled', text) + self.assertNotIn('ports.conf', text) + + def test_generated_database_credentials_are_restricted_literals(self): + self.assertEqual(_sql_string('abc123'), "'abc123'") + with self.assertRaises(Exception): + _sql_string("bad'quote") + + def test_package_upgrade_preserves_runtime_and_password_is_transient(self): + root = Path(__file__).resolve().parents[1] + postinst = (root / 'packaging/cmnd-linux/postinst').read_text() + prerm = (root / 'packaging/cmnd-linux/prerm').read_text() + self.assertIn('existing active CMND deployment preserved', postinst) + self.assertIn("db_set cmnd-linux/database-admin-password ''", postinst) + self.assertIn('upgrade|deconfigure', prerm) + upgrade_block = prerm.split('upgrade|deconfigure', 1)[1] + self.assertNotIn('disable --now', upgrade_block) + + def test_coexistence_source_sets_runtime_permissions(self): + root = Path(__file__).resolve().parents[1] + source = (root / 'src/cmnd_linux/coexist_deploy.py').read_text() + self.assertIn("os.chown(ETC/'java-cacerts',0,java.pw_gid)", source) + self.assertIn("MANAGEMENT.chmod(0o750)", source) + self.assertIn("management_file.chmod(0o640)", source) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_apt_repository.py b/tests/test_apt_repository.py index fe7f2d2b..88ef0410 100644 --- a/tests/test_apt_repository.py +++ b/tests/test_apt_repository.py @@ -11,6 +11,7 @@ def debs(): Path('linux-cmnd_0.8.0_amd64.deb'), Path('cmnd-linux_0.8.0_all.deb'), Path('cmnd-vendor-759_7.5.9-1_all.deb'), + Path('cmnd-tomcat9_9.0.121-1_all.deb'), ] @@ -21,25 +22,27 @@ def package_metadata(self, path): package, version, architecture = 'cmnd-linux', '0.8.0', 'all' elif name.startswith('cmnd-vendor-759_'): package, version, architecture = 'cmnd-vendor-759', '7.5.9-1', 'all' + elif name.startswith('cmnd-tomcat9_'): + package, version, architecture = 'cmnd-tomcat9', '9.0.121-1', 'all' else: package, version, architecture = 'linux-cmnd', '0.8.0', 'amd64' return {'package': package, 'version': version, 'architecture': architecture, 'size': 1234} - def test_plan_requires_tooling_meta_and_vendor_packages(self): - with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate_deb', side_effect=self.package_metadata): - output = Path(temp) / 'repo' + def test_plan_requires_complete_four_package_set(self): + with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate', side_effect=self.package_metadata): with self.assertRaisesRegex(ValueError, 'requires exactly'): - build_repository(output, debs()[:2], codename='noble', suite='development', - signing_key=None, allow_unsigned_development=True, execute=False) + build_repository(Path(temp) / 'repo', debs()[:3], codename='noble', + suite='development', signing_key=None, + allow_unsigned_development=True, execute=False) def test_unsigned_stable_repository_is_refused(self): - with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate_deb', side_effect=self.package_metadata): - with self.assertRaisesRegex(ValueError, 'signed repository metadata is required'): + with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate', side_effect=self.package_metadata): + with self.assertRaisesRegex(ValueError, 'signed metadata required'): build_repository(Path(temp) / 'repo', debs(), codename='noble', suite='stable', signing_key=None, allow_unsigned_development=False, execute=False) - def test_development_plan_is_non_mutating_and_accepts_explicit_unsigned_mode(self): - with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate_deb', side_effect=self.package_metadata): + def test_development_plan_is_non_mutating(self): + with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate', side_effect=self.package_metadata): output = Path(temp) / 'repo' plan = build_repository(output, debs(), codename='noble', suite='development', signing_key=None, allow_unsigned_development=True, execute=False) @@ -47,6 +50,7 @@ def test_development_plan_is_non_mutating_and_accepts_explicit_unsigned_mode(sel self.assertFalse(plan['signed']) self.assertEqual(plan['tooling_version'], '0.8.0') self.assertEqual(plan['vendor_version'], '7.5.9-1') + self.assertEqual(plan['tomcat_version'], '9.0.121-1') self.assertFalse(output.exists()) def test_mismatched_tooling_package_versions_are_refused(self): @@ -55,23 +59,27 @@ def metadata(path): if path.name.startswith('cmnd-linux_'): result = dict(result, version='0.8.1') return result + with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate', side_effect=metadata): + with self.assertRaisesRegex(ValueError, 'versions must match'): + build_repository(Path(temp) / 'repo', debs(), codename='noble', + suite='development', signing_key='TESTKEY', + allow_unsigned_development=False, execute=False) - with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate_deb', side_effect=metadata): - with self.assertRaisesRegex(ValueError, 'same version'): - build_repository(Path(temp) / 'repo', debs(), codename='noble', suite='development', - signing_key='TESTKEY', allow_unsigned_development=False, execute=False) - - def test_unreviewed_vendor_package_version_is_refused(self): - def metadata(path): - result = self.package_metadata(path) - if path.name.startswith('cmnd-vendor-759_'): - result = dict(result, version='7.5.9-2') - return result - - with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate_deb', side_effect=metadata): - with self.assertRaisesRegex(ValueError, 'reviewed vendor package version'): - build_repository(Path(temp) / 'repo', debs(), codename='noble', suite='development', - signing_key='TESTKEY', allow_unsigned_development=False, execute=False) + def test_unreviewed_vendor_and_tomcat_versions_are_refused(self): + for prefix, version, expected in ( + ('cmnd-vendor-759_', '7.5.9-2', 'unexpected vendor package version'), + ('cmnd-tomcat9_', '9.0.122-1', 'unexpected Tomcat package version'), + ): + def metadata(path, prefix=prefix, version=version): + result = self.package_metadata(path) + if path.name.startswith(prefix): + result = dict(result, version=version) + return result + with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate', side_effect=metadata): + with self.assertRaisesRegex(ValueError, expected): + build_repository(Path(temp) / 'repo', debs(), codename='noble', + suite='development', signing_key='TESTKEY', + allow_unsigned_development=False, execute=False) if __name__ == '__main__': diff --git a/tests/test_database_compatibility.py b/tests/test_database_compatibility.py index 9f40faa4..20c2de3a 100644 --- a/tests/test_database_compatibility.py +++ b/tests/test_database_compatibility.py @@ -8,6 +8,7 @@ COMPATIBLE_VARIABLES = { 'lower_case_table_names': '1', 'event_scheduler': 'ON', + 'local_infile': 'OFF', 'sql_mode': 'NO_ENGINE_SUBSTITUTION', 'character_set_server': 'latin1', 'collation_server': 'latin1_swedish_ci', @@ -35,6 +36,16 @@ def test_case_mode_zero_is_never_silently_changed_on_existing_server(self): self.assertTrue(any('changing it on an existing populated server is unsafe' in reason for reason in result.reasons)) + def test_shared_server_global_profile_must_already_match(self): + for key, value, fragment in ( + ('event_scheduler', 'OFF', 'event_scheduler'), + ('local_infile', 'ON', 'local_infile'), + ('sql_mode', 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION', 'sql_mode'), + ): + result = assess('5.7.44', dict(COMPATIBLE_VARIABLES, **{key: value})) + self.assertFalse(result.compatible) + self.assertTrue(any(fragment in reason for reason in result.reasons)) + def test_mysql8_requires_separate_shared_database_qualification(self): result = assess('8.0.43', COMPATIBLE_VARIABLES) self.assertFalse(result.compatible) diff --git a/tests/test_install_plan.py b/tests/test_install_plan.py index 8e0daf3f..c57924c0 100644 --- a/tests/test_install_plan.py +++ b/tests/test_install_plan.py @@ -18,7 +18,7 @@ def base_inventory(): }, 'docker': {'docker': {'present': False}, 'daemon_access': False, 'running_containers': []}, 'runtime': {'java': {'present': False, 'version': None, 'path': None}}, - 'cmnd': {'package_version': None, 'paths': {}}, + 'cmnd': {'package_version': None, 'paths': {}, 'runtime_paths': {}, 'active_runtime_detected': False}, } @@ -69,12 +69,36 @@ def test_existing_database_without_socket_auth_requests_transient_admin_credenti def test_existing_cmnd_blocks_fresh_install(self): inventory = base_inventory() - inventory['cmnd'] = {'package_version': '0.7.1', 'paths': {'/opt/cmnd': True}} + inventory['cmnd'] = { + 'package_version': '0.7.1', + 'paths': {'/opt/cmnd': True}, + 'runtime_paths': {'/var/lib/cmnd-deployment': True}, + 'active_runtime_detected': True, + } plan = build_plan(inventory) self.assertFalse(plan['fresh_install_allowed']) self.assertTrue(plan['existing_cmnd_detected']) self.assertTrue(any('Existing CMND state' in warning for warning in plan['warnings'])) + + def test_tooling_package_alone_does_not_block_first_activation(self): + inventory = base_inventory() + inventory['cmnd'] = { + 'package_version': '0.8.0', + 'paths': {'/opt/linux-cmnd': True, '/opt/cmnd': True, '/etc/cmnd': True}, + 'runtime_paths': { + '/var/lib/cmnd-deployment': False, + '/opt/cmnd/tomcat': False, + '/opt/cmnd/SmartCMS': False, + '/opt/Philips': False, + '/etc/cmnd/deployment.json': False, + }, + 'active_runtime_detected': False, + } + plan = build_plan(inventory) + self.assertTrue(plan['fresh_install_allowed']) + self.assertFalse(plan['existing_cmnd_detected']) + def test_unrelated_nginx_is_preserved(self): inventory = base_inventory() inventory['web']['nginx'] = {'present': True, 'path': '/usr/sbin/nginx'} diff --git a/tests/test_meta_deb.py b/tests/test_meta_deb.py index 68f75cd4..ab0f88ac 100644 --- a/tests/test_meta_deb.py +++ b/tests/test_meta_deb.py @@ -19,15 +19,22 @@ def ar_members(blob): class MetaDebianPackageTests(unittest.TestCase): - def test_user_facing_package_depends_on_exact_payload_versions(self): + def test_user_facing_package_contains_complete_apt_transaction(self): package = build() self.assertTrue(package.name.startswith('cmnd-linux_')) members = ar_members(package.read_bytes()) with tarfile.open(fileobj=BytesIO(members['control.tar.gz']), mode='r:gz') as archive: + names = set(archive.getnames()) control = archive.extractfile('control').read().decode() self.assertIn('Package: cmnd-linux\n', control) self.assertIn('Architecture: all\n', control) - self.assertIn('Depends: linux-cmnd (= 0.8.0), cmnd-vendor-759 (= 7.5.9-1)\n', control) + self.assertIn('linux-cmnd (= 0.8.0)', control) + self.assertIn('cmnd-vendor-759 (= 7.5.9-1)', control) + self.assertIn('cmnd-tomcat9 (= 9.0.121-1)', control) + self.assertTrue({'templates', 'config', 'postinst', 'prerm', 'postrm'} <= names) + with tarfile.open(fileobj=BytesIO(members['data.tar.gz']), mode='r:gz') as archive: + data_names = set(archive.getnames()) + self.assertIn('usr/lib/cmnd/packages/linux-cmnd_0.8.0_amd64.deb', data_names) def test_meta_build_is_reproducible(self): first = build().read_bytes() diff --git a/tests/test_package_config_preservation.py b/tests/test_package_config_preservation.py index 8abf049d..7f730d32 100644 --- a/tests/test_package_config_preservation.py +++ b/tests/test_package_config_preservation.py @@ -19,7 +19,7 @@ def guard(self, root): def test_native_upgrade_preserves_operator_environments(self): with tempfile.TemporaryDirectory(prefix='cmnd-package-') as directory: root = Path(directory) - (root / 'deployment.json').write_text(json.dumps({'managed_by': 'linux-cmnd-native'})) + (root / 'deployment.json').write_text(json.dumps({'managed_by': 'linux-cmnd-native', 'state': 'active'})) for name in ('tomcat.env', 'apache.env', 'compose.env'): (root / name).write_text('operator supplied value\n') before = {p.name: p.read_bytes() for p in root.iterdir()} @@ -27,11 +27,17 @@ def test_native_upgrade_preserves_operator_environments(self): self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(before, {p.name: p.read_bytes() for p in root.iterdir()}) + def test_apt_managed_upgrade_marker_is_accepted(self): + with tempfile.TemporaryDirectory(prefix='cmnd-package-') as directory: + root = Path(directory) + (root / 'deployment.json').write_text(json.dumps({'managed_by': 'linux-cmnd-apt', 'state': 'active'})) + self.assertEqual(self.guard(root).returncode, 0) + def test_unrecognized_or_symlink_marker_is_rejected(self): with tempfile.TemporaryDirectory(prefix='cmnd-package-') as directory: root = Path(directory) marker = root / 'deployment.json' - marker.write_text(json.dumps({'managed_by': 'unrecognized'})) + marker.write_text(json.dumps({'managed_by': 'unrecognized', 'state': 'active'})) self.assertNotEqual(self.guard(root).returncode, 0) marker.rename(root / 'other.json') marker.symlink_to(root / 'other.json')